glib

Struct MainContext

source
pub struct MainContext { /* private fields */ }
Expand description

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

GLib type: Shared boxed type with reference counted clone semantics.

Implementations§

source§

impl MainContext

source

pub fn as_ptr(&self) -> *mut GMainContext

Return the inner pointer to the underlying C value.

source

pub unsafe fn from_glib_ptr_borrow(ptr: &*mut GMainContext) -> &Self

Borrows the underlying C value.

source§

impl MainContext

source

pub fn new() -> MainContext

Creates a new #GMainContext structure.

§Returns

the new #GMainContext Creates a new #GMainContext structure.

§Returns

the new #GMainContext

source

pub fn with_flags(flags: MainContextFlags) -> MainContext

Available on crate feature v2_72 only.

Creates a new #GMainContext structure.

§flags

a bitwise-OR combination of #GMainContextFlags flags that can only be set at creation time.

§Returns

the new #GMainContext Creates a new #GMainContext structure.

§flags

a bitwise-OR combination of #GMainContextFlags flags that can only be set at creation time.

§Returns

the new #GMainContext

source

pub fn dispatch(&self)

Dispatches all pending sources.

You must have successfully acquired the context with g_main_context_acquire() before you may call this function.

Since 2.76 @self can be None to use the global-default main context. Dispatches all pending sources.

You must have successfully acquired the context with g_main_context_acquire() before you may call this function.

Since 2.76 @self can be None to use the global-default main context.

source

pub fn is_owner(&self) -> bool

Determines whether this thread holds the (recursive) ownership of this #GMainContext. This is useful to know before waiting on another thread that may be blocking to get ownership of @self.

§Returns

true if current thread is owner of @self. Determines whether this thread holds the (recursive) ownership of this #GMainContext. This is useful to know before waiting on another thread that may be blocking to get ownership of @self.

§Returns

true if current thread is owner of @self.

source

pub fn iteration(&self, may_block: bool) -> bool

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 @may_block is true, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Otherwise, if @may_block 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 @may_block is true, it is still possible for g_main_context_iteration() to return false, since the wait may be interrupted for other reasons than an event source becoming ready.

§may_block

whether the call may block.

§Returns

true if events were dispatched. 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 @may_block is true, waiting for a source to become ready, then dispatching the highest priority events sources that are ready. Otherwise, if @may_block 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 @may_block is true, it is still possible for g_main_context_iteration() to return false, since the wait may be interrupted for other reasons than an event source becoming ready.

§may_block

whether the call may block.

§Returns

true if events were dispatched.

source

pub fn pending(&self) -> bool

Checks if any sources have pending events for the given context.

§Returns

true if events are pending. Checks if any sources have pending events for the given context.

§Returns

true if events are pending.

source

pub fn wakeup(&self)

If @self is currently blocking in g_main_context_iteration() waiting for a source to become ready, cause it to stop blocking and return. Otherwise, cause the next invocation of g_main_context_iteration() to return without blocking.

This API is useful for low-level control over #GMainContext; for example, integrating it with main loop implementations such as #GMainLoop.

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

⚠️ The following code is in C ⚠️

  #define NUM_TASKS 10
  static gint tasks_remaining = NUM_TASKS;  // (atomic)
  ...

  while (g_atomic_int_get (&tasks_remaining) != 0)
    g_main_context_iteration (NULL, TRUE);

Then in a thread:

⚠️ The following code is in C ⚠️

  perform_work();

  if (g_atomic_int_dec_and_test (&tasks_remaining))
    g_main_context_wakeup (NULL);

If @self is currently blocking in g_main_context_iteration() waiting for a source to become ready, cause it to stop blocking and return. Otherwise, cause the next invocation of g_main_context_iteration() to return without blocking.

This API is useful for low-level control over #GMainContext; for example, integrating it with main loop implementations such as #GMainLoop.

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

⚠️ The following code is in C ⚠️

  #define NUM_TASKS 10
  static gint tasks_remaining = NUM_TASKS;  // (atomic)
  ...

  while (g_atomic_int_get (&tasks_remaining) != 0)
    g_main_context_iteration (NULL, TRUE);

Then in a thread:

⚠️ The following code is in C ⚠️

  perform_work();

  if (g_atomic_int_dec_and_test (&tasks_remaining))
    g_main_context_wakeup (NULL);
source

pub fn default() -> 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 g_main_context_get_thread_default().

§Returns

the global-default main context. 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 g_main_context_get_thread_default().

§Returns

the global-default main context.

source

pub fn thread_default() -> Option<MainContext>

Gets the thread-default #GMainContext 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 g_main_context_ref_thread_default() to get a #GMainContext 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 None if you are running in the default thread.)

If you need to hold a reference on the context, use g_main_context_ref_thread_default() instead.

§Returns

the thread-default #GMainContext, or None if the thread-default context is the global-default main context. Gets the thread-default #GMainContext 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 g_main_context_ref_thread_default() to get a #GMainContext 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 None if you are running in the default thread.)

If you need to hold a reference on the context, use g_main_context_ref_thread_default() instead.

§Returns

the thread-default #GMainContext, or None if the thread-default context is the global-default main context.

source

pub fn ref_thread_default() -> MainContext

Gets the thread-default #GMainContext for this thread, as with g_main_context_get_thread_default(), but also adds a reference to it with g_main_context_ref(). In addition, unlike g_main_context_get_thread_default(), if the thread-default context is the global-default context, this will return that #GMainContext (with a ref added to it) rather than returning None.

§Returns

the thread-default #GMainContext. Unref with g_main_context_unref() when you are done with it. Gets the thread-default #GMainContext for this thread, as with g_main_context_get_thread_default(), but also adds a reference to it with g_main_context_ref(). In addition, unlike g_main_context_get_thread_default(), if the thread-default context is the global-default context, this will return that #GMainContext (with a ref added to it) rather than returning None.

§Returns

the thread-default #GMainContext. Unref with g_main_context_unref() when you are done with it.

source§

impl MainContext

source

pub fn prepare(&self) -> (bool, i32)

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 g_main_context_acquire() before you may call this function.

§Returns

true if some source is ready to be dispatched prior to polling.

§priority

location to store priority of highest priority source already ready. 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 g_main_context_acquire() before you may call this function.

§Returns

true if some source is ready to be dispatched prior to polling.

§priority

location to store priority of highest priority source already ready.

source

pub fn find_source_by_id(&self, source_id: &SourceId) -> Option<Source>

Finds a #GSource given a pair of context and ID.

It is a programmer error to attempt to look up 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.

§source_id

the source ID, as returned by g_source_get_id().

§Returns

the #GSource Finds a #GSource given a pair of context and ID.

It is a programmer error to attempt to look up 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.

§source_id

the source ID, as returned by g_source_get_id().

§Returns

the #GSource

source

pub fn invoke<F>(&self, func: F)
where F: FnOnce() + Send + 'static,

Invokes func on the main context.

If the current thread is the owner of the main context or the main context currently has no owner then func will be called directly from inside this function. If this behaviour is not desired and func should always be called asynchronously then use MainContext::spawn glib::idle_add instead. Invokes a function in such a way that @self is owned during the invocation of @function.

If @self is None then the global-default main context — as returned by g_main_context_default() — is used.

If @self is owned by the current thread, @function is called directly. Otherwise, if @self is the thread-default main context of the current thread and g_main_context_acquire() succeeds, then @function is called and g_main_context_release() is called afterwards.

In any other case, an idle source is created to call @function and that source is attached to @self (presumably to be run in another thread). The idle source is attached with G_PRIORITY_DEFAULT priority. If you want a different priority, use g_main_context_invoke_full().

Note that, as with normal idle functions, @function should probably return false. If it returns true, it will be continuously run in a loop (and may prevent this call from returning).

§function

function to call Invokes a function in such a way that @self is owned during the invocation of @function.

If @self is None then the global-default main context — as returned by g_main_context_default() — is used.

If @self is owned by the current thread, @function is called directly. Otherwise, if @self is the thread-default main context of the current thread and g_main_context_acquire() succeeds, then @function is called and g_main_context_release() is called afterwards.

In any other case, an idle source is created to call @function and that source is attached to @self (presumably to be run in another thread). The idle source is attached with G_PRIORITY_DEFAULT priority. If you want a different priority, use g_main_context_invoke_full().

Note that, as with normal idle functions, @function should probably return false. If it returns true, it will be continuously run in a loop (and may prevent this call from returning).

§function

function to call

source

pub fn invoke_with_priority<F>(&self, priority: Priority, func: F)
where F: FnOnce() + Send + 'static,

Invokes func on the main context with the given priority.

If the current thread is the owner of the main context or the main context currently has no owner then func will be called directly from inside this function. If this behaviour is not desired and func should always be called asynchronously then use MainContext::spawn glib::idle_add instead.

source

pub fn invoke_local<F>(&self, func: F)
where F: FnOnce() + 'static,

Invokes func on the main context.

Different to invoke(), this does not require func to be Send but can only be called from the thread that owns the main context.

This function panics if called from a different thread than the one that owns the main context.

Note that this effectively means that func is called directly from inside this function or otherwise panics immediately. If this behaviour is not desired and func should always be called asynchronously then use MainContext::spawn_local glib::idle_add_local instead.

source

pub fn invoke_local_with_priority<F>(&self, _priority: Priority, func: F)
where F: FnOnce() + 'static,

Invokes func on the main context with the given priority.

Different to invoke_with_priority(), this does not require func to be Send but can only be called from the thread that owns the main context.

This function panics if called from a different thread than the one that owns the main context.

Note that this effectively means that func is called directly from inside this function or otherwise panics immediately. If this behaviour is not desired and func should always be called asynchronously then use MainContext::spawn_local glib::idle_add_local instead.

source

pub fn with_thread_default<R, F: FnOnce() -> R + Sized>( &self, func: F, ) -> Result<R, BoolError>

Call closure with the main context configured as the thread default one.

The thread default main context is changed in a panic-safe manner before calling func and released again afterwards regardless of whether closure panicked or not.

This will fail if the main context is owned already by another thread.

source

pub fn acquire(&self) -> Result<MainContextAcquireGuard<'_>, BoolError>

Acquire ownership of the main context.

Ownership will automatically be released again once the returned acquire guard is dropped.

This will fail if the main context is owned already by another thread. 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 g_main_context_release() is called as many times as g_main_context_acquire().

You must be the owner of a context before you can call g_main_context_prepare(), g_main_context_query(), g_main_context_check(), g_main_context_dispatch(), g_main_context_release().

Since 2.76 @self can be None to use the global-default main context.

§Returns

true if the operation succeeded, and this thread is now the owner of @self. 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 g_main_context_release() is called as many times as g_main_context_acquire().

You must be the owner of a context before you can call g_main_context_prepare(), g_main_context_query(), g_main_context_check(), g_main_context_dispatch(), g_main_context_release().

Since 2.76 @self can be None to use the global-default main context.

§Returns

true if the operation succeeded, and this thread is now the owner of @self.

source§

impl MainContext

source

pub fn spawn<R: Send + 'static, F: Future<Output = R> + Send + 'static>( &self, f: F, ) -> JoinHandle<R>

Spawn a new infallible Future on the main context.

This can be called from any thread and will execute the future from the thread where main context is running, e.g. via a MainLoop.

source

pub fn spawn_local<R: 'static, F: Future<Output = R> + 'static>( &self, f: F, ) -> JoinHandle<R>

Spawn a new infallible Future on the main context.

The given Future does not have to be Send.

This can be called only from the thread where the main context is running, e.g. from any other Future that is executed on this main context, or after calling with_thread_default or acquire on the main context.

source

pub fn spawn_with_priority<R: Send + 'static, F: Future<Output = R> + Send + 'static>( &self, priority: Priority, f: F, ) -> JoinHandle<R>

Spawn a new infallible Future on the main context, with a non-default priority.

This can be called from any thread and will execute the future from the thread where main context is running, e.g. via a MainLoop.

source

pub fn spawn_local_with_priority<R: 'static, F: Future<Output = R> + 'static>( &self, priority: Priority, f: F, ) -> JoinHandle<R>

Spawn a new infallible Future on the main context, with a non-default priority.

The given Future does not have to be Send.

This can be called only from the thread where the main context is running, e.g. from any other Future that is executed on this main context, or after calling with_thread_default or acquire on the main context.

source

pub fn spawn_from_within<R: Send + 'static, F: Future<Output = R> + 'static>( &self, func: impl FnOnce() -> F + Send + 'static, ) -> SpawnWithinJoinHandle<R>

Spawn a new infallible Future on the main context from inside the main context.

The given Future does not have to be Send but the closure to spawn it has to be.

This can be called only from any thread.

source

pub fn spawn_from_within_with_priority<R: Send + 'static, F: Future<Output = R> + 'static>( &self, priority: Priority, func: impl FnOnce() -> F + Send + 'static, ) -> SpawnWithinJoinHandle<R>

Spawn a new infallible Future on the main context from inside the main context.

The given Future does not have to be Send but the closure to spawn it has to be.

This can be called only from any thread.

source

pub fn block_on<F: Future>(&self, f: F) -> F::Output

Runs a new, infallible Future on the main context and block until it finished, returning the result of the Future.

The given Future does not have to be Send or 'static.

This must only be called if no MainLoop or anything else is running on this specific main context.

Trait Implementations§

source§

impl Clone for MainContext

source§

fn clone(&self) -> Self

Makes a clone of this shared reference.

This increments the strong reference count of the reference. Dropping the reference will decrement it again.

1.6.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for MainContext

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for MainContext

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl From<MainContext> for Value

source§

fn from(s: MainContext) -> Self

Converts to this type from the input type.
source§

impl HasParamSpec for MainContext

source§

type ParamSpec = ParamSpecBoxed

source§

type SetValue = MainContext

Preferred value to be used as setter for the associated ParamSpec.
source§

type BuilderFn = fn(_: &str) -> ParamSpecBoxedBuilder<'_, MainContext>

source§

fn param_spec_builder() -> Self::BuilderFn

source§

impl Hash for MainContext

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.6.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl LocalSpawn for MainContext

source§

fn spawn_local_obj( &self, f: LocalFutureObj<'static, ()>, ) -> Result<(), SpawnError>

Spawns a future that will be run to completion. Read more
§

fn status_local(&self) -> Result<(), SpawnError>

Determines whether the executor is able to spawn new tasks. Read more
source§

impl Ord for MainContext

source§

fn cmp(&self, other: &MainContext) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
source§

impl PartialEq for MainContext

source§

fn eq(&self, other: &MainContext) -> bool

Tests for self and other values to be equal, and is used by ==.
1.6.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for MainContext

source§

fn partial_cmp(&self, other: &MainContext) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.6.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.6.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.6.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.6.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Spawn for MainContext

source§

fn spawn_obj(&self, f: FutureObj<'static, ()>) -> Result<(), SpawnError>

Spawns a future that will be run to completion. Read more
§

fn status(&self) -> Result<(), SpawnError>

Determines whether the executor is able to spawn new tasks. Read more
source§

impl StaticType for MainContext

source§

fn static_type() -> Type

Returns the type identifier of Self.
source§

impl Eq for MainContext

source§

impl Send for MainContext

source§

impl StructuralPartialEq for MainContext

source§

impl Sync for MainContext

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *const GList> for T

source§

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *const GPtrArray> for T

source§

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *const GSList> for T

source§

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut GList> for T

source§

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut GPtrArray> for T

source§

impl<T> FromGlibContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut GSList> for T

source§

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *const GList> for T

source§

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *const GPtrArray> for T

source§

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *const GSList> for T

source§

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut GList> for T

source§

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut GPtrArray> for T

source§

impl<T> FromGlibPtrArrayContainerAsVec<<T as GlibPtrDefault>::GlibType, *mut GSList> for T

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoClosureReturnValue for T
where T: Into<Value>,

§

impl<Sp> LocalSpawnExt for Sp
where Sp: LocalSpawn + ?Sized,

§

fn spawn_local<Fut>(&self, future: Fut) -> Result<(), SpawnError>
where Fut: Future<Output = ()> + 'static,

Spawns a task that polls the given future with output () to completion. Read more
source§

impl<T> Property for T
where T: HasParamSpec,

source§

type Value = T

source§

impl<T> PropertyGet for T
where T: HasParamSpec,

source§

type Value = T

source§

fn get<R, F>(&self, f: F) -> R
where F: Fn(&<T as PropertyGet>::Value) -> R,

§

impl<Sp> SpawnExt for Sp
where Sp: Spawn + ?Sized,

§

fn spawn<Fut>(&self, future: Fut) -> Result<(), SpawnError>
where Fut: Future<Output = ()> + Send + 'static,

Spawns a task that polls the given future with output () to completion. Read more
source§

impl<T> StaticTypeExt for T
where T: StaticType,

source§

fn ensure_type()

Ensures that the type has been registered with the type system.
source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToSendValue for T
where T: Send + ToValue + ?Sized,

source§

fn to_send_value(&self) -> SendValue

Returns a SendValue clone of self.
source§

impl<T> TransparentType for T

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T> TryFromClosureReturnValue for T
where T: for<'a> FromValue<'a> + StaticType + 'static,

source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<'a, T, C, E> FromValueOptional<'a> for T
where T: FromValue<'a, Checker = C>, C: ValueTypeChecker<Error = ValueTypeMismatchOrNoneError<E>>, E: Error + Send + 'static,