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.65.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
.
Variant
s 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
IMPL
Boxed wrapper implementation.IMPL
BoxedInline wrapper implementation.Error
binding and helper trait.IMPL
Object wrapper implementation andObject
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
GObject
s 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
Thewrapper!
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 aroundClosure::new
that automatically type checks its arguments at run-time. - The same as
closure!
but usesClosure::new_local
as a constructor. This is useful for closures which can’t be sent across threads. See the documentation ofclosure!
for details. - debug
log
andlog_macros
A macro which behaves exactly aslog::debug!
except that it sets the current log target to the contents of aG_LOG_DOMAIN
constant (and fails to build if not defined). - error
log
andlog_macros
A macro which behaves exactly aslog::error!
except that it sets the current log target to the contents of aG_LOG_DOMAIN
constant (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
GString
using 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
andlog_macros
A macro which behaves exactly aslog::info!
except that it sets the current log target to the contents of aG_LOG_DOMAIN
constant (and fails to build if not defined). - Macro used to log using GLib structured logging system.
- trace
log
andlog_macros
A macro which behaves exactly aslog::trace!
except that it sets the current log target to the contents of aG_LOG_DOMAIN
constant (and fails to build if not defined). - warn
log
andlog_macros
A macro which behaves exactly aslog::warn!
except that it sets the current log target to the contents of aG_LOG_DOMAIN
constant (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_72
TheBindingGroup
can be used to bind multiple properties from an object collectively. - BindingGroupBuilder
v2_72
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 aglib::object::Object
is needed. The inserted value can then be borrowed as a Rust type, by using the various provided methods. - Contains the public fields of a GByteArray.
- A shared immutable byte slice (the equivalent of
Rc<[u8]>
). - An opaque structure representing a checksumming operation.
- A
CollationKey
allows ordering strings using the linguistically correct rules for the current locale. - An opaque structure that represents a date and time, including a time zone.
- 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
. - FileSetContentsFlags
v2_66
Flags to pass tofile_set_contents_full()
to affect its safety and performance. - A
FilenameCollationKey
allows 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
flags
for dynamically, at runtime, querying the values of the enum and using them - Representation of a single flags value of a
FlagsClass
. - Flags to modify the format of the string returned by
format_size_full()
. - 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.
- GlibLogger
log
An implementation of alog
compatible logger which logs over glib logging facilities. - The GIConv struct wraps an
iconv()
conversion descriptor. It contains private data and should only be accessed using the following functions. - A bitwise combination representing a condition to watch for on an event source.
- Task failure from awaiting a
JoinHandle
. - A handle to a task running on a
MainContext
. - The GKeyFile struct contains only private data and should not be accessed directly.
- Flags which influence the parsing.
- Structure representing a single field in a structured log entry.
- Flags specifying the level of log messages.
- The
GMainContext
struct is an opaque data type representing a set of sources to be handled in a main loop. - MainContextFlags
v2_72
Flags to pass toMainContext::with_flags()
which affect the behaviour of aMainContext
. - The
GMainLoop
struct is an opaque data type representing the main event loop of a GLib or GTK+ application. - A parse context is used to parse a stream of bytes that you expect to contain marked-up text.
- Flags which modify individual options.
- Through the
ParamFlags
flag values, certain aspects of parameters can be configured. - A
Receiver
that can be attached to a main context to receive items from its correspondingSender
orSyncSender
. - 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 signal flags are used to specify a signal’s behaviour.
- SignalGroup
v2_74
SignalGroup
manages to simplify the process of connecting many signals to aObject
as a group. As such there is no API to disconnect a signal from the group. - The
GSource
struct is an opaque data type representing an event source. - Represents a
Future
around aglib::Source
. The future will be resolved once the source has provided a value - Represents a
Stream
around aglib::Source
. The stream will be provide all values that are provided by the source - Variant of
JoinHandle
that is returned fromMainContext::spawn_from_within
. - A
SyncSender
that can be used to send items to the corresponding main context receiver. - A handle to a thread running on a
ThreadPool
. - 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.- Uri
v2_66
TheUri
type and related functions can be used to parse URIs into their components, and build valid URIs from individual components. - UriFlags
v2_66
Flags that describe a URI. - UriHideFlags
v2_66
Flags describing what parts of the URI to hide inUri::to_string_partial()
. Note thatPASSWORD
andAUTH_PARAMS
will only work if theUri
was parsed with the corresponding flags. - UriParamsFlags
v2_66
Flags modifying the way parameters are handled byg_uri_parse_params()
andGUriParamsIter
. VariantDict
is a mutable key/value store where the keys are always strings and the values areVariant
s.- 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
- The hashing algorithm to be used by
Checksum
when performing the digest of some data. - Error codes returned by character set conversion routines.
- A wrapper for
ConvertError
that can hold an offset into the input string. - Values corresponding to
errno
codes returned from file operations on UNIX. Unlikeerrno
codes, GFileError values are available on all systems, even Windows. The exact meaning of each code depends on what sort of file operation you were performing; the UNIX documentation gives more details. The following error code descriptions come from the GNU C Library manual, and are under the copyright of that manual. - Error type holding all possible failures when creating a
GStr
reference. - 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::Error
that can hold an offset into an input string. - Error codes returned by key file parsing.
- Return values from
GLogWriterFuncs
to indicate whether the given log entry was successfully handled by the writer, or whether there was an error in handling it (and hence a fallback writer should be used). - Error codes returned by markup parsing.
- Defines how a Unicode string is transformed in a canonical form, standardizing such issues as whether a character with an accent is represented as a base character and combining accent or as a single precomposed character. Unicode strings should generally be normalized before comparing them.
- 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 withPangoScript
. - UriError
v2_66
Error codes returned byUri
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 correspondinglog
functions.
Statics
- The set of uppercase ASCII alphabet characters. Used for specifying valid identifier characters in
GScannerConfig
. - The set of ASCII digits. Used for specifying valid identifier characters in
GScannerConfig
. - The set of lowercase ASCII alphabet characters. Used for specifying valid identifier characters in
GScannerConfig
. - The name of the main group of a desktop entry file, as defined in the Desktop Entry Specification. Consult the specification for more details about the meanings of the keys below.
- A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string list giving the available application actions. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings giving the categories in which the desktop entry should be shown in a menu. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the tooltip for the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a boolean set to true if the application is D-Bus activatable. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the command line to execute. It is only valid for desktop entries with theApplication
type. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the generic name of the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the desktop entry has been deleted by the user. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the name of the icon to be displayed for the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings giving the MIME types supported by this desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a localized string giving the specific name of the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings identifying the environments that should not display the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the desktop entry should be shown in menus. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a list of strings identifying the environments that should display the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string containing the working directory to run the program in. It is only valid for desktop entries with theApplication
type. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the application supports the Startup Notification Protocol Specification. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is string identifying the WM class or name hint of a window that the application will create, which can be used to emulate Startup Notification with older applications. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a boolean stating whether the program should be run in a terminal window. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the file name of a binary on disk used to determine if the program is actually installed. It is only valid for desktop entries with theApplication
type. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the type of the desktop entry. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the URL to access. It is only valid for desktop entries with theLink
type. - A key under
KEY_FILE_DESKTOP_GROUP
, whose value is a string giving the version of the Desktop Entry Specification used for the desktop entry file. - The value of the
KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing applications. - The value of the
KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing directories. - The value of the
KEY_FILE_DESKTOP_KEY_TYPE
, key for desktop entries representing links to documents. - If a long option in the main group has this name, it is not treated as a regular option. Instead it collects all non-option arguments which would otherwise be left in
argv
. The option must be of typeOptionArg::Callback
,OptionArg::StringArray
orOptionArg::FilenameArray
. - The standard delimiters, used in
g_strdelimit()
. - Creates a unique temporary directory for each unit test and uses
g_set_user_dirs()
to set XDG directories to point into subdirectories of it for the duration of the unit test. The directory tree is cleaned up after the test finishes successfully. Note that this doesn’t take effect untilg_test_run()
is called, so calls to (for example)g_get_user_home_dir()
will return the system-wide value when made in a test program’smain()
function. - Generic delimiters characters as defined in RFC 3986. Includes
:/?#[]@
. - Subcomponent delimiter characters as defined in RFC 3986. Includes
!$&'()*+,;=
.
Traits
- A trait implemented by the various
ParamSpec
builder 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 manyProperty
s together. The finalParamSpec
will be the one of the innermost type - A container type implementing this trait can be read by the default getter generated by the
Props
macro. - A container type implementing this trait can be written by the default setter generated by the
Props
macro. - A container type implementing this trait can be written by the default setter generated by the
Props
macro. 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
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 - console_charset
v2_62
- Add a timeout to a
Future
. - Add a timeout to a
Future
. - 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. - 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. - Sets whether GLib log functions output to stderr or stdout.
- os_info
v2_64
- Same as
get_prgname()
. - 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. - Same as
set_prgname()
. - Parses a command line into an argument vector, in much the same way the shell would, but without many of the expansions the shell would perform (variable expansion, globs, operators, filename expansion, etc. are not supported).
- Quotes a string so that the shell (/bin/sh) will interpret the quoted string to mean
unquoted_string
. - Unquotes a string as the shell (/bin/sh) would.
- Gets the smallest prime number from a built-in array of primes which is larger than
num
. This is used within GLib to calculate the optimum size of aGHashTable
. - Executes a child program asynchronously.
- spawn_async_with_fds
v2_58
and non-Windows - spawn_async_with_pipesNon-Windows
- spawn_check_exit_statusDeprecatedAn old name for
spawn_check_wait_status()
, deprecated because its name is misleading. - Set
error
ifwait_status
indicates the child exited abnormally (e.g. with a nonzero exit code, or via a fatal signal). - A simple version of
spawn_async()
that parses a command line withshell_parse_argv()
and passes it tospawn_async()
. - 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. - Looks up the Unicode script for
iso15924
. ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is ‘Arab’. This function accepts four letter codes encoded as aguint32
in a big-endian fashion. That is, the code expected for Arabic is 0x41726162 (0x41 is ASCII code for ‘A’, 0x72 is ASCII code for ‘r’, etc). - Looks up the ISO 15924 code for
script
. ISO 15924 assigns four-letter codes to scripts. For example, the code for Arabic is ‘Arab’. The four letter codes are encoded as aguint32
by this function in a big-endian fashion. That is, the code returned for Arabic is 0x41726162 (0x41 is ASCII code for ‘A’, 0x72 is ASCII code for ‘r’, etc). - Similar to the UNIX
pipe()
call, but on modern systems like Linux uses thepipe2()
system call, which atomically creates a pipe with the configured flags. The only supported flag currently isFD_CLOEXEC
. If for example you want to configureO_NONBLOCK
, that must still be done separately withfcntl()
. - 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 - A wrapper for the POSIX
unlink()
function. Theunlink()
function deletes a name from the filesystem. If this was the last link to the file and no processes have it opened, the diskspace occupied by the file is freed. - To set the default print handler, use the
set_print_handler
function. - To set the default print handler, use the
set_printerr_handler
function. - Removes an environment variable from the environment.
- user_state_dir
v2_72
- Pauses the current thread for the given number of microseconds.
- Parses the string
str
and verify if it is a UUID. - Generates a random UUID (RFC 4122 version 4) as a string. It has the same randomness guarantees as
GRand
, so must not be used for cryptographic purposes such as key generation, nonces, salts or one-time pads.
Type Definitions
Attribute Macros
- Attribute macro for defining flags using the
bitflags
crate. This macro will also define aGFlags::type_
function and theglib::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 theglib::Value
traits. Optionally, the type can be marked asnullable
to get an implemention ofglib::value::ToValueOptional
. - Macro for deriving implementations of
glib::clone::Downgrade
andglib::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. - This macro enables you to derive object properties in a quick way.
- Derive macro for defining a
SharedType
::get_type
function and theglib::Value
traits. Optionally, the type can be marked asnullable
to get an implemention ofglib::value::ToValueOptional
. - Example
- Derive macro for serializing/deserializing custom structs/enums as
glib::Variant
s.