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


Add instances for NativeFileChooserUserAction.

{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.UI.FLTK.LowLevel.NativeFileChooser
    (
     NativeFileChooserType(..),
     NativeFileChooserOption(..),
     NativeFileChooserUserAction(..),
     allNativeFileChooserOptions,
     -- * Constructor
     nativeFileChooserNew
     -- * Hierarchy
     --
     -- $hierarchy

     -- * Native_File_Chooser
     --
     -- $functions
    )
where
#include "Fl_ExportMacros.h"
#include "Fl_Types.h"
#include "Fl_Native_File_ChooserC.h"
import C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)

import Graphics.UI.FLTK.LowLevel.Fl_Types
import Graphics.UI.FLTK.LowLevel.Utils
import Graphics.UI.FLTK.LowLevel.Hierarchy
import Graphics.UI.FLTK.LowLevel.Dispatch
import qualified Data.Text as T

#c
enum NativeFileChooserType {
    BrowseFile           = BROWSE_FILE,
    BrowseDirectory      = BROWSE_DIRECTORY,
    BrowseMultiFile      = BROWSE_MULTI_FILE,
    BrowseMultiDirectory = BROWSE_MULTI_DIRECTORY,
    BrowseSaveFile       = BROWSE_SAVE_FILE,
    BrowseSaveDirectory  = BROWSE_SAVE_DIRECTORY
};

enum NativeFileChooserOption {
 NoOptions     = NO_OPTIONS,
 SaveasConfirm = SAVEAS_CONFIRM,
 NewFolder     = NEW_FOLDER,
 Preview       = PREVIEW,
 UseFilterExt  = USE_FILTER_EXT
};
#endc

{#enum NativeFileChooserType {} deriving (Show, Eq, Ord) #}
{#enum NativeFileChooserOption {} deriving (Show, Eq, Ord) #}

data NativeFileChooserUserAction =
  NativeFileChooserPicked |
  NativeFileChooserCancelled |
  NativeFileChooserError deriving (Show, Eq, Ord)

allNativeFileChooserOptions :: [NativeFileChooserOption]
allNativeFileChooserOptions =
  [
   NoOptions,
   SaveasConfirm,
   NewFolder,
   Preview,
   UseFilterExt
  ]

{# fun Fl_Native_File_Chooser_New_WithVal as newWithVal' { `Int' } -> `Ptr ()' id #}
{# fun Fl_Native_File_Chooser_New as new' {  } -> `Ptr ()' id #}
nativeFileChooserNew :: Maybe NativeFileChooserType -> IO (Ref NativeFileChooser)
nativeFileChooserNew t =
  case t of
   (Just t') -> newWithVal' (fromEnum t') >>= toRef
   Nothing -> new' >>= toRef

{# fun Fl_Native_File_Chooser_Destroy as nativeFileChooserDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}
instance (impl ~ IO ()) => Op (Destroy ()) NativeFileChooser orig impl where
  runOp _ _ chooser = swapRef chooser $ \chooserPtr -> do
    nativeFileChooserDestroy' chooserPtr
    return nullPtr
{# fun Fl_Native_File_Chooser_set_type as setType' { id `Ptr ()',`Int' } -> `()' #}
instance (impl ~ (NativeFileChooserType ->  IO ())) => Op (SetType ()) NativeFileChooser orig impl where
  runOp _ _ chooser type'' = withRef chooser $ \chooserPtr -> setType' chooserPtr (fromEnum type'')
{# fun Fl_Native_File_Chooser_type as type' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (NativeFileChooserType))) => Op (GetType_ ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> type' chooserPtr >>= return . toEnum
{# fun Fl_Native_File_Chooser_set_options as setOptions' { id `Ptr ()',`Int' } -> `()' #}
instance (impl ~ ([NativeFileChooserOption] ->  IO ())) => Op (SetOptions ()) NativeFileChooser orig impl where
   runOp _ _ chooser options = withRef chooser $ \chooserPtr -> setOptions' chooserPtr (combine options)
{# fun Fl_Native_File_Chooser_options as options' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO ([NativeFileChooserOption]))) => Op (GetOptions ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> do
     opts <- options' chooserPtr
     if (opts == 0)
       then return []
       else return (extract allNativeFileChooserOptions $ fromIntegral opts)
{# fun Fl_Native_File_Chooser_count as count' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (Int))) => Op (GetCount ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> count' chooserPtr
{# fun Fl_Native_File_Chooser_filename as filename' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilename ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filename' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_filename_with_i as filenameWithI' { id `Ptr ()',`Int' } -> `CString' #}
instance (impl ~ (AtIndex ->  IO (Maybe T.Text))) => Op (GetFilenameAt ()) NativeFileChooser orig impl where
   runOp _ _ chooser (AtIndex i) = withRef chooser $ \chooserPtr -> filenameWithI' chooserPtr i >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_set_directory as setDirectory' { id `Ptr ()',`CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetDirectory ()) NativeFileChooser orig impl where
   runOp _ _ chooser val = withRef chooser $ \chooserPtr -> copyTextToCString val >>= setDirectory' chooserPtr
{# fun Fl_Native_File_Chooser_directory as directory' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetDirectory ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> directory' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_set_title as setTitle' { id `Ptr ()',`CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetTitle ()) NativeFileChooser orig impl where
   runOp _ _ chooser title'' = withRef chooser $ \chooserPtr -> copyTextToCString title'' >>= setTitle' chooserPtr
{# fun Fl_Native_File_Chooser_title as title' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetTitle ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> title' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_filter as filter' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilter ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filter' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_set_filter as setFilter' { id `Ptr ()', `CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetFilter ()) NativeFileChooser orig impl where
   runOp _ _ chooser filter'' = withRef chooser $ \chooserPtr -> copyTextToCString filter'' >>= setFilter' chooserPtr
{# fun Fl_Native_File_Chooser_filters as filters' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (Int))) => Op (Filters ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filters' chooserPtr
{# fun Fl_Native_File_Chooser_set_filter_value as setFilterValue' { id `Ptr ()',`Int' } -> `()' #}
instance (impl ~ (AtIndex ->  IO ())) => Op (SetFilterValue ()) NativeFileChooser orig impl where
   runOp _ _ chooser (AtIndex i) = withRef chooser $ \chooserPtr -> setFilterValue' chooserPtr i
{# fun Fl_Native_File_Chooser_filter_value as filterValue' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (AtIndex))) => Op (GetFilterValue ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filterValue' chooserPtr >>= return . AtIndex
{# fun Fl_Native_File_Chooser_set_preset_file as setPresetFile' { id `Ptr ()',`CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetPresetFile ()) NativeFileChooser orig impl where
   runOp _ _ chooser preset' = withRef chooser $ \chooserPtr -> copyTextToCString preset' >>= setPresetFile' chooserPtr
{# fun Fl_Native_File_Chooser_preset_file as presetFile' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetPresetFile ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> presetFile' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_errmsg as errmsg' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetErrmsg ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> errmsg' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_show as show' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (NativeFileChooserUserAction))) => Op (ShowWidget ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> do
     res' <- show' chooserPtr
     return $ case res' of
       0    -> NativeFileChooserPicked
       1    -> NativeFileChooserCancelled
       (-1) -> NativeFileChooserError
       x''  -> error $ "NativeFileChooser::showWidget, unknown option:" ++ (show  x'')

-- $hierarchy
-- @
-- "Graphics.UI.FLTK.LowLevel.NativeFileChooser"
-- @

-- $functions
-- @
-- destroy :: 'Ref' 'NativeFileChooser' -> 'IO' ()
--
-- filters :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')
--
-- getCount :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')
--
-- getDirectory :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getErrmsg :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilename :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilenameAt :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilter :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilterValue :: 'Ref' 'NativeFileChooser' -> 'IO' ('AtIndex')
--
-- getOptions :: 'Ref' 'NativeFileChooser' -> 'IO' (['NativeFileChooserOption')]
--
-- getPresetFile :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getTitle :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getType_ :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserType')
--
-- setDirectory :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setFilter :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setFilterValue :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ()
--
-- setOptions :: 'Ref' 'NativeFileChooser' -> ['NativeFileChooserOption'] -> 'IO' ()
--
-- setPresetFile :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setTitle :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setType :: 'Ref' 'NativeFileChooser' -> 'NativeFileChooserType' -> 'IO' ()
--
-- showWidget :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserUserAction')
-- @

{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.UI.FLTK.LowLevel.NativeFileChooser
    (
     NativeFileChooserType(..),
     NativeFileChooserOption(..),
     NativeFileChooserUserAction(..),
     allNativeFileChooserOptions,
     -- * Constructor
     nativeFileChooserNew
     -- * Hierarchy
     --
     -- $hierarchy

     -- * Native_File_Chooser
     --
     -- $functions
    )
where
#include "Fl_ExportMacros.h"
#include "Fl_Types.h"
#include "Fl_Native_File_ChooserC.h"
import C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)

import Graphics.UI.FLTK.LowLevel.Fl_Types
import Graphics.UI.FLTK.LowLevel.Utils
import Graphics.UI.FLTK.LowLevel.Hierarchy
import Graphics.UI.FLTK.LowLevel.Dispatch
import qualified Data.Text as T

#c
enum NativeFileChooserType {
    BrowseFile           = BROWSE_FILE,
    BrowseDirectory      = BROWSE_DIRECTORY,
    BrowseMultiFile      = BROWSE_MULTI_FILE,
    BrowseMultiDirectory = BROWSE_MULTI_DIRECTORY,
    BrowseSaveFile       = BROWSE_SAVE_FILE,
    BrowseSaveDirectory  = BROWSE_SAVE_DIRECTORY
};

enum NativeFileChooserOption {
 NoOptions     = NO_OPTIONS,
 SaveasConfirm = SAVEAS_CONFIRM,
 NewFolder     = NEW_FOLDER,
 Preview       = PREVIEW,
 UseFilterExt  = USE_FILTER_EXT
};
#endc

{#enum NativeFileChooserType {} deriving (Show, Eq, Ord) #}
{#enum NativeFileChooserOption {} deriving (Show, Eq, Ord) #}

data NativeFileChooserUserAction =
  NativeFileChooserPicked |
  NativeFileChooserCancelled |
  NativeFileChooserError

allNativeFileChooserOptions :: [NativeFileChooserOption]
allNativeFileChooserOptions =
  [
   NoOptions,
   SaveasConfirm,
   NewFolder,
   Preview,
   UseFilterExt
  ]

{# fun Fl_Native_File_Chooser_New_WithVal as newWithVal' { `Int' } -> `Ptr ()' id #}
{# fun Fl_Native_File_Chooser_New as new' {  } -> `Ptr ()' id #}
nativeFileChooserNew :: Maybe NativeFileChooserType -> IO (Ref NativeFileChooser)
nativeFileChooserNew t =
  case t of
   (Just t') -> newWithVal' (fromEnum t') >>= toRef
   Nothing -> new' >>= toRef

{# fun Fl_Native_File_Chooser_Destroy as nativeFileChooserDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}
instance (impl ~ IO ()) => Op (Destroy ()) NativeFileChooser orig impl where
  runOp _ _ chooser = swapRef chooser $ \chooserPtr -> do
    nativeFileChooserDestroy' chooserPtr
    return nullPtr
{# fun Fl_Native_File_Chooser_set_type as setType' { id `Ptr ()',`Int' } -> `()' #}
instance (impl ~ (NativeFileChooserType ->  IO ())) => Op (SetType ()) NativeFileChooser orig impl where
  runOp _ _ chooser type'' = withRef chooser $ \chooserPtr -> setType' chooserPtr (fromEnum type'')
{# fun Fl_Native_File_Chooser_type as type' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (NativeFileChooserType))) => Op (GetType_ ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> type' chooserPtr >>= return . toEnum
{# fun Fl_Native_File_Chooser_set_options as setOptions' { id `Ptr ()',`Int' } -> `()' #}
instance (impl ~ ([NativeFileChooserOption] ->  IO ())) => Op (SetOptions ()) NativeFileChooser orig impl where
   runOp _ _ chooser options = withRef chooser $ \chooserPtr -> setOptions' chooserPtr (combine options)
{# fun Fl_Native_File_Chooser_options as options' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO ([NativeFileChooserOption]))) => Op (GetOptions ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> do
     opts <- options' chooserPtr
     if (opts == 0)
       then return []
       else return (extract allNativeFileChooserOptions $ fromIntegral opts)
{# fun Fl_Native_File_Chooser_count as count' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (Int))) => Op (GetCount ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> count' chooserPtr
{# fun Fl_Native_File_Chooser_filename as filename' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilename ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filename' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_filename_with_i as filenameWithI' { id `Ptr ()',`Int' } -> `CString' #}
instance (impl ~ (AtIndex ->  IO (Maybe T.Text))) => Op (GetFilenameAt ()) NativeFileChooser orig impl where
   runOp _ _ chooser (AtIndex i) = withRef chooser $ \chooserPtr -> filenameWithI' chooserPtr i >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_set_directory as setDirectory' { id `Ptr ()',`CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetDirectory ()) NativeFileChooser orig impl where
   runOp _ _ chooser val = withRef chooser $ \chooserPtr -> copyTextToCString val >>= setDirectory' chooserPtr
{# fun Fl_Native_File_Chooser_directory as directory' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetDirectory ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> directory' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_set_title as setTitle' { id `Ptr ()',`CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetTitle ()) NativeFileChooser orig impl where
   runOp _ _ chooser title'' = withRef chooser $ \chooserPtr -> copyTextToCString title'' >>= setTitle' chooserPtr
{# fun Fl_Native_File_Chooser_title as title' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetTitle ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> title' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_filter as filter' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilter ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filter' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_set_filter as setFilter' { id `Ptr ()', `CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetFilter ()) NativeFileChooser orig impl where
   runOp _ _ chooser filter'' = withRef chooser $ \chooserPtr -> copyTextToCString filter'' >>= setFilter' chooserPtr
{# fun Fl_Native_File_Chooser_filters as filters' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (Int))) => Op (Filters ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filters' chooserPtr
{# fun Fl_Native_File_Chooser_set_filter_value as setFilterValue' { id `Ptr ()',`Int' } -> `()' #}
instance (impl ~ (AtIndex ->  IO ())) => Op (SetFilterValue ()) NativeFileChooser orig impl where
   runOp _ _ chooser (AtIndex i) = withRef chooser $ \chooserPtr -> setFilterValue' chooserPtr i
{# fun Fl_Native_File_Chooser_filter_value as filterValue' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (AtIndex))) => Op (GetFilterValue ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> filterValue' chooserPtr >>= return . AtIndex
{# fun Fl_Native_File_Chooser_set_preset_file as setPresetFile' { id `Ptr ()',`CString' } -> `()' #}
instance (impl ~ (T.Text ->  IO ())) => Op (SetPresetFile ()) NativeFileChooser orig impl where
   runOp _ _ chooser preset' = withRef chooser $ \chooserPtr -> copyTextToCString preset' >>= setPresetFile' chooserPtr
{# fun Fl_Native_File_Chooser_preset_file as presetFile' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetPresetFile ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> presetFile' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_errmsg as errmsg' { id `Ptr ()' } -> `CString' #}
instance (impl ~ ( IO (Maybe T.Text))) => Op (GetErrmsg ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> errmsg' chooserPtr >>= \s -> cStringToText s >>= \s ->
     if (T.null s) then return Nothing else return (Just s)
{# fun Fl_Native_File_Chooser_show as show' { id `Ptr ()' } -> `Int' #}
instance (impl ~ ( IO (NativeFileChooserUserAction))) => Op (ShowWidget ()) NativeFileChooser orig impl where
   runOp _ _ chooser = withRef chooser $ \chooserPtr -> do
     res' <- show' chooserPtr
     return $ case res' of
       0    -> NativeFileChooserPicked
       1    -> NativeFileChooserCancelled
       (-1) -> NativeFileChooserError
       x''  -> error $ "NativeFileChooser::showWidget, unknown option:" ++ (show  x'')

-- $hierarchy
-- @
-- "Graphics.UI.FLTK.LowLevel.NativeFileChooser"
-- @

-- $functions
-- @
-- destroy :: 'Ref' 'NativeFileChooser' -> 'IO' ()
--
-- filters :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')
--
-- getCount :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')
--
-- getDirectory :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getErrmsg :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilename :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilenameAt :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilter :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getFilterValue :: 'Ref' 'NativeFileChooser' -> 'IO' ('AtIndex')
--
-- getOptions :: 'Ref' 'NativeFileChooser' -> 'IO' (['NativeFileChooserOption')]
--
-- getPresetFile :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getTitle :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')
--
-- getType_ :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserType')
--
-- setDirectory :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setFilter :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setFilterValue :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ()
--
-- setOptions :: 'Ref' 'NativeFileChooser' -> ['NativeFileChooserOption'] -> 'IO' ()
--
-- setPresetFile :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setTitle :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()
--
-- setType :: 'Ref' 'NativeFileChooser' -> 'NativeFileChooserType' -> 'IO' ()
--
-- showWidget :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserUserAction')
-- @


added nullDevPtr to Driver API

added nullDevPtr to Driver API

Ignore-this: 189a37a7feb6bc81462d75feffc40121

darcs-hash:20100212042424-879de-eb204d44749e5f29225464b0a30091ac7f29dc97.gz

{-# LANGUAGE ForeignFunctionInterface #-}
--------------------------------------------------------------------------------
-- |
-- Module    : Foreign.CUDA.Driver.Marshal
-- Copyright : (c) 2009 Trevor L. McDonell
-- License   : BSD
--
-- Memory management for low-level driver interface
--
--------------------------------------------------------------------------------

module Foreign.CUDA.Driver.Marshal
  (
    -- * Host Allocation
    HostPtr(..), AllocFlag(..),
    withHostPtr, mallocHostArray, freeHost,

    -- * Device Allocation
    DevicePtr,
    mallocArray, allocaArray, free, nullDevPtr,

    -- * Marshalling
    peekArray, peekArrayAsync, peekListArray,
    pokeArray, pokeArrayAsync, pokeListArray,
               copyArrayAsync,

    -- * Combined Allocation and Marshalling
    newListArray, withListArray, withListArrayLen,

    -- * Utility
    memset, getDevicePtr
  )
  where

#include <cuda.h>
{# context lib="cuda" #}

-- Friends
import Foreign.CUDA.Internal.C2HS
import Foreign.CUDA.Driver.Error
import Foreign.CUDA.Driver.Stream               (Stream(..))

-- System
import Unsafe.Coerce
import Control.Monad                            (liftM)
import Control.Exception.Extensible

import Foreign.C
import Foreign.Ptr
import Foreign.Storable
import qualified Foreign.Marshal as F

#c
typedef enum CUmemhostalloc_option_enum {
    CU_MEMHOSTALLOC_OPTION_PORTABLE       = CU_MEMHOSTALLOC_PORTABLE,
    CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED  = CU_MEMHOSTALLOC_DEVICEMAP,
    CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED
} CUmemhostalloc_option;
#endc

--------------------------------------------------------------------------------
-- Data Types
--------------------------------------------------------------------------------

-- |
-- A reference to memory allocated on the device
--
newtype DevicePtr a = DevicePtr { useDevicePtr :: {# type CUdeviceptr #}}

instance Storable (DevicePtr a) where
  sizeOf _      = sizeOf    (undefined :: {# type CUdeviceptr #})
  alignment _   = alignment (undefined :: {# type CUdeviceptr #})
  peek p        = DevicePtr `fmap` peek (castPtr p)
  poke p v      = poke (castPtr p) (useDevicePtr v)

-- |
-- A reference to memory on the host that is page-locked and directly-accessible
-- from the device. Since the memory can be accessed directly, it can be read or
-- written at a much higher bandwidth than pageable memory from the traditional
-- malloc.
--
-- The driver automatically accelerates calls to functions such as `memcpy'
-- which reference page-locked memory.
--
newtype HostPtr a = HostPtr { useHostPtr :: Ptr a }

-- |
-- Unwrap a host pointer and execute a computation using the base pointer object
--
withHostPtr :: HostPtr a -> (Ptr a -> IO b) -> IO b
withHostPtr p f = f (useHostPtr p)

-- |
-- Options for host allocation
--
{# enum CUmemhostalloc_option as AllocFlag
    { underscoreToCase }
    with prefix="CU_MEMHOSTALLOC_OPTION" deriving (Eq, Show) #}

--------------------------------------------------------------------------------
-- Host Allocation
--------------------------------------------------------------------------------

-- |
-- Allocate a section of linear memory on the host which is page-locked and
-- directly accessible from the device. The storage is sufficient to hold the
-- given number of elements of a storable type.
--
-- Note that since the amount of pageable memory is thusly reduced, overall
-- system performance may suffer. This is best used sparingly to allocate
-- staging areas for data exchange.
--
mallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)
mallocHostArray flags = doMalloc undefined
  where
    doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')
    doMalloc x n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags

{# fun unsafe cuMemHostAlloc
  { alloca'-        `HostPtr a'   peekHP*
  ,                 `Int'
  , combineBitMasks `[AllocFlag]'         } -> `Status' cToEnum #}
  where
    alloca'  = F.alloca
    peekHP p = (HostPtr . castPtr) `fmap` peek p

-- |
-- Free a section of page-locked host memory
--
freeHost :: HostPtr a -> IO ()
freeHost p = nothingIfOk =<< cuMemFreeHost p

{# fun unsafe cuMemFreeHost
  { useHP `HostPtr a' } -> `Status' cToEnum #}
  where
    useHP = castPtr . useHostPtr

--------------------------------------------------------------------------------
-- Device Allocation
--------------------------------------------------------------------------------

-- |
-- Allocate a section of linear memory on the device, and return a reference to
-- it. The memory is sufficient to hold the given number of elements of storable
-- type. It is suitably aligned for any type, and is not cleared.
--
mallocArray :: Storable a => Int -> IO (DevicePtr a)
mallocArray = doMalloc undefined
  where
    doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')
    doMalloc x n = resultIfOk =<< cuMemAlloc (n * sizeOf x)

{# fun unsafe cuMemAlloc
  { alloca'- `DevicePtr a' peekDP*
  ,          `Int'               } -> `Status' cToEnum #}
  where
    alloca' = F.alloca
    peekDP  = liftM DevicePtr . peek

-- |
-- Execute a computation on the device, passing a pointer to a temporarily
-- allocated block of memory sufficient to hold the given number of elements of
-- storable type. The memory is freed when the computation terminates (normally
-- or via an exception), so the pointer must not be used after this.
--
-- Note that kernel launches can be asynchronous, so you may want to add a
-- synchronisation point using 'sync' as part of the computation.
--
allocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b
allocaArray n = bracket (mallocArray n) free

-- |
-- Release a section of device memory
--
free :: DevicePtr a -> IO ()
free dp = nothingIfOk =<< cuMemFree dp

{# fun unsafe cuMemFree
  { useDevicePtr `DevicePtr a' } -> `Status' cToEnum #}

-- |
-- The constant 'nullDevPtr' contains the distinguished memory location that is
-- not associated with a valid memory location
--
nullDevPtr :: DevicePtr a
nullDevPtr =  DevicePtr 0

--------------------------------------------------------------------------------
-- Marshalling
--------------------------------------------------------------------------------

-- |
-- Copy a number of elements from the device to host memory. This is a
-- synchronous operation
--
peekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()
peekArray n dptr hptr = doPeek undefined dptr
  where
    doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()
    doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)

{# fun unsafe cuMemcpyDtoH
  { castPtr      `Ptr a'
  , useDevicePtr `DevicePtr a'
  ,              `Int'         } -> `Status' cToEnum #}

-- |
-- Copy memory from the device asynchronously, possibly associated with a
-- particular stream. The destination host memory must be page-locked.
--
peekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()
peekArrayAsync n dptr hptr mst = doPeek undefined dptr
  where
    doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()
    doPeek x _ =
      nothingIfOk =<< case mst of
        Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (Stream nullPtr)
        Just st -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) st

{# fun unsafe cuMemcpyDtoHAsync
  { useHP        `HostPtr a'
  , useDevicePtr `DevicePtr a'
  ,              `Int'
  , useStream    `Stream'  } -> `Status' cToEnum #}
  where
    useHP = castPtr . useHostPtr

-- |
-- Copy a number of elements from the device into a new Haskell list. Note that
-- this requires two memory copies: firstly from the device into a heap
-- allocated array, and from there marshalled into a list.
--
peekListArray :: Storable a => Int -> DevicePtr a -> IO [a]
peekListArray n dptr =
  F.allocaArray n $ \p -> do
    peekArray   n dptr p
    F.peekArray n p

-- |
-- Copy a number of elements onto the device. This is a synchronous operation
--
pokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()
pokeArray n hptr dptr = doPoke undefined dptr
  where
    doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()
    doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)

{# fun unsafe cuMemcpyHtoD
  { useDevicePtr `DevicePtr a'
  , castPtr      `Ptr a'
  ,              `Int'         } -> `Status' cToEnum #}

-- |
-- Copy memory onto the device asynchronously, possibly associated with a
-- particular stream. The source host memory must be page-locked.
--
pokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()
pokeArrayAsync n hptr dptr mst = dopoke undefined dptr
  where
    dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()
    dopoke x _ =
      nothingIfOk =<< case mst of
        Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (Stream nullPtr)
        Just st -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) st

{# fun unsafe cuMemcpyHtoDAsync
  { useDevicePtr `DevicePtr a'
  , useHP        `HostPtr a'
  ,              `Int'
  , useStream    `Stream'      } -> `Status' cToEnum #}
  where
    useHP = castPtr . useHostPtr

-- |
-- Write a list of storable elements into a device array. The device array must
-- be sufficiently large to hold the entire list. This requires two marshalling
-- operations.
--
pokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()
pokeListArray xs dptr = F.withArrayLen xs $ \len p -> pokeArray len p dptr

-- |
-- Copy the given number of elements from the first device array (source) to the
-- second (destination). The copied areas may not overlap. This operation is
-- asynchronous with respect to the host, but will never overlap with kernel
-- execution.
--
copyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()
copyArrayAsync n = docopy undefined
  where
    docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()
    docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)

{# fun unsafe cuMemcpyDtoD
  { useDevicePtr `DevicePtr a'
  , useDevicePtr `DevicePtr a'
  ,              `Int'         } -> `Status' cToEnum #}

--------------------------------------------------------------------------------
-- Combined Allocation and Marshalling
--------------------------------------------------------------------------------

-- |
-- Write a list of storable elements into a newly allocated device array. Note
-- that this requires two memory copies: firstly from a Haskell list to a heap
-- allocated array, and from there onto the graphics device. The memory should
-- be 'free'd when no longer required.
--
newListArray :: Storable a => [a] -> IO (DevicePtr a)
newListArray xs =
  F.withArrayLen xs                     $ \len p ->
  bracketOnError (mallocArray len) free $ \d_xs  -> do
    pokeArray len p d_xs
    return d_xs

-- |
-- Temporarily store a list of elements into a newly allocated device array. An
-- IO action is applied to to the array, the result of which is returned.
-- Similar to 'newListArray', this requires copying the data twice.
--
-- As with 'allocaArray', the memory is freed once the action completes, so you
-- should not return the pointer from the action, and be wary of asynchronous
-- kernel execution.
--
withListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b
withListArray xs = withListArrayLen xs . const

-- |
-- A variant of 'withListArray' which also supplies the number of elements in
-- the array to the applied function
--
withListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b
withListArrayLen xs f =
  allocaArray   len $ \d_xs -> do
  F.allocaArray len $ \h_xs -> do
    F.pokeArray h_xs xs
    pokeArray len h_xs d_xs
  f len d_xs
  where
    len = length xs

--------------------------------------------------------------------------------
-- Utility
--------------------------------------------------------------------------------

-- |
-- Set a number of data elements to the specified value, which may be either 8-,
-- 16-, or 32-bits wide.
--
memset :: Storable a => DevicePtr a -> Int -> a -> IO ()
memset dptr n val = case sizeOf val of
    1 -> nothingIfOk =<< cuMemsetD8  dptr val n
    2 -> nothingIfOk =<< cuMemsetD16 dptr val n
    4 -> nothingIfOk =<< cuMemsetD32 dptr val n
    _ -> cudaError "can only memset 8-, 16-, and 32-bit values"

--
-- We use unsafe coerce below to reinterpret the bits of the value to memset as,
-- into the integer type required by the setting functions.
--
{# fun unsafe cuMemsetD8
  { useDevicePtr `DevicePtr a'
  , unsafeCoerce `a'
  ,              `Int'         } -> `Status' cToEnum #}

{# fun unsafe cuMemsetD16
  { useDevicePtr `DevicePtr a'
  , unsafeCoerce `a'
  ,              `Int'         } -> `Status' cToEnum #}

{# fun unsafe cuMemsetD32
  { useDevicePtr `DevicePtr a'
  , unsafeCoerce `a'
  ,              `Int'         } -> `Status' cToEnum #}

-- |
-- Return the device pointer associated with a mapped, pinned host buffer, which
-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.
--
-- Currently, no options are supported and this must be empty.
--
getDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)
getDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags

{# fun unsafe cuMemHostGetDevicePointer
  { alloca'-        `DevicePtr a' peekDP*
  , useHP           `HostPtr a'
  , combineBitMasks `[AllocFlag]'         } -> `Status' cToEnum #}
  where
    alloca' = F.alloca
    useHP   = castPtr . useHostPtr
    peekDP  = liftM DevicePtr . peek

{-# LANGUAGE ForeignFunctionInterface #-}
--------------------------------------------------------------------------------
-- |
-- Module    : Foreign.CUDA.Driver.Marshal
-- Copyright : (c) 2009 Trevor L. McDonell
-- License   : BSD
--
-- Memory management for low-level driver interface
--
--------------------------------------------------------------------------------

module Foreign.CUDA.Driver.Marshal
  (
    -- * Host Allocation
    HostPtr(..), AllocFlag(..),
    withHostPtr, mallocHostArray, freeHost,

    -- * Device Allocation
    DevicePtr,
    mallocArray, allocaArray, free,

    -- * Marshalling
    peekArray, peekArrayAsync, peekListArray,
    pokeArray, pokeArrayAsync, pokeListArray,
               copyArrayAsync,

    -- * Combined Allocation and Marshalling
    newListArray, withListArray, withListArrayLen,

    -- * Utility
    memset, getDevicePtr
  )
  where

#include <cuda.h>
{# context lib="cuda" #}

-- Friends
import Foreign.CUDA.Internal.C2HS
import Foreign.CUDA.Driver.Error
import Foreign.CUDA.Driver.Stream               (Stream(..))

-- System
import Unsafe.Coerce
import Control.Monad                            (liftM)
import Control.Exception.Extensible

import Foreign.C
import Foreign.Ptr
import Foreign.Storable
import qualified Foreign.Marshal as F

#c
typedef enum CUmemhostalloc_option_enum {
    CU_MEMHOSTALLOC_OPTION_PORTABLE       = CU_MEMHOSTALLOC_PORTABLE,
    CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED  = CU_MEMHOSTALLOC_DEVICEMAP,
    CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED
} CUmemhostalloc_option;
#endc

--------------------------------------------------------------------------------
-- Data Types
--------------------------------------------------------------------------------

-- |
-- A reference to memory allocated on the device
--
newtype DevicePtr a = DevicePtr { useDevicePtr :: {# type CUdeviceptr #}}

instance Storable (DevicePtr a) where
  sizeOf _      = sizeOf    (undefined :: {# type CUdeviceptr #})
  alignment _   = alignment (undefined :: {# type CUdeviceptr #})
  peek p        = DevicePtr `fmap` peek (castPtr p)
  poke p v      = poke (castPtr p) (useDevicePtr v)

-- |
-- A reference to memory on the host that is page-locked and directly-accessible
-- from the device. Since the memory can be accessed directly, it can be read or
-- written at a much higher bandwidth than pageable memory from the traditional
-- malloc.
--
-- The driver automatically accelerates calls to functions such as `memcpy'
-- which reference page-locked memory.
--
newtype HostPtr a = HostPtr { useHostPtr :: Ptr a }

-- |
-- Unwrap a host pointer and execute a computation using the base pointer object
--
withHostPtr :: HostPtr a -> (Ptr a -> IO b) -> IO b
withHostPtr p f = f (useHostPtr p)

-- |
-- Options for host allocation
--
{# enum CUmemhostalloc_option as AllocFlag
    { underscoreToCase }
    with prefix="CU_MEMHOSTALLOC_OPTION" deriving (Eq, Show) #}

--------------------------------------------------------------------------------
-- Host Allocation
--------------------------------------------------------------------------------

-- |
-- Allocate a section of linear memory on the host which is page-locked and
-- directly accessible from the device. The storage is sufficient to hold the
-- given number of elements of a storable type.
--
-- Note that since the amount of pageable memory is thusly reduced, overall
-- system performance may suffer. This is best used sparingly to allocate
-- staging areas for data exchange.
--
mallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)
mallocHostArray flags = doMalloc undefined
  where
    doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')
    doMalloc x n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags

{# fun unsafe cuMemHostAlloc
  { alloca'-        `HostPtr a'   peekHP*
  ,                 `Int'
  , combineBitMasks `[AllocFlag]'         } -> `Status' cToEnum #}
  where
    alloca'  = F.alloca
    peekHP p = (HostPtr . castPtr) `fmap` peek p

-- |
-- Free a section of page-locked host memory
--
freeHost :: HostPtr a -> IO ()
freeHost p = nothingIfOk =<< cuMemFreeHost p

{# fun unsafe cuMemFreeHost
  { useHP `HostPtr a' } -> `Status' cToEnum #}
  where
    useHP = castPtr . useHostPtr

--------------------------------------------------------------------------------
-- Device Allocation
--------------------------------------------------------------------------------

-- |
-- Allocate a section of linear memory on the device, and return a reference to
-- it. The memory is sufficient to hold the given number of elements of storable
-- type. It is suitably aligned for any type, and is not cleared.
--
mallocArray :: Storable a => Int -> IO (DevicePtr a)
mallocArray = doMalloc undefined
  where
    doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')
    doMalloc x n = resultIfOk =<< cuMemAlloc (n * sizeOf x)

{# fun unsafe cuMemAlloc
  { alloca'- `DevicePtr a' peekDP*
  ,          `Int'               } -> `Status' cToEnum #}
  where
    alloca' = F.alloca
    peekDP  = liftM DevicePtr . peek

-- |
-- Execute a computation on the device, passing a pointer to a temporarily
-- allocated block of memory sufficient to hold the given number of elements of
-- storable type. The memory is freed when the computation terminates (normally
-- or via an exception), so the pointer must not be used after this.
--
-- Note that kernel launches can be asynchronous, so you may want to add a
-- synchronisation point using 'sync' as part of the computation.
--
allocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b
allocaArray n = bracket (mallocArray n) free

-- |
-- Release a section of device memory
--
free :: DevicePtr a -> IO ()
free dp = nothingIfOk =<< cuMemFree dp

{# fun unsafe cuMemFree
  { useDevicePtr `DevicePtr a' } -> `Status' cToEnum #}

--------------------------------------------------------------------------------
-- Marshalling
--------------------------------------------------------------------------------

-- |
-- Copy a number of elements from the device to host memory. This is a
-- synchronous operation
--
peekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()
peekArray n dptr hptr = doPeek undefined dptr
  where
    doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()
    doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)

{# fun unsafe cuMemcpyDtoH
  { castPtr      `Ptr a'
  , useDevicePtr `DevicePtr a'
  ,              `Int'         } -> `Status' cToEnum #}

-- |
-- Copy memory from the device asynchronously, possibly associated with a
-- particular stream. The destination host memory must be page-locked.
--
peekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()
peekArrayAsync n dptr hptr mst = doPeek undefined dptr
  where
    doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()
    doPeek x _ =
      nothingIfOk =<< case mst of
        Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (Stream nullPtr)
        Just st -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) st

{# fun unsafe cuMemcpyDtoHAsync
  { useHP        `HostPtr a'
  , useDevicePtr `DevicePtr a'
  ,              `Int'
  , useStream    `Stream'  } -> `Status' cToEnum #}
  where
    useHP = castPtr . useHostPtr

-- |
-- Copy a number of elements from the device into a new Haskell list. Note that
-- this requires two memory copies: firstly from the device into a heap
-- allocated array, and from there marshalled into a list.
--
peekListArray :: Storable a => Int -> DevicePtr a -> IO [a]
peekListArray n dptr =
  F.allocaArray n $ \p -> do
    peekArray   n dptr p
    F.peekArray n p

-- |
-- Copy a number of elements onto the device. This is a synchronous operation
--
pokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()
pokeArray n hptr dptr = doPoke undefined dptr
  where
    doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()
    doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)

{# fun unsafe cuMemcpyHtoD
  { useDevicePtr `DevicePtr a'
  , castPtr      `Ptr a'
  ,              `Int'         } -> `Status' cToEnum #}

-- |
-- Copy memory onto the device asynchronously, possibly associated with a
-- particular stream. The source host memory must be page-locked.
--
pokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()
pokeArrayAsync n hptr dptr mst = dopoke undefined dptr
  where
    dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()
    dopoke x _ =
      nothingIfOk =<< case mst of
        Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (Stream nullPtr)
        Just st -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) st

{# fun unsafe cuMemcpyHtoDAsync
  { useDevicePtr `DevicePtr a'
  , useHP        `HostPtr a'
  ,              `Int'
  , useStream    `Stream'      } -> `Status' cToEnum #}
  where
    useHP = castPtr . useHostPtr

-- |
-- Write a list of storable elements into a device array. The device array must
-- be sufficiently large to hold the entire list. This requires two marshalling
-- operations.
--
pokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()
pokeListArray xs dptr = F.withArrayLen xs $ \len p -> pokeArray len p dptr

-- |
-- Copy the given number of elements from the first device array (source) to the
-- second (destination). The copied areas may not overlap. This operation is
-- asynchronous with respect to the host, but will never overlap with kernel
-- execution.
--
copyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()
copyArrayAsync n = docopy undefined
  where
    docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()
    docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)

{# fun unsafe cuMemcpyDtoD
  { useDevicePtr `DevicePtr a'
  , useDevicePtr `DevicePtr a'
  ,              `Int'         } -> `Status' cToEnum #}

--------------------------------------------------------------------------------
-- Combined Allocation and Marshalling
--------------------------------------------------------------------------------

-- |
-- Write a list of storable elements into a newly allocated device array. Note
-- that this requires two memory copies: firstly from a Haskell list to a heap
-- allocated array, and from there onto the graphics device. The memory should
-- be 'free'd when no longer required.
--
newListArray :: Storable a => [a] -> IO (DevicePtr a)
newListArray xs =
  F.withArrayLen xs                     $ \len p ->
  bracketOnError (mallocArray len) free $ \d_xs  -> do
    pokeArray len p d_xs
    return d_xs

-- |
-- Temporarily store a list of elements into a newly allocated device array. An
-- IO action is applied to to the array, the result of which is returned.
-- Similar to 'newListArray', this requires copying the data twice.
--
-- As with 'allocaArray', the memory is freed once the action completes, so you
-- should not return the pointer from the action, and be wary of asynchronous
-- kernel execution.
--
withListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b
withListArray xs = withListArrayLen xs . const

-- |
-- A variant of 'withListArray' which also supplies the number of elements in
-- the array to the applied function
--
withListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b
withListArrayLen xs f =
  allocaArray   len $ \d_xs -> do
  F.allocaArray len $ \h_xs -> do
    F.pokeArray h_xs xs
    pokeArray len h_xs d_xs
  f len d_xs
  where
    len = length xs

--------------------------------------------------------------------------------
-- Utility
--------------------------------------------------------------------------------

-- |
-- Set a number of data elements to the specified value, which may be either 8-,
-- 16-, or 32-bits wide.
--
memset :: Storable a => DevicePtr a -> Int -> a -> IO ()
memset dptr n val = case sizeOf val of
    1 -> nothingIfOk =<< cuMemsetD8  dptr val n
    2 -> nothingIfOk =<< cuMemsetD16 dptr val n
    4 -> nothingIfOk =<< cuMemsetD32 dptr val n
    _ -> cudaError "can only memset 8-, 16-, and 32-bit values"

--
-- We use unsafe coerce below to reinterpret the bits of the value to memset as,
-- into the integer type required by the setting functions.
--
{# fun unsafe cuMemsetD8
  { useDevicePtr `DevicePtr a'
  , unsafeCoerce `a'
  ,              `Int'         } -> `Status' cToEnum #}

{# fun unsafe cuMemsetD16
  { useDevicePtr `DevicePtr a'
  , unsafeCoerce `a'
  ,              `Int'         } -> `Status' cToEnum #}

{# fun unsafe cuMemsetD32
  { useDevicePtr `DevicePtr a'
  , unsafeCoerce `a'
  ,              `Int'         } -> `Status' cToEnum #}

-- |
-- Return the device pointer associated with a mapped, pinned host buffer, which
-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.
--
-- Currently, no options are supported and this must be empty.
--
getDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)
getDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags

{# fun unsafe cuMemHostGetDevicePointer
  { alloca'-        `DevicePtr a' peekDP*
  , useHP           `HostPtr a'
  , combineBitMasks `[AllocFlag]'         } -> `Status' cToEnum #}
  where
    alloca' = F.alloca
    useHP   = castPtr . useHostPtr
    peekDP  = liftM DevicePtr . peek