Expand description
Rust GLib and GObject bindings
Rust bindings and wrappers for GLib, part of gtk-rs-core.
GLib 2.56 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.64.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:
# This will not compile
[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::BorrowedObject;pub use self::object::Cast;pub use self::object::CastNone;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 self::FileError;pub use collections::ptr_slice::IntoPtrSlice;pub use collections::strv::IntoStrV;pub use collections::List;pub use collections::PtrSlice;pub use collections::SList;pub use collections::Slice;pub use collections::StrV;pub use self::char::*;pub use self::source::*;
Modules
IMPLBoxed wrapper implementation.IMPLBoxedInline wrapper implementation.Errorbinding and helper trait.IMPLObject wrapper implementation andObjectbinding.- Traits and essential types intended for blanket imports.
IMPLShared (reference counted) wrapper implementation.IMPLLow 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.
Valuebinding and helper traits.Variantbinding and helper traits.IMPLThewrapper!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
Closureobject. This is a wrapper aroundClosure::newthat automatically type checks its arguments at run-time. - The same as
closure!but usesClosure::new_localas a constructor. This is useful for closures which can’t be sent across threads. See the documentation ofclosure!for details. - debug
log_macrosA macro which behaves exactly aslog::debug!except that it sets the current log target to the contents of aG_LOG_DOMAINconstant (and fails to build if not defined). - error
log_macrosA macro which behaves exactly aslog::error!except that it sets the current log target to the contents of aG_LOG_DOMAINconstant (and fails to build if not defined). - This macro returns the name of the enclosing function. As the internal implementation is based on the
std::any::type_name, this macro derives all the limitations of this function. - 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.
- Creates a
GStringusing interpolation of runtime expressions. - 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.
- info
log_macrosA macro which behaves exactly aslog::info!except that it sets the current log target to the contents of aG_LOG_DOMAINconstant (and fails to build if not defined). - Macro used to log using GLib structured logging system.
- trace
log_macrosA macro which behaves exactly aslog::trace!except that it sets the current log target to the contents of aG_LOG_DOMAINconstant (and fails to build if not defined). - warn
log_macrosA macro which behaves exactly aslog::warn!except that it sets the current log target to the contents of aG_LOG_DOMAINconstant (and fails to build if not defined). - Defines a wrapper type and implements the appropriate traits.
Structs
- Flags to be passed to
ObjectExt::bind_property()or [ObjectExt::bind_property_full()][crate::prelude::ObjectExt::bind_property_full()]. - BindingGroup
v2_72TheBindingGroupcan be used to bind multiple properties from an object collectively. - BindingGroupBuilder
v2_72Builder for binding group bindings. - This is a subclass of
glib::object::Objectcapable of storing any Rust type. It let’s you insert a Rust type anywhere aglib::object::Objectis 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
CollationKeyallows ordering strings using the linguistically correct rules for the current locale. - Representation of an
enumfor dynamically, at runtime, querying the values of the enum and using them. - Representation of a single enum value of an
EnumClass. - FileSetContentsFlags
v2_66 - A
FilenameCollationKeyallows ordering file names using the linguistically correct rules for the current locale. Compared toCollationKey, 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
flagsfor dynamically, at runtime, querying the values of the enum and using them - Representation of a single flags value of a
FlagsClass. - The error returned when a future times out.
- Representation of a borrowed
GString. - Error type indicating that a buffer had unexpected nul-bytes.
- A type representing an owned, C-compatible, nul-terminated UTF-8 string.
- A mutable text buffer that grows automatically.
- Error type indicating that a buffer had unexpected nul-bytes.
- Error type indicating that a buffer did not have a trailing nul-byte.
NULL-terminated UTF-8 string as stored in [StrV].- Error type indicating that a buffer had invalid UTF-8.
- An implementation of a
logcompatible logger which logs over glib logging facilities. - Task failure from awaiting a
JoinHandle. - A handle to a task running on a
MainContext. - Structure representing a single field in a structured log entry.
- MainContextFlags
v2_72 - A
Receiverthat can be attached to a main context to receive items from its correspondingSenderorSyncSender. - A
Senderthat can be used to send items to the corresponding main context receiver. - SignalGroup
v2_74 - Represents a
Futurearound aglib::Source. The future will be resolved once the source has provided a value - Represents a
Streamaround aglib::Source. The stream will be provide all values that are provided by the source - Variant of
JoinHandlethat is returned fromMainContext::spawn_from_within. - A
SyncSenderthat can be used to send items to the corresponding main context receiver. - A handle to a thread running on a
ThreadPool. - A value representing an interval of time, in microseconds.
- Uri
v2_66 - UriFlags
v2_66Flags that describe a URI. - UriHideFlags
v2_66Flags describing what parts of the URI to hide inUri::to_string_partial(). Note thatPASSWORDandAUTH_PARAMSwill only work if theUriwas parsed with the corresponding flags. - UriParamsFlags
v2_66Flags modifying the way parameters are handled byg_uri_parse_params()andGUriParamsIter. VariantDictis a mutable key/value store where the keys are always strings and the values areVariants.- Iterator over items in a variant.
- Iterator over items in a variant of type
as. - Describes
Varianttypes. - An iterator over the individual components of a tuple VariantTy.
- Describes
Varianttypes.
Enums
- A wrapper for
ConvertErrorthat can hold an offset into the input string. - Error type holding all possible failures when creating a
GStrreference. - Error type holding all possible failures when creating a
GString. - Enumeration of the possible domain handling behaviours for a
GlibLogger. - Enumeration of the possible formatting behaviours for a
GlibLogger. - A wrapper for
std::io::Errorthat can hold an offset into an input string. - UriError
v2_66Error codes returned byUrimethods. - 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
Variantinstances.
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 correspondinglogfunctions.
Statics
Traits
- A trait implemented by the various
ParamSpecbuilder types. - A type that can be used as a property. It covers every type which have an associated
ParamSpec(HasParamSpec) and some useful types wrappingHasParamSpec. The definition is recursive, so you can nest manyPropertys together. The finalParamSpecwill be the one of the innermost type - A container type implementing this trait can be read by the default getter generated by the
Propsmacro. - A container type implementing this trait can be written by the default setter generated by the
Propsmacro. - A container type implementing this trait can be written by the default setter generated by the
Propsmacro. It takes aFnOnce(&mut Self::Value)so that the caller may access nested fields of a struct by doing${Self::Value}.member
Functions
- Obtain the character set for the current locale.
- Create a
Futurethat will resolve once the child process with the given pid exits - Create a
Futurethat will resolve once the child process with the given pid exits - console_charset
v2_62 - 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 inmsgctxtid. If 0 is passed asmsgidoffset, 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 inmsgctxtid. - 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
contentsto a file namedfilename. This is a convenience wrapper around callingfile_set_contents_full()withflagsset toG_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTINGandmodeset to0666. - Writes all of
contentsto a file namedfilename, with good error checking. If a file calledfilenamealready 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
filename_to_utf8(), the result is guaranteed to be non-Noneeven 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 a string from UTF-8 to the encoding GLib uses for filenames. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the [current locale][setlocale].
- Converts an absolute filename to an escaped ASCII-encoded URI, with the path component following Section 3.3. of RFC 2396.
- Converts a string which is in the encoding used by GLib for filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8 for filenames; on other platforms, this function indirectly depends on the [current locale][setlocale].
- Add a timeout to a
Future. - Add a timeout to a
Future. - Returns the value of an environment variable.
- Return a name for the machine.
- Tests if
hostnamecontains segments with an ASCII-compatible encoding of an Internationalized Domain Name. If this returnstrue, you should decode the hostname withhostname_to_unicode()before displaying it to the user. - Tests if
hostnameis the string form of an IPv4 or IPv6 address. (Eg, “192.168.0.1”.) - Tests if
hostnamecontains Unicode characters. If this returnstrue, you need to encode the hostname withhostname_to_ascii()before using it in non-IDN-aware contexts. - Converts
hostnameto its canonical ASCII form; an ASCII-only string containing no uppercase letters and not ending with a trailing dot. - Converts
hostnameto its canonical presentation form; a UTF-8 string in Unicode normalization form C, containing no uppercase letters, no forbidden characters, and no ASCII-encoded segments, and not ending with a trailing dot. - Create a
Streamthat will provide a value every given number of milliseconds. - Create a
Streamthat will provide a value every given number of seconds. - Create a
Streamthat will provide a value every given number of seconds. - Create a
Streamthat 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”.
- Gets the names of all variables set in the environment.
- Converts a string from UTF-8 to the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the [current locale][setlocale]. On Windows this means the system codepage.
- Converts a string which is in the encoding used for strings by the C runtime (usually the same as that used by the operating system) in the [current locale][setlocale] into a UTF-8 string.
- Returns a list of derived variants of
locale, 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. This function handles territory, charset and extra locale modifiers. Seesetlocale(3)for information about locales and their format. - To set back the default print handler, use the
log_unset_default_handlerfunction. - To set the default print handler, use the
log_set_default_handlerfunction. - Sets whether GLib log functions output to stderr or stdout.
- Returns the currently firing source for this thread.
- Returns the depth of the stack of calls to
MainContext::dispatch()on anyMainContextin the current thread. That is, when called from the toplevel, it gives 0. When called from within a callback fromMainContext::iteration()(orMainLoop::run(), etc.) it returns 1. When called from within a callback to a recursive call toMainContext::iteration(), it returns 2. And so forth. - Escapes text so that the markup parser will parse it verbatim. Less than, greater than, ampersand, etc. are replaced with the corresponding entities. This function would typically be used when writing out a file to be parsed with the markup parser.
- Create a directory if it doesn’t already exist. Create intermediate parent directories as needed, too.
- Creates a temporary directory. See the
mkdtemp()documentation on most UNIX-like systems. - Creates a temporary directory. See the
mkdtemp()documentation on most UNIX-like systems. - Opens a temporary file. See the
mkstemp()documentation on most UNIX-like systems. - Opens a temporary file. See the
mkstemp()documentation on most UNIX-like systems. - Queries the system monotonic time.
- Determine the approximate number of threads that the system will schedule simultaneously for this process. This is intended to be used as a parameter to [
ThreadPool::new()][crate::ThreadPool::new()] for CPU bound tasks and similar cases. - Prompts the user with
[E]xit, [H]alt, show [S]tack trace or [P]roceed. This function is intended to be used for debugging use only. The following example shows how it can be used together with theg_log()functions. - Invokes gdb, which attaches to the current process and shows a stack trace. Called by
on_error_query()when the “[S]tack trace” option is selected. You can get the current process’s program name withg_get_prgname(), assuming that you have calledgtk_init()orgdk_init(). - os_info
v2_64Get information about the operating system. - Same as
get_prgname(). - Returns a random
gdoubleequally distributed over the range [0..1). - Returns a random
gdoubleequally distributed over the range [begin..end). - Return a random
guint32equally distributed over the range [0..2^32-1]. - Returns a random
gint32equally distributed over the range [begin..end-1]. - Sets the seed for the global random number generator, which is used by the g_random_* functions, to
seed. - Gets the real name of the user. This usually comes from the user’s entry in the
passwdfile. The encoding of the returned string is system-defined. (On Windows, it is, however, always UTF-8.) If the real user name cannot be determined, the string “Unknown” is returned. - Queries the system wall-clock time.
- Resets the cache used for
user_special_dir(), so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself. - Provides a glib log handler which routes all logging messages to the
log crate. - Sets a human-readable name for the application. This name should be localized if possible, and is intended for display to the user. Contrast with
g_set_prgname(), which sets a non-localized name.g_set_prgname()will be called automatically bygtk_init(), butset_application_name()will not. - To set back the default print handler, use the
unset_print_handlerfunction. - To set back the default print handler, use the
unset_printerr_handlerfunction. - Same as
set_prgname(). - Sets an environment variable. On UNIX, both the variable’s name and value can be arbitrary byte strings, except that the variable’s name cannot contain ‘=’. On Windows, they should be in UTF-8.
- spawn_async_with_fds
v2_58and non-Windows - spawn_async_with_pipesNon-Windows
- Returns an ordered list of base directories in which to access system-wide configuration information.
- Returns an ordered list of base directories in which to access system-wide application data.
- Create a
Futurethat will resolve after the given number of milliseconds. - Create a
Futurethat will resolve after the given number of seconds. - Create a
Futurethat will resolve after the given number of seconds. - Create a
Futurethat will resolve after the given number of milliseconds. - Gets the directory to use for temporary files.
- Create a
Futurethat will resolve once the given UNIX signal is raised - Create a
Futurethat will resolve once the given UNIX signal is raised - Create a
Streamthat will provide a value whenever the given UNIX signal is raised - Create a
Streamthat will provide a value whenever the given UNIX signal is raised - To set the default print handler, use the
set_print_handlerfunction. - To set the default print handler, use the
set_printerr_handlerfunction. - Returns a base directory in which to store non-essential, cached data specific to particular user.
- Returns a base directory in which to store user-specific application configuration information such as user preferences and settings.
- Returns a base directory in which to access application data such as icons that is customized for a particular user.
- Gets the user name of the current user. The encoding of the returned string is system-defined. On UNIX, it might be the preferred file name encoding, or something else, and there is no guarantee that it is even consistent on a machine. On Windows, it is always UTF-8.
- Returns a directory that is unique to the current user on the local system.
- Returns the full path of a special directory using its logical id.
- user_state_dir
v2_72Returns a base directory in which to store state files specific to particular user.
Type Definitions
Attribute Macros
- Attribute macro for defining flags using the
bitflagscrate. This macro will also define aGFlags::type_function and theglib::Valuetraits. - Macro for boilerplate of
ObjectInterfaceimplementations. - Macro for boilerplate of
ObjectSubclassimplementations.
Derive Macros
- Derive macro for defining a
BoxedType::type_function and theglib::Valuetraits. Optionally, the type can be marked asnullableto get an implemention ofglib::value::ToValueOptional. - Macro for deriving implementations of
glib::clone::Downgradeandglib::clone::Upgradetraits and a weak type. - Derive macro for register a rust enum in the glib type system and derive the the
glib::Valuetraits. - Derive macro for defining a GLib error domain and its associated
ErrorDomaintrait. - This macro enables you to derive object properties in a quick way.
- Derive macro for defining a
SharedType::get_typefunction and theglib::Valuetraits. Optionally, the type can be marked asnullableto get an implemention ofglib::value::ToValueOptional. - Example
- Derive macro for serializing/deserializing custom structs/enums as
glib::Variants.