Crate glib

source · []
Expand description

Rust GLib and GObject bindings

Rust bindings and wrappers for GLib, part of gtk-rs-core.

GLib 2.48 is the lowest supported version for the underlying library.

This library contains bindings to GLib and GObject types and APIs as well as common building blocks used in both handmade and machine generated bindings to GTK and other GLib-based libraries.

It is the foundation for higher level libraries with uniform Rusty (safe and strongly typed) APIs. It avoids exposing GLib-specific data types where possible and is not meant to provide comprehensive GLib bindings, which would often amount to duplicating the Rust Standard Library or other utility crates.

Minimum supported Rust version

Currently, the minimum supported Rust version is 1.56.0.

Dynamic typing

Most types in the GLib family have Type identifiers. Their corresponding Rust types implement the StaticType trait.

A dynamically typed Value can carry values of any StaticType. Variants can carry values of StaticVariantType.

Errors

Errors are represented by Error, which can carry values from various error domains such as FileError.

Objects

Each class and interface has a corresponding smart pointer struct representing an instance of that type (e.g. Object for GObject or gtk::Widget for GtkWidget). They are reference counted and feature interior mutability similarly to Rust’s Rc<RefCell<T>> idiom. Consequently, cloning objects is cheap and their methods never require mutable borrows. Two smart pointers are equal if they point to the same object.

The root of the object hierarchy is Object. Inheritance and subtyping is denoted with the IsA marker trait. The Cast trait enables upcasting and downcasting.

Interfaces and non-leaf classes also have corresponding traits (e.g. ObjectExt or gtk::WidgetExt), which are blanketly implemented for all their subtypes.

You can create new subclasses of Object or other object types. Look at the module’s documentation for further details and a code example.

Under the hood

GLib-based libraries largely operate on pointers to various boxed or reference counted structures so the bindings have to implement corresponding smart pointers (wrappers), which encapsulate resource management and safety checks. Such wrappers are defined via the wrapper macro, which uses abstractions defined in the wrapper, boxed, shared and object modules.

The translate module defines and partly implements conversions between high level Rust types (including the aforementioned wrappers) and their FFI counterparts.

Documentation

Using

We recommend using crates from crates.io, as demonstrated here.

If you want to track the bleeding edge, use the git dependency instead:

[dependencies]
glib = { git = "https://github.com/gtk-rs/gtk-rs-core.git", package = "glib" }

Avoid mixing versioned and git crates like this:

[dependencies]
glib = "0.13"
glib = { git = "https://github.com/gtk-rs/gtk-rs-core.git", package = "glib" }

License

glib is available under the MIT License, please refer to it.

Re-exports

pub use ffi;
pub use gobject_ffi;
pub use self::closure::Closure;
pub use self::closure::RustClosure;
pub use self::error::BoolError;
pub use self::error::Error;
pub use self::object::Cast;
pub use self::object::Class;
pub use self::object::InitiallyUnowned;
pub use self::object::Interface;
pub use self::object::IsA;
pub use self::object::Object;
pub use self::object::ObjectExt;
pub use self::object::ObjectType;
pub use self::object::SendWeakRef;
pub use self::object::WeakRef;
pub use self::signal::signal_handler_block;
pub use self::signal::signal_handler_disconnect;
pub use self::signal::signal_handler_unblock;
pub use self::signal::signal_stop_emission_by_name;
pub use self::signal::SignalHandlerId;
pub use self::types::ILong;
pub use self::types::Pointer;
pub use self::types::StaticType;
pub use self::types::StaticTypeExt;
pub use self::types::Type;
pub use self::types::ULong;
pub use self::value::BoxedValue;
pub use self::value::SendValue;
pub use self::value::ToSendValue;
pub use self::value::ToValue;
pub use self::value::Value;
pub use self::variant::FixedSizeVariantArray;
pub use self::variant::FixedSizeVariantType;
pub use self::variant::FromVariant;
pub use self::variant::StaticVariantType;
pub use self::variant::ToVariant;
pub use self::variant::Variant;
pub use collections::List;
pub use collections::PtrSlice;
pub use collections::SList;
pub use collections::Slice;
pub use self::char::*;
pub use self::source::*;
pub use self::send_unique::SendUnique;
pub use self::send_unique::SendUniqueCell;

Modules

IMPL Boxed wrapper implementation.

IMPL BoxedInline wrapper implementation.

Error binding and helper trait.

IMPL Object wrapper implementation and Object binding.

Traits and essential types intended for blanket imports.

IMPL Shared (reference counted) wrapper implementation.

IMPL Low level signal support.

Module containing infrastructure for subclassing GObjects and registering boxed types.

Translation between GLib/GLib-based FFI types and their Rust counterparts.

Runtime type information.

Value binding and helper traits.

Variant binding and helper traits.

IMPL The wrapper! macro and miscellaneous wrapper traits.

Macros

Generic error used for functions that fail without any further information

Macro for passing variables as strong or weak references into a closure.

Macro for creating a Closure object. This is a wrapper around Closure::new that automatically type checks its arguments at run-time.

The same as closure! but uses Closure::new_local as a constructor. This is useful for closures which can’t be sent across threads. See the documentation of closure! for details.

debuglog_macros

A macro which behaves exactly as log::debug! except that it sets the current log target to the contents of a G_LOG_DOMAIN constant (and fails to build if not defined).

errorlog_macros

A macro which behaves exactly as log::error! except that it sets the current log target to the contents of a G_LOG_DOMAIN constant (and fails to build if not defined).

Macro used to log using GLib logging system. It uses g_log.

Macro used to log using GLib logging system. It uses g_log.

Macro used to log using GLib logging system. It uses g_log.

Macro used to log using GLib logging system. It uses g_log.

Macro used to log using GLib logging system. It uses g_log.

Macro used to log using GLib logging system. It uses g_log.

Macro used to print messages. It uses g_print.

Macro used to print error messages. It uses g_printerr.

Macro used to log using GLib logging system. It uses g_log.

Wrapper implementations for BoxedInline types. See wrapper!.

Wrapper implementations for Boxed types. See wrapper!.

ObjectType implementations for Object types. See wrapper!.

Wrapper implementations for shared types. See wrapper!.

Converts a static string literal into a static nul-terminated string.

infolog_macros

A macro which behaves exactly as log::info! except that it sets the current log target to the contents of a G_LOG_DOMAIN constant (and fails to build if not defined).

Macro used to log using GLib structured logging system.

tracelog_macros

A macro which behaves exactly as log::trace! except that it sets the current log target to the contents of a G_LOG_DOMAIN constant (and fails to build if not defined).

warnlog_macros

A macro which behaves exactly as log::warn! except that it sets the current log target to the contents of a G_LOG_DOMAIN constant (and fails to build if not defined).

Defines a wrapper type and implements the appropriate traits.

Structs

Builder for binding group bindings.

This is a subclass of glib::object::Object capable of storing any Rust type. It let’s you insert a Rust type anywhere a glib::object::Object is needed. The inserted value can then be borrowed as a Rust type, by using the various provided methods.

A shared immutable byte slice (the equivalent of Rc<[u8]>).

A CollationKey allows ordering strings using the linguistically correct rules for the current locale.

Representation of an enum for dynamically, at runtime, querying the values of the enum and using them.

Representation of a single enum value of an EnumClass.

A FilenameCollationKey allows ordering file names using the linguistically correct rules for the current locale. Compared to CollationKey, filename collation keys take into consideration dots and other characters commonly found in file names.

Builder for conveniently setting/unsetting flags and returning a Value.

Representation of a flags for dynamically, at runtime, querying the values of the enum and using them

Representation of a single flags value of a FlagsClass.

Representaion of a borrowed GString.

A type representing an owned, C-compatible, nul-terminated UTF-8 string.

A mutable text buffer that grows automatically.

An implementation of a log compatible logger which logs over glib logging facilities.

Structure representing a single field in a structured log entry.

Flags to pass to MainContext::with_flags() which affect the behaviour of a MainContext.

The GMainLoop struct is an opaque data type representing the main event loop of a GLib or GTK+ application.

Flags which modify individual options.

Through the ParamFlags flag values, certain aspects of parameters can be configured.

ParamSpec is an object structure that encapsulates the metadata required to specify parameters, such as e.g. Object properties.

A Receiver that can be attached to a main context to receive items from its corresponding Sender or SyncSender.

A Sender that can be used to send items to the corresponding main context receiver.

The signal flags are used to specify a signal’s behaviour.

The GSource struct is an opaque data type representing an event source.

Represents a Future around a glib::Source. The future will be resolved once the source has provided a value

Represents a Stream around a glib::Source. The stream will be provide all values that are provided by the source

Flags passed to g_spawn_sync(), spawn_async() and g_spawn_async_with_pipes().

A SyncSender that can be used to send items to the corresponding main context receiver.

The ThreadPool struct represents a thread pool. It has three public read-only members, but the underlying struct is bigger, so you must not copy this struct.

A value representing an interval of time, in microseconds.

TimeZone is an opaque structure whose members cannot be accessed directly.

The Uri type and related functions can be used to parse URIs into their components, and build valid URIs from individual components.

Flags that describe a URI.

Flags describing what parts of the URI to hide in Uri::to_string_partial(). Note that PASSWORD and AUTH_PARAMS will only work if the Uri was parsed with the corresponding flags.

Flags modifying the way parameters are handled by g_uri_parse_params() and GUriParamsIter.

VariantDict is a mutable key/value store where the keys are always strings and the values are Variants.

Iterator over items in a variant.

Iterator over items in a variant of type as.

Describes Variant types.

An iterator over the individual components of a tuple VariantTy.

Describes Variant types.

Enums

Enumeration of the possible domain handling behaviours for a GlibLogger.

Enumeration of the possible formatting behaviours for a GlibLogger.

The OptionArg enum values determine which type of extra argument the options expect to find. If an option expects an extra argument, it can be specified in several ways; with a short option: -x arg, with a long option: --name arg or combined in a single argument: --name=arg.

An enumeration specifying the base position for a g_io_channel_seek_position() operation.

Disambiguates a given time in two ways.

The UnicodeScript enumeration identifies different writing systems. The values correspond to the names as defined in the Unicode standard. The enumeration has been added in GLib 2.14, and is interchangeable with PangoScript.

Error codes returned by Uri methods.

These are logical ids for special directories which are defined depending on the platform used. You should use user_special_dir() to retrieve the full path associated to the logical id.

The range of possible top-level types of Variant instances.

Constants

This is the log domain used by the clone! macro. If you want to use a custom logger (it prints to stdout by default), you can set your own logger using the corresponding log functions.

Statics

Traits

Functions

A wrapper for the POSIX access() function. This function is used to test a pathname for one or several of read, write or execute permissions, or just existence.

Gets a human-readable name for the application, as set by set_application_name(). This name should be localized if possible, and is intended for display to the user. Contrast with g_get_prgname(), which gets a non-localized name. If set_application_name() has not been called, returns the result of g_get_prgname() (which may be None if g_set_prgname() has also not been called).

Decode a sequence of Base-64 encoded text into binary data. Note that the returned binary data is not necessarily zero-terminated, so it should not be used as a character string.

Encode a sequence of binary data into its Base-64 stringified representation.

Obtain the character set for the current locale.

Checks that the GLib library in use is compatible with the given version.

Create a Future that will resolve once the child process with the given pid exits

Create a Future that will resolve once the child process with the given pid exits

Gets the character set for the current locale.

Computes the checksum for a binary data. This is a convenience wrapper for Checksum::new(), Checksum::string() and g_checksum_free().

Computes the checksum for a binary data of length. This is a convenience wrapper for Checksum::new(), Checksum::string() and g_checksum_free().

Computes the HMAC for a binary data. This is a convenience wrapper for g_hmac_new(), g_hmac_get_string() and g_hmac_unref().

Computes the HMAC for a binary data of length. This is a convenience wrapper for g_hmac_new(), g_hmac_get_string() and g_hmac_unref().

Obtains the character set used by the console attached to the process, which is suitable for printing output to the terminal.

This is a variant of dgettext() that allows specifying a locale category instead of always using LC_MESSAGES. See dgettext() for more information about how this functions differs from calling dcgettext() directly.

This function is a wrapper of dgettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

This function is a wrapper of dngettext() which does not translate the message if the default domain as set with textdomain() has no translations for the current locale.

This function is a variant of dgettext() which supports a disambiguating message context. GNU gettext uses the ‘\004’ character to separate the message context and message id in msgctxtid. If 0 is passed as msgidoffset, this function will fall back to trying to use the deprecated convention of using “|” as a separation character.

This function is a variant of dgettext() which supports a disambiguating message context. GNU gettext uses the ‘\004’ character to separate the message context and message id in msgctxtid.

Gets the list of environment variables for the current process.

Reads an entire file into allocated memory, with good error checking.

Opens a file for writing in the preferred directory for temporary files (as returned by tmp_dir()).

Writes all of contents to a file named filename. This is a convenience wrapper around calling file_set_contents_full() with flags set to G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING and mode set to 0666.

Writes all of contents to a file named filename, with good error checking. If a file called filename already exists it will be overwritten.

Returns the display basename for the particular filename, guaranteed to be valid UTF-8. The display name might not be identical to the filename, for instance there might be problems converting it to UTF-8, and some files can be translated in the display.

Converts a filename into a valid UTF-8 string. The conversion is not necessarily reversible, so you should keep the original around and use the return value of this function only for display purposes. Unlike g_filename_to_utf8(), the result is guaranteed to be non-None even if the filename actually isn’t in the GLib file name encoding.

Converts an escaped ASCII-encoded URI to a local filename in the encoding used for filenames.

Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.

Locates the first executable named program in the user’s path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or None if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and None otherwise.

Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (kB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string “3.2 MB”. The returned string is UTF-8, and may use a non-breaking space to separate the number and units, to ensure they aren’t separated when line wrapped.

Formats a size.

Gets the current user’s home directory.

Return a name for the machine.

Create a Stream that will provide a value every given number of milliseconds.

Create a Stream that will provide a value every given number of seconds.

Create a Stream that will provide a value every given number of seconds.

Create a Stream that will provide a value every given number of milliseconds.

Computes a list of applicable locale names, which can be used to e.g. construct locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale “C”.

Computes a list of applicable locale names with a locale category name, which can be used to construct the fallback locale-dependent filenames or search paths. The returned list is sorted from most desirable to least desirable and always contains the default locale “C”.

To set back the default print handler, use the log_unset_default_handler function.

To set the default print handler, use the log_set_default_handler function.

os_infov2_64

Provides a glib log handler which routes all logging messages to the log crate.

To set back the default print handler, use the unset_print_handler function.

To set back the default print handler, use the unset_printerr_handler function.

spawn_async_with_fdsv2_58 and non-Windows

Create a Future that will resolve after the given number of milliseconds.

Create a Future that will resolve after the given number of seconds.

Create a Future that will resolve after the given number of seconds.

Create a Future that will resolve after the given number of milliseconds.

Create a Future that will resolve once the given UNIX signal is raised

Create a Future that will resolve once the given UNIX signal is raised

Create a Stream that will provide a value whenever the given UNIX signal is raised

Create a Stream that will provide a value whenever the given UNIX signal is raised

To set the default print handler, use the set_print_handler function.

To set the default print handler, use the set_printerr_handler function.

Type Definitions

Attribute Macros

Attribute macro for defining flags using the bitflags crate. This macro will also define a GFlags::type_ function and the glib::Value traits.

Macro for boilerplate of ObjectInterface implementations.

Macro for boilerplate of ObjectSubclass implementations.

Derive Macros

Derive macro for defining a BoxedType::type_ function and the glib::Value traits.

Macro for deriving implementations of glib::clone::Downgrade and glib::clone::Upgrade traits and a weak type.

Derive macro for register a rust enum in the glib type system and derive the the [glib::Value] traits.

Derive macro for defining a GLib error domain and its associated ErrorDomain trait.

Derive macro for defining a SharedType::get_type function and the glib::Value traits.

Derive macro for serializing/deserializing custom structs as glib::Variants.