gio

Struct Task

Source
pub struct Task<V: ValueType + Send> { /* private fields */ }
Expand description

Task provides idiomatic access to gio’s GTask API, for instance by being generic over their value type, while not completely departing from the underlying C API. Task is Send and Sync and requires its value to also be Send and Sync, thus is useful to to implement gio style asynchronous tasks that run in threads. If you need to only run tasks in glib main loop see the LocalTask type.

The constructors of LocalTask and Task is marked as unsafe because this API does not allow to automatically enforce all the invariants required to be a completely safe abstraction. The caller is responsible to ensure the following requirements are satisfied

  • You should not create a LocalTask, upcast it to a glib::Object and then downcast it to a Task, as this will bypass the thread safety requirements
  • You should ensure that the return_result, return_error_if_cancelled and propagate() methods are only called once. A GTask represents and manages a cancellable ‘task’.

§Asynchronous operations

The most common usage of GTask is as a AsyncResult, to manage data during an asynchronous operation. You call new() in the ‘start’ method, followed by [set_task_data()][Self::set_task_data()] and the like if you need to keep some additional data associated with the task, and then pass the task object around through your asynchronous operation. Eventually, you will call a method such as [return_pointer()][Self::return_pointer()] or [return_error()][Self::return_error()], which will save the value you give it and then invoke the task’s callback function in the thread-default main context (see [glib::MainContext::push_thread_default()][crate::glib::MainContext::push_thread_default()]) where it was created (waiting until the next iteration of the main loop first, if necessary). The caller will pass the GTask back to the operation’s finish function (as a AsyncResult), and you can use [propagate_pointer()][Self::propagate_pointer()] or the like to extract the return value.

Using GTask requires the thread-default glib::MainContext from when the GTask was constructed to be running at least until the task has completed and its data has been freed.

If a GTask has been constructed and its callback set, it is an error to not call g_task_return_*() on it. GLib will warn at runtime if this happens (since 2.76).

Here is an example for using GTask as a AsyncResult: ⚠️ The following code is in c ⚠️

typedef struct {
  CakeFrostingType frosting;
  char *message;
} DecorationData;

static void
decoration_data_free (DecorationData *decoration)
{
  g_free (decoration->message);
  g_slice_free (DecorationData, decoration);
}

static void
baked_cb (Cake     *cake,
          gpointer  user_data)
{
  GTask *task = user_data;
  DecorationData *decoration = g_task_get_task_data (task);
  GError *error = NULL;

  if (cake == NULL)
    {
      g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
                               "Go to the supermarket");
      g_object_unref (task);
      return;
    }

  if (!cake_decorate (cake, decoration->frosting, decoration->message, &error))
    {
      g_object_unref (cake);
      // g_task_return_error() takes ownership of error
      g_task_return_error (task, error);
      g_object_unref (task);
      return;
    }

  g_task_return_pointer (task, cake, g_object_unref);
  g_object_unref (task);
}

void
baker_bake_cake_async (Baker               *self,
                       guint                radius,
                       CakeFlavor           flavor,
                       CakeFrostingType     frosting,
                       const char          *message,
                       GCancellable        *cancellable,
                       GAsyncReadyCallback  callback,
                       gpointer             user_data)
{
  GTask *task;
  DecorationData *decoration;
  Cake  *cake;

  task = g_task_new (self, cancellable, callback, user_data);
  if (radius < 3)
    {
      g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_TOO_SMALL,
                               "%ucm radius cakes are silly",
                               radius);
      g_object_unref (task);
      return;
    }

  cake = _baker_get_cached_cake (self, radius, flavor, frosting, message);
  if (cake != NULL)
    {
      // _baker_get_cached_cake() returns a reffed cake
      g_task_return_pointer (task, cake, g_object_unref);
      g_object_unref (task);
      return;
    }

  decoration = g_slice_new (DecorationData);
  decoration->frosting = frosting;
  decoration->message = g_strdup (message);
  g_task_set_task_data (task, decoration, (GDestroyNotify) decoration_data_free);

  _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
}

Cake *
baker_bake_cake_finish (Baker         *self,
                        GAsyncResult  *result,
                        GError       **error)
{
  g_return_val_if_fail (g_task_is_valid (result, self), NULL);

  return g_task_propagate_pointer (G_TASK (result), error);
}

§Chained asynchronous operations

GTask also tries to simplify asynchronous operations that internally chain together several smaller asynchronous operations. cancellable(), context(), and priority() allow you to get back the task’s Cancellable, glib::MainContext, and I/O priority when starting a new subtask, so you don’t have to keep track of them yourself. [attach_source()][Self::attach_source()] simplifies the case of waiting for a source to fire (automatically using the correct glib::MainContext and priority).

Here is an example for chained asynchronous operations: ⚠️ The following code is in c ⚠️

typedef struct {
  Cake *cake;
  CakeFrostingType frosting;
  char *message;
} BakingData;

static void
decoration_data_free (BakingData *bd)
{
  if (bd->cake)
    g_object_unref (bd->cake);
  g_free (bd->message);
  g_slice_free (BakingData, bd);
}

static void
decorated_cb (Cake         *cake,
              GAsyncResult *result,
              gpointer      user_data)
{
  GTask *task = user_data;
  GError *error = NULL;

  if (!cake_decorate_finish (cake, result, &error))
    {
      g_object_unref (cake);
      g_task_return_error (task, error);
      g_object_unref (task);
      return;
    }

  // baking_data_free() will drop its ref on the cake, so we have to
  // take another here to give to the caller.
  g_task_return_pointer (task, g_object_ref (cake), g_object_unref);
  g_object_unref (task);
}

static gboolean
decorator_ready (gpointer user_data)
{
  GTask *task = user_data;
  BakingData *bd = g_task_get_task_data (task);

  cake_decorate_async (bd->cake, bd->frosting, bd->message,
                       g_task_get_cancellable (task),
                       decorated_cb, task);

  return G_SOURCE_REMOVE;
}

static void
baked_cb (Cake     *cake,
          gpointer  user_data)
{
  GTask *task = user_data;
  BakingData *bd = g_task_get_task_data (task);
  GError *error = NULL;

  if (cake == NULL)
    {
      g_task_return_new_error (task, BAKER_ERROR, BAKER_ERROR_NO_FLOUR,
                               "Go to the supermarket");
      g_object_unref (task);
      return;
    }

  bd->cake = cake;

  // Bail out now if the user has already cancelled
  if (g_task_return_error_if_cancelled (task))
    {
      g_object_unref (task);
      return;
    }

  if (cake_decorator_available (cake))
    decorator_ready (task);
  else
    {
      GSource *source;

      source = cake_decorator_wait_source_new (cake);
      // Attach @source to @task’s GMainContext and have it call
      // decorator_ready() when it is ready.
      g_task_attach_source (task, source, decorator_ready);
      g_source_unref (source);
    }
}

void
baker_bake_cake_async (Baker               *self,
                       guint                radius,
                       CakeFlavor           flavor,
                       CakeFrostingType     frosting,
                       const char          *message,
                       gint                 priority,
                       GCancellable        *cancellable,
                       GAsyncReadyCallback  callback,
                       gpointer             user_data)
{
  GTask *task;
  BakingData *bd;

  task = g_task_new (self, cancellable, callback, user_data);
  g_task_set_priority (task, priority);

  bd = g_slice_new0 (BakingData);
  bd->frosting = frosting;
  bd->message = g_strdup (message);
  g_task_set_task_data (task, bd, (GDestroyNotify) baking_data_free);

  _baker_begin_cake (self, radius, flavor, cancellable, baked_cb, task);
}

Cake *
baker_bake_cake_finish (Baker         *self,
                        GAsyncResult  *result,
                        GError       **error)
{
  g_return_val_if_fail (g_task_is_valid (result, self), NULL);

  return g_task_propagate_pointer (G_TASK (result), error);
}

§Asynchronous operations from synchronous ones

You can use run_in_thread() to turn a synchronous operation into an asynchronous one, by running it in a thread. When it completes, the result will be dispatched to the thread-default main context (see [glib::MainContext::push_thread_default()][crate::glib::MainContext::push_thread_default()]) where the GTask was created.

Running a task in a thread: ⚠️ The following code is in c ⚠️

typedef struct {
  guint radius;
  CakeFlavor flavor;
  CakeFrostingType frosting;
  char *message;
} CakeData;

static void
cake_data_free (CakeData *cake_data)
{
  g_free (cake_data->message);
  g_slice_free (CakeData, cake_data);
}

static void
bake_cake_thread (GTask         *task,
                  gpointer       source_object,
                  gpointer       task_data,
                  GCancellable  *cancellable)
{
  Baker *self = source_object;
  CakeData *cake_data = task_data;
  Cake *cake;
  GError *error = NULL;

  cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
                    cake_data->frosting, cake_data->message,
                    cancellable, &error);
  if (cake)
    g_task_return_pointer (task, cake, g_object_unref);
  else
    g_task_return_error (task, error);
}

void
baker_bake_cake_async (Baker               *self,
                       guint                radius,
                       CakeFlavor           flavor,
                       CakeFrostingType     frosting,
                       const char          *message,
                       GCancellable        *cancellable,
                       GAsyncReadyCallback  callback,
                       gpointer             user_data)
{
  CakeData *cake_data;
  GTask *task;

  cake_data = g_slice_new (CakeData);
  cake_data->radius = radius;
  cake_data->flavor = flavor;
  cake_data->frosting = frosting;
  cake_data->message = g_strdup (message);
  task = g_task_new (self, cancellable, callback, user_data);
  g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
  g_task_run_in_thread (task, bake_cake_thread);
  g_object_unref (task);
}

Cake *
baker_bake_cake_finish (Baker         *self,
                        GAsyncResult  *result,
                        GError       **error)
{
  g_return_val_if_fail (g_task_is_valid (result, self), NULL);

  return g_task_propagate_pointer (G_TASK (result), error);
}

§Adding cancellability to uncancellable tasks

Finally, run_in_thread() and [run_in_thread_sync()][Self::run_in_thread_sync()] can be used to turn an uncancellable operation into a cancellable one. If you call set_return_on_cancel(), passing TRUE, then if the task’s Cancellable is cancelled, it will return control back to the caller immediately, while allowing the task thread to continue running in the background (and simply discarding its result when it finally does finish). Provided that the task thread is careful about how it uses locks and other externally-visible resources, this allows you to make ‘GLib-friendly’ asynchronous and cancellable synchronous variants of blocking APIs.

Cancelling a task: ⚠️ The following code is in c ⚠️

static void
bake_cake_thread (GTask         *task,
                  gpointer       source_object,
                  gpointer       task_data,
                  GCancellable  *cancellable)
{
  Baker *self = source_object;
  CakeData *cake_data = task_data;
  Cake *cake;
  GError *error = NULL;

  cake = bake_cake (baker, cake_data->radius, cake_data->flavor,
                    cake_data->frosting, cake_data->message,
                    &error);
  if (error)
    {
      g_task_return_error (task, error);
      return;
    }

  // If the task has already been cancelled, then we don’t want to add
  // the cake to the cake cache. Likewise, we don’t  want to have the
  // task get cancelled in the middle of updating the cache.
  // g_task_set_return_on_cancel() will return %TRUE here if it managed
  // to disable return-on-cancel, or %FALSE if the task was cancelled
  // before it could.
  if (g_task_set_return_on_cancel (task, FALSE))
    {
      // If the caller cancels at this point, their
      // GAsyncReadyCallback won’t be invoked until we return,
      // so we don’t have to worry that this code will run at
      // the same time as that code does. But if there were
      // other functions that might look at the cake cache,
      // then we’d probably need a GMutex here as well.
      baker_add_cake_to_cache (baker, cake);
      g_task_return_pointer (task, cake, g_object_unref);
    }
}

void
baker_bake_cake_async (Baker               *self,
                       guint                radius,
                       CakeFlavor           flavor,
                       CakeFrostingType     frosting,
                       const char          *message,
                       GCancellable        *cancellable,
                       GAsyncReadyCallback  callback,
                       gpointer             user_data)
{
  CakeData *cake_data;
  GTask *task;

  cake_data = g_slice_new (CakeData);

  ...

  task = g_task_new (self, cancellable, callback, user_data);
  g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
  g_task_set_return_on_cancel (task, TRUE);
  g_task_run_in_thread (task, bake_cake_thread);
}

Cake *
baker_bake_cake_sync (Baker               *self,
                      guint                radius,
                      CakeFlavor           flavor,
                      CakeFrostingType     frosting,
                      const char          *message,
                      GCancellable        *cancellable,
                      GError             **error)
{
  CakeData *cake_data;
  GTask *task;
  Cake *cake;

  cake_data = g_slice_new (CakeData);

  ...

  task = g_task_new (self, cancellable, NULL, NULL);
  g_task_set_task_data (task, cake_data, (GDestroyNotify) cake_data_free);
  g_task_set_return_on_cancel (task, TRUE);
  g_task_run_in_thread_sync (task, bake_cake_thread);

  cake = g_task_propagate_pointer (task, error);
  g_object_unref (task);
  return cake;
}

§Porting from Gio::SimpleAsyncResult

GTask’s API attempts to be simpler than Gio::SimpleAsyncResult’s in several ways:

  • You can save task-specific data with [set_task_data()][Self::set_task_data()], and retrieve it later with [task_data()][Self::task_data()]. This replaces the abuse of Gio::SimpleAsyncResult::set_op_res_gpointer() for the same purpose with Gio::SimpleAsyncResult.
  • In addition to the task data, GTask also keeps track of the priority, Cancellable, and glib::MainContext associated with the task, so tasks that consist of a chain of simpler asynchronous operations will have easy access to those values when starting each sub-task.
  • return_error_if_cancelled() provides simplified handling for cancellation. In addition, cancellation overrides any other GTask return value by default, like Gio::SimpleAsyncResult does when Gio::SimpleAsyncResult::set_check_cancellable() is called. (You can use set_check_cancellable() to turn off that behavior.) On the other hand, run_in_thread() guarantees that it will always run your task_func, even if the task’s Cancellable is already cancelled before the task gets a chance to run; you can start your task_func with a return_error_if_cancelled() check if you need the old behavior.
  • The ‘return’ methods (eg, [return_pointer()][Self::return_pointer()]) automatically cause the task to be ‘completed’ as well, and there is no need to worry about the ‘complete’ vs ‘complete in idle’ distinction. (GTask automatically figures out whether the task’s callback can be invoked directly, or if it needs to be sent to another glib::MainContext, or delayed until the next iteration of the current glib::MainContext.)
  • The ‘finish’ functions for GTask based operations are generally much simpler than Gio::SimpleAsyncResult ones, normally consisting of only a single call to [propagate_pointer()][Self::propagate_pointer()] or the like. Since [propagate_pointer()][Self::propagate_pointer()] ‘steals’ the return value from the GTask, it is not necessary to juggle pointers around to prevent it from being freed twice.
  • With Gio::SimpleAsyncResult, it was common to call Gio::SimpleAsyncResult::propagate_error() from the _finish() wrapper function, and have virtual method implementations only deal with successful returns. This behavior is deprecated, because it makes it difficult for a subclass to chain to a parent class’s async methods. Instead, the wrapper function should just be a simple wrapper, and the virtual method should call an appropriate g_task_propagate_ function. Note that wrapper methods can now use AsyncResultExt::legacy_propagate_error() to do old-style Gio::SimpleAsyncResult error-returning behavior, and Gio::AsyncResult::is_tagged() to check if a result is tagged as having come from the _async() wrapper function (for ‘short-circuit’ results, such as when passing 0 to InputStreamExtManual::read_async()).

§Thread-safety considerations

Due to some infelicities in the API design, there is a thread-safety concern that users of GTask have to be aware of:

If the main thread drops its last reference to the source object or the task data before the task is finalized, then the finalizers of these objects may be called on the worker thread.

This is a problem if the finalizers use non-threadsafe API, and can lead to hard-to-debug crashes. Possible workarounds include:

  • Clear task data in a signal handler for notify::completed
  • Keep iterating a main context in the main thread and defer dropping the reference to the source object to that main context when the task is finalized

§Properties

§completed

Whether the task has completed, meaning its callback (if set) has been invoked.

This can only happen after g_task_return_pointer(), g_task_return_error() or one of the other return functions have been called on the task. However, it is not guaranteed to happen immediately after those functions are called, as the task’s callback may need to be scheduled to run in a different thread.

That means it is not safe to use this property to track whether a return function has been called on the #GTask. Callers must do that tracking themselves, typically by linking the lifetime of the #GTask to the control flow of their code.

This property is guaranteed to change from false to true exactly once.

The #GObject::notify signal for this change is emitted in the same main context as the task’s callback, immediately after that callback is invoked.

Readable

§Implements

[trait@glib::ObjectExt], AsyncResultExt

GLib type: GObject with reference counted clone semantics.

Implementations§

Source§

impl<V: Into<Value> + ValueType + Send> Task<V>

Source

pub unsafe fn new<S, P, Q>( source_object: Option<&S>, cancellable: Option<&P>, callback: Q, ) -> Self
where S: IsA<Object> + Send, P: IsA<Cancellable>, Q: FnOnce(Task<V>, Option<&S>) + Send + 'static,

Source

pub fn cancellable(&self) -> Option<Cancellable>

Source

pub fn is_check_cancellable(&self) -> bool

Source

pub fn set_check_cancellable(&self, check_cancellable: bool)

Source

pub fn set_name(&self, name: Option<&str>)

Available on crate feature v2_60 only.
Source

pub fn set_return_on_cancel(&self, return_on_cancel: bool) -> bool

Source

pub fn is_valid( result: &impl IsA<AsyncResult>, source_object: Option<&impl IsA<Object>>, ) -> bool

Source

pub fn priority(&self) -> Priority

Source

pub fn set_priority(&self, priority: Priority)

Source

pub fn is_completed(&self) -> bool

Source

pub fn context(&self) -> MainContext

Source

pub fn name(&self) -> Option<GString>

Available on crate feature v2_60 only.
Source

pub fn is_return_on_cancel(&self) -> bool

Source

pub fn had_error(&self) -> bool

Source

pub fn connect_completed_notify<F>(&self, f: F) -> SignalHandlerId
where F: Fn(&Task<V>) + Send + 'static,

Source

pub unsafe fn return_error_if_cancelled(&self) -> bool

Source

pub unsafe fn return_result(self, result: Result<V, Error>)

Source

pub unsafe fn propagate(self) -> Result<V, Error>

Source§

impl<V: ValueType + Send> Task<V>

Source

pub fn run_in_thread<S, Q>(&self, task_func: Q)
where S: IsA<Object> + Send, Q: FnOnce(Self, Option<&S>, Option<&Cancellable>) + Send + 'static,

Trait Implementations§

Source§

impl<V: ValueType + Send> Clone for Task<V>

Source§

fn clone(&self) -> Self

Makes a clone of this shared reference.

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

1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<V: ValueType + Send> Debug for Task<V>

Source§

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

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

impl<V: ValueType + Send> HasParamSpec for Task<V>

Source§

type ParamSpec = ParamSpecObject

Source§

type SetValue = Task<V>

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

type BuilderFn = fn(_: &str) -> ParamSpecObjectBuilder<'_, Task<V>>

Source§

fn param_spec_builder() -> Self::BuilderFn

Source§

impl<V: ValueType + Send> Hash for Task<V>

Source§

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

Hashes the memory address of this object.

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<V: ValueType + Send> Ord for Task<V>

Source§

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

Comparison for two GObjects.

Compares the memory addresses of the provided objects.

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<V: ValueType + Send> ParentClassIs for Task<V>

Source§

impl<OT: ObjectType, V: ValueType + Send> PartialEq<OT> for Task<V>

Source§

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

Equality for two GObjects.

Two GObjects are equal if their memory addresses are equal.

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<OT: ObjectType, V: ValueType + Send> PartialOrd<OT> for Task<V>

Source§

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

Partial comparison for two GObjects.

Compares the memory addresses of the provided objects.

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<V: ValueType + Send> StaticType for Task<V>

Source§

fn static_type() -> Type

Returns the type identifier of Self.
Source§

impl<V: ValueType + Send> Eq for Task<V>

Source§

impl<V: ValueType + Send> IsA<AsyncResult> for Task<V>

Source§

impl<V: ValueType + Send> Send for Task<V>

Source§

impl<V: ValueType + Send> Sync for Task<V>

Auto Trait Implementations§

§

impl<V> Freeze for Task<V>

§

impl<V> RefUnwindSafe for Task<V>
where V: RefUnwindSafe,

§

impl<V> Unpin for Task<V>
where V: Unpin,

§

impl<V> UnwindSafe for Task<V>
where V: UnwindSafe,

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<O> AsyncResultExt for O
where O: IsA<AsyncResult>,

Source§

fn source_object(&self) -> Option<Object>

Gets the source object from a AsyncResult. Read more
Source§

fn legacy_propagate_error(&self) -> Result<(), Error>

If @self is a Gio::SimpleAsyncResult, this is equivalent to Gio::SimpleAsyncResult::propagate_error(). Otherwise it returns FALSE. 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> Cast for T
where T: ObjectType,

Source§

fn upcast<T>(self) -> T
where T: ObjectType, Self: IsA<T>,

Upcasts an object to a superclass or interface T. Read more
Source§

fn upcast_ref<T>(&self) -> &T
where T: ObjectType, Self: IsA<T>,

Upcasts an object to a reference of its superclass or interface T. Read more
Source§

fn downcast<T>(self) -> Result<T, Self>
where T: ObjectType, Self: MayDowncastTo<T>,

Tries to downcast to a subclass or interface implementor T. Read more
Source§

fn downcast_ref<T>(&self) -> Option<&T>
where T: ObjectType, Self: MayDowncastTo<T>,

Tries to downcast to a reference of its subclass or interface implementor T. Read more
Source§

fn dynamic_cast<T>(self) -> Result<T, Self>
where T: ObjectType,

Tries to cast to an object of type T. This handles upcasting, downcasting and casting between interface and interface implementors. All checks are performed at runtime, while upcast will do many checks at compile-time already. downcast will perform the same checks at runtime as dynamic_cast, but will also ensure some amount of compile-time safety. Read more
Source§

fn dynamic_cast_ref<T>(&self) -> Option<&T>
where T: ObjectType,

Tries to cast to reference to an object of type T. This handles upcasting, downcasting and casting between interface and interface implementors. All checks are performed at runtime, while downcast and upcast will do many checks at compile-time already. Read more
Source§

unsafe fn unsafe_cast<T>(self) -> T
where T: ObjectType,

Casts to T unconditionally. Read more
Source§

unsafe fn unsafe_cast_ref<T>(&self) -> &T
where T: ObjectType,

Casts to &T unconditionally. 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, 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>,

Source§

impl<U> IsSubclassableExt for U

Source§

impl<T> ObjectExt for T
where T: ObjectType,

Source§

fn is<U>(&self) -> bool
where U: StaticType,

Returns true if the object is an instance of (can be cast to) T.
Source§

fn type_(&self) -> Type

Returns the type of the object.
Source§

fn object_class(&self) -> &Class<Object>

Returns the ObjectClass of the object. Read more
Source§

fn class(&self) -> &Class<T>
where T: IsClass,

Returns the class of the object.
Source§

fn class_of<U>(&self) -> Option<&Class<U>>
where U: IsClass,

Returns the class of the object in the given type T. Read more
Source§

fn interface<U>(&self) -> Option<InterfaceRef<'_, U>>
where U: IsInterface,

Returns the interface T of the object. Read more
Source§

fn set_property(&self, property_name: &str, value: impl Into<Value>)

Sets the property property_name of the object to value value. Read more
Source§

fn set_property_from_value(&self, property_name: &str, value: &Value)

Sets the property property_name of the object to value value. Read more
Source§

fn set_properties(&self, property_values: &[(&str, &dyn ToValue)])

Sets multiple properties of the object at once. Read more
Source§

fn set_properties_from_value(&self, property_values: &[(&str, Value)])

Sets multiple properties of the object at once. Read more
Source§

fn property<V>(&self, property_name: &str) -> V
where V: for<'b> FromValue<'b> + 'static,

Gets the property property_name of the object and cast it to the type V. Read more
Source§

fn property_value(&self, property_name: &str) -> Value

Gets the property property_name of the object. Read more
Source§

fn has_property(&self, property_name: &str, type_: Option<Type>) -> bool

Check if the object has a property property_name of the given type_. Read more
Source§

fn property_type(&self, property_name: &str) -> Option<Type>

Get the type of the property property_name of this object. Read more
Source§

fn find_property(&self, property_name: &str) -> Option<ParamSpec>

Get the ParamSpec of the property property_name of this object.
Source§

fn list_properties(&self) -> PtrSlice<ParamSpec>

Return all ParamSpec of the properties of this object.
Source§

fn freeze_notify(&self) -> PropertyNotificationFreezeGuard

Freeze all property notifications until the return guard object is dropped. Read more
Source§

unsafe fn set_qdata<QD>(&self, key: Quark, value: QD)
where QD: 'static,

Set arbitrary data on this object with the given key. Read more
Source§

unsafe fn qdata<QD>(&self, key: Quark) -> Option<NonNull<QD>>
where QD: 'static,

Return previously set arbitrary data of this object with the given key. Read more
Source§

unsafe fn steal_qdata<QD>(&self, key: Quark) -> Option<QD>
where QD: 'static,

Retrieve previously set arbitrary data of this object with the given key. Read more
Source§

unsafe fn set_data<QD>(&self, key: &str, value: QD)
where QD: 'static,

Set arbitrary data on this object with the given key. Read more
Source§

unsafe fn data<QD>(&self, key: &str) -> Option<NonNull<QD>>
where QD: 'static,

Return previously set arbitrary data of this object with the given key. Read more
Source§

unsafe fn steal_data<QD>(&self, key: &str) -> Option<QD>
where QD: 'static,

Retrieve previously set arbitrary data of this object with the given key. Read more
Source§

fn block_signal(&self, handler_id: &SignalHandlerId)

Block a given signal handler. Read more
Source§

fn unblock_signal(&self, handler_id: &SignalHandlerId)

Unblock a given signal handler.
Source§

fn stop_signal_emission(&self, signal_id: SignalId, detail: Option<Quark>)

Stop emission of the currently emitted signal.
Source§

fn stop_signal_emission_by_name(&self, signal_name: &str)

Stop emission of the currently emitted signal by the (possibly detailed) signal name.
Source§

fn connect<F>( &self, signal_name: &str, after: bool, callback: F, ) -> SignalHandlerId
where F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static,

Connect to the signal signal_name on this object. Read more
Source§

fn connect_id<F>( &self, signal_id: SignalId, details: Option<Quark>, after: bool, callback: F, ) -> SignalHandlerId
where F: Fn(&[Value]) -> Option<Value> + Send + Sync + 'static,

Connect to the signal signal_id on this object. Read more
Source§

fn connect_local<F>( &self, signal_name: &str, after: bool, callback: F, ) -> SignalHandlerId
where F: Fn(&[Value]) -> Option<Value> + 'static,

Connect to the signal signal_name on this object. Read more
Source§

fn connect_local_id<F>( &self, signal_id: SignalId, details: Option<Quark>, after: bool, callback: F, ) -> SignalHandlerId
where F: Fn(&[Value]) -> Option<Value> + 'static,

Connect to the signal signal_id on this object. Read more
Source§

unsafe fn connect_unsafe<F>( &self, signal_name: &str, after: bool, callback: F, ) -> SignalHandlerId
where F: Fn(&[Value]) -> Option<Value>,

Connect to the signal signal_name on this object. Read more
Source§

unsafe fn connect_unsafe_id<F>( &self, signal_id: SignalId, details: Option<Quark>, after: bool, callback: F, ) -> SignalHandlerId
where F: Fn(&[Value]) -> Option<Value>,

Connect to the signal signal_id on this object. Read more
Source§

fn connect_closure( &self, signal_name: &str, after: bool, closure: RustClosure, ) -> SignalHandlerId

Connect a closure to the signal signal_name on this object. Read more
Source§

fn connect_closure_id( &self, signal_id: SignalId, details: Option<Quark>, after: bool, closure: RustClosure, ) -> SignalHandlerId

Connect a closure to the signal signal_id on this object. Read more
Source§

fn watch_closure(&self, closure: &impl AsRef<Closure>)

Limits the lifetime of closure to the lifetime of the object. When the object’s reference count drops to zero, the closure will be invalidated. An invalidated closure will ignore any calls to invoke_with_values, or invoke when using Rust closures.
Source§

fn emit<R>(&self, signal_id: SignalId, args: &[&dyn ToValue]) -> R

Emit signal by signal id. Read more
Source§

fn emit_with_values(&self, signal_id: SignalId, args: &[Value]) -> Option<Value>

Same as Self::emit but takes Value for the arguments.
Source§

fn emit_by_name<R>(&self, signal_name: &str, args: &[&dyn ToValue]) -> R

Emit signal by its name. Read more
Source§

fn emit_by_name_with_values( &self, signal_name: &str, args: &[Value], ) -> Option<Value>

Emit signal by its name. Read more
Source§

fn emit_by_name_with_details<R>( &self, signal_name: &str, details: Quark, args: &[&dyn ToValue], ) -> R

Emit signal by its name with details. Read more
Source§

fn emit_by_name_with_details_and_values( &self, signal_name: &str, details: Quark, args: &[Value], ) -> Option<Value>

Emit signal by its name with details. Read more
Source§

fn emit_with_details<R>( &self, signal_id: SignalId, details: Quark, args: &[&dyn ToValue], ) -> R

Emit signal by signal id with details. Read more
Source§

fn emit_with_details_and_values( &self, signal_id: SignalId, details: Quark, args: &[Value], ) -> Option<Value>

Emit signal by signal id with details. Read more
Source§

fn disconnect(&self, handler_id: SignalHandlerId)

Disconnect a previously connected signal handler.
Source§

fn connect_notify<F>(&self, name: Option<&str>, f: F) -> SignalHandlerId
where F: Fn(&T, &ParamSpec) + Send + Sync + 'static,

Connect to the notify signal of the object. Read more
Source§

fn connect_notify_local<F>(&self, name: Option<&str>, f: F) -> SignalHandlerId
where F: Fn(&T, &ParamSpec) + 'static,

Connect to the notify signal of the object. Read more
Source§

unsafe fn connect_notify_unsafe<F>( &self, name: Option<&str>, f: F, ) -> SignalHandlerId
where F: Fn(&T, &ParamSpec),

Connect to the notify signal of the object. Read more
Source§

fn notify(&self, property_name: &str)

Notify that the given property has changed its value. Read more
Source§

fn notify_by_pspec(&self, pspec: &ParamSpec)

Notify that the given property has changed its value. Read more
Source§

fn downgrade(&self) -> WeakRef<T>

Downgrade this object to a weak reference.
Source§

fn add_weak_ref_notify<F>(&self, f: F) -> WeakRefNotify<T>
where F: FnOnce() + Send + 'static,

Add a callback to be notified when the Object is disposed.
Source§

fn add_weak_ref_notify_local<F>(&self, f: F) -> WeakRefNotify<T>
where F: FnOnce() + 'static,

Add a callback to be notified when the Object is disposed. Read more
Source§

fn bind_property<'a, 'f, 't, O>( &'a self, source_property: &'a str, target: &'a O, target_property: &'a str, ) -> BindingBuilder<'a, 'f, 't>
where O: ObjectType,

Bind property source_property on this object to the target_property on the target object. Read more
Source§

fn ref_count(&self) -> u32

Returns the strong reference count of this object.
Source§

unsafe fn run_dispose(&self)

Runs the dispose mechanism of the object. 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,

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,

Source§

impl<Super, Sub> MayDowncastTo<Sub> for Super
where Super: IsA<Super>, Sub: IsA<Super>,