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

The @GMainContext@ struct is an opaque data
type representing a set of sources to be handled in a main loop.
-}

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

module GI.GLib.Structs.MainContext
    (

-- * Exported types
    MainContext(..)                         ,
    noMainContext                           ,


 -- * Methods
-- ** acquire #method:acquire#

#if ENABLE_OVERLOADING
    MainContextAcquireMethodInfo            ,
#endif
    mainContextAcquire                      ,


-- ** addPoll #method:addPoll#

#if ENABLE_OVERLOADING
    MainContextAddPollMethodInfo            ,
#endif
    mainContextAddPoll                      ,


-- ** check #method:check#

#if ENABLE_OVERLOADING
    MainContextCheckMethodInfo              ,
#endif
    mainContextCheck                        ,


-- ** default #method:default#

    mainContextDefault                      ,


-- ** dispatch #method:dispatch#

#if ENABLE_OVERLOADING
    MainContextDispatchMethodInfo           ,
#endif
    mainContextDispatch                     ,


-- ** findSourceByFuncsUserData #method:findSourceByFuncsUserData#

#if ENABLE_OVERLOADING
    MainContextFindSourceByFuncsUserDataMethodInfo,
#endif
    mainContextFindSourceByFuncsUserData    ,


-- ** findSourceById #method:findSourceById#

#if ENABLE_OVERLOADING
    MainContextFindSourceByIdMethodInfo     ,
#endif
    mainContextFindSourceById               ,


-- ** findSourceByUserData #method:findSourceByUserData#

#if ENABLE_OVERLOADING
    MainContextFindSourceByUserDataMethodInfo,
#endif
    mainContextFindSourceByUserData         ,


-- ** getThreadDefault #method:getThreadDefault#

    mainContextGetThreadDefault             ,


-- ** invokeFull #method:invokeFull#

#if ENABLE_OVERLOADING
    MainContextInvokeFullMethodInfo         ,
#endif
    mainContextInvokeFull                   ,


-- ** isOwner #method:isOwner#

#if ENABLE_OVERLOADING
    MainContextIsOwnerMethodInfo            ,
#endif
    mainContextIsOwner                      ,


-- ** iteration #method:iteration#

#if ENABLE_OVERLOADING
    MainContextIterationMethodInfo          ,
#endif
    mainContextIteration                    ,


-- ** new #method:new#

    mainContextNew                          ,


-- ** pending #method:pending#

#if ENABLE_OVERLOADING
    MainContextPendingMethodInfo            ,
#endif
    mainContextPending                      ,


-- ** popThreadDefault #method:popThreadDefault#

#if ENABLE_OVERLOADING
    MainContextPopThreadDefaultMethodInfo   ,
#endif
    mainContextPopThreadDefault             ,


-- ** prepare #method:prepare#

#if ENABLE_OVERLOADING
    MainContextPrepareMethodInfo            ,
#endif
    mainContextPrepare                      ,


-- ** pushThreadDefault #method:pushThreadDefault#

#if ENABLE_OVERLOADING
    MainContextPushThreadDefaultMethodInfo  ,
#endif
    mainContextPushThreadDefault            ,


-- ** query #method:query#

#if ENABLE_OVERLOADING
    MainContextQueryMethodInfo              ,
#endif
    mainContextQuery                        ,


-- ** ref #method:ref#

#if ENABLE_OVERLOADING
    MainContextRefMethodInfo                ,
#endif
    mainContextRef                          ,


-- ** refThreadDefault #method:refThreadDefault#

    mainContextRefThreadDefault             ,


-- ** release #method:release#

#if ENABLE_OVERLOADING
    MainContextReleaseMethodInfo            ,
#endif
    mainContextRelease                      ,


-- ** removePoll #method:removePoll#

#if ENABLE_OVERLOADING
    MainContextRemovePollMethodInfo         ,
#endif
    mainContextRemovePoll                   ,


-- ** unref #method:unref#

#if ENABLE_OVERLOADING
    MainContextUnrefMethodInfo              ,
#endif
    mainContextUnref                        ,


-- ** wait #method:wait#

#if ENABLE_OVERLOADING
    MainContextWaitMethodInfo               ,
#endif
    mainContextWait                         ,


-- ** wakeup #method:wakeup#

#if ENABLE_OVERLOADING
    MainContextWakeupMethodInfo             ,
#endif
    mainContextWakeup                       ,




    ) 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 {-# SOURCE #-} qualified GI.GLib.Structs.Cond as GLib.Cond
import {-# SOURCE #-} qualified GI.GLib.Structs.PollFD as GLib.PollFD
import {-# SOURCE #-} qualified GI.GLib.Structs.Source as GLib.Source
import {-# SOURCE #-} qualified GI.GLib.Structs.SourceFuncs as GLib.SourceFuncs
import {-# SOURCE #-} qualified GI.GLib.Unions.Mutex as GLib.Mutex

-- | Memory-managed wrapper type.
newtype MainContext = MainContext (ManagedPtr MainContext)
foreign import ccall "g_main_context_get_type" c_g_main_context_get_type ::
    IO GType

instance BoxedObject MainContext where
    boxedType _ = c_g_main_context_get_type

-- | A convenience alias for `Nothing` :: `Maybe` `MainContext`.
noMainContext :: Maybe MainContext
noMainContext = Nothing


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

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

foreign import ccall "g_main_context_new" g_main_context_new ::
    IO (Ptr MainContext)

{- |
Creates a new 'GI.GLib.Structs.MainContext.MainContext' structure.
-}
mainContextNew ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m MainContext
    {- ^ __Returns:__ the new 'GI.GLib.Structs.MainContext.MainContext' -}
mainContextNew  = liftIO $ do
    result <- g_main_context_new
    checkUnexpectedReturnNULL "mainContextNew" result
    result' <- (wrapBoxed MainContext) result
    return result'

#if ENABLE_OVERLOADING
#endif

-- method MainContext::acquire
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", 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_main_context_acquire" g_main_context_acquire ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO CInt

{- |
Tries to become the owner of the specified context.
If some other thread is the owner of the context,
returns 'False' immediately. Ownership is properly
recursive: the owner can require ownership again
and will release ownership when 'GI.GLib.Structs.MainContext.mainContextRelease'
is called as many times as 'GI.GLib.Structs.MainContext.mainContextAcquire'.

You must be the owner of a context before you
can call 'GI.GLib.Structs.MainContext.mainContextPrepare', 'GI.GLib.Structs.MainContext.mainContextQuery',
'GI.GLib.Structs.MainContext.mainContextCheck', 'GI.GLib.Structs.MainContext.mainContextDispatch'.
-}
mainContextAcquire ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m Bool
    {- ^ __Returns:__ 'True' if the operation succeeded, and
  this thread is now the owner of /@context@/. -}
mainContextAcquire context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_acquire context'
    let result' = (/= 0) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextAcquireMethodInfo
instance (signature ~ (m Bool), MonadIO m) => O.MethodInfo MainContextAcquireMethodInfo MainContext signature where
    overloadedMethod _ = mainContextAcquire

#endif

-- method MainContext::add_poll
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext (or %NULL for the default context)", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "fd", argType = TInterface (Name {namespace = "GLib", name = "PollFD"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GPollFD structure holding information about a file\n     descriptor to watch.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "priority", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the priority for this file descriptor which should be\n     the same as the priority used for g_source_attach() to ensure that the\n     file descriptor is polled whenever the results may be needed.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_add_poll" g_main_context_add_poll ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Ptr GLib.PollFD.PollFD ->               -- fd : TInterface (Name {namespace = "GLib", name = "PollFD"})
    Int32 ->                                -- priority : TBasicType TInt
    IO ()

{- |
Adds a file descriptor to the set of file descriptors polled for
this context. This will very seldom be used directly. Instead
a typical event source will use 'GI.GLib.Structs.Source.sourceAddUnixFd' instead.
-}
mainContextAddPoll ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' (or 'Nothing' for the default context) -}
    -> GLib.PollFD.PollFD
    {- ^ /@fd@/: a 'GI.GLib.Structs.PollFD.PollFD' structure holding information about a file
     descriptor to watch. -}
    -> Int32
    {- ^ /@priority@/: the priority for this file descriptor which should be
     the same as the priority used for 'GI.GLib.Structs.Source.sourceAttach' to ensure that the
     file descriptor is polled whenever the results may be needed. -}
    -> m ()
mainContextAddPoll context fd priority = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    fd' <- unsafeManagedPtrGetPtr fd
    g_main_context_add_poll context' fd' priority
    touchManagedPtr context
    touchManagedPtr fd
    return ()

#if ENABLE_OVERLOADING
data MainContextAddPollMethodInfo
instance (signature ~ (GLib.PollFD.PollFD -> Int32 -> m ()), MonadIO m) => O.MethodInfo MainContextAddPollMethodInfo MainContext signature where
    overloadedMethod _ = mainContextAddPoll

#endif

-- method MainContext::check
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "max_priority", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the maximum numerical priority of sources to check", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "fds", argType = TCArray False (-1) 3 (TInterface (Name {namespace = "GLib", name = "PollFD"})), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "array of #GPollFD's that was passed to\n      the last call to g_main_context_query()", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "n_fds", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "return value of g_main_context_query()", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : [Arg {argCName = "n_fds", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "return value of g_main_context_query()", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- returnType : Just (TBasicType TBoolean)
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_check" g_main_context_check ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Int32 ->                                -- max_priority : TBasicType TInt
    Ptr GLib.PollFD.PollFD ->               -- fds : TCArray False (-1) 3 (TInterface (Name {namespace = "GLib", name = "PollFD"}))
    Int32 ->                                -- n_fds : TBasicType TInt
    IO CInt

{- |
Passes the results of polling back to the main loop.

You must have successfully acquired the context with
'GI.GLib.Structs.MainContext.mainContextAcquire' before you may call this function.
-}
mainContextCheck ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> Int32
    {- ^ /@maxPriority@/: the maximum numerical priority of sources to check -}
    -> [GLib.PollFD.PollFD]
    {- ^ /@fds@/: array of 'GI.GLib.Structs.PollFD.PollFD'\'s that was passed to
      the last call to 'GI.GLib.Structs.MainContext.mainContextQuery' -}
    -> m Bool
    {- ^ __Returns:__ 'True' if some sources are ready to be dispatched. -}
mainContextCheck context maxPriority fds = liftIO $ do
    let nFds = fromIntegral $ length fds
    context' <- unsafeManagedPtrGetPtr context
    fds' <- mapM unsafeManagedPtrGetPtr fds
    fds'' <- packBlockArray 8 fds'
    result <- g_main_context_check context' maxPriority fds'' nFds
    let result' = (/= 0) result
    touchManagedPtr context
    mapM_ touchManagedPtr fds
    freeMem fds''
    return result'

#if ENABLE_OVERLOADING
data MainContextCheckMethodInfo
instance (signature ~ (Int32 -> [GLib.PollFD.PollFD] -> m Bool), MonadIO m) => O.MethodInfo MainContextCheckMethodInfo MainContext signature where
    overloadedMethod _ = mainContextCheck

#endif

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

foreign import ccall "g_main_context_dispatch" g_main_context_dispatch ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO ()

{- |
Dispatches all pending sources.

You must have successfully acquired the context with
'GI.GLib.Structs.MainContext.mainContextAcquire' before you may call this function.
-}
mainContextDispatch ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m ()
mainContextDispatch context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    g_main_context_dispatch context'
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextDispatchMethodInfo
instance (signature ~ (m ()), MonadIO m) => O.MethodInfo MainContextDispatchMethodInfo MainContext signature where
    overloadedMethod _ = mainContextDispatch

#endif

-- method MainContext::find_source_by_funcs_user_data
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext (if %NULL, the default context will be used).", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "funcs", argType = TInterface (Name {namespace = "GLib", name = "SourceFuncs"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the @source_funcs passed to g_source_new().", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "user_data", argType = TBasicType TPtr, direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "the user data from the callback.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "GLib", name = "Source"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_find_source_by_funcs_user_data" g_main_context_find_source_by_funcs_user_data ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Ptr GLib.SourceFuncs.SourceFuncs ->     -- funcs : TInterface (Name {namespace = "GLib", name = "SourceFuncs"})
    Ptr () ->                               -- user_data : TBasicType TPtr
    IO (Ptr GLib.Source.Source)

{- |
Finds a source with the given source functions and user data.  If
multiple sources exist with the same source function and user data,
the first one found will be returned.
-}
mainContextFindSourceByFuncsUserData ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' (if 'Nothing', the default context will be used). -}
    -> GLib.SourceFuncs.SourceFuncs
    {- ^ /@funcs@/: the /@sourceFuncs@/ passed to 'GI.GLib.Structs.Source.sourceNew'. -}
    -> Ptr ()
    {- ^ /@userData@/: the user data from the callback. -}
    -> m GLib.Source.Source
    {- ^ __Returns:__ the source, if one was found, otherwise 'Nothing' -}
mainContextFindSourceByFuncsUserData context funcs userData = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    funcs' <- unsafeManagedPtrGetPtr funcs
    result <- g_main_context_find_source_by_funcs_user_data context' funcs' userData
    checkUnexpectedReturnNULL "mainContextFindSourceByFuncsUserData" result
    result' <- (newBoxed GLib.Source.Source) result
    touchManagedPtr context
    touchManagedPtr funcs
    return result'

#if ENABLE_OVERLOADING
data MainContextFindSourceByFuncsUserDataMethodInfo
instance (signature ~ (GLib.SourceFuncs.SourceFuncs -> Ptr () -> m GLib.Source.Source), MonadIO m) => O.MethodInfo MainContextFindSourceByFuncsUserDataMethodInfo MainContext signature where
    overloadedMethod _ = mainContextFindSourceByFuncsUserData

#endif

-- method MainContext::find_source_by_id
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext (if %NULL, the default context will be used)", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "source_id", argType = TBasicType TUInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the source ID, as returned by g_source_get_id().", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "GLib", name = "Source"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_find_source_by_id" g_main_context_find_source_by_id ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Word32 ->                               -- source_id : TBasicType TUInt
    IO (Ptr GLib.Source.Source)

{- |
Finds a 'GI.GLib.Structs.Source.Source' given a pair of context and ID.

It is a programmer error to attempt to lookup a non-existent source.

More specifically: source IDs can be reissued after a source has been
destroyed and therefore it is never valid to use this function with a
source ID which may have already been removed.  An example is when
scheduling an idle to run in another thread with @/g_idle_add()/@: the
idle may already have run and been removed by the time this function
is called on its (now invalid) source ID.  This source ID may have
been reissued, leading to the operation being performed against the
wrong source.
-}
mainContextFindSourceById ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' (if 'Nothing', the default context will be used) -}
    -> Word32
    {- ^ /@sourceId@/: the source ID, as returned by 'GI.GLib.Structs.Source.sourceGetId'. -}
    -> m GLib.Source.Source
    {- ^ __Returns:__ the 'GI.GLib.Structs.Source.Source' -}
mainContextFindSourceById context sourceId = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_find_source_by_id context' sourceId
    checkUnexpectedReturnNULL "mainContextFindSourceById" result
    result' <- (newBoxed GLib.Source.Source) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextFindSourceByIdMethodInfo
instance (signature ~ (Word32 -> m GLib.Source.Source), MonadIO m) => O.MethodInfo MainContextFindSourceByIdMethodInfo MainContext signature where
    overloadedMethod _ = mainContextFindSourceById

#endif

-- method MainContext::find_source_by_user_data
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "user_data", argType = TBasicType TPtr, direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "the user_data for the callback.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Just (TInterface (Name {namespace = "GLib", name = "Source"}))
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_find_source_by_user_data" g_main_context_find_source_by_user_data ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Ptr () ->                               -- user_data : TBasicType TPtr
    IO (Ptr GLib.Source.Source)

{- |
Finds a source with the given user data for the callback.  If
multiple sources exist with the same user data, the first
one found will be returned.
-}
mainContextFindSourceByUserData ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> Ptr ()
    {- ^ /@userData@/: the user_data for the callback. -}
    -> m GLib.Source.Source
    {- ^ __Returns:__ the source, if one was found, otherwise 'Nothing' -}
mainContextFindSourceByUserData context userData = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_find_source_by_user_data context' userData
    checkUnexpectedReturnNULL "mainContextFindSourceByUserData" result
    result' <- (newBoxed GLib.Source.Source) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextFindSourceByUserDataMethodInfo
instance (signature ~ (Ptr () -> m GLib.Source.Source), MonadIO m) => O.MethodInfo MainContextFindSourceByUserDataMethodInfo MainContext signature where
    overloadedMethod _ = mainContextFindSourceByUserData

#endif

-- method MainContext::invoke_full
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext, or %NULL", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "priority", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "the priority at which to run @function", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "function", argType = TInterface (Name {namespace = "GLib", name = "SourceFunc"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "function to call", sinceVersion = Nothing}, argScope = ScopeTypeNotified, argClosure = 3, argDestroy = 4, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "data", argType = TBasicType TPtr, direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "data to pass to @function", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "notify", argType = TInterface (Name {namespace = "GLib", name = "DestroyNotify"}), direction = DirectionIn, mayBeNull = True, argDoc = Documentation {rawDocText = Just "a function to call when @data is no longer in use, or %NULL.", sinceVersion = Nothing}, argScope = ScopeTypeAsync, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_invoke_full" g_main_context_invoke_full ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Int32 ->                                -- priority : TBasicType TInt
    FunPtr GLib.Callbacks.C_SourceFunc ->   -- function : TInterface (Name {namespace = "GLib", name = "SourceFunc"})
    Ptr () ->                               -- data : TBasicType TPtr
    FunPtr GLib.Callbacks.C_DestroyNotify -> -- notify : TInterface (Name {namespace = "GLib", name = "DestroyNotify"})
    IO ()

{- |
Invokes a function in such a way that /@context@/ is owned during the
invocation of /@function@/.

This function is the same as @/g_main_context_invoke()/@ except that it
lets you specify the priority in case /@function@/ ends up being
scheduled as an idle and also lets you give a 'GI.GLib.Callbacks.DestroyNotify' for /@data@/.

/@notify@/ should not assume that it is called from any particular
thread or with any particular context acquired.

/Since: 2.28/
-}
mainContextInvokeFull ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext', or 'Nothing' -}
    -> Int32
    {- ^ /@priority@/: the priority at which to run /@function@/ -}
    -> GLib.Callbacks.SourceFunc
    {- ^ /@function@/: function to call -}
    -> m ()
mainContextInvokeFull context priority function = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    function' <- GLib.Callbacks.mk_SourceFunc (GLib.Callbacks.wrap_SourceFunc Nothing (GLib.Callbacks.drop_closures_SourceFunc function))
    let data_ = castFunPtrToPtr function'
    let notify = safeFreeFunPtrPtr
    g_main_context_invoke_full context' priority function' data_ notify
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextInvokeFullMethodInfo
instance (signature ~ (Int32 -> GLib.Callbacks.SourceFunc -> m ()), MonadIO m) => O.MethodInfo MainContextInvokeFullMethodInfo MainContext signature where
    overloadedMethod _ = mainContextInvokeFull

#endif

-- method MainContext::is_owner
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", 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_main_context_is_owner" g_main_context_is_owner ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO CInt

{- |
Determines whether this thread holds the (recursive)
ownership of this 'GI.GLib.Structs.MainContext.MainContext'. This is useful to
know before waiting on another thread that may be
blocking to get ownership of /@context@/.

/Since: 2.10/
-}
mainContextIsOwner ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m Bool
    {- ^ __Returns:__ 'True' if current thread is owner of /@context@/. -}
mainContextIsOwner context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_is_owner context'
    let result' = (/= 0) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextIsOwnerMethodInfo
instance (signature ~ (m Bool), MonadIO m) => O.MethodInfo MainContextIsOwnerMethodInfo MainContext signature where
    overloadedMethod _ = mainContextIsOwner

#endif

-- method MainContext::iteration
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext (if %NULL, the default context will be used)", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "may_block", argType = TBasicType TBoolean, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "whether the call may block.", 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_main_context_iteration" g_main_context_iteration ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    CInt ->                                 -- may_block : TBasicType TBoolean
    IO CInt

{- |
Runs a single iteration for the given main loop. This involves
checking to see if any event sources are ready to be processed,
then if no events sources are ready and /@mayBlock@/ is 'True', waiting
for a source to become ready, then dispatching the highest priority
events sources that are ready. Otherwise, if /@mayBlock@/ is 'False'
sources are not waited to become ready, only those highest priority
events sources will be dispatched (if any), that are ready at this
given moment without further waiting.

Note that even when /@mayBlock@/ is 'True', it is still possible for
'GI.GLib.Structs.MainContext.mainContextIteration' to return 'False', since the wait may
be interrupted for other reasons than an event source becoming ready.
-}
mainContextIteration ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' (if 'Nothing', the default context will be used) -}
    -> Bool
    {- ^ /@mayBlock@/: whether the call may block. -}
    -> m Bool
    {- ^ __Returns:__ 'True' if events were dispatched. -}
mainContextIteration context mayBlock = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    let mayBlock' = (fromIntegral . fromEnum) mayBlock
    result <- g_main_context_iteration context' mayBlock'
    let result' = (/= 0) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextIterationMethodInfo
instance (signature ~ (Bool -> m Bool), MonadIO m) => O.MethodInfo MainContextIterationMethodInfo MainContext signature where
    overloadedMethod _ = mainContextIteration

#endif

-- method MainContext::pending
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext (if %NULL, the default context will be used)", 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_main_context_pending" g_main_context_pending ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO CInt

{- |
Checks if any sources have pending events for the given context.
-}
mainContextPending ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' (if 'Nothing', the default context will be used) -}
    -> m Bool
    {- ^ __Returns:__ 'True' if events are pending. -}
mainContextPending context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_pending context'
    let result' = (/= 0) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextPendingMethodInfo
instance (signature ~ (m Bool), MonadIO m) => O.MethodInfo MainContextPendingMethodInfo MainContext signature where
    overloadedMethod _ = mainContextPending

#endif

-- method MainContext::pop_thread_default
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext object, or %NULL", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_pop_thread_default" g_main_context_pop_thread_default ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO ()

{- |
Pops /@context@/ off the thread-default context stack (verifying that
it was on the top of the stack).

/Since: 2.22/
-}
mainContextPopThreadDefault ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' object, or 'Nothing' -}
    -> m ()
mainContextPopThreadDefault context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    g_main_context_pop_thread_default context'
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextPopThreadDefaultMethodInfo
instance (signature ~ (m ()), MonadIO m) => O.MethodInfo MainContextPopThreadDefaultMethodInfo MainContext signature where
    overloadedMethod _ = mainContextPopThreadDefault

#endif

-- method MainContext::prepare
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "priority", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "location to store priority of highest priority\n           source already ready.", 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_main_context_prepare" g_main_context_prepare ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Int32 ->                                -- priority : TBasicType TInt
    IO CInt

{- |
Prepares to poll sources within a main loop. The resulting information
for polling is determined by calling g_main_context_query ().

You must have successfully acquired the context with
'GI.GLib.Structs.MainContext.mainContextAcquire' before you may call this function.
-}
mainContextPrepare ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> Int32
    {- ^ /@priority@/: location to store priority of highest priority
           source already ready. -}
    -> m Bool
    {- ^ __Returns:__ 'True' if some source is ready to be dispatched
              prior to polling. -}
mainContextPrepare context priority = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_prepare context' priority
    let result' = (/= 0) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextPrepareMethodInfo
instance (signature ~ (Int32 -> m Bool), MonadIO m) => O.MethodInfo MainContextPrepareMethodInfo MainContext signature where
    overloadedMethod _ = mainContextPrepare

#endif

-- method MainContext::push_thread_default
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext, or %NULL for the global default context", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_push_thread_default" g_main_context_push_thread_default ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO ()

{- |
Acquires /@context@/ and sets it as the thread-default context for the
current thread. This will cause certain asynchronous operations
(such as most [gio][gio]-based I\/O) which are
started in this thread to run under /@context@/ and deliver their
results to its main loop, rather than running under the global
default context in the main thread. Note that calling this function
changes the context returned by 'GI.GLib.Functions.mainContextGetThreadDefault',
not the one returned by 'GI.GLib.Functions.mainContextDefault', so it does not affect
the context used by functions like @/g_idle_add()/@.

Normally you would call this function shortly after creating a new
thread, passing it a 'GI.GLib.Structs.MainContext.MainContext' which will be run by a
'GI.GLib.Structs.MainLoop.MainLoop' in that thread, to set a new default context for all
async operations in that thread. In this case you may not need to
ever call 'GI.GLib.Structs.MainContext.mainContextPopThreadDefault', assuming you want the
new 'GI.GLib.Structs.MainContext.MainContext' to be the default for the whole lifecycle of the
thread.

If you don\'t have control over how the new thread was created (e.g.
in the new thread isn\'t newly created, or if the thread life
cycle is managed by a 'GI.GLib.Structs.ThreadPool.ThreadPool'), it is always suggested to wrap
the logic that needs to use the new 'GI.GLib.Structs.MainContext.MainContext' inside a
'GI.GLib.Structs.MainContext.mainContextPushThreadDefault' \/ 'GI.GLib.Structs.MainContext.mainContextPopThreadDefault'
pair, otherwise threads that are re-used will end up never explicitly
releasing the 'GI.GLib.Structs.MainContext.MainContext' reference they hold.

In some cases you may want to schedule a single operation in a
non-default context, or temporarily use a non-default context in
the main thread. In that case, you can wrap the call to the
asynchronous operation inside a
'GI.GLib.Structs.MainContext.mainContextPushThreadDefault' \/
'GI.GLib.Structs.MainContext.mainContextPopThreadDefault' pair, but it is up to you to
ensure that no other asynchronous operations accidentally get
started while the non-default context is active.

Beware that libraries that predate this function may not correctly
handle being used from a thread with a thread-default context. Eg,
see @/g_file_supports_thread_contexts()/@.

/Since: 2.22/
-}
mainContextPushThreadDefault ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext', or 'Nothing' for the global default context -}
    -> m ()
mainContextPushThreadDefault context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    g_main_context_push_thread_default context'
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextPushThreadDefaultMethodInfo
instance (signature ~ (m ()), MonadIO m) => O.MethodInfo MainContextPushThreadDefaultMethodInfo MainContext signature where
    overloadedMethod _ = mainContextPushThreadDefault

#endif

-- method MainContext::query
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "max_priority", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "maximum priority source to check", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "timeout_", argType = TBasicType TInt, direction = DirectionOut, mayBeNull = False, argDoc = Documentation {rawDocText = Just "location to store timeout to be used in polling", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferEverything},Arg {argCName = "fds", argType = TCArray False (-1) 4 (TInterface (Name {namespace = "GLib", name = "PollFD"})), direction = DirectionOut, mayBeNull = False, argDoc = Documentation {rawDocText = Just "location to\n      store #GPollFD records that need to be polled.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = True, transfer = TransferNothing},Arg {argCName = "n_fds", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "length of @fds.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : [Arg {argCName = "n_fds", argType = TBasicType TInt, direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "length of @fds.", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- returnType : Just (TBasicType TInt)
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_query" g_main_context_query ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Int32 ->                                -- max_priority : TBasicType TInt
    Ptr Int32 ->                            -- timeout_ : TBasicType TInt
    Ptr GLib.PollFD.PollFD ->               -- fds : TCArray False (-1) 4 (TInterface (Name {namespace = "GLib", name = "PollFD"}))
    Int32 ->                                -- n_fds : TBasicType TInt
    IO Int32

{- |
Determines information necessary to poll this main loop.

You must have successfully acquired the context with
'GI.GLib.Structs.MainContext.mainContextAcquire' before you may call this function.
-}
mainContextQuery ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> Int32
    {- ^ /@maxPriority@/: maximum priority source to check -}
    -> [GLib.PollFD.PollFD]
    {- ^ /@fds@/: location to
      store 'GI.GLib.Structs.PollFD.PollFD' records that need to be polled. -}
    -> m ((Int32, Int32, [GLib.PollFD.PollFD]))
    {- ^ __Returns:__ the number of records actually stored in /@fds@/,
  or, if more than /@nFds@/ records need to be stored, the number
  of records that need to be stored. -}
mainContextQuery context maxPriority fds = liftIO $ do
    let nFds = fromIntegral $ length fds
    context' <- unsafeManagedPtrGetPtr context
    timeout_ <- allocMem :: IO (Ptr Int32)
    fds' <- mapM unsafeManagedPtrGetPtr fds
    fds'' <- packBlockArray 8 fds'
    result <- g_main_context_query context' maxPriority timeout_ fds'' nFds
    timeout_' <- peek timeout_
    fds''' <- (unpackBoxedArrayWithLength 8 nFds) fds''
    fds'''' <- mapM (newBoxed GLib.PollFD.PollFD) fds'''
    touchManagedPtr context
    mapM_ touchManagedPtr fds
    freeMem timeout_
    return (result, timeout_', fds'''')

#if ENABLE_OVERLOADING
data MainContextQueryMethodInfo
instance (signature ~ (Int32 -> [GLib.PollFD.PollFD] -> m ((Int32, Int32, [GLib.PollFD.PollFD]))), MonadIO m) => O.MethodInfo MainContextQueryMethodInfo MainContext signature where
    overloadedMethod _ = mainContextQuery

#endif

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

foreign import ccall "g_main_context_ref" g_main_context_ref ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO (Ptr MainContext)

{- |
Increases the reference count on a 'GI.GLib.Structs.MainContext.MainContext' object by one.
-}
mainContextRef ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m MainContext
    {- ^ __Returns:__ the /@context@/ that was passed in (since 2.6) -}
mainContextRef context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    result <- g_main_context_ref context'
    checkUnexpectedReturnNULL "mainContextRef" result
    result' <- (wrapBoxed MainContext) result
    touchManagedPtr context
    return result'

#if ENABLE_OVERLOADING
data MainContextRefMethodInfo
instance (signature ~ (m MainContext), MonadIO m) => O.MethodInfo MainContextRefMethodInfo MainContext signature where
    overloadedMethod _ = mainContextRef

#endif

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

foreign import ccall "g_main_context_release" g_main_context_release ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO ()

{- |
Releases ownership of a context previously acquired by this thread
with 'GI.GLib.Structs.MainContext.mainContextAcquire'. If the context was acquired multiple
times, the ownership will be released only when 'GI.GLib.Structs.MainContext.mainContextRelease'
is called as many times as it was acquired.
-}
mainContextRelease ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m ()
mainContextRelease context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    g_main_context_release context'
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextReleaseMethodInfo
instance (signature ~ (m ()), MonadIO m) => O.MethodInfo MainContextReleaseMethodInfo MainContext signature where
    overloadedMethod _ = mainContextRelease

#endif

-- method MainContext::remove_poll
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "fd", argType = TInterface (Name {namespace = "GLib", name = "PollFD"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GPollFD descriptor previously added with g_main_context_add_poll()", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing}]
-- Lengths : []
-- returnType : Nothing
-- throws : False
-- Skip return : False

foreign import ccall "g_main_context_remove_poll" g_main_context_remove_poll ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Ptr GLib.PollFD.PollFD ->               -- fd : TInterface (Name {namespace = "GLib", name = "PollFD"})
    IO ()

{- |
Removes file descriptor from the set of file descriptors to be
polled for a particular context.
-}
mainContextRemovePoll ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> GLib.PollFD.PollFD
    {- ^ /@fd@/: a 'GI.GLib.Structs.PollFD.PollFD' descriptor previously added with 'GI.GLib.Structs.MainContext.mainContextAddPoll' -}
    -> m ()
mainContextRemovePoll context fd = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    fd' <- unsafeManagedPtrGetPtr fd
    g_main_context_remove_poll context' fd'
    touchManagedPtr context
    touchManagedPtr fd
    return ()

#if ENABLE_OVERLOADING
data MainContextRemovePollMethodInfo
instance (signature ~ (GLib.PollFD.PollFD -> m ()), MonadIO m) => O.MethodInfo MainContextRemovePollMethodInfo MainContext signature where
    overloadedMethod _ = mainContextRemovePoll

#endif

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

foreign import ccall "g_main_context_unref" g_main_context_unref ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO ()

{- |
Decreases the reference count on a 'GI.GLib.Structs.MainContext.MainContext' object by one. If
the result is zero, free the context and free all associated memory.
-}
mainContextUnref ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m ()
mainContextUnref context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    g_main_context_unref context'
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextUnrefMethodInfo
instance (signature ~ (m ()), MonadIO m) => O.MethodInfo MainContextUnrefMethodInfo MainContext signature where
    overloadedMethod _ = mainContextUnref

#endif

-- method MainContext::wait
-- method type : OrdinaryMethod
-- Args : [Arg {argCName = "context", argType = TInterface (Name {namespace = "GLib", name = "MainContext"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a #GMainContext", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "cond", argType = TInterface (Name {namespace = "GLib", name = "Cond"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a condition variable", sinceVersion = Nothing}, argScope = ScopeTypeInvalid, argClosure = -1, argDestroy = -1, argCallerAllocates = False, transfer = TransferNothing},Arg {argCName = "mutex", argType = TInterface (Name {namespace = "GLib", name = "Mutex"}), direction = DirectionIn, mayBeNull = False, argDoc = Documentation {rawDocText = Just "a mutex, currently held", 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_main_context_wait" g_main_context_wait ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    Ptr GLib.Cond.Cond ->                   -- cond : TInterface (Name {namespace = "GLib", name = "Cond"})
    Ptr GLib.Mutex.Mutex ->                 -- mutex : TInterface (Name {namespace = "GLib", name = "Mutex"})
    IO CInt

{-# DEPRECATED mainContextWait ["(Since version 2.58)","Use 'GI.GLib.Structs.MainContext.mainContextIsOwner' and separate locking instead."] #-}
{- |
Tries to become the owner of the specified context,
as with 'GI.GLib.Structs.MainContext.mainContextAcquire'. But if another thread
is the owner, atomically drop /@mutex@/ and wait on /@cond@/ until
that owner releases ownership or until /@cond@/ is signaled, then
try again (once) to become the owner.
-}
mainContextWait ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> GLib.Cond.Cond
    {- ^ /@cond@/: a condition variable -}
    -> GLib.Mutex.Mutex
    {- ^ /@mutex@/: a mutex, currently held -}
    -> m Bool
    {- ^ __Returns:__ 'True' if the operation succeeded, and
  this thread is now the owner of /@context@/. -}
mainContextWait context cond mutex = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    cond' <- unsafeManagedPtrGetPtr cond
    mutex' <- unsafeManagedPtrGetPtr mutex
    result <- g_main_context_wait context' cond' mutex'
    let result' = (/= 0) result
    touchManagedPtr context
    touchManagedPtr cond
    touchManagedPtr mutex
    return result'

#if ENABLE_OVERLOADING
data MainContextWaitMethodInfo
instance (signature ~ (GLib.Cond.Cond -> GLib.Mutex.Mutex -> m Bool), MonadIO m) => O.MethodInfo MainContextWaitMethodInfo MainContext signature where
    overloadedMethod _ = mainContextWait

#endif

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

foreign import ccall "g_main_context_wakeup" g_main_context_wakeup ::
    Ptr MainContext ->                      -- context : TInterface (Name {namespace = "GLib", name = "MainContext"})
    IO ()

{- |
If /@context@/ is currently blocking in 'GI.GLib.Structs.MainContext.mainContextIteration'
waiting for a source to become ready, cause it to stop blocking
and return.  Otherwise, cause the next invocation of
'GI.GLib.Structs.MainContext.mainContextIteration' to return without blocking.

This API is useful for low-level control over 'GI.GLib.Structs.MainContext.MainContext'; for
example, integrating it with main loop implementations such as
'GI.GLib.Structs.MainLoop.MainLoop'.

Another related use for this function is when implementing a main
loop with a termination condition, computed from multiple threads:


=== /C code/
>
>  #define NUM_TASKS 10
>  static volatile gint tasks_remaining = NUM_TASKS;
>  ...
> 
>  while (g_atomic_int_get (&tasks_remaining) != 0)
>    g_main_context_iteration (NULL, TRUE);

 
Then in a thread:

=== /C code/
>
>  perform_work();
>
>  if (g_atomic_int_dec_and_test (&tasks_remaining))
>    g_main_context_wakeup (NULL);
-}
mainContextWakeup ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    MainContext
    {- ^ /@context@/: a 'GI.GLib.Structs.MainContext.MainContext' -}
    -> m ()
mainContextWakeup context = liftIO $ do
    context' <- unsafeManagedPtrGetPtr context
    g_main_context_wakeup context'
    touchManagedPtr context
    return ()

#if ENABLE_OVERLOADING
data MainContextWakeupMethodInfo
instance (signature ~ (m ()), MonadIO m) => O.MethodInfo MainContextWakeupMethodInfo MainContext signature where
    overloadedMethod _ = mainContextWakeup

#endif

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

foreign import ccall "g_main_context_default" g_main_context_default ::
    IO (Ptr MainContext)

{- |
Returns the global default main context. This is the main context
used for main loop functions when a main loop is not explicitly
specified, and corresponds to the \"main\" main loop. See also
'GI.GLib.Functions.mainContextGetThreadDefault'.
-}
mainContextDefault ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m MainContext
    {- ^ __Returns:__ the global default main context. -}
mainContextDefault  = liftIO $ do
    result <- g_main_context_default
    checkUnexpectedReturnNULL "mainContextDefault" result
    result' <- (newBoxed MainContext) result
    return result'

#if ENABLE_OVERLOADING
#endif

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

foreign import ccall "g_main_context_get_thread_default" g_main_context_get_thread_default ::
    IO (Ptr MainContext)

{- |
Gets the thread-default 'GI.GLib.Structs.MainContext.MainContext' for this thread. Asynchronous
operations that want to be able to be run in contexts other than
the default one should call this method or
'GI.GLib.Functions.mainContextRefThreadDefault' to get a 'GI.GLib.Structs.MainContext.MainContext' to add
their @/GSources/@ to. (Note that even in single-threaded
programs applications may sometimes want to temporarily push a
non-default context, so it is not safe to assume that this will
always return 'Nothing' if you are running in the default thread.)

If you need to hold a reference on the context, use
'GI.GLib.Functions.mainContextRefThreadDefault' instead.

/Since: 2.22/
-}
mainContextGetThreadDefault ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m MainContext
    {- ^ __Returns:__ the thread-default 'GI.GLib.Structs.MainContext.MainContext', or
'Nothing' if the thread-default context is the global default context. -}
mainContextGetThreadDefault  = liftIO $ do
    result <- g_main_context_get_thread_default
    checkUnexpectedReturnNULL "mainContextGetThreadDefault" result
    result' <- (newBoxed MainContext) result
    return result'

#if ENABLE_OVERLOADING
#endif

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

foreign import ccall "g_main_context_ref_thread_default" g_main_context_ref_thread_default ::
    IO (Ptr MainContext)

{- |
Gets the thread-default 'GI.GLib.Structs.MainContext.MainContext' for this thread, as with
'GI.GLib.Functions.mainContextGetThreadDefault', but also adds a reference to
it with 'GI.GLib.Structs.MainContext.mainContextRef'. In addition, unlike
'GI.GLib.Functions.mainContextGetThreadDefault', if the thread-default context
is the global default context, this will return that 'GI.GLib.Structs.MainContext.MainContext'
(with a ref added to it) rather than returning 'Nothing'.

/Since: 2.32/
-}
mainContextRefThreadDefault ::
    (B.CallStack.HasCallStack, MonadIO m) =>
    m MainContext
    {- ^ __Returns:__ the thread-default 'GI.GLib.Structs.MainContext.MainContext'. Unref
    with 'GI.GLib.Structs.MainContext.mainContextUnref' when you are done with it. -}
mainContextRefThreadDefault  = liftIO $ do
    result <- g_main_context_ref_thread_default
    checkUnexpectedReturnNULL "mainContextRefThreadDefault" result
    result' <- (wrapBoxed MainContext) result
    return result'

#if ENABLE_OVERLOADING
#endif

#if ENABLE_OVERLOADING
type family ResolveMainContextMethod (t :: Symbol) (o :: *) :: * where
    ResolveMainContextMethod "acquire" o = MainContextAcquireMethodInfo
    ResolveMainContextMethod "addPoll" o = MainContextAddPollMethodInfo
    ResolveMainContextMethod "check" o = MainContextCheckMethodInfo
    ResolveMainContextMethod "dispatch" o = MainContextDispatchMethodInfo
    ResolveMainContextMethod "findSourceByFuncsUserData" o = MainContextFindSourceByFuncsUserDataMethodInfo
    ResolveMainContextMethod "findSourceById" o = MainContextFindSourceByIdMethodInfo
    ResolveMainContextMethod "findSourceByUserData" o = MainContextFindSourceByUserDataMethodInfo
    ResolveMainContextMethod "invokeFull" o = MainContextInvokeFullMethodInfo
    ResolveMainContextMethod "isOwner" o = MainContextIsOwnerMethodInfo
    ResolveMainContextMethod "iteration" o = MainContextIterationMethodInfo
    ResolveMainContextMethod "pending" o = MainContextPendingMethodInfo
    ResolveMainContextMethod "popThreadDefault" o = MainContextPopThreadDefaultMethodInfo
    ResolveMainContextMethod "prepare" o = MainContextPrepareMethodInfo
    ResolveMainContextMethod "pushThreadDefault" o = MainContextPushThreadDefaultMethodInfo
    ResolveMainContextMethod "query" o = MainContextQueryMethodInfo
    ResolveMainContextMethod "ref" o = MainContextRefMethodInfo
    ResolveMainContextMethod "release" o = MainContextReleaseMethodInfo
    ResolveMainContextMethod "removePoll" o = MainContextRemovePollMethodInfo
    ResolveMainContextMethod "unref" o = MainContextUnrefMethodInfo
    ResolveMainContextMethod "wait" o = MainContextWaitMethodInfo
    ResolveMainContextMethod "wakeup" o = MainContextWakeupMethodInfo
    ResolveMainContextMethod l o = O.MethodResolutionFailed l o

instance (info ~ ResolveMainContextMethod t MainContext, O.MethodInfo info MainContext p) => OL.IsLabel t (MainContext -> 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