{-# LANGUAGE ImplicitParams, RankNTypes, TypeApplications #-}


-- | Copyright  : Will Thompson and Iñaki García Etxebarria
-- License    : LGPL-2.1
-- Maintainer : Iñaki García Etxebarria
-- 
-- @GCancellable@ allows operations to be cancelled.
-- 
-- @GCancellable@ is a thread-safe operation cancellation stack used
-- throughout GIO to allow for cancellation of synchronous and
-- asynchronous operations.

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

module GI.Gio.Objects.Cancellable
    ( 

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


 -- * Methods
-- | 
-- 
--  === __Click to display all available methods, including inherited ones__
-- ==== Methods
-- [bindProperty]("GI.GObject.Objects.Object#g:method:bindProperty"), [bindPropertyFull]("GI.GObject.Objects.Object#g:method:bindPropertyFull"), [cancel]("GI.Gio.Objects.Cancellable#g:method:cancel"), [connect]("GI.Gio.Objects.Cancellable#g:method:connect"), [disconnect]("GI.Gio.Objects.Cancellable#g:method:disconnect"), [forceFloating]("GI.GObject.Objects.Object#g:method:forceFloating"), [freezeNotify]("GI.GObject.Objects.Object#g:method:freezeNotify"), [getv]("GI.GObject.Objects.Object#g:method:getv"), [isCancelled]("GI.Gio.Objects.Cancellable#g:method:isCancelled"), [isFloating]("GI.GObject.Objects.Object#g:method:isFloating"), [makePollfd]("GI.Gio.Objects.Cancellable#g:method:makePollfd"), [notify]("GI.GObject.Objects.Object#g:method:notify"), [notifyByPspec]("GI.GObject.Objects.Object#g:method:notifyByPspec"), [popCurrent]("GI.Gio.Objects.Cancellable#g:method:popCurrent"), [pushCurrent]("GI.Gio.Objects.Cancellable#g:method:pushCurrent"), [ref]("GI.GObject.Objects.Object#g:method:ref"), [refSink]("GI.GObject.Objects.Object#g:method:refSink"), [releaseFd]("GI.Gio.Objects.Cancellable#g:method:releaseFd"), [reset]("GI.Gio.Objects.Cancellable#g:method:reset"), [runDispose]("GI.GObject.Objects.Object#g:method:runDispose"), [sourceNew]("GI.Gio.Objects.Cancellable#g:method:sourceNew"), [stealData]("GI.GObject.Objects.Object#g:method:stealData"), [stealQdata]("GI.GObject.Objects.Object#g:method:stealQdata"), [thawNotify]("GI.GObject.Objects.Object#g:method:thawNotify"), [unref]("GI.GObject.Objects.Object#g:method:unref"), [watchClosure]("GI.GObject.Objects.Object#g:method:watchClosure").
-- 
-- ==== Getters
-- [getData]("GI.GObject.Objects.Object#g:method:getData"), [getFd]("GI.Gio.Objects.Cancellable#g:method:getFd"), [getProperty]("GI.GObject.Objects.Object#g:method:getProperty"), [getQdata]("GI.GObject.Objects.Object#g:method:getQdata").
-- 
-- ==== Setters
-- [setData]("GI.GObject.Objects.Object#g:method:setData"), [setDataFull]("GI.GObject.Objects.Object#g:method:setDataFull"), [setErrorIfCancelled]("GI.Gio.Objects.Cancellable#g:method:setErrorIfCancelled"), [setProperty]("GI.GObject.Objects.Object#g:method:setProperty").

#if defined(ENABLE_OVERLOADING)
    ResolveCancellableMethod                ,
#endif

-- ** cancel #method:cancel#

#if defined(ENABLE_OVERLOADING)
    CancellableCancelMethodInfo             ,
#endif
    cancellableCancel                       ,


-- ** connect #method:connect#

#if defined(ENABLE_OVERLOADING)
    CancellableConnectMethodInfo            ,
#endif
    cancellableConnect                      ,


-- ** disconnect #method:disconnect#

#if defined(ENABLE_OVERLOADING)
    CancellableDisconnectMethodInfo         ,
#endif
    cancellableDisconnect                   ,


-- ** getCurrent #method:getCurrent#

    cancellableGetCurrent                   ,


-- ** getFd #method:getFd#

#if defined(ENABLE_OVERLOADING)
    CancellableGetFdMethodInfo              ,
#endif
    cancellableGetFd                        ,


-- ** isCancelled #method:isCancelled#

#if defined(ENABLE_OVERLOADING)
    CancellableIsCancelledMethodInfo        ,
#endif
    cancellableIsCancelled                  ,


-- ** makePollfd #method:makePollfd#

#if defined(ENABLE_OVERLOADING)
    CancellableMakePollfdMethodInfo         ,
#endif
    cancellableMakePollfd                   ,


-- ** new #method:new#

    cancellableNew                          ,


-- ** popCurrent #method:popCurrent#

#if defined(ENABLE_OVERLOADING)
    CancellablePopCurrentMethodInfo         ,
#endif
    cancellablePopCurrent                   ,


-- ** pushCurrent #method:pushCurrent#

#if defined(ENABLE_OVERLOADING)
    CancellablePushCurrentMethodInfo        ,
#endif
    cancellablePushCurrent                  ,


-- ** releaseFd #method:releaseFd#

#if defined(ENABLE_OVERLOADING)
    CancellableReleaseFdMethodInfo          ,
#endif
    cancellableReleaseFd                    ,


-- ** reset #method:reset#

#if defined(ENABLE_OVERLOADING)
    CancellableResetMethodInfo              ,
#endif
    cancellableReset                        ,


-- ** setErrorIfCancelled #method:setErrorIfCancelled#

#if defined(ENABLE_OVERLOADING)
    CancellableSetErrorIfCancelledMethodInfo,
#endif
    cancellableSetErrorIfCancelled          ,


-- ** sourceNew #method:sourceNew#

#if defined(ENABLE_OVERLOADING)
    CancellableSourceNewMethodInfo          ,
#endif
    cancellableSourceNew                    ,




 -- * Signals


-- ** cancelled #signal:cancelled#

    CancellableCancelledCallback            ,
#if defined(ENABLE_OVERLOADING)
    CancellableCancelledSignalInfo          ,
#endif
    afterCancellableCancelled               ,
    onCancellableCancelled                  ,




    ) 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.BasicTypes as B.Types
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GArray as B.GArray
import qualified Data.GI.Base.GClosure as B.GClosure
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GHashTable as B.GHT
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.GI.Base.Signals as B.Signals
import qualified Control.Monad.IO.Class as MIO
import qualified Data.Coerce as Coerce
import qualified Data.Text as T
import qualified Data.Kind as DK
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 GHC.Records as R
import qualified Data.Word as DW
import qualified Data.Int as DI
import qualified System.Posix.Types as SPT
import qualified Foreign.C.Types as FCT

-- Workaround for https://gitlab.haskell.org/ghc/ghc/-/issues/23392
#if MIN_VERSION_base(4,18,0)
import qualified GI.GLib.Callbacks as GLib.Callbacks
import qualified GI.GLib.Structs.PollFD as GLib.PollFD
import qualified GI.GLib.Structs.Source as GLib.Source
import qualified GI.GObject.Callbacks as GObject.Callbacks
import qualified GI.GObject.Objects.Object as GObject.Object

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

#endif

-- | Memory-managed wrapper type.
newtype Cancellable = Cancellable (SP.ManagedPtr Cancellable)
    deriving (Eq)

instance SP.ManagedPtrNewtype Cancellable where
    toManagedPtr (Cancellable p) = p

foreign import ccall "g_cancellable_get_type"
    c_g_cancellable_get_type :: IO B.Types.GType

instance B.Types.TypedObject Cancellable where
    glibType = c_g_cancellable_get_type

instance B.Types.GObject Cancellable

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

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

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

-- | Convert t'Cancellable' to and from t'Data.GI.Base.GValue.GValue'. See 'Data.GI.Base.GValue.toGValue' and 'Data.GI.Base.GValue.fromGValue'.
instance B.GValue.IsGValue (Maybe Cancellable) where
    gvalueGType_ = c_g_cancellable_get_type
    gvalueSet_ gv P.Nothing = B.GValue.set_object gv (FP.nullPtr :: FP.Ptr Cancellable)
    gvalueSet_ gv (P.Just obj) = B.ManagedPtr.withManagedPtr obj (B.GValue.set_object gv)
    gvalueGet_ gv = do
        ptr <- B.GValue.get_object gv :: IO (FP.Ptr Cancellable)
        if ptr /= FP.nullPtr
        then P.Just <$> B.ManagedPtr.newObject Cancellable ptr
        else return P.Nothing
        
    

#if defined(ENABLE_OVERLOADING)
type family ResolveCancellableMethod (t :: Symbol) (o :: DK.Type) :: DK.Type 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 "sourceNew" o = CancellableSourceNewMethodInfo
    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 "setDataFull" o = GObject.Object.ObjectSetDataFullMethodInfo
    ResolveCancellableMethod "setErrorIfCancelled" o = CancellableSetErrorIfCancelledMethodInfo
    ResolveCancellableMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo
    ResolveCancellableMethod l o = O.MethodResolutionFailed l o

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

#if MIN_VERSION_base(4,13,0)
instance (info ~ ResolveCancellableMethod t Cancellable, O.OverloadedMethod info Cancellable p, R.HasField t Cancellable p) => R.HasField t Cancellable p where
    getField = O.overloadedMethod @info

#endif

instance (info ~ ResolveCancellableMethod t Cancellable, O.OverloadedMethodInfo info Cancellable) => OL.IsLabel t (O.MethodProxy info Cancellable) where
#if MIN_VERSION_base(4,10,0)
    fromLabel = O.MethodProxy
#else
    fromLabel _ = O.MethodProxy
#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 ()

type C_CancellableCancelledCallback =
    Ptr Cancellable ->                      -- 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_CancellableCancelledCallback :: 
    GObject a => (a -> CancellableCancelledCallback) ->
    C_CancellableCancelledCallback
wrap_CancellableCancelledCallback gi'cb gi'selfPtr _ = do
    B.ManagedPtr.withNewObject gi'selfPtr $ \gi'self -> gi'cb (Coerce.coerce gi'self) 


-- | Connect a signal handler for the [cancelled](#signal: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 -> ((?self :: a) => CancellableCancelledCallback) -> m SignalHandlerId
onCancellableCancelled obj cb = liftIO $ do
    let wrapped self = let ?self = self in cb
    let wrapped' = wrap_CancellableCancelledCallback wrapped
    wrapped'' <- mk_CancellableCancelledCallback wrapped'
    connectSignalFunPtr obj "cancelled" wrapped'' SignalConnectBefore Nothing

-- | Connect a signal handler for the [cancelled](#signal: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
-- @
-- 
-- 
-- 
-- By default the object invoking the signal is not passed to the callback.
-- If you need to access it, you can use the implit @?self@ parameter.
-- Note that this requires activating the @ImplicitParams@ GHC extension.
-- 
afterCancellableCancelled :: (IsCancellable a, MonadIO m) => a -> ((?self :: a) => CancellableCancelledCallback) -> m SignalHandlerId
afterCancellableCancelled obj cb = liftIO $ do
    let wrapped self = let ?self = self in cb
    let wrapped' = wrap_CancellableCancelledCallback wrapped
    wrapped'' <- mk_CancellableCancelledCallback wrapped'
    connectSignalFunPtr obj "cancelled" wrapped'' SignalConnectAfter Nothing


#if defined(ENABLE_OVERLOADING)
data CancellableCancelledSignalInfo
instance SignalInfo CancellableCancelledSignalInfo where
    type HaskellCallbackType CancellableCancelledSignalInfo = CancellableCancelledCallback
    connectSignal obj cb connectMode detail = do
        let cb' = wrap_CancellableCancelledCallback cb
        cb'' <- mk_CancellableCancelledCallback cb'
        connectSignalFunPtr obj "cancelled" cb'' connectMode detail
    dbgSignalInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable::cancelled"
        , O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#g:signal:cancelled"})

#endif

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

#if defined(ENABLE_OVERLOADING)
#endif

#if defined(ENABLE_OVERLOADING)
type instance O.SignalList Cancellable = CancellableSignalList
type CancellableSignalList = ('[ '("cancelled", CancellableCancelledSignalInfo), '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, DK.Type)])

#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 t'GI.Gio.Objects.Cancellable.Cancellable' object.
-- 
-- Applications that want to start one or more operations
-- that should be cancellable should create a t'GI.Gio.Objects.Cancellable.Cancellable'
-- and pass it to the operations.
-- 
-- One t'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 t'GI.Gio.Objects.Cancellable.Cancellable'.
cancellableNew  = liftIO $ do
    result <- g_cancellable_new
    checkUnexpectedReturnNULL "cancellableNew" result
    result' <- (wrapObject Cancellable) result
    return result'

#if defined(ENABLE_OVERLOADING)
#endif

-- method Cancellable::cancel
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable object."
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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
-- [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal: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 'P.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 t'GI.Gio.Callbacks.AsyncReadyCallback' will not be invoked until
-- the application returns to the main loop.
-- 
-- It is safe (although useless, since it will be a no-op) to call
-- this function from a [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled") signal handler.
cancellableCancel ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' object.
    -> m ()
cancellableCancel cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    g_cancellable_cancel maybeCancellable
    whenJust cancellable touchManagedPtr
    return ()

#if defined(ENABLE_OVERLOADING)
data CancellableCancelMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableCancelMethodInfo a signature where
    overloadedMethod i = cancellableCancel (Just i)

instance O.OverloadedMethodInfo CancellableCancelMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableCancel",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableCancel"
        })


#endif

-- method Cancellable::connect
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "A #GCancellable." , sinceVersion = Nothing }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "callback"
--           , argType =
--               TInterface Name { namespace = "GObject" , name = "Callback" }
--           , argCType = Just "GCallback"
--           , direction = DirectionIn
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "The #GCallback to connect."
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeNotified
--           , argClosure = 2
--           , argDestroy = 3
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "data"
--           , argType = TBasicType TPtr
--           , argCType = Just "gpointer"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "Data to pass to @callback."
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "data_destroy_func"
--           , argType =
--               TInterface Name { namespace = "GLib" , name = "DestroyNotify" }
--           , argCType = Just "GDestroyNotify"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "Free function for @data or %NULL."
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeAsync
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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 FCT.CULong

-- | Convenience function to connect to the [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled")
-- signal. Also handles the race condition that may happen
-- if the cancellable is cancelled right before connecting.
-- 
-- /@callback@/ is called exactly once each time /@cancellable@/ is cancelled,
-- either directly at the time of the connect if /@cancellable@/ is already
-- cancelled, or when /@cancellable@/ is cancelled in some thread.
-- In case the cancellable is reset via 'GI.Gio.Objects.Cancellable.cancellableReset'
-- then the callback can be called again if the /@cancellable@/ is cancelled and
-- if it had not been previously cancelled at the time
-- 'GI.Gio.Objects.Cancellable.cancellableConnect' was called (e.g. if the connection actually
-- took place, returning a non-zero value).
-- 
-- /@dataDestroyFunc@/ will be called when the handler is
-- disconnected, or immediately if the cancellable is already
-- cancelled.
-- 
-- See [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal: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'.
-- Note that since 2.82 GLib still holds a lock during the callback but it’s
-- designed in a way that most of the t'GI.Gio.Objects.Cancellable.Cancellable' methods can be
-- called, including 'GI.Gio.Objects.Cancellable.cancellableCancel' or
-- 'GI.GObject.Objects.Object.objectUnref'.
-- 
-- There are still some methods that will deadlock (by design) when
-- called from the [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled") callbacks:
-- * 'GI.Gio.Objects.Cancellable.cancellableConnect'
-- * 'GI.Gio.Objects.Cancellable.cancellableDisconnect'
-- * 'GI.Gio.Objects.Cancellable.cancellableReset'
-- * 'GI.Gio.Objects.Cancellable.cancellableMakePollfd'
-- * 'GI.Gio.Objects.Cancellable.cancellableReleaseFd'
-- 
-- 
-- /Since: 2.22/
cancellableConnect ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: A t'GI.Gio.Objects.Cancellable.Cancellable'.
    -> GObject.Callbacks.Callback
    -- ^ /@callback@/: The t'GI.GObject.Callbacks.Callback' to connect.
    -> m FCT.CULong
    -- ^ __Returns:__ The id of the signal handler or 0 if /@cancellable@/ has already
    --          been cancelled.
cancellableConnect cancellable callback = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    callback' <- GObject.Callbacks.mk_Callback (GObject.Callbacks.wrap_Callback Nothing callback)
    let data_ = castFunPtrToPtr callback'
    let dataDestroyFunc = SP.safeFreeFunPtrPtr
    result <- g_cancellable_connect maybeCancellable callback' data_ dataDestroyFunc
    whenJust cancellable touchManagedPtr
    return result

#if defined(ENABLE_OVERLOADING)
data CancellableConnectMethodInfo
instance (signature ~ (GObject.Callbacks.Callback -> m FCT.CULong), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableConnectMethodInfo a signature where
    overloadedMethod i = cancellableConnect (Just i)

instance O.OverloadedMethodInfo CancellableConnectMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableConnect",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableConnect"
        })


#endif

-- method Cancellable::disconnect
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "A #GCancellable or %NULL."
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "handler_id"
--           , argType = TBasicType TULong
--           , argCType = Just "gulong"
--           , 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
--           , argCallbackUserData = 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"})
    FCT.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
-- [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal: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 [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled") for
-- details on how to use this.
-- 
-- If /@cancellable@/ is 'P.Nothing' or /@handlerId@/ is @0@ this function does
-- nothing.
-- 
-- /Since: 2.22/
cancellableDisconnect ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: A t'GI.Gio.Objects.Cancellable.Cancellable' or 'P.Nothing'.
    -> FCT.CULong
    -- ^ /@handlerId@/: Handler id of the handler to be disconnected, or @0@.
    -> m ()
cancellableDisconnect cancellable handlerId = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    g_cancellable_disconnect maybeCancellable handlerId
    whenJust cancellable touchManagedPtr
    return ()

#if defined(ENABLE_OVERLOADING)
data CancellableDisconnectMethodInfo
instance (signature ~ (FCT.CULong -> m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableDisconnectMethodInfo a signature where
    overloadedMethod i = cancellableDisconnect (Just i)

instance O.OverloadedMethodInfo CancellableDisconnectMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableDisconnect",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableDisconnect"
        })


#endif

-- method Cancellable::get_fd
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable." , sinceVersion = Nothing }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'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
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    result <- g_cancellable_get_fd maybeCancellable
    whenJust cancellable touchManagedPtr
    return result

#if defined(ENABLE_OVERLOADING)
data CancellableGetFdMethodInfo
instance (signature ~ (m Int32), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableGetFdMethodInfo a signature where
    overloadedMethod i = cancellableGetFd (Just i)

instance O.OverloadedMethodInfo CancellableGetFdMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableGetFd",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableGetFd"
        })


#endif

-- method Cancellable::is_cancelled
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable or %NULL"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' or 'P.Nothing'
    -> m Bool
    -- ^ __Returns:__ 'P.True' if /@cancellable@/ is cancelled,
    -- FALSE if called with 'P.Nothing' or if item is not cancelled.
cancellableIsCancelled cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    result <- g_cancellable_is_cancelled maybeCancellable
    let result' = (/= 0) result
    whenJust cancellable touchManagedPtr
    return result'

#if defined(ENABLE_OVERLOADING)
data CancellableIsCancelledMethodInfo
instance (signature ~ (m Bool), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableIsCancelledMethodInfo a signature where
    overloadedMethod i = cancellableIsCancelled (Just i)

instance O.OverloadedMethodInfo CancellableIsCancelledMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableIsCancelled",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableIsCancelled"
        })


#endif

-- method Cancellable::make_pollfd
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable or %NULL"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = False
--           , transfer = TransferNothing
--           }
--       , Arg
--           { argCName = "pollfd"
--           , argType =
--               TInterface Name { namespace = "GLib" , name = "PollFD" }
--           , argCType = Just "GPollFD*"
--           , direction = DirectionIn
--           , mayBeNull = False
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a pointer to a #GPollFD"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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 t'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 'P.True', you should use
-- 'GI.Gio.Objects.Cancellable.cancellableReleaseFd' to free up resources allocated for the
-- /@pollfd@/. After a 'P.False' return, do not call 'GI.Gio.Objects.Cancellable.cancellableReleaseFd'.
-- 
-- If this function returns 'P.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'.
-- 
-- Note that in the event that a [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled") signal handler is
-- currently running, this call will block until the handler has finished.
-- Calling this function from a signal handler will therefore result in a
-- deadlock.
-- 
-- /Since: 2.22/
cancellableMakePollfd ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' or 'P.Nothing'
    -> GLib.PollFD.PollFD
    -- ^ /@pollfd@/: a pointer to a t'GI.GLib.Structs.PollFD.PollFD'
    -> m Bool
    -- ^ __Returns:__ 'P.True' if /@pollfd@/ was successfully initialized, 'P.False' on
    --          failure to prepare the cancellable.
cancellableMakePollfd cancellable pollfd = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    pollfd' <- unsafeManagedPtrGetPtr pollfd
    result <- g_cancellable_make_pollfd maybeCancellable pollfd'
    let result' = (/= 0) result
    whenJust cancellable touchManagedPtr
    touchManagedPtr pollfd
    return result'

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

instance O.OverloadedMethodInfo CancellableMakePollfdMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableMakePollfd",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableMakePollfd"
        })


#endif

-- method Cancellable::pop_current
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable object"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' object
    -> m ()
cancellablePopCurrent cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    g_cancellable_pop_current maybeCancellable
    whenJust cancellable touchManagedPtr
    return ()

#if defined(ENABLE_OVERLOADING)
data CancellablePopCurrentMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellablePopCurrentMethodInfo a signature where
    overloadedMethod i = cancellablePopCurrent (Just i)

instance O.OverloadedMethodInfo CancellablePopCurrentMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellablePopCurrent",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellablePopCurrent"
        })


#endif

-- method Cancellable::push_current
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable object"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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. t'GI.Gio.Interfaces.File.File' operations,
-- so you rarely have to call this yourself.
cancellablePushCurrent ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' object
    -> m ()
cancellablePushCurrent cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    g_cancellable_push_current maybeCancellable
    whenJust cancellable touchManagedPtr
    return ()

#if defined(ENABLE_OVERLOADING)
data CancellablePushCurrentMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellablePushCurrentMethodInfo a signature where
    overloadedMethod i = cancellablePushCurrent (Just i)

instance O.OverloadedMethodInfo CancellablePushCurrentMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellablePushCurrent",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellablePushCurrent"
        })


#endif

-- method Cancellable::release_fd
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable" , sinceVersion = Nothing }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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.
-- 
-- Note that in the event that a [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled") signal handler is
-- currently running, this call will block until the handler has finished.
-- Calling this function from a signal handler will therefore result in a
-- deadlock.
-- 
-- /Since: 2.22/
cancellableReleaseFd ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable'
    -> m ()
cancellableReleaseFd cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    g_cancellable_release_fd maybeCancellable
    whenJust cancellable touchManagedPtr
    return ()

#if defined(ENABLE_OVERLOADING)
data CancellableReleaseFdMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableReleaseFdMethodInfo a signature where
    overloadedMethod i = cancellableReleaseFd (Just i)

instance O.OverloadedMethodInfo CancellableReleaseFdMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableReleaseFd",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableReleaseFd"
        })


#endif

-- method Cancellable::reset
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable object."
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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.
-- 
-- In the event that a [Cancellable::cancelled]("GI.Gio.Objects.Cancellable#g:signal:cancelled") signal handler is currently
-- running, this call will block until the handler has finished.
-- Calling this function from a signal handler will therefore result in a
-- deadlock.
cancellableReset ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' object.
    -> m ()
cancellableReset cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    g_cancellable_reset maybeCancellable
    whenJust cancellable touchManagedPtr
    return ()

#if defined(ENABLE_OVERLOADING)
data CancellableResetMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableResetMethodInfo a signature where
    overloadedMethod i = cancellableReset (Just i)

instance O.OverloadedMethodInfo CancellableResetMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableReset",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableReset"
        })


#endif

-- method Cancellable::set_error_if_cancelled
-- method type : OrdinaryMethod
-- Args: [ Arg
--           { argCName = "cancellable"
--           , argType =
--               TInterface Name { namespace = "Gio" , name = "Cancellable" }
--           , argCType = Just "GCancellable*"
--           , direction = DirectionIn
--           , mayBeNull = True
--           , argDoc =
--               Documentation
--                 { rawDocText = Just "a #GCancellable or %NULL"
--                 , sinceVersion = Nothing
--                 }
--           , argScope = ScopeTypeInvalid
--           , argClosure = -1
--           , argDestroy = -1
--           , argCallerAllocates = False
--           , argCallbackUserData = 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) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable' or 'P.Nothing'
    -> m ()
    -- ^ /(Can throw 'Data.GI.Base.GError.GError')/
cancellableSetErrorIfCancelled cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    onException (do
        _ <- propagateGError $ g_cancellable_set_error_if_cancelled maybeCancellable
        whenJust cancellable touchManagedPtr
        return ()
     ) (do
        return ()
     )

#if defined(ENABLE_OVERLOADING)
data CancellableSetErrorIfCancelledMethodInfo
instance (signature ~ (m ()), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableSetErrorIfCancelledMethodInfo a signature where
    overloadedMethod i = cancellableSetErrorIfCancelled (Just i)

instance O.OverloadedMethodInfo CancellableSetErrorIfCancelledMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableSetErrorIfCancelled",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableSetErrorIfCancelled"
        })


#endif

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

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

-- | Creates a source that triggers if /@cancellable@/ is cancelled and
-- calls its callback of type t'GI.Gio.Callbacks.CancellableSourceFunc'. This is
-- primarily useful for attaching to another (non-cancellable) source
-- with 'GI.GLib.Structs.Source.sourceAddChildSource' to add cancellability to it.
-- 
-- For convenience, you can call this with a 'P.Nothing' t'GI.Gio.Objects.Cancellable.Cancellable',
-- in which case the source will never trigger.
-- 
-- The new t'GI.GLib.Structs.Source.Source' will hold a reference to the t'GI.Gio.Objects.Cancellable.Cancellable'.
-- 
-- /Since: 2.28/
cancellableSourceNew ::
    (B.CallStack.HasCallStack, MonadIO m, IsCancellable a) =>
    Maybe (a)
    -- ^ /@cancellable@/: a t'GI.Gio.Objects.Cancellable.Cancellable', or 'P.Nothing'
    -> m GLib.Source.Source
    -- ^ __Returns:__ the new t'GI.GLib.Structs.Source.Source'.
cancellableSourceNew cancellable = liftIO $ do
    maybeCancellable <- case cancellable of
        Nothing -> return FP.nullPtr
        Just jCancellable -> do
            jCancellable' <- unsafeManagedPtrCastPtr jCancellable
            return jCancellable'
    result <- g_cancellable_source_new maybeCancellable
    checkUnexpectedReturnNULL "cancellableSourceNew" result
    result' <- (wrapBoxed GLib.Source.Source) result
    whenJust cancellable touchManagedPtr
    return result'

#if defined(ENABLE_OVERLOADING)
data CancellableSourceNewMethodInfo
instance (signature ~ (m GLib.Source.Source), MonadIO m, IsCancellable a) => O.OverloadedMethod CancellableSourceNewMethodInfo a signature where
    overloadedMethod i = cancellableSourceNew (Just i)

instance O.OverloadedMethodInfo CancellableSourceNewMethodInfo a where
    overloadedMethodInfo = P.Just (O.ResolvedSymbolInfo {
        O.resolvedSymbolName = "GI.Gio.Objects.Cancellable.cancellableSourceNew",
        O.resolvedSymbolURL = "https://hackage.haskell.org/package/gi-gio-2.0.38/docs/GI-Gio-Objects-Cancellable.html#v:cancellableSourceNew"
        })


#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 t'GI.Gio.Objects.Cancellable.Cancellable' from the top
    -- of the stack, or 'P.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 defined(ENABLE_OVERLOADING)
#endif


