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 MainContext structure.

§Returns

the new #GMainContext Creates a new MainContext structure.

§Returns

the new #GMainContext

Source

pub fn with_flags(flags: MainContextFlags) -> MainContext

Available on crate feature v2_72 only.

Creates a new MainContext structure.

§flags

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

§Returns

the new #GMainContext Creates a new MainContext 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 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 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 MainContext. 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 MainContext. 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 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 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 iteration() waiting for a source to become ready, cause it to stop blocking and return. Otherwise, cause the next invocation of iteration() to return without blocking.

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

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 iteration() waiting for a source to become ready, cause it to stop blocking and return. Otherwise, cause the next invocation of iteration() to return without blocking.

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

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 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 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 ref_thread_default() to get a MainContext to add their Sources 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 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 ref_thread_default() to get a MainContext to add their Sources 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 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 MainContext for this thread, as with thread_default(), but also adds a reference to it with GLib::MainContext::ref(). In addition, unlike thread_default(), if the thread-default context is the global-default context, this will return that MainContext (with a ref added to it) rather than returning None.

§Returns

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

§Returns

the thread-default #GMainContext. Unref with GLib::MainContext::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 GLib::MainContext::query().

You must have successfully acquired the context with 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 GLib::MainContext::query().

You must have successfully acquired the context with 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 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 GLib::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 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 GLib::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 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 acquire() succeeds, then @function is called and [release()][Self::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 GLib::PRIORITY_DEFAULT priority. If you want a different priority, use [invoke_full()][Self::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 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 acquire() succeeds, then @function is called and [release()][Self::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 GLib::PRIORITY_DEFAULT priority. If you want a different priority, use [invoke_full()][Self::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 [release()][Self::release()] is called as many times as acquire().

You must be the owner of a context before you can call prepare(), GLib::MainContext::query(), GLib::MainContext::check(), dispatch(), [release()][Self::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 [release()][Self::release()] is called as many times as acquire().

You must be the owner of a context before you can call prepare(), GLib::MainContext::query(), GLib::MainContext::check(), dispatch(), [release()][Self::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.0.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.3.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.0.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.0.0 · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.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.0.0 · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.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 u8)

🔬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,