Pick the right function to load a Pixbuf on Windows.

{-# LANGUAGE CPP #-}
-- -*-haskell-*-
--  GIMP Toolkit (GTK) Pixbuf Animation
--
--  Author : Matthew Arsenault
--
--  Created: 14 November 2009
--
--  Copyright (C) 2009 Matthew Arsenault
--
--  This library is free software; you can redistribute it and/or
--  modify it under the terms of the GNU Lesser General Public
--  License as published by the Free Software Foundation; either
--  version 2.1 of the License, or (at your option) any later version.
--
--  This library is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--  Lesser General Public License for more details.
--
-- |
-- Maintainer  : gtk2hs-users@lists.sourceforge.net
-- Stability   : provisional
-- Portability : portable (depends on GHC)
--
module Graphics.UI.Gtk.Gdk.PixbufAnimation (
-- * Class Hierarchy
-- |
-- @
-- |  'GObject'
-- |   +----'PixbufAnimation'
-- |        +----'PixbufSimpleAnim'
-- @

-- * Types
  PixbufAnimation,
  PixbufAnimationClass,
  castToPixbufAnimation, gTypePixbufAnimation,
  toPixbufAnimation,

  PixbufAnimationIter,
  PixbufAnimationIterClass,
  castToPixbufAnimationIter, gTypePixbufAnimationIter,
  toPixbufAnimationIter,

  PixbufSimpleAnim,
  PixbufSimpleAnimClass,
  castToPixbufSimpleAnim, gTypePixbufSimpleAnim,
  toPixbufSimpleAnim,

-- * Constructors
  pixbufAnimationNewFromFile,
#if GTK_CHECK_VERSION(2,8,0)
  pixbufSimpleAnimNew,
#endif

-- * Methods
  pixbufAnimationGetWidth,
  pixbufAnimationGetHeight,
  pixbufAnimationGetIter,
  pixbufAnimationIsStaticImage,
  pixbufAnimationGetStaticImage,
  pixbufAnimationIterAdvance,
  pixbufAnimationIterGetDelayTime,
  pixbufAnimationIterOnCurrentlyLoadingFrame,
  pixbufAnimationIterGetPixbuf,
#if GTK_CHECK_VERSION(2,8,0)
  pixbufSimpleAnimAddFrame,
#endif

#if GTK_CHECK_VERSION(2,18,0)
  pixbufSimpleAnimSetLoop,
  pixbufSimpleAnimGetLoop
#endif
  ) where

import Control.Monad (liftM)
import System.Glib.FFI
import System.Glib.UTFString
import System.Glib.GDateTime
import System.Glib.GObject
{#import Graphics.UI.Gtk.Types#}
import System.Glib.GError	(GError(..), GErrorClass(..), GErrorDomain,
				propagateGError)
{# import Graphics.UI.Gtk.Gdk.Pixbuf #}

{# context prefix="gdk" #}

--CHECKME: Domain error doc, GFileError ???
-- | Creates a new animation by loading it from a file. The file
--   format is detected automatically. If the file's format does not
--   support multi-frame images, then an animation with a single frame
--   will be created. Possible errors are in the 'PixbufError' and
--   'GFileError' domains.
--
-- Any of several error conditions may occur: the file could not be
-- opened, there was no loader for the file's format, there was not
-- enough memory to allocate the image buffer, or the image file
-- contained invalid data.
--
-- * If an error occurs, the function will throw an exception that can
--   be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the
--   error codes in 'PixbufError' or 'GFileError'
--
pixbufAnimationNewFromFile :: FilePath               -- ^ Name of file to load, in the GLib file name encoding
                           -> IO PixbufAnimation     -- ^ A newly-created animation
pixbufAnimationNewFromFile fname =
  constructNewGObject mkPixbufAnimation $
  propagateGError $ \errPtrPtr ->
     withUTFString fname $ \strPtr ->
#if defined (WIN32) && GTK_CHECK_VERSION(2,6,5)
     {#call unsafe pixbuf_animation_new_from_file_utf8#} strPtr errPtrPtr
#else
     {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr
#endif

-- | Queries the width of the bounding box of a pixbuf animation.
pixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.
                        -> IO Int          -- ^ Width of the bounding box of the animation.
pixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self

-- | Queries the height of the bounding box of a pixbuf animation.
pixbufAnimationGetHeight :: PixbufAnimation  -- ^ An animation.
                         -> IO Int           -- ^ Height of the bounding box of the animation.
pixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self

-- | Get an iterator for displaying an animation. The iterator
--   provides the frames that should be displayed at a given time. The
--   start time would normally come from 'gGetCurrentTime', and marks
--   the beginning of animation playback. After creating an iterator,
--   you should immediately display the pixbuf returned by
--   'pixbufAnimationIterGetPixbuf'. Then, you should install a
--   timeout (with 'timeoutAdd') or by some other mechanism ensure
--   that you'll update the image after
--   'pixbufAnimationIterGetDelayTime' milliseconds. Each time the
--   image is updated, you should reinstall the timeout with the new,
--   possibly-changed delay time.
--
-- As a shortcut, if start_time is @Nothing@, the result of
-- 'gGetCurrentTime' will be used automatically.
--
-- To update the image (i.e. possibly change the result of
-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),
-- call 'pixbufAnimationIterAdvance'.
--
--  If you're using 'PixbufLoader', in addition to updating the image
--  after the delay time, you should also update it whenever you
--  receive the area_updated signal and
--  'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In
--  this case, the frame currently being fed into the loader has
--  received new data, so needs to be refreshed. The delay time for a
--  frame may also be modified after an area_updated signal, for
--  example if the delay time for a frame is encoded in the data after
--  the frame itself. So your timeout should be reinstalled after any
--  area_updated signal.
--
-- A delay time of -1 is possible, indicating "infinite."
--
pixbufAnimationGetIter :: PixbufAnimation            -- ^ a 'PixbufAnimation'
                       -> Maybe GTimeVal             -- ^ time when the animation starts playing
                       -> IO PixbufAnimationIter     -- ^ an iterator to move over the animation
pixbufAnimationGetIter self tv = maybeWith with tv $ \stPtr ->
                                 constructNewGObject mkPixbufAnimationIter $
                                   {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)

-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns
--   out to be a plain, unanimated image, then this function will
--   return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve
--   the image.
--
pixbufAnimationIsStaticImage :: PixbufAnimation
                             -> IO Bool          -- ^ TRUE if the "animation" was really just an image
pixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self

-- | If an animation is really just a plain image (has only one
--   frame), this function returns that image. If the animation is an
--   animation, this function returns a reasonable thing to display as
--   a static unanimated image, which might be the first frame, or
--   something more sophisticated. If an animation hasn't loaded any
--   frames yet, this function will return @Nothing@.
--
pixbufAnimationGetStaticImage :: PixbufAnimation
                              -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation
pixbufAnimationGetStaticImage self =
  maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self

-- | Possibly advances an animation to a new frame. Chooses the frame
--   based on the start time passed to 'pixbufAnimationGetIter'.
--
-- current_time would normally come from 'gGetCurrentTime', and must
-- be greater than or equal to the time passed to
-- 'pixbufAnimationGetIter', and must increase or remain unchanged
-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you
-- can't go backward in time; animations only play forward.
--
--  As a shortcut, pass @Nothing@ for the current time and
-- 'gGetCurrentTime' will be invoked on your behalf. So you only need
-- to explicitly pass current_time if you're doing something odd like
-- playing the animation at double speed.
--
-- If this function returns @False@, there's no need to update the
-- animation display, assuming the display had been rendered prior to
-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and
-- update the display with the new pixbuf.
--
pixbufAnimationIterAdvance :: PixbufAnimationIter  -- ^ A 'PixbufAnimationIter'
                           -> Maybe GTimeVal       -- ^ current time
                           -> IO Bool              -- ^ @True@ if the image may need updating
pixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \tvPtr ->
                                                {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)

-- | Gets the number of milliseconds the current pixbuf should be
--   displayed, or -1 if the current pixbuf should be displayed
--   forever. 'timeoutAdd' conveniently takes a timeout in
--   milliseconds, so you can use a timeout to schedule the next
--   update.
--
pixbufAnimationIterGetDelayTime :: PixbufAnimationIter  -- ^ an animation iterator
                                -> IO Int               -- ^ delay time in milliseconds (thousandths of a second)
pixbufAnimationIterGetDelayTime self = liftM fromIntegral $
  {#call unsafe pixbuf_animation_iter_get_delay_time#} self

-- | Used to determine how to respond to the area_updated signal on
--   'PixbufLoader' when loading an animation. area_updated is emitted
--   for an area of the frame currently streaming in to the loader. So
--   if you're on the currently loading frame, you need to redraw the
--   screen for the updated area.
--
pixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter
                                           -> IO Bool              -- ^ @True@ if the frame we're on is partially loaded, or the last frame
pixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $
  {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter

--CHECKME: referencing, usage of constructNewGObject
-- | Gets the current pixbuf which should be displayed; the pixbuf will
-- be the same size as the animation itself
-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This
-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'
-- milliseconds. The caller of this function does not own a reference
-- to the returned pixbuf; the returned pixbuf will become invalid
-- when the iterator advances to the next frame, which may happen
-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to
-- keep it (don't just add a reference), as it may get recycled as you
-- advance the iterator.
--
pixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator
                                -> IO Pixbuf        -- ^ the pixbuf to be displayed
pixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $
   {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter

#if GTK_CHECK_VERSION(2,8,0)
-- | Creates a new, empty animation.
--
-- * Available since Gtk+ version 2.8
--
pixbufSimpleAnimNew :: Int   -- ^ the width of the animation
                    -> Int   -- ^ the height of the animation
                    -> Float -- ^ the speed of the animation, in frames per second
                    -> IO PixbufSimpleAnim  -- ^ a newly allocated 'PixbufSimpleAnim'
pixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $
  {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)

-- | Adds a new frame to animation. The pixbuf must have the
--   dimensions specified when the animation was constructed.
--
-- * Available since Gtk+ version 2.8
--
pixbufSimpleAnimAddFrame :: PixbufSimpleAnim   -- ^ a 'PixbufSimpleAnim'
                         -> Pixbuf             -- ^ the pixbuf to add
                         -> IO ()
pixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb

#endif

#if GTK_CHECK_VERSION(2,18,0)

-- | Sets whether animation should loop indefinitely when it reaches
--   the end.
--
-- * Available since Gtk+ version 2.18
--
pixbufSimpleAnimSetLoop :: PixbufSimpleAnim  -- ^ a 'PixbufSimpleAnim'
                           -> Bool           -- ^ whether to loop the animation
                           -> IO ()
pixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)

-- | Gets whether animation should loop indefinitely when it reaches
--   the end.
--
-- * Available since Gtk+ version 2.18
--
pixbufSimpleAnimGetLoop :: PixbufSimpleAnim  -- ^ a 'PixbufSimpleAnim'
                           -> IO Bool        -- ^ @True@ if the animation loops forever, @False@ otherwise
pixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation

#endif

{-# LANGUAGE CPP #-}
-- -*-haskell-*-
--  GIMP Toolkit (GTK) Pixbuf Animation
--
--  Author : Matthew Arsenault
--
--  Created: 14 November 2009
--
--  Copyright (C) 2009 Matthew Arsenault
--
--  This library is free software; you can redistribute it and/or
--  modify it under the terms of the GNU Lesser General Public
--  License as published by the Free Software Foundation; either
--  version 2.1 of the License, or (at your option) any later version.
--
--  This library is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--  Lesser General Public License for more details.
--
-- |
-- Maintainer  : gtk2hs-users@lists.sourceforge.net
-- Stability   : provisional
-- Portability : portable (depends on GHC)
--
module Graphics.UI.Gtk.Gdk.PixbufAnimation (
-- * Class Hierarchy
-- |
-- @
-- |  'GObject'
-- |   +----'PixbufAnimation'
-- |        +----'PixbufSimpleAnim'
-- @

-- * Types
  PixbufAnimation,
  PixbufAnimationClass,
  castToPixbufAnimation, gTypePixbufAnimation,
  toPixbufAnimation,

  PixbufAnimationIter,
  PixbufAnimationIterClass,
  castToPixbufAnimationIter, gTypePixbufAnimationIter,
  toPixbufAnimationIter,

  PixbufSimpleAnim,
  PixbufSimpleAnimClass,
  castToPixbufSimpleAnim, gTypePixbufSimpleAnim,
  toPixbufSimpleAnim,

-- * Constructors
  pixbufAnimationNewFromFile,
#if GTK_CHECK_VERSION(2,8,0)
  pixbufSimpleAnimNew,
#endif

-- * Methods
  pixbufAnimationGetWidth,
  pixbufAnimationGetHeight,
  pixbufAnimationGetIter,
  pixbufAnimationIsStaticImage,
  pixbufAnimationGetStaticImage,
  pixbufAnimationIterAdvance,
  pixbufAnimationIterGetDelayTime,
  pixbufAnimationIterOnCurrentlyLoadingFrame,
  pixbufAnimationIterGetPixbuf,
#if GTK_CHECK_VERSION(2,8,0)
  pixbufSimpleAnimAddFrame,
#endif

#if GTK_CHECK_VERSION(2,18,0)
  pixbufSimpleAnimSetLoop,
  pixbufSimpleAnimGetLoop
#endif
  ) where

import Control.Monad (liftM)
import System.Glib.FFI
import System.Glib.UTFString
import System.Glib.GDateTime
import System.Glib.GObject
{#import Graphics.UI.Gtk.Types#}
import System.Glib.GError	(GError(..), GErrorClass(..), GErrorDomain,
				propagateGError)
{# import Graphics.UI.Gtk.Gdk.Pixbuf #}

{# context prefix="gdk" #}

--CHECKME: Domain error doc, GFileError ???
-- | Creates a new animation by loading it from a file. The file
--   format is detected automatically. If the file's format does not
--   support multi-frame images, then an animation with a single frame
--   will be created. Possible errors are in the 'PixbufError' and
--   'GFileError' domains.
--
-- Any of several error conditions may occur: the file could not be
-- opened, there was no loader for the file's format, there was not
-- enough memory to allocate the image buffer, or the image file
-- contained invalid data.
--
-- * If an error occurs, the function will throw an exception that can
--   be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the
--   error codes in 'PixbufError' or 'GFileError'
--
pixbufAnimationNewFromFile :: FilePath               -- ^ Name of file to load, in the GLib file name encoding
                           -> IO PixbufAnimation     -- ^ A newly-created animation
pixbufAnimationNewFromFile fname =
  constructNewGObject mkPixbufAnimation $
  propagateGError $ \errPtrPtr ->
     withUTFString fname $ \strPtr ->
     {#call unsafe pixbuf_animation_new_from_file#} strPtr errPtrPtr

-- | Queries the width of the bounding box of a pixbuf animation.
pixbufAnimationGetWidth :: PixbufAnimation -- ^ An animation.
                        -> IO Int          -- ^ Width of the bounding box of the animation.
pixbufAnimationGetWidth self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_width#} self

-- | Queries the height of the bounding box of a pixbuf animation.
pixbufAnimationGetHeight :: PixbufAnimation  -- ^ An animation.
                         -> IO Int           -- ^ Height of the bounding box of the animation.
pixbufAnimationGetHeight self = liftM fromIntegral $ {#call unsafe pixbuf_animation_get_height#} self

-- | Get an iterator for displaying an animation. The iterator
--   provides the frames that should be displayed at a given time. The
--   start time would normally come from 'gGetCurrentTime', and marks
--   the beginning of animation playback. After creating an iterator,
--   you should immediately display the pixbuf returned by
--   'pixbufAnimationIterGetPixbuf'. Then, you should install a
--   timeout (with 'timeoutAdd') or by some other mechanism ensure
--   that you'll update the image after
--   'pixbufAnimationIterGetDelayTime' milliseconds. Each time the
--   image is updated, you should reinstall the timeout with the new,
--   possibly-changed delay time.
--
-- As a shortcut, if start_time is @Nothing@, the result of
-- 'gGetCurrentTime' will be used automatically.
--
-- To update the image (i.e. possibly change the result of
-- 'pixbufAnimationIterGetPixbuf' to a new frame of the animation),
-- call 'pixbufAnimationIterAdvance'.
--
--  If you're using 'PixbufLoader', in addition to updating the image
--  after the delay time, you should also update it whenever you
--  receive the area_updated signal and
--  'pixbufAnimationIterOnCurrentlyLoadingFrame' returns @True@. In
--  this case, the frame currently being fed into the loader has
--  received new data, so needs to be refreshed. The delay time for a
--  frame may also be modified after an area_updated signal, for
--  example if the delay time for a frame is encoded in the data after
--  the frame itself. So your timeout should be reinstalled after any
--  area_updated signal.
--
-- A delay time of -1 is possible, indicating "infinite."
--
pixbufAnimationGetIter :: PixbufAnimation            -- ^ a 'PixbufAnimation'
                       -> Maybe GTimeVal             -- ^ time when the animation starts playing
                       -> IO PixbufAnimationIter     -- ^ an iterator to move over the animation
pixbufAnimationGetIter self tv = maybeWith with tv $ \stPtr ->
                                 constructNewGObject mkPixbufAnimationIter $
                                   {#call unsafe pixbuf_animation_get_iter#} self (castPtr stPtr)

-- | If you load a file with 'pixbufAnimationNewFromFile' and it turns
--   out to be a plain, unanimated image, then this function will
--   return @True@. Use 'pixbufAnimationGetStaticImage' to retrieve
--   the image.
--
pixbufAnimationIsStaticImage :: PixbufAnimation
                             -> IO Bool          -- ^ TRUE if the "animation" was really just an image
pixbufAnimationIsStaticImage self = liftM toBool $ {#call unsafe pixbuf_animation_is_static_image#} self

-- | If an animation is really just a plain image (has only one
--   frame), this function returns that image. If the animation is an
--   animation, this function returns a reasonable thing to display as
--   a static unanimated image, which might be the first frame, or
--   something more sophisticated. If an animation hasn't loaded any
--   frames yet, this function will return @Nothing@.
--
pixbufAnimationGetStaticImage :: PixbufAnimation
                              -> IO (Maybe Pixbuf) -- ^ unanimated image representing the animation
pixbufAnimationGetStaticImage self =
  maybeNull (constructNewGObject mkPixbuf) $ {#call unsafe pixbuf_animation_get_static_image#} self

-- | Possibly advances an animation to a new frame. Chooses the frame
--   based on the start time passed to 'pixbufAnimationGetIter'.
--
-- current_time would normally come from 'gGetCurrentTime', and must
-- be greater than or equal to the time passed to
-- 'pixbufAnimationGetIter', and must increase or remain unchanged
-- each time 'pixbufAnimationIterGetPixbuf' is called. That is, you
-- can't go backward in time; animations only play forward.
--
--  As a shortcut, pass @Nothing@ for the current time and
-- 'gGetCurrentTime' will be invoked on your behalf. So you only need
-- to explicitly pass current_time if you're doing something odd like
-- playing the animation at double speed.
--
-- If this function returns @False@, there's no need to update the
-- animation display, assuming the display had been rendered prior to
-- advancing; if @True@, you need to call 'animationIterGetPixbuf' and
-- update the display with the new pixbuf.
--
pixbufAnimationIterAdvance :: PixbufAnimationIter  -- ^ A 'PixbufAnimationIter'
                           -> Maybe GTimeVal       -- ^ current time
                           -> IO Bool              -- ^ @True@ if the image may need updating
pixbufAnimationIterAdvance iter currentTime = liftM toBool $ maybeWith with currentTime $ \tvPtr ->
                                                {# call unsafe pixbuf_animation_iter_advance #} iter (castPtr tvPtr)

-- | Gets the number of milliseconds the current pixbuf should be
--   displayed, or -1 if the current pixbuf should be displayed
--   forever. 'timeoutAdd' conveniently takes a timeout in
--   milliseconds, so you can use a timeout to schedule the next
--   update.
--
pixbufAnimationIterGetDelayTime :: PixbufAnimationIter  -- ^ an animation iterator
                                -> IO Int               -- ^ delay time in milliseconds (thousandths of a second)
pixbufAnimationIterGetDelayTime self = liftM fromIntegral $
  {#call unsafe pixbuf_animation_iter_get_delay_time#} self

-- | Used to determine how to respond to the area_updated signal on
--   'PixbufLoader' when loading an animation. area_updated is emitted
--   for an area of the frame currently streaming in to the loader. So
--   if you're on the currently loading frame, you need to redraw the
--   screen for the updated area.
--
pixbufAnimationIterOnCurrentlyLoadingFrame :: PixbufAnimationIter
                                           -> IO Bool              -- ^ @True@ if the frame we're on is partially loaded, or the last frame
pixbufAnimationIterOnCurrentlyLoadingFrame iter = liftM toBool $
  {# call unsafe pixbuf_animation_iter_on_currently_loading_frame #} iter

--CHECKME: referencing, usage of constructNewGObject
-- | Gets the current pixbuf which should be displayed; the pixbuf will
-- be the same size as the animation itself
-- ('pixbufAnimationGetWidth', 'pixbufAnimationGetHeight'). This
-- pixbuf should be displayed for 'pixbufAnimationIterGetDelayTime'
-- milliseconds. The caller of this function does not own a reference
-- to the returned pixbuf; the returned pixbuf will become invalid
-- when the iterator advances to the next frame, which may happen
-- anytime you call 'pixbufAnimationIterAdvance'. Copy the pixbuf to
-- keep it (don't just add a reference), as it may get recycled as you
-- advance the iterator.
--
pixbufAnimationIterGetPixbuf :: PixbufAnimationIter -- ^ an animation iterator
                                -> IO Pixbuf        -- ^ the pixbuf to be displayed
pixbufAnimationIterGetPixbuf iter = constructNewGObject mkPixbuf $
   {# call unsafe pixbuf_animation_iter_get_pixbuf #} iter

#if GTK_CHECK_VERSION(2,8,0)
-- | Creates a new, empty animation.
--
-- * Available since Gtk+ version 2.8
--
pixbufSimpleAnimNew :: Int   -- ^ the width of the animation
                    -> Int   -- ^ the height of the animation
                    -> Float -- ^ the speed of the animation, in frames per second
                    -> IO PixbufSimpleAnim  -- ^ a newly allocated 'PixbufSimpleAnim'
pixbufSimpleAnimNew width height rate = constructNewGObject mkPixbufSimpleAnim $
  {#call unsafe pixbuf_simple_anim_new#} (fromIntegral width) (fromIntegral height) (realToFrac rate)

-- | Adds a new frame to animation. The pixbuf must have the
--   dimensions specified when the animation was constructed.
--
-- * Available since Gtk+ version 2.8
--
pixbufSimpleAnimAddFrame :: PixbufSimpleAnim   -- ^ a 'PixbufSimpleAnim'
                         -> Pixbuf             -- ^ the pixbuf to add
                         -> IO ()
pixbufSimpleAnimAddFrame psa pb = {#call unsafe pixbuf_simple_anim_add_frame#} psa pb

#endif

#if GTK_CHECK_VERSION(2,18,0)

-- | Sets whether animation should loop indefinitely when it reaches
--   the end.
--
-- * Available since Gtk+ version 2.18
--
pixbufSimpleAnimSetLoop :: PixbufSimpleAnim  -- ^ a 'PixbufSimpleAnim'
                           -> Bool           -- ^ whether to loop the animation
                           -> IO ()
pixbufSimpleAnimSetLoop animation loop = {#call unsafe pixbuf_simple_anim_set_loop#} animation (fromBool loop)

-- | Gets whether animation should loop indefinitely when it reaches
--   the end.
--
-- * Available since Gtk+ version 2.18
--
pixbufSimpleAnimGetLoop :: PixbufSimpleAnim  -- ^ a 'PixbufSimpleAnim'
                           -> IO Bool        -- ^ @True@ if the animation loops forever, @False@ otherwise
pixbufSimpleAnimGetLoop animation = liftM toBool $ {#call unsafe pixbuf_simple_anim_get_loop#} animation

#endif


Fix crash bug of treeViewColumnGetWidget.

When you first call treeViewColumnGetWidget will got error "main: user error (makeNewObject: object is NULL)"
Details see : http://library.gnome.org/devel/gtk/stable/GtkTreeViewColumn.html#gtk-tree-view-column-get-widget

{-# LANGUAGE CPP #-}
-- -*-haskell-*-
--  GIMP Toolkit (GTK) TreeViewColumn TreeView
--
--  Author : Axel Simon
--
--  Created: 9 May 2001
--
--  Copyright (C) 2001-2005 Axel Simon
--
--  This library is free software; you can redistribute it and/or
--  modify it under the terms of the GNU Lesser General Public
--  License as published by the Free Software Foundation; either
--  version 2.1 of the License, or (at your option) any later version.
--
--  This library is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--  Lesser General Public License for more details.
--
-- |
-- Maintainer  : gtk2hs-users@lists.sourceforge.net
-- Stability   : provisional
-- Portability : portable (depends on GHC)
--
-- A visible column in a 'TreeView' widget
--
module Graphics.UI.Gtk.ModelView.TreeViewColumn (
-- * Detail
--
-- | The 'TreeViewColumn' object represents a visible column in a 'TreeView'
-- widget. It allows to set properties of the column header, and functions as a
-- holding pen for the cell renderers which determine how the data in the
-- column is displayed.
--

-- * Class Hierarchy
-- |
-- @
-- |  'GObject'
-- |   +----'Object'
-- |         +----TreeViewColumn
-- @

-- * Types
  TreeViewColumn,
  TreeViewColumnClass,
  castToTreeViewColumn, gTypeTreeViewColumn,
  toTreeViewColumn,

-- * Constructors
  treeViewColumnNew,

-- * Methods
  treeViewColumnPackStart,
  treeViewColumnPackEnd,
  treeViewColumnClear,
  treeViewColumnGetCellRenderers,
  treeViewColumnSetSpacing,
  treeViewColumnGetSpacing,
  treeViewColumnSetVisible,
  treeViewColumnGetVisible,
  treeViewColumnSetResizable,
  treeViewColumnGetResizable,
  TreeViewColumnSizing(..),
  treeViewColumnSetSizing,
  treeViewColumnGetSizing,
  treeViewColumnGetWidth,
  treeViewColumnSetFixedWidth,
  treeViewColumnGetFixedWidth,
  treeViewColumnSetMinWidth,
  treeViewColumnGetMinWidth,
  treeViewColumnSetMaxWidth,
  treeViewColumnGetMaxWidth,
  treeViewColumnClicked,
  treeViewColumnSetTitle,
  treeViewColumnGetTitle,
  treeViewColumnSetClickable,
  treeViewColumnGetClickable,
  treeViewColumnSetWidget,
  treeViewColumnGetWidget,
  treeViewColumnSetAlignment,
  treeViewColumnGetAlignment,
  treeViewColumnSetReorderable,
  treeViewColumnGetReorderable,
  treeViewColumnSetSortColumnId,
  treeViewColumnGetSortColumnId,
  treeViewColumnSetSortIndicator,
  treeViewColumnGetSortIndicator,
  treeViewColumnSetSortOrder,
  treeViewColumnGetSortOrder,
  SortType(..),
#if GTK_CHECK_VERSION(2,4,0)
  treeViewColumnSetExpand,
  treeViewColumnGetExpand,
#endif
  treeViewColumnCellIsVisible,
#if GTK_CHECK_VERSION(2,2,0)
  treeViewColumnFocusCell,
#if GTK_CHECK_VERSION(2,8,0)
  treeViewColumnQueueResize,
#endif
#endif

-- * Attributes
  treeViewColumnVisible,
  treeViewColumnResizable,
  treeViewColumnWidth,
  treeViewColumnSpacing,
  treeViewColumnSizing,
  treeViewColumnFixedWidth,
  treeViewColumnMinWidth,
  treeViewColumnMaxWidth,
  treeViewColumnTitle,
  treeViewColumnExpand,
  treeViewColumnClickable,
  treeViewColumnWidget,
  treeViewColumnAlignment,
  treeViewColumnReorderable,
  treeViewColumnSortIndicator,
  treeViewColumnSortOrder,
  treeViewColumnSortColumnId,

-- * Signals
  onColClicked,
  afterColClicked
  ) where

import Control.Monad	(liftM)

import System.Glib.FFI
import System.Glib.UTFString
{#import System.Glib.GList#}			(fromGList)
import System.Glib.Attributes
import System.Glib.Properties
import Graphics.UI.Gtk.Abstract.Object		(makeNewObject)
{#import Graphics.UI.Gtk.Types#}
{#import Graphics.UI.Gtk.Signals#}
import Graphics.UI.Gtk.General.Enums		(TreeViewColumnSizing(..),
						 SortType(..))
import Graphics.UI.Gtk.General.Structs          (SortColumnId)
{#import Graphics.UI.Gtk.ModelView.TreeModel#}	()

{# context lib="gtk" prefix="gtk" #}

--------------------
-- Constructors

-- | Generate a new TreeViewColumn widget.
--
treeViewColumnNew :: IO TreeViewColumn
treeViewColumnNew  = makeNewObject mkTreeViewColumn
  {# call tree_view_column_new #}

--------------------
-- Methods

-- | Add a cell renderer at the beginning of a column.
--
-- * Excess space is divided equally among all renderers which have
--   @expand@ set to True.
--
treeViewColumnPackStart :: CellRendererClass cell => TreeViewColumn
 -> cell
 -> Bool
 -> IO ()
treeViewColumnPackStart self cell expand =
  {# call unsafe tree_view_column_pack_start #}
    self
    (toCellRenderer cell)
    (fromBool expand)

-- | Add a cell renderer at the end of a column.
--
-- * Excess space is divided equally among all renderers which have
--   @expand@ set to True.
--
treeViewColumnPackEnd :: CellRendererClass cell => TreeViewColumn
 -> cell
 -> Bool
 -> IO ()
treeViewColumnPackEnd self cell expand =
  {# call unsafe tree_view_column_pack_end #}
    self
    (toCellRenderer cell)
    (fromBool expand)

-- | Remove the associations of attributes to a store for all 'CellRenderer's.
--
treeViewColumnClear :: TreeViewColumn -> IO ()
treeViewColumnClear self =
  {# call tree_view_column_clear #}
    self

-- | Retrieve all 'CellRenderer's that are contained in this column.
--
treeViewColumnGetCellRenderers :: TreeViewColumn -> IO [CellRenderer]
treeViewColumnGetCellRenderers self =
  {# call unsafe tree_view_column_get_cell_renderers #}
    self
  >>= fromGList
  >>= mapM (makeNewObject mkCellRenderer . return)

-- | Set the number of pixels between two cell renderers.
--
treeViewColumnSetSpacing :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetSpacing self spacing =
  {# call tree_view_column_set_spacing #}
    self
    (fromIntegral spacing)

-- | Get the number of pixels between two cell renderers.
--
treeViewColumnGetSpacing :: TreeViewColumn -> IO Int
treeViewColumnGetSpacing self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_spacing #}
    self

-- | Set the visibility of a given column.
--
treeViewColumnSetVisible :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetVisible self visible =
  {# call tree_view_column_set_visible #}
    self
    (fromBool visible)

-- | Get the visibility of a given column.
--
treeViewColumnGetVisible :: TreeViewColumn -> IO Bool
treeViewColumnGetVisible self =
  liftM toBool $
  {# call unsafe tree_view_column_get_visible #}
    self

-- | Set if a given column is resizable by the user.
--
treeViewColumnSetResizable :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetResizable self resizable =
  {# call tree_view_column_set_resizable #}
    self
    (fromBool resizable)

-- | Get if a given column is resizable by the user.
--
treeViewColumnGetResizable :: TreeViewColumn -> IO Bool
treeViewColumnGetResizable self =
  liftM toBool $
  {# call unsafe tree_view_column_get_resizable #}
    self

-- | Set wether the column can be resized.
--
treeViewColumnSetSizing :: TreeViewColumn
 -> TreeViewColumnSizing
 -> IO ()
treeViewColumnSetSizing self type_ =
  {# call tree_view_column_set_sizing #}
    self
    ((fromIntegral . fromEnum) type_)

-- | Return the resizing type of the column.
--
treeViewColumnGetSizing :: TreeViewColumn
 -> IO TreeViewColumnSizing
treeViewColumnGetSizing self =
  liftM (toEnum . fromIntegral) $
  {# call unsafe tree_view_column_get_sizing #}
    self

-- | Query the current width of the column.
--
treeViewColumnGetWidth :: TreeViewColumn -> IO Int
treeViewColumnGetWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_width #}
    self

-- | Set the width of the column.
--
-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.
--
treeViewColumnSetFixedWidth :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetFixedWidth self fixedWidth =
  {# call tree_view_column_set_fixed_width #}
    self
    (fromIntegral fixedWidth)

-- | Gets the fixed width of the column.
--
-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.
--
-- * This value is only meaning may not be the actual width of the column on the
-- screen, just what is requested.
--
treeViewColumnGetFixedWidth :: TreeViewColumn -> IO Int
treeViewColumnGetFixedWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_fixed_width #}
    self

-- | Set minimum width of the column.
--
treeViewColumnSetMinWidth :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetMinWidth self minWidth =
  {# call tree_view_column_set_min_width #}
    self
    (fromIntegral minWidth)

-- | Get the minimum width of a column. Returns -1 if this width was not set.
--
treeViewColumnGetMinWidth :: TreeViewColumn -> IO Int
treeViewColumnGetMinWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_min_width #}
    self

-- | Set maximum width of the column.
--
treeViewColumnSetMaxWidth :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetMaxWidth self maxWidth =
  {# call tree_view_column_set_max_width #}
    self
    (fromIntegral maxWidth)

-- | Get the maximum width of a column. Returns -1 if this width was not set.
--
treeViewColumnGetMaxWidth :: TreeViewColumn -> IO Int
treeViewColumnGetMaxWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_max_width #}
    self

-- | Emit the @clicked@ signal on the column.
--
treeViewColumnClicked :: TreeViewColumn -> IO ()
treeViewColumnClicked self =
  {# call tree_view_column_clicked #}
    self

-- | Set the widget's title if a custom widget has not been set.
--
treeViewColumnSetTitle :: TreeViewColumn -> String -> IO ()
treeViewColumnSetTitle self title =
  withUTFString title $ \titlePtr ->
  {# call tree_view_column_set_title #}
    self
    titlePtr

-- | Get the widget's title.
--
treeViewColumnGetTitle :: TreeViewColumn -> IO (Maybe String)
treeViewColumnGetTitle self =
  {# call unsafe tree_view_column_get_title #}
    self
  >>= maybePeek peekUTFString

-- | Set if the column should be sensitive to mouse clicks.
--
treeViewColumnSetClickable :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetClickable self clickable =
  {# call tree_view_column_set_clickable #}
    self
    (fromBool clickable)

-- | Returns True if the user can click on the header for the column.
--
treeViewColumnGetClickable :: TreeViewColumn -> IO Bool
treeViewColumnGetClickable self =
  liftM toBool $
  {# call tree_view_column_get_clickable #}
    self

-- | Set the column's title to this widget.
--
treeViewColumnSetWidget :: WidgetClass widget => TreeViewColumn
 -> Maybe widget
 -> IO ()
treeViewColumnSetWidget self widget =
  {# call tree_view_column_set_widget #}
    self
    (maybe (Widget nullForeignPtr) toWidget widget)

-- | Retrieve the widget responsible for
-- showing the column title. In case only a text title was set this will be a
-- 'Alignment' widget with a 'Label' inside.
--
treeViewColumnGetWidget :: TreeViewColumn
 -> IO (Maybe Widget) -- ^ returns the 'Widget' in the column header, or 'Nothing'
treeViewColumnGetWidget self = do
  widgetPtr <- {# call unsafe tree_view_column_get_widget #} self
  if widgetPtr == nullPtr
     then return Nothing
     else liftM Just $ makeNewObject mkWidget (return widgetPtr)

-- | Sets the alignment of the title or custom widget inside the column
-- header. The alignment determines its location inside the button -- 0.0 for
-- left, 0.5 for center, 1.0 for right.
--
treeViewColumnSetAlignment :: TreeViewColumn
 -> Float          -- ^ @xalign@ - The alignment, which is between [0.0 and
                   -- 1.0] inclusive.
 -> IO ()
treeViewColumnSetAlignment self xalign =
  {# call tree_view_column_set_alignment #}
    self
    (realToFrac xalign)

-- | Returns the current x alignment of the tree column. This value can range
-- between 0.0 and 1.0.
--
treeViewColumnGetAlignment :: TreeViewColumn -> IO Float
treeViewColumnGetAlignment self =
  liftM realToFrac $
  {# call unsafe tree_view_column_get_alignment #}
    self

-- | Set if the column can be reordered by the end user dragging the header.
--
treeViewColumnSetReorderable :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetReorderable self reorderable =
  {# call tree_view_column_set_reorderable #}
    self
    (fromBool reorderable)

-- | Returns whether the column can be reordered by the user.
--
treeViewColumnGetReorderable :: TreeViewColumn -> IO Bool
treeViewColumnGetReorderable self =
  liftM toBool $
  {# call unsafe tree_view_column_get_reorderable #}
    self

-- | Set the column by which to sort.
--
-- * Sets the logical @columnId@ that this column sorts on when
--   this column is selected for sorting. The selected column's header
--   will be clickable after this call. Logical refers to the
--   'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' for which
--   a comparison function was set.
--
treeViewColumnSetSortColumnId :: TreeViewColumn -> SortColumnId -> IO ()
treeViewColumnSetSortColumnId self sortColumnId =
  {# call tree_view_column_set_sort_column_id #}
    self
    (fromIntegral sortColumnId)

-- | Get the column by which to sort.
--
-- * Retrieves the logical @columnId@ that the model sorts on when this column
--   is selected for sorting.
--
-- * Returns
--   'Graphics.UI.Gtk.ModelView.TreeSortable.treeSortableDefaultSortColumnId'
--   if this tree view column has no
--   'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' associated with it.
--
treeViewColumnGetSortColumnId :: TreeViewColumn -> IO SortColumnId
treeViewColumnGetSortColumnId self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_sort_column_id #}
    self

-- | Set if a given column has sorting arrows in its heading.
--
treeViewColumnSetSortIndicator :: TreeViewColumn
 -> Bool -> IO ()
treeViewColumnSetSortIndicator self setting =
  {# call tree_view_column_set_sort_indicator #}
    self
    (fromBool setting)

-- | Query if a given column has sorting arrows in its heading.
--
treeViewColumnGetSortIndicator :: TreeViewColumn -> IO Bool
treeViewColumnGetSortIndicator self =
  liftM toBool $
  {# call unsafe tree_view_column_get_sort_indicator #}
    self

-- | Set if a given column is sorted in ascending or descending order.
--
-- * In order for sorting to work, it is necessary to either use automatic
--   sorting via 'treeViewColumnSetSortColumnId' or to use a
--   user defined sorting on the elements in a 'TreeModel'.
--
treeViewColumnSetSortOrder :: TreeViewColumn
 -> SortType -> IO ()
treeViewColumnSetSortOrder self order =
  {# call tree_view_column_set_sort_order #}
    self
    ((fromIntegral . fromEnum) order)

-- | Query if a given column is sorted in ascending or descending order.
--
treeViewColumnGetSortOrder :: TreeViewColumn -> IO SortType
treeViewColumnGetSortOrder self =
  liftM (toEnum . fromIntegral) $
  {# call unsafe tree_view_column_get_sort_order #}
    self

#if GTK_CHECK_VERSION(2,4,0)
-- %hash c:7808 d:942b
-- | Sets the column to take available extra space. This space is shared
-- equally amongst all columns that have the expand set to @True@. If no column
-- has this option set, then the last column gets all extra space. By default,
-- every column is created with this @False@.
--
-- * Available since Gtk+ version 2.4
--
treeViewColumnSetExpand :: TreeViewColumn
 -> Bool -- ^ @expand@ - @True@ if the column should take available extra
         -- space, @False@ if not
 -> IO ()
treeViewColumnSetExpand self expand =
  {# call gtk_tree_view_column_set_expand #}
    self
    (fromBool expand)

-- %hash c:ee41 d:f16b
-- | Return @True@ if the column expands to take any available space.
--
-- * Available since Gtk+ version 2.4
--
treeViewColumnGetExpand :: TreeViewColumn
 -> IO Bool -- ^ returns @True@, if the column expands
treeViewColumnGetExpand self =
  liftM toBool $
  {# call gtk_tree_view_column_get_expand #}
    self
#endif

-- %hash c:77e0 d:e1c7
-- | Returns @True@ if any of the cells packed into the @treeColumn@ are
-- visible. For this to be meaningful, you must first initialize the cells with
-- 'treeViewColumnCellSetCellData'
--
treeViewColumnCellIsVisible :: TreeViewColumn
 -> IO Bool -- ^ returns @True@, if any of the cells packed into the
            -- @treeColumn@ are currently visible
treeViewColumnCellIsVisible self =
  liftM toBool $
  {# call gtk_tree_view_column_cell_is_visible #}
    self

#if GTK_CHECK_VERSION(2,2,0)
-- %hash c:a202 d:1401
-- | Sets the current keyboard focus to be at @cell@, if the column contains 2
-- or more editable and activatable cells.
--
-- * Available since Gtk+ version 2.2
--
treeViewColumnFocusCell :: CellRendererClass cell => TreeViewColumn
 -> cell -- ^ @cell@ - A 'CellRenderer'
 -> IO ()
treeViewColumnFocusCell self cell =
  {# call gtk_tree_view_column_focus_cell #}
    self
    (toCellRenderer cell)

#if GTK_CHECK_VERSION(2,8,0)
-- %hash c:4420 d:bfde
-- | Flags the column, and the cell renderers added to this column, to have
-- their sizes renegotiated.
--
-- * Available since Gtk+ version 2.8
--
treeViewColumnQueueResize :: TreeViewColumn -> IO ()
treeViewColumnQueueResize self =
  {# call gtk_tree_view_column_queue_resize #}
    self
#endif
#endif

--------------------
-- Attributes

-- | Whether to display the column.
--
-- Default value: @True@
--
treeViewColumnVisible :: Attr TreeViewColumn Bool
treeViewColumnVisible = newAttr
  treeViewColumnGetVisible
  treeViewColumnSetVisible

-- | Column is user-resizable.
--
-- Default value: @False@
--
treeViewColumnResizable :: Attr TreeViewColumn Bool
treeViewColumnResizable = newAttr
  treeViewColumnGetResizable
  treeViewColumnSetResizable

-- | Current width of the column.
--
-- Allowed values: >= 0
--
-- Default value: 0
--
treeViewColumnWidth :: ReadAttr TreeViewColumn Int
treeViewColumnWidth = readAttrFromIntProperty "width"

-- | Space which is inserted between cells.
--
-- Allowed values: >= 0
--
-- Default value: 0
--
treeViewColumnSpacing :: Attr TreeViewColumn Int
treeViewColumnSpacing = newAttr
  treeViewColumnGetSpacing
  treeViewColumnSetSpacing

-- | Resize mode of the column.
--
-- Default value: 'TreeViewColumnGrowOnly'
--
treeViewColumnSizing :: Attr TreeViewColumn TreeViewColumnSizing
treeViewColumnSizing = newAttr
  treeViewColumnGetSizing
  treeViewColumnSetSizing

-- | Current fixed width of the column.
--
-- Allowed values: >= 1
--
-- Default value: 1
--
treeViewColumnFixedWidth :: Attr TreeViewColumn Int
treeViewColumnFixedWidth = newAttr
  treeViewColumnGetFixedWidth
  treeViewColumnSetFixedWidth

-- | Minimum allowed width of the column.
--
-- Allowed values: >= -1
--
-- Default value: -1
--
treeViewColumnMinWidth :: Attr TreeViewColumn Int
treeViewColumnMinWidth = newAttr
  treeViewColumnGetMinWidth
  treeViewColumnSetMinWidth

-- | Maximum allowed width of the column.
--
-- Allowed values: >= -1
--
-- Default value: -1
--
treeViewColumnMaxWidth :: Attr TreeViewColumn Int
treeViewColumnMaxWidth = newAttr
  treeViewColumnGetMaxWidth
  treeViewColumnSetMaxWidth

-- | Title to appear in column header.
--
-- Default value: \"\"
--
treeViewColumnTitle :: ReadWriteAttr TreeViewColumn (Maybe String) String
treeViewColumnTitle = newAttr
  treeViewColumnGetTitle
  treeViewColumnSetTitle

-- %hash c:800 d:eb1a
-- | Column gets share of extra width allocated to the widget.
--
-- Default value: @False@
--
treeViewColumnExpand :: Attr TreeViewColumn Bool
treeViewColumnExpand = newAttrFromBoolProperty "expand"

-- | Whether the header can be clicked.
--
-- Default value: @False@
--
treeViewColumnClickable :: Attr TreeViewColumn Bool
treeViewColumnClickable = newAttr
  treeViewColumnGetClickable
  treeViewColumnSetClickable

-- | Widget to put in column header button instead of column title.
--
treeViewColumnWidget :: WidgetClass widget => ReadWriteAttr TreeViewColumn (Maybe Widget) (Maybe widget)
treeViewColumnWidget = newAttr
  treeViewColumnGetWidget
  treeViewColumnSetWidget

-- | X Alignment of the column header text or widget.
--
-- Allowed values: [0,1]
--
-- Default value: 0
--
treeViewColumnAlignment :: Attr TreeViewColumn Float
treeViewColumnAlignment = newAttr
  treeViewColumnGetAlignment
  treeViewColumnSetAlignment

-- | Whether the column can be reordered around the headers.
--
-- Default value: @False@
--
treeViewColumnReorderable :: Attr TreeViewColumn Bool
treeViewColumnReorderable = newAttr
  treeViewColumnGetReorderable
  treeViewColumnSetReorderable

-- | Whether to show a sort indicator.
--
-- Default value: @False@
--
treeViewColumnSortIndicator :: Attr TreeViewColumn Bool
treeViewColumnSortIndicator = newAttr
  treeViewColumnGetSortIndicator
  treeViewColumnSetSortIndicator

-- | Sort direction the sort indicator should indicate.
--
-- Default value: 'SortAscending'
--
treeViewColumnSortOrder :: Attr TreeViewColumn SortType
treeViewColumnSortOrder = newAttr
  treeViewColumnGetSortOrder
  treeViewColumnSetSortOrder

-- | \'sortColumnId\' property. See 'treeViewColumnGetSortColumnId' and
-- 'treeViewColumnSetSortColumnId'
--
treeViewColumnSortColumnId :: Attr TreeViewColumn SortColumnId
treeViewColumnSortColumnId = newAttr
  treeViewColumnGetSortColumnId
  treeViewColumnSetSortColumnId

--------------------
-- Signals

-- | Emitted when the header of this column has been clicked on.
--
onColClicked, afterColClicked :: TreeViewColumnClass self => self
 -> IO ()
 -> IO (ConnectId self)
onColClicked = connect_NONE__NONE "clicked" False
afterColClicked = connect_NONE__NONE "clicked" True

{-# LANGUAGE CPP #-}
-- -*-haskell-*-
--  GIMP Toolkit (GTK) TreeViewColumn TreeView
--
--  Author : Axel Simon
--
--  Created: 9 May 2001
--
--  Copyright (C) 2001-2005 Axel Simon
--
--  This library is free software; you can redistribute it and/or
--  modify it under the terms of the GNU Lesser General Public
--  License as published by the Free Software Foundation; either
--  version 2.1 of the License, or (at your option) any later version.
--
--  This library is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--  Lesser General Public License for more details.
--
-- |
-- Maintainer  : gtk2hs-users@lists.sourceforge.net
-- Stability   : provisional
-- Portability : portable (depends on GHC)
--
-- A visible column in a 'TreeView' widget
--
module Graphics.UI.Gtk.ModelView.TreeViewColumn (
-- * Detail
--
-- | The 'TreeViewColumn' object represents a visible column in a 'TreeView'
-- widget. It allows to set properties of the column header, and functions as a
-- holding pen for the cell renderers which determine how the data in the
-- column is displayed.
--

-- * Class Hierarchy
-- |
-- @
-- |  'GObject'
-- |   +----'Object'
-- |         +----TreeViewColumn
-- @

-- * Types
  TreeViewColumn,
  TreeViewColumnClass,
  castToTreeViewColumn, gTypeTreeViewColumn,
  toTreeViewColumn,

-- * Constructors
  treeViewColumnNew,

-- * Methods
  treeViewColumnPackStart,
  treeViewColumnPackEnd,
  treeViewColumnClear,
  treeViewColumnGetCellRenderers,
  treeViewColumnSetSpacing,
  treeViewColumnGetSpacing,
  treeViewColumnSetVisible,
  treeViewColumnGetVisible,
  treeViewColumnSetResizable,
  treeViewColumnGetResizable,
  TreeViewColumnSizing(..),
  treeViewColumnSetSizing,
  treeViewColumnGetSizing,
  treeViewColumnGetWidth,
  treeViewColumnSetFixedWidth,
  treeViewColumnGetFixedWidth,
  treeViewColumnSetMinWidth,
  treeViewColumnGetMinWidth,
  treeViewColumnSetMaxWidth,
  treeViewColumnGetMaxWidth,
  treeViewColumnClicked,
  treeViewColumnSetTitle,
  treeViewColumnGetTitle,
  treeViewColumnSetClickable,
  treeViewColumnGetClickable,
  treeViewColumnSetWidget,
  treeViewColumnGetWidget,
  treeViewColumnSetAlignment,
  treeViewColumnGetAlignment,
  treeViewColumnSetReorderable,
  treeViewColumnGetReorderable,
  treeViewColumnSetSortColumnId,
  treeViewColumnGetSortColumnId,
  treeViewColumnSetSortIndicator,
  treeViewColumnGetSortIndicator,
  treeViewColumnSetSortOrder,
  treeViewColumnGetSortOrder,
  SortType(..),
#if GTK_CHECK_VERSION(2,4,0)
  treeViewColumnSetExpand,
  treeViewColumnGetExpand,
#endif
  treeViewColumnCellIsVisible,
#if GTK_CHECK_VERSION(2,2,0)
  treeViewColumnFocusCell,
#if GTK_CHECK_VERSION(2,8,0)
  treeViewColumnQueueResize,
#endif
#endif

-- * Attributes
  treeViewColumnVisible,
  treeViewColumnResizable,
  treeViewColumnWidth,
  treeViewColumnSpacing,
  treeViewColumnSizing,
  treeViewColumnFixedWidth,
  treeViewColumnMinWidth,
  treeViewColumnMaxWidth,
  treeViewColumnTitle,
  treeViewColumnExpand,
  treeViewColumnClickable,
  treeViewColumnWidget,
  treeViewColumnAlignment,
  treeViewColumnReorderable,
  treeViewColumnSortIndicator,
  treeViewColumnSortOrder,
  treeViewColumnSortColumnId,

-- * Signals
  onColClicked,
  afterColClicked
  ) where

import Control.Monad	(liftM)

import System.Glib.FFI
import System.Glib.UTFString
{#import System.Glib.GList#}			(fromGList)
import System.Glib.Attributes
import System.Glib.Properties
import Graphics.UI.Gtk.Abstract.Object		(makeNewObject)
{#import Graphics.UI.Gtk.Types#}
{#import Graphics.UI.Gtk.Signals#}
import Graphics.UI.Gtk.General.Enums		(TreeViewColumnSizing(..),
						 SortType(..))
import Graphics.UI.Gtk.General.Structs          (SortColumnId)
{#import Graphics.UI.Gtk.ModelView.TreeModel#}	()

{# context lib="gtk" prefix="gtk" #}

--------------------
-- Constructors

-- | Generate a new TreeViewColumn widget.
--
treeViewColumnNew :: IO TreeViewColumn
treeViewColumnNew  = makeNewObject mkTreeViewColumn
  {# call tree_view_column_new #}

--------------------
-- Methods

-- | Add a cell renderer at the beginning of a column.
--
-- * Excess space is divided equally among all renderers which have
--   @expand@ set to True.
--
treeViewColumnPackStart :: CellRendererClass cell => TreeViewColumn
 -> cell
 -> Bool
 -> IO ()
treeViewColumnPackStart self cell expand =
  {# call unsafe tree_view_column_pack_start #}
    self
    (toCellRenderer cell)
    (fromBool expand)

-- | Add a cell renderer at the end of a column.
--
-- * Excess space is divided equally among all renderers which have
--   @expand@ set to True.
--
treeViewColumnPackEnd :: CellRendererClass cell => TreeViewColumn
 -> cell
 -> Bool
 -> IO ()
treeViewColumnPackEnd self cell expand =
  {# call unsafe tree_view_column_pack_end #}
    self
    (toCellRenderer cell)
    (fromBool expand)

-- | Remove the associations of attributes to a store for all 'CellRenderer's.
--
treeViewColumnClear :: TreeViewColumn -> IO ()
treeViewColumnClear self =
  {# call tree_view_column_clear #}
    self

-- | Retrieve all 'CellRenderer's that are contained in this column.
--
treeViewColumnGetCellRenderers :: TreeViewColumn -> IO [CellRenderer]
treeViewColumnGetCellRenderers self =
  {# call unsafe tree_view_column_get_cell_renderers #}
    self
  >>= fromGList
  >>= mapM (makeNewObject mkCellRenderer . return)

-- | Set the number of pixels between two cell renderers.
--
treeViewColumnSetSpacing :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetSpacing self spacing =
  {# call tree_view_column_set_spacing #}
    self
    (fromIntegral spacing)

-- | Get the number of pixels between two cell renderers.
--
treeViewColumnGetSpacing :: TreeViewColumn -> IO Int
treeViewColumnGetSpacing self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_spacing #}
    self

-- | Set the visibility of a given column.
--
treeViewColumnSetVisible :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetVisible self visible =
  {# call tree_view_column_set_visible #}
    self
    (fromBool visible)

-- | Get the visibility of a given column.
--
treeViewColumnGetVisible :: TreeViewColumn -> IO Bool
treeViewColumnGetVisible self =
  liftM toBool $
  {# call unsafe tree_view_column_get_visible #}
    self

-- | Set if a given column is resizable by the user.
--
treeViewColumnSetResizable :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetResizable self resizable =
  {# call tree_view_column_set_resizable #}
    self
    (fromBool resizable)

-- | Get if a given column is resizable by the user.
--
treeViewColumnGetResizable :: TreeViewColumn -> IO Bool
treeViewColumnGetResizable self =
  liftM toBool $
  {# call unsafe tree_view_column_get_resizable #}
    self

-- | Set wether the column can be resized.
--
treeViewColumnSetSizing :: TreeViewColumn
 -> TreeViewColumnSizing
 -> IO ()
treeViewColumnSetSizing self type_ =
  {# call tree_view_column_set_sizing #}
    self
    ((fromIntegral . fromEnum) type_)

-- | Return the resizing type of the column.
--
treeViewColumnGetSizing :: TreeViewColumn
 -> IO TreeViewColumnSizing
treeViewColumnGetSizing self =
  liftM (toEnum . fromIntegral) $
  {# call unsafe tree_view_column_get_sizing #}
    self

-- | Query the current width of the column.
--
treeViewColumnGetWidth :: TreeViewColumn -> IO Int
treeViewColumnGetWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_width #}
    self

-- | Set the width of the column.
--
-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.
--
treeViewColumnSetFixedWidth :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetFixedWidth self fixedWidth =
  {# call tree_view_column_set_fixed_width #}
    self
    (fromIntegral fixedWidth)

-- | Gets the fixed width of the column.
--
-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.
--
-- * This value is only meaning may not be the actual width of the column on the
-- screen, just what is requested.
--
treeViewColumnGetFixedWidth :: TreeViewColumn -> IO Int
treeViewColumnGetFixedWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_fixed_width #}
    self

-- | Set minimum width of the column.
--
treeViewColumnSetMinWidth :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetMinWidth self minWidth =
  {# call tree_view_column_set_min_width #}
    self
    (fromIntegral minWidth)

-- | Get the minimum width of a column. Returns -1 if this width was not set.
--
treeViewColumnGetMinWidth :: TreeViewColumn -> IO Int
treeViewColumnGetMinWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_min_width #}
    self

-- | Set maximum width of the column.
--
treeViewColumnSetMaxWidth :: TreeViewColumn -> Int -> IO ()
treeViewColumnSetMaxWidth self maxWidth =
  {# call tree_view_column_set_max_width #}
    self
    (fromIntegral maxWidth)

-- | Get the maximum width of a column. Returns -1 if this width was not set.
--
treeViewColumnGetMaxWidth :: TreeViewColumn -> IO Int
treeViewColumnGetMaxWidth self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_max_width #}
    self

-- | Emit the @clicked@ signal on the column.
--
treeViewColumnClicked :: TreeViewColumn -> IO ()
treeViewColumnClicked self =
  {# call tree_view_column_clicked #}
    self

-- | Set the widget's title if a custom widget has not been set.
--
treeViewColumnSetTitle :: TreeViewColumn -> String -> IO ()
treeViewColumnSetTitle self title =
  withUTFString title $ \titlePtr ->
  {# call tree_view_column_set_title #}
    self
    titlePtr

-- | Get the widget's title.
--
treeViewColumnGetTitle :: TreeViewColumn -> IO (Maybe String)
treeViewColumnGetTitle self =
  {# call unsafe tree_view_column_get_title #}
    self
  >>= maybePeek peekUTFString

-- | Set if the column should be sensitive to mouse clicks.
--
treeViewColumnSetClickable :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetClickable self clickable =
  {# call tree_view_column_set_clickable #}
    self
    (fromBool clickable)

-- | Returns True if the user can click on the header for the column.
--
treeViewColumnGetClickable :: TreeViewColumn -> IO Bool
treeViewColumnGetClickable self =
  liftM toBool $
  {# call tree_view_column_get_clickable #}
    self

-- | Set the column's title to this widget.
--
treeViewColumnSetWidget :: WidgetClass widget => TreeViewColumn
 -> widget
 -> IO ()
treeViewColumnSetWidget self widget =
  {# call tree_view_column_set_widget #}
    self
    (toWidget widget)

-- | Retrieve the widget responsible for
-- showing the column title. In case only a text title was set this will be a
-- 'Alignment' widget with a 'Label' inside.
--
treeViewColumnGetWidget :: TreeViewColumn -> IO Widget
treeViewColumnGetWidget self =
  makeNewObject mkWidget $
  {# call unsafe tree_view_column_get_widget #}
    self

-- | Sets the alignment of the title or custom widget inside the column
-- header. The alignment determines its location inside the button -- 0.0 for
-- left, 0.5 for center, 1.0 for right.
--
treeViewColumnSetAlignment :: TreeViewColumn
 -> Float          -- ^ @xalign@ - The alignment, which is between [0.0 and
                   -- 1.0] inclusive.
 -> IO ()
treeViewColumnSetAlignment self xalign =
  {# call tree_view_column_set_alignment #}
    self
    (realToFrac xalign)

-- | Returns the current x alignment of the tree column. This value can range
-- between 0.0 and 1.0.
--
treeViewColumnGetAlignment :: TreeViewColumn -> IO Float
treeViewColumnGetAlignment self =
  liftM realToFrac $
  {# call unsafe tree_view_column_get_alignment #}
    self

-- | Set if the column can be reordered by the end user dragging the header.
--
treeViewColumnSetReorderable :: TreeViewColumn -> Bool -> IO ()
treeViewColumnSetReorderable self reorderable =
  {# call tree_view_column_set_reorderable #}
    self
    (fromBool reorderable)

-- | Returns whether the column can be reordered by the user.
--
treeViewColumnGetReorderable :: TreeViewColumn -> IO Bool
treeViewColumnGetReorderable self =
  liftM toBool $
  {# call unsafe tree_view_column_get_reorderable #}
    self

-- | Set the column by which to sort.
--
-- * Sets the logical @columnId@ that this column sorts on when
--   this column is selected for sorting. The selected column's header
--   will be clickable after this call. Logical refers to the
--   'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' for which
--   a comparison function was set.
--
treeViewColumnSetSortColumnId :: TreeViewColumn -> SortColumnId -> IO ()
treeViewColumnSetSortColumnId self sortColumnId =
  {# call tree_view_column_set_sort_column_id #}
    self
    (fromIntegral sortColumnId)

-- | Get the column by which to sort.
--
-- * Retrieves the logical @columnId@ that the model sorts on when this column
--   is selected for sorting.
--
-- * Returns
--   'Graphics.UI.Gtk.ModelView.TreeSortable.treeSortableDefaultSortColumnId'
--   if this tree view column has no
--   'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' associated with it.
--
treeViewColumnGetSortColumnId :: TreeViewColumn -> IO SortColumnId
treeViewColumnGetSortColumnId self =
  liftM fromIntegral $
  {# call unsafe tree_view_column_get_sort_column_id #}
    self

-- | Set if a given column has sorting arrows in its heading.
--
treeViewColumnSetSortIndicator :: TreeViewColumn
 -> Bool -> IO ()
treeViewColumnSetSortIndicator self setting =
  {# call tree_view_column_set_sort_indicator #}
    self
    (fromBool setting)

-- | Query if a given column has sorting arrows in its heading.
--
treeViewColumnGetSortIndicator :: TreeViewColumn -> IO Bool
treeViewColumnGetSortIndicator self =
  liftM toBool $
  {# call unsafe tree_view_column_get_sort_indicator #}
    self

-- | Set if a given column is sorted in ascending or descending order.
--
-- * In order for sorting to work, it is necessary to either use automatic
--   sorting via 'treeViewColumnSetSortColumnId' or to use a
--   user defined sorting on the elements in a 'TreeModel'.
--
treeViewColumnSetSortOrder :: TreeViewColumn
 -> SortType -> IO ()
treeViewColumnSetSortOrder self order =
  {# call tree_view_column_set_sort_order #}
    self
    ((fromIntegral . fromEnum) order)

-- | Query if a given column is sorted in ascending or descending order.
--
treeViewColumnGetSortOrder :: TreeViewColumn -> IO SortType
treeViewColumnGetSortOrder self =
  liftM (toEnum . fromIntegral) $
  {# call unsafe tree_view_column_get_sort_order #}
    self

#if GTK_CHECK_VERSION(2,4,0)
-- %hash c:7808 d:942b
-- | Sets the column to take available extra space. This space is shared
-- equally amongst all columns that have the expand set to @True@. If no column
-- has this option set, then the last column gets all extra space. By default,
-- every column is created with this @False@.
--
-- * Available since Gtk+ version 2.4
--
treeViewColumnSetExpand :: TreeViewColumn
 -> Bool -- ^ @expand@ - @True@ if the column should take available extra
         -- space, @False@ if not
 -> IO ()
treeViewColumnSetExpand self expand =
  {# call gtk_tree_view_column_set_expand #}
    self
    (fromBool expand)

-- %hash c:ee41 d:f16b
-- | Return @True@ if the column expands to take any available space.
--
-- * Available since Gtk+ version 2.4
--
treeViewColumnGetExpand :: TreeViewColumn
 -> IO Bool -- ^ returns @True@, if the column expands
treeViewColumnGetExpand self =
  liftM toBool $
  {# call gtk_tree_view_column_get_expand #}
    self
#endif

-- %hash c:77e0 d:e1c7
-- | Returns @True@ if any of the cells packed into the @treeColumn@ are
-- visible. For this to be meaningful, you must first initialize the cells with
-- 'treeViewColumnCellSetCellData'
--
treeViewColumnCellIsVisible :: TreeViewColumn
 -> IO Bool -- ^ returns @True@, if any of the cells packed into the
            -- @treeColumn@ are currently visible
treeViewColumnCellIsVisible self =
  liftM toBool $
  {# call gtk_tree_view_column_cell_is_visible #}
    self

#if GTK_CHECK_VERSION(2,2,0)
-- %hash c:a202 d:1401
-- | Sets the current keyboard focus to be at @cell@, if the column contains 2
-- or more editable and activatable cells.
--
-- * Available since Gtk+ version 2.2
--
treeViewColumnFocusCell :: CellRendererClass cell => TreeViewColumn
 -> cell -- ^ @cell@ - A 'CellRenderer'
 -> IO ()
treeViewColumnFocusCell self cell =
  {# call gtk_tree_view_column_focus_cell #}
    self
    (toCellRenderer cell)

#if GTK_CHECK_VERSION(2,8,0)
-- %hash c:4420 d:bfde
-- | Flags the column, and the cell renderers added to this column, to have
-- their sizes renegotiated.
--
-- * Available since Gtk+ version 2.8
--
treeViewColumnQueueResize :: TreeViewColumn -> IO ()
treeViewColumnQueueResize self =
  {# call gtk_tree_view_column_queue_resize #}
    self
#endif
#endif

--------------------
-- Attributes

-- | Whether to display the column.
--
-- Default value: @True@
--
treeViewColumnVisible :: Attr TreeViewColumn Bool
treeViewColumnVisible = newAttr
  treeViewColumnGetVisible
  treeViewColumnSetVisible

-- | Column is user-resizable.
--
-- Default value: @False@
--
treeViewColumnResizable :: Attr TreeViewColumn Bool
treeViewColumnResizable = newAttr
  treeViewColumnGetResizable
  treeViewColumnSetResizable

-- | Current width of the column.
--
-- Allowed values: >= 0
--
-- Default value: 0
--
treeViewColumnWidth :: ReadAttr TreeViewColumn Int
treeViewColumnWidth = readAttrFromIntProperty "width"

-- | Space which is inserted between cells.
--
-- Allowed values: >= 0
--
-- Default value: 0
--
treeViewColumnSpacing :: Attr TreeViewColumn Int
treeViewColumnSpacing = newAttr
  treeViewColumnGetSpacing
  treeViewColumnSetSpacing

-- | Resize mode of the column.
--
-- Default value: 'TreeViewColumnGrowOnly'
--
treeViewColumnSizing :: Attr TreeViewColumn TreeViewColumnSizing
treeViewColumnSizing = newAttr
  treeViewColumnGetSizing
  treeViewColumnSetSizing

-- | Current fixed width of the column.
--
-- Allowed values: >= 1
--
-- Default value: 1
--
treeViewColumnFixedWidth :: Attr TreeViewColumn Int
treeViewColumnFixedWidth = newAttr
  treeViewColumnGetFixedWidth
  treeViewColumnSetFixedWidth

-- | Minimum allowed width of the column.
--
-- Allowed values: >= -1
--
-- Default value: -1
--
treeViewColumnMinWidth :: Attr TreeViewColumn Int
treeViewColumnMinWidth = newAttr
  treeViewColumnGetMinWidth
  treeViewColumnSetMinWidth

-- | Maximum allowed width of the column.
--
-- Allowed values: >= -1
--
-- Default value: -1
--
treeViewColumnMaxWidth :: Attr TreeViewColumn Int
treeViewColumnMaxWidth = newAttr
  treeViewColumnGetMaxWidth
  treeViewColumnSetMaxWidth

-- | Title to appear in column header.
--
-- Default value: \"\"
--
treeViewColumnTitle :: ReadWriteAttr TreeViewColumn (Maybe String) String
treeViewColumnTitle = newAttr
  treeViewColumnGetTitle
  treeViewColumnSetTitle

-- %hash c:800 d:eb1a
-- | Column gets share of extra width allocated to the widget.
--
-- Default value: @False@
--
treeViewColumnExpand :: Attr TreeViewColumn Bool
treeViewColumnExpand = newAttrFromBoolProperty "expand"

-- | Whether the header can be clicked.
--
-- Default value: @False@
--
treeViewColumnClickable :: Attr TreeViewColumn Bool
treeViewColumnClickable = newAttr
  treeViewColumnGetClickable
  treeViewColumnSetClickable

-- | Widget to put in column header button instead of column title.
--
treeViewColumnWidget :: WidgetClass widget => ReadWriteAttr TreeViewColumn Widget widget
treeViewColumnWidget = newAttr
  treeViewColumnGetWidget
  treeViewColumnSetWidget

-- | X Alignment of the column header text or widget.
--
-- Allowed values: [0,1]
--
-- Default value: 0
--
treeViewColumnAlignment :: Attr TreeViewColumn Float
treeViewColumnAlignment = newAttr
  treeViewColumnGetAlignment
  treeViewColumnSetAlignment

-- | Whether the column can be reordered around the headers.
--
-- Default value: @False@
--
treeViewColumnReorderable :: Attr TreeViewColumn Bool
treeViewColumnReorderable = newAttr
  treeViewColumnGetReorderable
  treeViewColumnSetReorderable

-- | Whether to show a sort indicator.
--
-- Default value: @False@
--
treeViewColumnSortIndicator :: Attr TreeViewColumn Bool
treeViewColumnSortIndicator = newAttr
  treeViewColumnGetSortIndicator
  treeViewColumnSetSortIndicator

-- | Sort direction the sort indicator should indicate.
--
-- Default value: 'SortAscending'
--
treeViewColumnSortOrder :: Attr TreeViewColumn SortType
treeViewColumnSortOrder = newAttr
  treeViewColumnGetSortOrder
  treeViewColumnSetSortOrder

-- | \'sortColumnId\' property. See 'treeViewColumnGetSortColumnId' and
-- 'treeViewColumnSetSortColumnId'
--
treeViewColumnSortColumnId :: Attr TreeViewColumn SortColumnId
treeViewColumnSortColumnId = newAttr
  treeViewColumnGetSortColumnId
  treeViewColumnSetSortColumnId

--------------------
-- Signals

-- | Emitted when the header of this column has been clicked on.
--
onColClicked, afterColClicked :: TreeViewColumnClass self => self
 -> IO ()
 -> IO (ConnectId self)
onColClicked = connect_NONE__NONE "clicked" False
afterColClicked = connect_NONE__NONE "clicked" True


Minor cleanups.

Minor cleanups.

{-# LANGUAGE ForeignFunctionInterface #-}

-- | The WinSCard module wraps the WinSCard API.
-- It should be regarded as a low-level wrapper, though, as it still feels rather C-ish.
-- Still missing are the getAttribute and setAttribute functions.
module Lowlevel.WinSCard ( establishContext
                         , releaseContext
                         , validateContext
                         , listReaders
                         , listReaderGroups
                         , transmit
                         , connect
                         , disconnect
                         , reconnect
                         , status
                         , beginTransaction
                         , endTransaction
                         , APDU )
where

import Foreign
import Foreign.C
import Foreign.C.String
import Lowlevel.PCSCLite
import Data.List
import Data.List.Utils
import Data.Bits
import Control.Monad

#include <winscard.h>

-- | Creates a communication context to the PC\/SC Resource Manager. This must be the first function called in a PC\/SC application.
establishContext :: SCardScope -> IO (Either SCardStatus SCardContext)
establishContext s = alloca $ \ctx_ptr ->
                        do rt  <- liftM fromCLong $ {#call SCardEstablishContext as ^#} (fromIntegral(fromEnum s)) nullPtr nullPtr ctx_ptr
                           ctx <- peek ctx_ptr
                           if rt == Ok then return $Right ctx
                                       else return $Left rt

-- | Destroys a communication context to the PC\/SC Resource Manager. This must be the last function called in a PC\/SC application.
releaseContext :: SCardContext -> IO (SCardStatus)
releaseContext c = liftM fromCLong $ {#call SCardReleaseContext as ^#} c

-- | Determines whether a 'SCardContext' is still valid.
-- After a 'SCardContext' has been set by 'SCardEstablishContext', it may become not valid if the resource manager service has been shut down.
validateContext :: SCardContext -> IO (Bool)
validateContext c = do rt <- liftM fromCLong $ {#call SCardIsValidContext as ^#} c
                       return $ rt == Ok

listReaders_ = {#call SCardListReaders as ^#}

getReaderSize_ :: SCardContext -> IO (Int)
getReaderSize_ c = alloca $ \s -> do listReaders_ c nullPtr nullPtr s
                                     s' <- peek s
                                     return $fromIntegral s'

-- | Given a 'SCardContext', lists the connected readers, or gives an error.
listReaders :: SCardContext -> IO (Either SCardStatus [String])
listReaders c = do n <- getReaderSize_ c
                   allocaArray n $ \rs ->
                        do alloca $ \size -> do poke size $fromIntegral n
                                                rt  <- liftM fromCLong $ listReaders_ c nullPtr rs size
                                                n'  <- peek size
                                                rs' <- peekArray (fromIntegral n') rs
                                                if (rt == Ok) then return $ Right $ filter (not . null) $ f rs'
                                                              else return $ Left  $ rt
                                                                   where f  = Data.List.Utils.split "\0" . map castCCharToChar
type SCardHandle = {#type SCARDHANDLE#}

-- | Smartcard /Application Protocol Data Unit/
type APDU = [Word8]

-- | Combines the given 'SCardProtocol's into one OR'd 'CULong'
combine :: [SCardProtocol] -> CULong
combine = fromIntegral . foldr ((.|.) . fromEnum) 0

-- | Given a context, establishes a connection to the reader specified as a 'String'.
-- A 'SCardShare' describing the type of connection can be given as well as a list of possible 'SCardProtocol's.
-- The first connection will power up and perform a reset on the card.
connect :: SCardContext -> String -> SCardShare -> [SCardProtocol] -> IO (Either SCardStatus (SCardProtocol, SCardHandle))
connect c r s ps = let connect_ = {#call SCardConnect as ^#}
                   in alloca $ \p ->
                        alloca $ \h ->
                          withCString r $ \r' ->
                            do rt <- liftM fromCLong $ connect_ c r' (fromIntegral $ fromEnum s) (combine ps) h p
                               p' <- liftM toSCardProtocol $ peek p
                               h' <- peek h
                               if (rt == Ok) then return $Right (p', h')
                                             else return $Left  rt

-- | Reestablishes a connection to a reader that was previously connected to using 'connect'.
-- In a multi application environment it is possible for an application to reset the card in 'Shared' mode.
-- When this occurs any other application trying to access certain commands will be returned the value 'CardReset'.
-- 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.
reconnect:: SCardHandle -> SCardShare -> [SCardProtocol] -> SCardAction-> IO (Either SCardStatus SCardProtocol)
reconnect h s ps a = let reconnect_ = {#call SCardReconnect as ^#}
                     in alloca $ \p ->
                           do rt <- liftM fromCLong $ reconnect_ h (fromIntegral $ fromEnum s) (combine ps) (fromIntegral $ fromEnum a) p
                              p' <- liftM toSCardProtocol $ peek p
                              if (rt == Ok) then return $Right p'
                                            else return $Left rt

-- | Terminates a connection, using the specified 'SCardAction'.
disconnect :: SCardHandle -> SCardAction -> IO (SCardStatus)
disconnect h a = let disconnect_ = {#call SCardDisconnect as ^ #}
                 in  liftM fromCLong $ disconnect_ h (fromIntegral $ fromEnum a)

-- | Establishes a temporary exclusive access mode for doing a series of commands or transaction.
-- You might want to use this when you are selecting a few files and then writing a large file so you can make sure
-- that another application will not change the current file.
-- If another application has a lock on this reader or this application is in 'Exclusive' there will be no action taken.
beginTransaction :: SCardHandle -> IO (SCardStatus)
beginTransaction h = liftM fromCLong $ {#call SCardBeginTransaction as ^#} h

-- | Ends a previously begun transaction.
-- The calling application must be the owner of the previously begun transaction or an error will occur.
-- 'a' can have the following values:
-- 'LeaveCard', 'ResetCard', 'UnpowerCard', 'EjectCard'
-- The disposition action is not currently used in this release.
endTransaction :: SCardHandle -> SCardAction -> IO (SCardStatus)
endTransaction h a = let end_ = {#call SCardDisconnect as ^ #}
                     in  liftM fromCLong $ end_ h (fromIntegral $ fromEnum a)

-- | Cancels all pending blocking requests on the 'getStatusChange' function.
cancel :: SCardHandle -> IO (SCardStatus)
cancel h = liftM fromCLong $ {#call SCardCancel as ^ #} h

-- | Sends a command directly to the IFD Handler to be processed by the reader.
control :: SCardHandle -> Int -> [Word8] -> Int -> IO (Either SCardStatus [Word8])
control h op cmd lr = let f  = fromIntegral . length
                          l  = length
                          cp = castPtr
                          fi = fromIntegral
                      in allocaArray (l cmd) $ \sb ->
                           allocaArray lr $ \rb ->
                             alloca $ \lr' ->
                               do rt <- liftM fromCLong $ {#call SCardControl as ^ #} h (fi op) (cp (sb :: Ptr Word8)) (f cmd) (cp (rb :: Ptr Word8)) (fi lr) lr'
                                  lr'' <- peek lr'
                                  res  <- peekArray (fromIntegral lr'') (castPtr rb)
                                  if (rt == Ok) then return $Right (res :: [Word8])
                                                else return $Left rt

-- | Sends an APDU given as list of 'Word8' to the smartcard / RFID tag connected to by 'connect'.
-- The maximum expected length for the given request is given as lr and the protocol to be used as p.
transmit :: SCardHandle -> APDU -> Int -> SCardProtocol -> IO (Either SCardStatus [Word8])
transmit h d lr p = allocaArray (length d) $ \sb ->
                      allocaArray lr $ \rb ->
                         alloca $ \lo ->
                           alloca $ \pci -> let f p' = case p' of
                                                         T0  -> mkSCardIORequestT0
                                                         T1  -> mkSCardIORequestT1
                                                         Raw -> mkSCardIORequestRaw
                                                h'   = fromCLong h
                                                pci' = castPtr pci
                                                fl   = fromIntegral . length
                                            in do poke pci $ f p
                                                  poke lo $fromIntegral lr
                                                  pokeArray sb d
                                                  rt  <- transmit_ h' pci' (castPtr (sb :: Ptr Word8)) (fl d) pci' (rb :: Ptr Word8) lo
                                                  len <- peek lo
                                                  res <- peekArray (fromIntegral len) rb
                                                  if (rt == Ok) then return $Right res
                                                                else return $Left rt
transmit_ = {#fun SCardTransmit as ^{ `Int'
                                    , castPtr `Ptr SCardIORequest'
                                    , castPtr `Ptr Word8'
                                    , fromIntegral `Int'
                                    , castPtr `Ptr SCardIORequest'
                                    , castPtr `Ptr Word8'
                                    , castPtr `Ptr CULong'
                                    } -> `SCardStatus' fromCLong#}

-- | Given a handle and the lengths for the send and receive buffers this function returns the current status of the reader connected to.
-- It's friendly name will be returned as a 'String'.
-- The current state is returned as a List of 'SCardCardState', and the Protocol as 'SCardProtocol'.
status :: SCardHandle -> Int -> Int -> IO (Either SCardStatus (String, [SCardCardState], SCardProtocol, [Word8]))
status h lr al = allocaArray lr $ \rs ->
                   alloca $ \s ->
                     alloca $ \st ->
                       alloca $ \p ->
                         alloca $ \atr ->
                           alloca $ \atrl -> do poke s $ fromIntegral lr
                                                poke atrl $ fromIntegral al
                                                rt    <- liftM fromCLong $ {#call SCardStatus as ^ #} (fromCLong h) rs s st p atr atrl
                                                rs'   <- peekCAString rs
                                                st'   <- peek st
                                                p'    <- peek p
                                                atrl' <- peek atrl
                                                atr'  <- peekArray (fromIntegral atrl') atr
                                                if (rt == Ok) then return $ Right (rs', (fromSCardStates . fromIntegral) st', toSCardProtocol p', map fromIntegral atr')
                                                              else return $ Left  rt

-- | Returns a list of currently available reader groups.
listReaderGroups :: SCardContext -> Int -> IO (Either SCardStatus [String])
listReaderGroups c lr = allocaArray lr $ \rb ->
                          alloca $ \s -> do poke s $ fromIntegral lr
                                            rt <- liftM fromCLong $ {#call SCardListReaderGroups as ^ #} c rb s
                                            s' <- peek s
                                            rb' <- peekArray (fromIntegral s') rb
                                            if (rt == Ok) then return $ Right $ filter (not . null) $ f rb'
                                                          else return $ Left  $ rt
                                                          where f  = Data.List.Utils.split "\0" . map castCCharToChar

fromSCardStates :: Int -> [SCardCardState]
fromSCardStates x = let v   = [Unknown, Absent, Present, Powered, Negotiable, Specific]
                        f k = (x .&. fromEnum k) /= 0
                    in filter f v

{-# LANGUAGE ForeignFunctionInterface #-}

-- | The WinSCard module wraps the WinSCard API.
-- It should be regarded as a low-level wrapper, though, as it still feels rather C-ish.
module Lowlevel.WinSCard ( establishContext
                         , releaseContext
                         , validateContext
                         , listReaders
                         , listReaderGroups
                         , transmit
                         , connect
                         , disconnect
                         , reconnect
                         , status
                         , beginTransaction
                         , endTransaction
                         , APDU )
where

import Foreign
import Foreign.C
import Foreign.C.String
import Lowlevel.PCSCLite
import Data.List
import Data.List.Utils
import Data.Bits
import Control.Monad

#include <winscard.h>

-- | Creates a communication context to the PC\/SC Resource Manager. This must be the first function called in a PC\/SC application.
establishContext :: SCardScope -> IO (Either SCardStatus SCardContext)
establishContext s = alloca $ \ctx_ptr ->
                        do rt  <- liftM fromCLong $ {#call SCardEstablishContext as ^#} (fromIntegral(fromEnum s)) nullPtr nullPtr ctx_ptr
                           ctx <- peek ctx_ptr
                           if rt == Ok then return $Right ctx
                                       else return $Left rt

-- | Destroys a communication context to the PC\/SC Resource Manager. This must be the last function called in a PC\/SC application.
releaseContext :: SCardContext -> IO (SCardStatus)
releaseContext c = liftM fromCLong $ {#call SCardReleaseContext as ^#} c

-- | Determines whether a 'SCardContext' is still valid.
-- After a 'SCardContext' has been set by 'SCardEstablishContext', it may become not valid if the resource manager service has been shut down.
validateContext :: SCardContext -> IO (Bool)
validateContext c = do rt <- liftM fromCLong $ {#call SCardIsValidContext as ^#} c
                       return $ rt == Ok

listReaders_ = {#call SCardListReaders as ^#}

getReaderSize_ :: SCardContext -> IO (Int)
getReaderSize_ c = alloca $ \s -> do listReaders_ c nullPtr nullPtr s
                                     s' <- peek s
                                     return $fromIntegral s'

-- | Given a 'SCardContext', lists the connected readers, or gives an error.
listReaders :: SCardContext -> IO (Either SCardStatus [String])
listReaders c = do n <- getReaderSize_ c
                   allocaArray n $ \rs ->
                        do alloca $ \size -> do poke size $fromIntegral n
                                                rt  <- liftM fromCLong $ listReaders_ c nullPtr rs size
                                                n'  <- peek size
                                                rs' <- peekArray (fromIntegral n') rs
                                                if (rt == Ok) then return $ Right $ filter (not . null) $ f rs'
                                                              else return $ Left  $ rt
                                                                   where f  = Data.List.Utils.split "\0" . map castCCharToChar
type SCardHandle = {#type SCARDHANDLE#}

-- | Smartcard /Application Protocol Data Unit/
type APDU = [Word8]

combine :: [SCardProtocol] -> CULong
combine = fromIntegral . foldr ((.|.) . fromEnum) 0

-- | Given a context, establishes a connection to the reader specified as a 'String'.
-- A 'SCardShare' describing the type of connection can be given as well as a list of possible 'SCardProtocol's.
-- The first connection will power up and perform a reset on the card.
connect :: SCardContext -> String -> SCardShare -> [SCardProtocol] -> IO (Either SCardStatus (SCardProtocol, SCardHandle))
connect c r s ps = let connect_ = {#call SCardConnect as ^#}
                   in alloca $ \p ->
                        alloca $ \h ->
                          withCString r $ \r' ->
                            do rt <- liftM fromCLong $ connect_ c r' (fromIntegral $ fromEnum s) (combine ps) h p
                               p' <- liftM toSCardProtocol $ peek p
                               h' <- peek h
                               if (rt == Ok) then return $Right (p', h')
                                             else return $Left  rt

-- | Reestablishes a connection to a reader that was previously connected to using 'connect'.
-- In a multi application environment it is possible for an application to reset the card in 'Shared' mode.
-- When this occurs any other application trying to access certain commands will be returned the value 'CardReset'.
-- 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.
reconnect:: SCardHandle -> SCardShare -> [SCardProtocol] -> SCardAction-> IO (Either SCardStatus SCardProtocol)
reconnect h s ps a = let reconnect_ = {#call SCardReconnect as ^#}
                     in alloca $ \p ->
                           do rt <- liftM fromCLong $ reconnect_ h (fromIntegral $ fromEnum s) (combine ps) (fromIntegral $ fromEnum a) p
                              p' <- liftM toSCardProtocol $ peek p
                              if (rt == Ok) then return $Right p'
                                            else return $Left rt

-- | Terminates a connection, using the specified 'SCardAction'.
disconnect :: SCardHandle -> SCardAction -> IO (SCardStatus)
disconnect h a = let disconnect_ = {#call SCardDisconnect as ^ #}
                 in  liftM fromCLong $ disconnect_ h (fromIntegral $ fromEnum a)

-- | Establishes a temporary exclusive access mode for doing a series of commands or transaction.
-- You might want to use this when you are selecting a few files and then writing a large file so you can make sure
-- that another application will not change the current file.
-- If another application has a lock on this reader or this application is in 'Exclusive' there will be no action taken.
beginTransaction :: SCardHandle -> IO (SCardStatus)
beginTransaction h = liftM fromCLong $ {#call SCardBeginTransaction as ^#} h

-- | Ends a previously begun transaction.
-- The calling application must be the owner of the previously begun transaction or an error will occur.
-- 'a' can have the following values:
-- 'LeaveCard', 'ResetCard', 'UnpowerCard', 'EjectCard'
-- The disposition action is not currently used in this release.
endTransaction :: SCardHandle -> SCardAction -> IO (SCardStatus)
endTransaction h a = let end_ = {#call SCardDisconnect as ^ #}
                     in  liftM fromCLong $ end_ h (fromIntegral $ fromEnum a)

-- | Cancels all pending blocking requests on the 'getStatusChange' function.
cancel :: SCardHandle -> IO (SCardStatus)
cancel h = liftM fromCLong $ {#call SCardCancel as ^ #} h

-- | Sends a command directly to the IFD Handler to be processed by the reader.
control :: SCardHandle -> Int -> [Word8] -> Int -> IO (Either SCardStatus [Word8])
control h op cmd lr = let f  = fromIntegral . length
                          l  = length
                          cp = castPtr
                          fi = fromIntegral
                      in allocaArray (l cmd) $ \sb ->
                           allocaArray lr $ \rb ->
                             alloca $ \lr' ->
                               do rt <- liftM fromCLong $ {#call SCardControl as ^ #} h (fi op) (cp (sb :: Ptr Word8)) (f cmd) (cp (rb :: Ptr Word8)) (fi lr) lr'
                                  lr'' <- peek lr'
                                  res  <- peekArray (fromIntegral lr'') (castPtr rb)
                                  if (rt == Ok) then return $Right (res :: [Word8])
                                                else return $Left rt

-- | Sends an APDU given as list of 'Word8' to the smartcard / RFID tag connected to by 'connect'.
-- The maximum expected length for the given request is given as lr and the protocol to be used as p.
transmit :: SCardHandle -> APDU -> Int -> SCardProtocol -> IO (Either SCardStatus [Word8])
transmit h d lr p = allocaArray (length d) $ \sb ->
                      allocaArray lr $ \rb ->
                         alloca $ \lo ->
                           alloca $ \pci -> let f p' = case p' of
                                                         T0  -> mkSCardIORequestT0
                                                         T1  -> mkSCardIORequestT1
                                                         Raw -> mkSCardIORequestRaw
                                                h'   = fromCLong h
                                                pci' = castPtr pci
                                                fl   = fromIntegral . length
                                            in do poke pci $ f p
                                                  poke lo $fromIntegral lr
                                                  pokeArray sb d
                                                  rt  <- transmit_ h' pci' (castPtr (sb :: Ptr Word8)) (fl d) pci' (rb :: Ptr Word8) lo
                                                  len <- peek lo
                                                  res <- peekArray (fromIntegral len) rb
                                                  if (rt == Ok) then return $Right res
                                                                else return $Left rt
transmit_ = {#fun SCardTransmit as ^{ `Int'
                                    , castPtr `Ptr SCardIORequest'
                                    , castPtr `Ptr Word8'
                                    , fromIntegral `Int'
                                    , castPtr `Ptr SCardIORequest'
                                    , castPtr `Ptr Word8'
                                    , castPtr `Ptr CULong'
                                    } -> `SCardStatus' fromCLong#}

-- | Given a handle and the lengths for the send and receive buffers this function returns the current status of the reader connected to.
-- It's friendly name will be returned as a 'String'.
-- The current state is returned as a List of 'SCardCardState', and the Protocol as 'SCardProtocol'.
status :: SCardHandle -> Int -> Int -> IO (Either SCardStatus (String, [SCardCardState], SCardProtocol, [Word8]))
status h lr al = allocaArray lr $ \rs ->
                   alloca $ \s ->
                     alloca $ \st ->
                       alloca $ \p ->
                         alloca $ \atr ->
                           alloca $ \atrl -> do poke s $ fromIntegral lr
                                                poke atrl $ fromIntegral al
                                                rt    <- liftM fromCLong $ {#call SCardStatus as ^ #} (fromCLong h) rs s st p atr atrl
                                                rs'   <- peekCAString rs
                                                st'   <- peek st
                                                p'    <- peek p
                                                atrl' <- peek atrl
                                                atr'  <- peekArray (fromIntegral atrl') atr
                                                if (rt == Ok) then return $ Right (rs', (fromSCardStates . fromIntegral) st', toSCardProtocol p', map fromIntegral atr')
                                                              else return $ Left  rt

-- | Returns a list of currently available reader groups.
listReaderGroups :: SCardContext -> Int -> IO (Either SCardStatus [String])
listReaderGroups c lr = allocaArray lr $ \rb ->
                          alloca $ \s -> do poke s $ fromIntegral lr
                                            rt <- liftM fromCLong $ {#call SCardListReaderGroups as ^ #} c rb s
                                            s' <- peek s
                                            rb' <- peekArray (fromIntegral s') rb
                                            if (rt == Ok) then return $ Right $ filter (not . null) $ f rb'
                                                          else return $ Left  $ rt
                                                          where f  = Data.List.Utils.split "\0" . map castCCharToChar

fromSCardStates :: Int -> [SCardCardState]
fromSCardStates x = let v   = [Unknown, Absent, Present, Powered, Negotiable, Specific]
                        f k = (x .&. fromEnum k) /= 0
                    in filter f v