{- |
Copyright  : Will Thompson, Iñaki García Etxebarria and Jonas Platte
License    : LGPL-2.1
Maintainer : Iñaki García Etxebarria (inaki@blueleaf.cc)

GCancellable is a thread-safe operation cancellation stack used
throughout GIO to allow for cancellation of synchronous and
asynchronous operations.
-}

#define ENABLE_OVERLOADING (MIN_VERSION_haskell_gi_overloading(1,0,0) \
       && !defined(__HADDOCK_VERSION__))

module GI.Gio.Objects.Cancellable
    (

-- * Exported types
    Cancellable(..)                         ,
    IsCancellable                           ,
    toCancellable                           ,
    noCancellable                           ,


 -- * Methods
-- ** cancel #method:cancel#

#if ENABLE_OVERLOADING
    CancellableCancelMethodInfo             ,
#endif
    cancellableCancel                       ,


-- ** connect #method:connect#

#if ENABLE_OVERLOADING
    CancellableConnectMethodInfo            ,
#endif
    cancellableConnect                      ,


-- ** disconnect #method:disconnect#

#if ENABLE_OVERLOADING
    CancellableDisconnectMethodInfo         ,
#endif
    cancellableDisconnect                   ,


-- ** getCurrent #method:getCurrent#

    cancellableGetCurrent                   ,


-- ** getFd #method:getFd#

#if ENABLE_OVERLOADING
    CancellableGetFdMethodInfo              ,
#endif
    cancellableGetFd                        ,


-- ** isCancelled #method:isCancelled#

#if ENABLE_OVERLOADING
    CancellableIsCancelledMethodInfo        ,
#endif
    cancellableIsCancelled                  ,


-- ** makePollfd #method:makePollfd#

#if ENABLE_OVERLOADING
    CancellableMakePollfdMethodInfo         ,
#endif
    cancellableMakePollfd                   ,


-- ** new #method:new#

    cancellableNew                          ,


-- ** popCurrent #method:popCurrent#

#if ENABLE_OVERLOADING
    CancellablePopCurrentMethodInfo         ,
#endif
    cancellablePopCurrent                   ,


-- ** pushCurrent #method:pushCurrent#

#if ENABLE_OVERLOADING
    CancellablePushCurrentMethodInfo        ,
#endif
    cancellablePushCurrent                  ,


-- ** releaseFd #method:releaseFd#

#if ENABLE_OVERLOADING
    CancellableReleaseFdMethodInfo          ,
#endif
    cancellableReleaseFd                    ,


-- ** reset #method:reset#

#if ENABLE_OVERLOADING
    CancellableResetMethodInfo              ,
#endif
    cancellableReset                        ,


-- ** setErrorIfCancelled #method:setErrorIfCancelled#

#if ENABLE_OVERLOADING
    CancellableSetErrorIfCancelledMethodInfo,
#endif
    cancellableSetErrorIfCancelled          ,




 -- * Signals
-- ** cancelled #signal:cancelled#

    C_CancellableCancelledCallback          ,
    CancellableCancelledCallback            ,
#if ENABLE_OVERLOADING
    CancellableCancelledSignalInfo          ,
#endif
    afterCancellableCancelled               ,
    genClosure_CancellableCancelled         ,
    mk_CancellableCancelledCallback         ,
    noCancellableCancelledCallback          ,
    onCancellableCancelled                  ,
    wrap_CancellableCancelledCallback       ,




    ) where

import Data.GI.Base.ShortPrelude
import qualified Data.GI.Base.ShortPrelude as SP
import qualified Data.GI.Base.Overloading as O
import qualified Prelude as P

import qualified Data.GI.Base.Attributes as GI.Attributes
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GClosure as B.GClosure
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GVariant as B.GVariant
import qualified Data.GI.Base.GValue as B.GValue
import qualified Data.GI.Base.GParamSpec as B.GParamSpec
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.GI.Base.Properties as B.Properties
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Foreign.Ptr as FP
import qualified GHC.OverloadedLabels as OL

import qualified GI.GLib.Callbacks as GLib.Callbacks
import qualified GI.GLib.Structs.PollFD as GLib.PollFD
import qualified GI.GObject.Callbacks as GObject.Callbacks
import qualified GI.GObject.Objects.Object as GObject.Object

-- | Memory-managed wrapper type.
newtype Cancellable = Cancellable (ManagedPtr Cancellable)
foreign import ccall "g_cancellable_get_type"
    c_g_cancellable_get_type :: IO GType

instance GObject Cancellable where
    gobjectType = c_g_cancellable_get_type


-- | Type class for types which can be safely cast to `Cancellable`, for instance with `toCancellable`.
class (GObject o, O.IsDescendantOf Cancellable o) => IsCancellable o
instance (GObject o, O.IsDescendantOf Cancellable o) => IsCancellable o

instance O.HasParentTypes Cancellable
type instance O.ParentTypes Cancellable = '[GObject.Object.Object]

-- | Cast to `Cancellable`, for types for which this is known to be safe. For general casts, use `Data.GI.Base.ManagedPtr.castTo`.
toCancellable :: (MonadIO m, IsCancellable o) => o -> m Cancellable
toCancellable = liftIO . unsafeCastTo Cancellable

-- | A convenience alias for `Nothing` :: `Maybe` `Cancellable`.
noCancellable :: Maybe Cancellable
noCancellable = Nothing

#if ENABLE_OVERLOADING
type family ResolveCancellableMethod (t :: Symbol) (o :: *) :: * where
    ResolveCancellableMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo
    ResolveCancellableMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo
    ResolveCancellableMethod "cancel" o = CancellableCancelMethodInfo
    ResolveCancellableMethod "connect" o = CancellableConnectMethodInfo
    ResolveCancellableMethod "disconnect" o = CancellableDisconnectMethodInfo
    ResolveCancellableMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo
    ResolveCancellableMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo
    ResolveCancellableMethod "getv" o = GObject.Object.ObjectGetvMethodInfo
    ResolveCancellableMethod "isCancelled" o = CancellableIsCancelledMethodInfo
    ResolveCancellableMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo
    ResolveCancellableMethod "makePollfd" o = CancellableMakePollfdMethodInfo
    ResolveCancellableMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo
    ResolveCancellableMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo
    ResolveCancellableMethod "popCurrent" o = CancellablePopCurrentMethodInfo
    ResolveCancellableMethod "pushCurrent" o = CancellablePushCurrentMethodInfo
    ResolveCancellableMethod "ref" o = GObject.Object.ObjectRefMethodInfo
    ResolveCancellableMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo
    ResolveCancellableMethod "releaseFd" o = CancellableReleaseFdMethodInfo
    ResolveCancellableMethod "reset" o = CancellableResetMethodInfo
    ResolveCancellableMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo
    ResolveCancellableMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo
    ResolveCancellableMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo
    ResolveCancellableMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo
    ResolveCancellableMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo
    ResolveCancellableMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo
    ResolveCancellableMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo
    ResolveCancellableMethod "getFd" o = CancellableGetFdMethodInfo
    ResolveCancellableMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo
    ResolveCancellableMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo
    ResolveCancellableMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo
    ResolveCancellableMethod "setErrorIfCancelled" o = CancellableSetErrorIfCancelledMethodInfo
    ResolveCancellableMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo
    ResolveCancellableMethod l o = O.MethodResolutionFailed l o

instance (info ~ ResolveCancellableMethod t Cancellable, O.MethodInfo info Cancellable p) => OL.IsLabel t (Cancellable -> p) where
#if MIN_VERSION_base(4,10,0)
    fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#else
    fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#endif

#endif

-- signal Cancellable::cancelled
{- |
Emitted when the operation has been cancelled.

Can be used by implementations of cancellable operations. If the
operation is cancelled from another thread, the signal will be
emitted in the thread that cancelled the operation, not the
thread that is running the operation.

Note that disconnecting from this signal (or any signal) in a
multi-threaded program is prone to race conditions. For instance
it is possible that a signal handler may be invoked even after
a call to 'GI.GObject.Functions.signalHandlerDisconnect' for that handler has
already returned.

There is also a problem when cancellation happens right before
connecting to the signal. If this happens the signal will
unexpectedly not be emitted, and checking before connecting to
the signal leaves a race condition where this is still happening.

In order to make it safe and easy to connect handlers there
are two helper functions: 'GI.Gio.Objects.Cancellable.cancellableConnect' and
'GI.Gio.Objects.Cancellable.cancellableDisconnect' which protect against problems
like this.

An example of how to us this:

=== /C code/
>
>    // Make sure we don't do unnecessary work if already cancelled
>    if (g_cancellable_set_error_if_cancelled (cancellable, error))
>      return;
>
>    // Set up all the data needed to be able to handle cancellation
>    // of the operation
>    my_data = my_data_new (...);
>
>    id = 0;
>    if (cancellable)
>      id = g_cancellable_connect (cancellable,
>    			      G_CALLBACK (cancelled_handler)
>    			      data, NULL);
>
>    // cancellable operation here...
>
>    g_cancellable_disconnect (cancellable, id);
>
>    // cancelled_handler is never called after this, it is now safe
>    // to free the data
>    my_data_free (my_data);


Note that the cancelled signal is emitted in the thread that
the user cancelled from, which may be the main thread. So, the
cancellable signal should not do something that can block.
-}
type CancellableCancelledCallback =
    IO ()

-- | A convenience synonym for @`Nothing` :: `Maybe` `CancellableCancelledCallback`@.
noCancellableCancelledCallback :: Maybe CancellableCancelledCallback
noCancellableCancelledCallback = Nothing

-- | Type for the callback on the (unwrapped) C side.
type C_CancellableCancelledCallback =
    Ptr () ->                               -- object
    Ptr () ->                               -- user_data
    IO ()

-- | Generate a function pointer callable from C code, from a `C_CancellableCancelledCallback`.
foreign import ccall "wrapper"
    mk_CancellableCancelledCallback :: C_CancellableCancelledCallback -> IO (FunPtr C_CancellableCancelledCallback)

-- | Wrap the callback into a `GClosure`.
genClosure_CancellableCancelled :: MonadIO m => CancellableCancelledCallback -> m (GClosure C_CancellableCancelledCallback)
genClosure_CancellableCancelled cb = liftIO $ do
    let cb' = wrap_CancellableCancelledCallback cb
    mk_CancellableCancelledCallback cb' >>= B.GClosure.newGClosure


-- | Wrap a `CancellableCancelledCallback` into a `C_CancellableCancelledCallback`.
wrap_CancellableCancelledCallback ::
    CancellableCancelledCallback ->
    C_CancellableCancelledCallback
wrap_CancellableCancelledCallback _cb _ _ = do
    _cb


{- |
Connect a signal handler for the “@cancelled@” signal, to be run before the default handler.
When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to

@
'Data.GI.Base.Signals.on' cancellable #cancelled callback
@
-}
onCancellableCancelled :: (IsCancellable a, MonadIO m) => a -> CancellableCancelledCallback -> m SignalHandlerId
onCancellableCancelled obj cb = liftIO $ do
    let cb' = wrap_CancellableCancelledCallback cb
    cb'' <- mk_CancellableCancelledCallback cb'
    connectSignalFunPtr obj "cancelled" cb'' SignalConnectBefore

{- |
Connect a signal handler for the “@cancelled@” signal, to be run after the default handler.
When <https://github.com/haskell-gi/haskell-gi/wiki/Overloading overloading> is enabled, this is equivalent to

@
'Data.GI.Base.Signals.after' cancellable #cancelled callback
@
-}
afterCancellableCancelled :: (IsCancellable a, MonadIO m) => a -> CancellableCancelledCallback -> m SignalHandlerId
afterCancellableCancelled obj cb = liftIO $ do
    let cb' = wrap_CancellableCancelledCallback cb
    cb'' <- mk_CancellableCancelledCallback cb'
    connectSignalFunPtr obj "cancelled" cb'' SignalConnectAfter


#if ENABLE_OVERLOADING
instance O.HasAttributeList Cancellable
type instance O.AttributeList Cancellable = CancellableAttributeList
type CancellableAttributeList = ('[ ] :: [(Symbol, *)])
#endif

#if ENABLE_OVERLOADING
#endif

#if ENABLE_OVERLOADING
data CancellableCancelledSignalInfo
instance SignalInfo CancellableCancelledSignalInfo where
    type HaskellCallbackType CancellableCancelledSignalInfo = CancellableCancelledCallback
    connectSignal _ obj cb connectMode = do
        let cb' = wrap_CancellableCancelledCallback cb
        cb'' <- mk_CancellableCancelledCallback cb'
        connectSignalFunPtr obj "cancelled" cb'' connectMode

type instance O.SignalList Cancellable = CancellableSignalList
type CancellableSignalList = ('[ '("cancelled", CancellableCancelledSignalInfo), '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)])

#endif

-- method Cancellable::new
-- method type : Constructor
-- Args : []
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "Gio", name = "Cancellable"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_new" g_cancellable_new ::
    IO (Ptr Cancellable)

{- |
Creates a new 'GI.Gio.Objects.Cancellable.Cancellable' object.

Applications that want to start one or more operations
that should be cancellable should create a 'GI.Gio.Objects.Cancellable.Cancellable'
and pass it to the operations.

One 'GI.Gio.Objects.Cancellable.Cancellable' can be used in multiple consecutive
operations or in multiple concurrent operations.
-}
cancellableNew ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m Cancellable
    {- ^ __Returns:__ a 'GI.Gio.Objects.Cancellable.Cancellable'. -}
cancellableNew  = liftIO $ do
    result <- g_cancellable_new
    checkUnexpectedReturnNULL "cancellableNew" result
    result' <- (wrapObject Cancellable) result
    return result'

#if ENABLE_OVERLOADING
#endif

-- method Cancellable::cancel
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable object.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_cancel" g_cancellable_cancel ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO ()

{- |
Will set /@cancellable@/ to cancelled, and will emit the
'GI.Gio.Objects.Cancellable.Cancellable'::@/cancelled/@ signal. (However, see the warning about
race conditions in the documentation for that signal if you are
planning to connect to it.)

This function is thread-safe. In other words, you can safely call
it from a thread other than the one running the operation that was
passed the /@cancellable@/.

If /@cancellable@/ is 'Nothing', this function returns immediately for convenience.

The convention within GIO is that cancelling an asynchronous
operation causes it to complete asynchronously. That is, if you
cancel the operation from the same thread in which it is running,
then the operation\'s 'GI.Gio.Callbacks.AsyncReadyCallback' will not be invoked until
the application returns to the main loop.
-}
cancellableCancel ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' object. -}
    -> m ()
cancellableCancel cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    g_cancellable_cancel cancellable'
    touchManagedPtr cancellable
    return ()

#if ENABLE_OVERLOADING
data CancellableCancelMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellableCancelMethodInfo a signature where
    overloadedMethod _ = cancellableCancel

#endif

-- method Cancellable::connect
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "A #GCancellable.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "callback", argType = TInterface (Name {namespace = "GObject", name = "Callback"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "The #GCallback to connect.", sinceVersion = Nothing}, argScope = ScopeTypeNotified, argClosure = 2, argDestroy = 3, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "data", argType = TBasicType TPtr, direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "Data to pass to @callback.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "data_destroy_func", argType = TInterface (Name {namespace = "GLib", name = "DestroyNotify"}), direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "Free function for @data or %NULL.", sinceVersion = Nothing}, argScope = ScopeTypeAsync, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TBasicType TULong)
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_connect" g_cancellable_connect ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    FunPtr GObject.Callbacks.C_Callback ->  -- callback : TInterface (Name {namespace = "GObject", name = "Callback"})
    Ptr () ->                               -- data : TBasicType TPtr
    FunPtr GLib.Callbacks.C_DestroyNotify -> -- data_destroy_func : TInterface (Name {namespace = "GLib", name = "DestroyNotify"})
    IO CULong

{- |
Convenience function to connect to the 'GI.Gio.Objects.Cancellable.Cancellable'::@/cancelled/@
signal. Also handles the race condition that may happen
if the cancellable is cancelled right before connecting.

/@callback@/ is called at most once, either directly at the
time of the connect if /@cancellable@/ is already cancelled,
or when /@cancellable@/ is cancelled in some thread.

/@dataDestroyFunc@/ will be called when the handler is
disconnected, or immediately if the cancellable is already
cancelled.

See 'GI.Gio.Objects.Cancellable.Cancellable'::@/cancelled/@ for details on how to use this.

Since GLib 2.40, the lock protecting /@cancellable@/ is not held when
/@callback@/ is invoked.  This lifts a restriction in place for
earlier GLib versions which now makes it easier to write cleanup
code that unconditionally invokes e.g. 'GI.Gio.Objects.Cancellable.cancellableCancel'.

/Since: 2.22/
-}
cancellableConnect ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: A 'GI.Gio.Objects.Cancellable.Cancellable'. -}
    -> GObject.Callbacks.Callback
    {- ^ /@callback@/: The 'GI.GObject.Callbacks.Callback' to connect. -}
    -> m CULong
    {- ^ __Returns:__ The id of the signal handler or 0 if /@cancellable@/ has already
         been cancelled. -}
cancellableConnect cancellable callback = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    callback' <- GObject.Callbacks.mk_Callback (GObject.Callbacks.wrap_Callback Nothing callback)
    let data_ = castFunPtrToPtr callback'
    let dataDestroyFunc = safeFreeFunPtrPtr
    result <- g_cancellable_connect cancellable' callback' data_ dataDestroyFunc
    touchManagedPtr cancellable
    return result

#if ENABLE_OVERLOADING
data CancellableConnectMethodInfo
instance (signature ~ (GObject.Callbacks.Callback -> m CULong), MonadIO m, IsCancellable a) => O.MethodInfo CancellableConnectMethodInfo a signature where
    overloadedMethod _ = cancellableConnect

#endif

-- method Cancellable::disconnect
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "A #GCancellable or %NULL.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "handler_id", argType = TBasicType TULong, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "Handler id of the handler to be disconnected, or `0`.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_disconnect" g_cancellable_disconnect ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    CULong ->                               -- handler_id : TBasicType TULong
    IO ()

{- |
Disconnects a handler from a cancellable instance similar to
'GI.GObject.Functions.signalHandlerDisconnect'.  Additionally, in the event that a
signal handler is currently running, this call will block until the
handler has finished.  Calling this function from a
'GI.Gio.Objects.Cancellable.Cancellable'::@/cancelled/@ signal handler will therefore result in a
deadlock.

This avoids a race condition where a thread cancels at the
same time as the cancellable operation is finished and the
signal handler is removed. See 'GI.Gio.Objects.Cancellable.Cancellable'::@/cancelled/@ for
details on how to use this.

If /@cancellable@/ is 'Nothing' or /@handlerId@/ is @0@ this function does
nothing.

/Since: 2.22/
-}
cancellableDisconnect ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: A 'GI.Gio.Objects.Cancellable.Cancellable' or 'Nothing'. -}
    -> CULong
    {- ^ /@handlerId@/: Handler id of the handler to be disconnected, or @0@. -}
    -> m ()
cancellableDisconnect cancellable handlerId = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    g_cancellable_disconnect cancellable' handlerId
    touchManagedPtr cancellable
    return ()

#if ENABLE_OVERLOADING
data CancellableDisconnectMethodInfo
instance (signature ~ (CULong -> m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellableDisconnectMethodInfo a signature where
    overloadedMethod _ = cancellableDisconnect

#endif

-- method Cancellable::get_fd
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TBasicType TInt)
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_get_fd" g_cancellable_get_fd ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO Int32

{- |
Gets the file descriptor for a cancellable job. This can be used to
implement cancellable operations on Unix systems. The returned fd will
turn readable when /@cancellable@/ is cancelled.

You are not supposed to read from the fd yourself, just check for
readable status. Reading to unset the readable status is done
with 'GI.Gio.Objects.Cancellable.cancellableReset'.

After a successful return from this function, you should use
'GI.Gio.Objects.Cancellable.cancellableReleaseFd' to free up resources allocated for
the returned file descriptor.

See also 'GI.Gio.Objects.Cancellable.cancellableMakePollfd'.
-}
cancellableGetFd ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable'. -}
    -> m Int32
    {- ^ __Returns:__ A valid file descriptor. @-1@ if the file descriptor
is not supported, or on errors. -}
cancellableGetFd cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    result <- g_cancellable_get_fd cancellable'
    touchManagedPtr cancellable
    return result

#if ENABLE_OVERLOADING
data CancellableGetFdMethodInfo
instance (signature ~ (m Int32), MonadIO m, IsCancellable a) => O.MethodInfo CancellableGetFdMethodInfo a signature where
    overloadedMethod _ = cancellableGetFd

#endif

-- method Cancellable::is_cancelled
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable or %NULL", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TBasicType TBoolean)
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_is_cancelled" g_cancellable_is_cancelled ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO CInt

{- |
Checks if a cancellable job has been cancelled.
-}
cancellableIsCancelled ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' or 'Nothing' -}
    -> m Bool
    {- ^ __Returns:__ 'True' if /@cancellable@/ is cancelled,
FALSE if called with 'Nothing' or if item is not cancelled. -}
cancellableIsCancelled cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    result <- g_cancellable_is_cancelled cancellable'
    let result' = (/= 0) result
    touchManagedPtr cancellable
    return result'

#if ENABLE_OVERLOADING
data CancellableIsCancelledMethodInfo
instance (signature ~ (m Bool), MonadIO m, IsCancellable a) => O.MethodInfo CancellableIsCancelledMethodInfo a signature where
    overloadedMethod _ = cancellableIsCancelled

#endif

-- method Cancellable::make_pollfd
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable or %NULL", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "pollfd", argType = TInterface (Name {namespace = "GLib", name = "PollFD"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a pointer to a #GPollFD", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TBasicType TBoolean)
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_make_pollfd" g_cancellable_make_pollfd ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    Ptr GLib.PollFD.PollFD ->               -- pollfd : TInterface (Name {namespace = "GLib", name = "PollFD"})
    IO CInt

{- |
Creates a 'GI.GLib.Structs.PollFD.PollFD' corresponding to /@cancellable@/; this can be passed
to 'GI.GLib.Functions.poll' and used to poll for cancellation. This is useful both
for unix systems without a native poll and for portability to
windows.

When this function returns 'True', you should use
'GI.Gio.Objects.Cancellable.cancellableReleaseFd' to free up resources allocated for the
/@pollfd@/. After a 'False' return, do not call 'GI.Gio.Objects.Cancellable.cancellableReleaseFd'.

If this function returns 'False', either no /@cancellable@/ was given or
resource limits prevent this function from allocating the necessary
structures for polling. (On Linux, you will likely have reached
the maximum number of file descriptors.) The suggested way to handle
these cases is to ignore the /@cancellable@/.

You are not supposed to read from the fd yourself, just check for
readable status. Reading to unset the readable status is done
with 'GI.Gio.Objects.Cancellable.cancellableReset'.

/Since: 2.22/
-}
cancellableMakePollfd ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' or 'Nothing' -}
    -> GLib.PollFD.PollFD
    {- ^ /@pollfd@/: a pointer to a 'GI.GLib.Structs.PollFD.PollFD' -}
    -> m Bool
    {- ^ __Returns:__ 'True' if /@pollfd@/ was successfully initialized, 'False' on
         failure to prepare the cancellable. -}
cancellableMakePollfd cancellable pollfd = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    pollfd' <- unsafeManagedPtrGetPtr pollfd
    result <- g_cancellable_make_pollfd cancellable' pollfd'
    let result' = (/= 0) result
    touchManagedPtr cancellable
    touchManagedPtr pollfd
    return result'

#if ENABLE_OVERLOADING
data CancellableMakePollfdMethodInfo
instance (signature ~ (GLib.PollFD.PollFD -> m Bool), MonadIO m, IsCancellable a) => O.MethodInfo CancellableMakePollfdMethodInfo a signature where
    overloadedMethod _ = cancellableMakePollfd

#endif

-- method Cancellable::pop_current
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable object", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_pop_current" g_cancellable_pop_current ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO ()

{- |
Pops /@cancellable@/ off the cancellable stack (verifying that /@cancellable@/
is on the top of the stack).
-}
cancellablePopCurrent ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' object -}
    -> m ()
cancellablePopCurrent cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    g_cancellable_pop_current cancellable'
    touchManagedPtr cancellable
    return ()

#if ENABLE_OVERLOADING
data CancellablePopCurrentMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellablePopCurrentMethodInfo a signature where
    overloadedMethod _ = cancellablePopCurrent

#endif

-- method Cancellable::push_current
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable object", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_push_current" g_cancellable_push_current ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO ()

{- |
Pushes /@cancellable@/ onto the cancellable stack. The current
cancellable can then be received using 'GI.Gio.Objects.Cancellable.cancellableGetCurrent'.

This is useful when implementing cancellable operations in
code that does not allow you to pass down the cancellable object.

This is typically called automatically by e.g. 'GI.Gio.Interfaces.File.File' operations,
so you rarely have to call this yourself.
-}
cancellablePushCurrent ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' object -}
    -> m ()
cancellablePushCurrent cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    g_cancellable_push_current cancellable'
    touchManagedPtr cancellable
    return ()

#if ENABLE_OVERLOADING
data CancellablePushCurrentMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellablePushCurrentMethodInfo a signature where
    overloadedMethod _ = cancellablePushCurrent

#endif

-- method Cancellable::release_fd
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_release_fd" g_cancellable_release_fd ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO ()

{- |
Releases a resources previously allocated by 'GI.Gio.Objects.Cancellable.cancellableGetFd'
or 'GI.Gio.Objects.Cancellable.cancellableMakePollfd'.

For compatibility reasons with older releases, calling this function
is not strictly required, the resources will be automatically freed
when the /@cancellable@/ is finalized. However, the /@cancellable@/ will
block scarce file descriptors until it is finalized if this function
is not called. This can cause the application to run out of file
descriptors when many @/GCancellables/@ are used at the same time.

/Since: 2.22/
-}
cancellableReleaseFd ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' -}
    -> m ()
cancellableReleaseFd cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    g_cancellable_release_fd cancellable'
    touchManagedPtr cancellable
    return ()

#if ENABLE_OVERLOADING
data CancellableReleaseFdMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellableReleaseFdMethodInfo a signature where
    overloadedMethod _ = cancellableReleaseFd

#endif

-- method Cancellable::reset
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable object.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_reset" g_cancellable_reset ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    IO ()

{- |
Resets /@cancellable@/ to its uncancelled state.

If cancellable is currently in use by any cancellable operation
then the behavior of this function is undefined.

Note that it is generally not a good idea to reuse an existing
cancellable for more operations after it has been cancelled once,
as this function might tempt you to do. The recommended practice
is to drop the reference to a cancellable after cancelling it,
and let it die with the outstanding async operations. You should
create a fresh cancellable for further async operations.
-}
cancellableReset ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' object. -}
    -> m ()
cancellableReset cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    g_cancellable_reset cancellable'
    touchManagedPtr cancellable
    return ()

#if ENABLE_OVERLOADING
data CancellableResetMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellableResetMethodInfo a signature where
    overloadedMethod _ = cancellableReset

#endif

-- method Cancellable::set_error_if_cancelled
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "cancellable", argType = TInterface (Name {namespace = "Gio", name = "Cancellable"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GCancellable or %NULL", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TBasicType TBoolean)
-- throws : True
-- Skip return : False

foreign import ccall "g_cancellable_set_error_if_cancelled" g_cancellable_set_error_if_cancelled ::
    Ptr Cancellable ->                      -- cancellable : TInterface (Name {namespace = "Gio", name = "Cancellable"})
    Ptr (Ptr GError) ->                     -- error
    IO CInt

{- |
If the /@cancellable@/ is cancelled, sets the error to notify
that the operation was cancelled.
-}
cancellableSetErrorIfCancelled ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    a
    {- ^ /@cancellable@/: a 'GI.Gio.Objects.Cancellable.Cancellable' or 'Nothing' -}
    -> m ()
    {- ^ /(Can throw 'Data.GI.Base.GError.GError')/ -}
cancellableSetErrorIfCancelled cancellable = liftIO $ do
    cancellable' <- unsafeManagedPtrCastPtr cancellable
    onException (do
        _ <- propagateGError $ g_cancellable_set_error_if_cancelled cancellable'
        touchManagedPtr cancellable
        return ()
     ) (do
        return ()
     )

#if ENABLE_OVERLOADING
data CancellableSetErrorIfCancelledMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.MethodInfo CancellableSetErrorIfCancelledMethodInfo a signature where
    overloadedMethod _ = cancellableSetErrorIfCancelled

#endif

-- method Cancellable::get_current
-- method type : MemberFunction
-- Args : []
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "Gio", name = "Cancellable"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_cancellable_get_current" g_cancellable_get_current ::
    IO (Ptr Cancellable)

{- |
Gets the top cancellable from the stack.
-}
cancellableGetCurrent ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m (Maybe Cancellable)
    {- ^ __Returns:__ a 'GI.Gio.Objects.Cancellable.Cancellable' from the top
of the stack, or 'Nothing' if the stack is empty. -}
cancellableGetCurrent  = liftIO $ do
    result <- g_cancellable_get_current
    maybeResult <- convertIfNonNull result $ \result' -> do
        result'' <- (newObject Cancellable) result'
        return result''
    return maybeResult

#if ENABLE_OVERLOADING
#endif