Crate glib

Source
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.70.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 gtk4::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 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 self::closure::Closure;
pub use self::closure::RustClosure;
pub use self::enums::EnumClass;
pub use self::enums::EnumValue;
pub use self::enums::FlagsBuilder;
pub use self::enums::FlagsClass;
pub use self::enums::FlagsValue;
pub use self::enums::UserDirectory;
pub use self::error::BoolError;
pub use self::error::Error;
pub use self::object::BorrowedObject;
pub use self::object::Class;
pub use self::object::InitiallyUnowned;
pub use self::object::Interface;
pub use self::object::Object;
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::Propagation;
pub use self::signal::SignalHandlerId;
pub use self::types::ILong;
pub use self::types::Pointer;
pub use self::types::Type;
pub use self::types::ULong;
pub use self::value::BoxedValue;
pub use self::value::SendValue;
pub use self::value::Value;
pub use self::variant::FixedSizeVariantArray;
pub use self::variant::Variant;
pub use self::FileError;
pub use collections::List;
pub use collections::PtrSlice;
pub use collections::SList;
pub use collections::Slice;
pub use collections::StrV;
pub use self::char::Char;
pub use self::char::UChar;
pub use self::match_info::MatchInfo;
pub use bitflags;
pub use glib_sys as ffi;
pub use gobject_sys as gobject_ffi;
pub use self::source::*;

Modules§

boxed
IMPL Boxed wrapper implementation.
boxed_inline
IMPL BoxedInline wrapper implementation.
char
clone
closure
collections
enums
error
Error binding and helper trait.
match_info
object
IMPL Object wrapper implementation and Object binding.
prelude
Traits and essential types intended for blanket imports.
property
regex
This module is inefficient and should not be used by Rust programs except for compatibility with GLib.Regex based APIs.
shared
IMPL Shared (reference counted) wrapper implementation.
signal
IMPL Low level signal support.
source
subclass
Module containing infrastructure for subclassing GObjects and registering boxed types.
thread_guard
translate
Translation between GLib/GLib-based FFI types and their Rust counterparts.
types
Runtime type information.
value
Value binding and helper traits.
variant
Variant binding and helper traits.
wrapper
IMPL The wrapper! macro and miscellaneous wrapper traits.

Macros§

bool_error
Generic error used for functions that fail without any further information
clone
Macro for passing variables as strong or weak references into a closure.
closure
Macro for creating a Closure object. This is a wrapper around Closure::new that automatically type checks its arguments at run-time.
closure_local
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 and log_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 and log_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).
function_name
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.
g_critical
Macro used to log using GLib logging system. It uses g_log.
g_debug
Macro used to log using GLib logging system. It uses g_log.
g_error
Macro used to log using GLib logging system. It uses g_log.
g_info
Macro used to log using GLib logging system. It uses g_log.
g_log
Macro used to log using GLib logging system. It uses g_log.
g_message
Macro used to log using GLib logging system. It uses g_log.
g_print
Macro used to print messages. It uses g_print.
g_printerr
Macro used to print error messages. It uses g_printerr.
g_warning
Macro used to log using GLib logging system. It uses g_log.
gformat
Creates a GString using interpolation of runtime expressions.
glib_boxed_inline_wrapper
Wrapper implementations for BoxedInline types. See wrapper!.
glib_boxed_wrapper
Wrapper implementations for Boxed types. See wrapper!.
glib_object_wrapper
ObjectType implementations for Object types. See wrapper!.
glib_shared_wrapper
Wrapper implementations for shared types. See wrapper!.
gstr
Converts a static string literal into a static nul-terminated string.
infolog and log_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).
log_structured
Macro used to log using GLib structured logging system.
result_from_gboolean
tracelog and log_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 and log_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).
wrapper
Defines a wrapper type and implements the appropriate traits.

Structs§

Binding
GLib type: GObject with reference counted clone semantics.
BindingFlags
BindingGroupv2_72
GLib type: GObject with reference counted clone semantics.
BindingGroupBuilderv2_72
Builder for binding group bindings.
BoxedAnyObject
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.
ByteArray
GLib type: Shared boxed type with reference counted clone semantics.
Bytes
A shared immutable byte slice (the equivalent of Rc<[u8]>).
Checksum
GLib type: Boxed type with copy-on-clone semantics.
CollationKey
A CollationKey allows ordering strings using the linguistically correct rules for the current locale.
Date
GLib type: Inline allocated boxed type with stack copy semantics.
DateTime
GLib type: Shared boxed type with reference counted clone semantics.
ExitCode
FileSetContentsFlagsv2_66
FilenameCollationKey
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.
FormatSizeFlags
FutureWithTimeoutError
The error returned when a future times out.
GStr
Representation of a borrowed GString.
GStrInteriorNulError
Error type indicating that a buffer had unexpected nul-bytes.
GString
A type representing an owned, C-compatible, nul-terminated UTF-8 string.
GStringBuilder
A mutable text buffer that grows automatically.
GStringInteriorNulError
Error type indicating that a buffer had unexpected nul-bytes.
GStringNoTrailingNulError
Error type indicating that a buffer did not have a trailing nul-byte.
GStringPtr
NULL-terminated UTF-8 string as stored in StrV.
GStringUtf8Error
Error type indicating that a buffer had invalid UTF-8.
GlibLoggerlog
An implementation of a log compatible logger which logs over glib logging facilities.
IConv
IOCondition
InterfaceInfo
JoinError
Task failure from awaiting a JoinHandle.
JoinHandle
A handle to a task running on a MainContext.
KeyFile
GLib type: Shared boxed type with reference counted clone semantics.
KeyFileFlags
LogField
Structure representing a single field in a structured log entry.
LogHandlerId
LogLevelFlags
LogLevels
MainContext
GLib type: Shared boxed type with reference counted clone semantics.
MainContextAcquireGuard
MainContextFlagsv2_72
MainLoop
GLib type: Shared boxed type with reference counted clone semantics.
MarkupParseContext
GLib type: Shared boxed type with reference counted clone semantics.
OptionFlags
ParamFlags
ParamSpec
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecBoolean
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecBooleanBuilder
ParamSpecBoxed
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecBoxedBuilder
ParamSpecChar
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecCharBuilder
ParamSpecDouble
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecDoubleBuilder
ParamSpecEnum
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecEnumBuilder
ParamSpecFlags
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecFlagsBuilder
ParamSpecFloat
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecFloatBuilder
ParamSpecGType
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecGTypeBuilder
ParamSpecInt
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecInt64
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecInt64Builder
ParamSpecIntBuilder
ParamSpecLong
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecLongBuilder
ParamSpecObject
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecObjectBuilder
ParamSpecOverride
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecOverrideBuilder
ParamSpecParam
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecParamBuilder
ParamSpecPointer
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecPointerBuilder
ParamSpecString
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecStringBuilder
ParamSpecUChar
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecUCharBuilder
ParamSpecUInt
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecUInt64
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecUInt64Builder
ParamSpecUIntBuilder
ParamSpecULong
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecULongBuilder
ParamSpecUnichar
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecUnicharBuilder
ParamSpecValueArray
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecValueArrayBuilder
ParamSpecVariant
GLib type: Shared boxed type with reference counted clone semantics.
ParamSpecVariantBuilder
Quark
Regex
GLib type: Shared boxed type with reference counted clone semantics.
RegexCompileFlags
RegexMatchFlags
SignalFlags
SignalGroupv2_74
GLib type: GObject with reference counted clone semantics.
Source
GLib type: Shared boxed type with reference counted clone semantics.
SourceFuture
Represents a Future around a glib::Source. The future will be resolved once the source has provided a value
SourceStream
Represents a Stream around a glib::Source. The stream will be provide all values that are provided by the source
SpawnFlags
SpawnWithinJoinHandle
Variant of JoinHandle that is returned from MainContext::spawn_from_within.
ThreadHandle
A handle to a thread running on a ThreadPool.
ThreadPool
TimeSpan
A value representing an interval of time, in microseconds.
TimeZone
GLib type: Shared boxed type with reference counted clone semantics.
TypeFlags
TypeInfo
TypeModule
GLib type: GObject with reference counted clone semantics.
TypePlugin
GLib type: GObject with reference counted clone semantics.
TypeValueTable
Uriv2_66
GLib type: Shared boxed type with reference counted clone semantics.
UriFlagsv2_66
UriHideFlagsv2_66
UriParamsFlagsv2_66
ValueArray
GLib type: Boxed type with copy-on-clone semantics.
VariantDict
VariantDict is a mutable key/value store where the keys are always strings and the values are Variants.
VariantIter
Iterator over items in a variant.
VariantStrIter
Iterator over items in a variant of type as.
VariantTy
Describes Variant types.
VariantTyIterator
An iterator over the individual components of a tuple VariantTy.
VariantType
Describes Variant types.

Enums§

CharacterDecomposition
The result of a single step of the Unicode canonical decomposition algorithm
ChecksumType
ControlFlow
Continue calling the closure in the future iterations or drop it.
ConvertError
CvtError
A wrapper for ConvertError that can hold an offset into the input string.
DateMonth
DateWeekday
DecompositionKind
The kind of decomposition to perform
FileError
GStrError
Error type holding all possible failures when creating a GStr reference.
GStringFromError
Error type holding all possible failures when creating a GString.
GlibLoggerDomainlog
Enumeration of the possible domain handling behaviours for a GlibLogger.
GlibLoggerFormatlog
Enumeration of the possible formatting behaviours for a GlibLogger.
IConvError
A wrapper for std::io::Error that can hold an offset into an input string.
KeyFileError
LogLevel
LogWriterOutput
MarkupError
NormalizeMode
OptionArg
SeekType
TimeType
UnicodeBreakType
UnicodeScript
UnicodeType
UriErrorv2_66
VariantClass

Constants§

CLONE_MACRO_LOG_DOMAIN
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.
NONE_STR

Statics§

CSET_A_2_Z
CSET_DIGITS
CSET_a_2_z
KEY_FILE_DESKTOP_GROUP
KEY_FILE_DESKTOP_KEY_ACTIONS
KEY_FILE_DESKTOP_KEY_CATEGORIES
KEY_FILE_DESKTOP_KEY_COMMENT
KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE
KEY_FILE_DESKTOP_KEY_EXEC
KEY_FILE_DESKTOP_KEY_GENERIC_NAME
KEY_FILE_DESKTOP_KEY_HIDDEN
KEY_FILE_DESKTOP_KEY_ICON
KEY_FILE_DESKTOP_KEY_MIME_TYPE
KEY_FILE_DESKTOP_KEY_NAME
KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN
KEY_FILE_DESKTOP_KEY_NO_DISPLAY
KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN
KEY_FILE_DESKTOP_KEY_PATH
KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY
KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS
KEY_FILE_DESKTOP_KEY_TERMINAL
KEY_FILE_DESKTOP_KEY_TRY_EXEC
KEY_FILE_DESKTOP_KEY_TYPE
KEY_FILE_DESKTOP_KEY_URL
KEY_FILE_DESKTOP_KEY_VERSION
KEY_FILE_DESKTOP_TYPE_APPLICATION
KEY_FILE_DESKTOP_TYPE_DIRECTORY
KEY_FILE_DESKTOP_TYPE_LINK
OPTION_REMAINING
STR_DELIMITERS
TEST_OPTION_ISOLATE_DIRSv2_60
TEST_OPTION_NONFATAL_ASSERTIONSv2_84
TEST_OPTION_NO_PRGNAMEv2_84
URI_RESERVED_CHARS_GENERIC_DELIMITERS
URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS

Traits§

HasParamSpec
IntoGStr
A trait to accept both &str or &GStr as an argument.
IntoOptionalGStr
A trait to accept both Option<&str> or Option<&GStr> as an argument.
ParamSpecBuilderExt
A trait implemented by the various ParamSpec builder types.
ParamSpecType
Unichar
This trait provides access to Unicode character classification and manipulations functions provided by GLib that do not exist in the standard library

Functions§

access
application_name
base64_decode
base64_encode
casefold
charset
Obtain the character set for the current locale.
check_version
child_watch_future
Create a Future that will resolve once the child process with the given pid exits
child_watch_future_with_priority
Create a Future that will resolve once the child process with the given pid exits
codeset
compute_checksum_for_bytes
compute_checksum_for_data
compute_checksum_for_string
compute_hmac_for_bytes
compute_hmac_for_data
console_charsetv2_62
convert
convert_with_fallback
current_dir
dcgettext
dgettext
dngettext
dpgettext
dpgettext2
environ
environ_getenv
file_get_contents
file_open_tmp
file_set_contents
file_set_contents_fullv2_66
filename_charsets
filename_display_basename
filename_display_name
filename_from_uri
filename_from_utf8
filename_to_uri
filename_to_utf8
find_program_in_path
format_size
format_size_full
future_with_timeout
Add a timeout to a Future.
future_with_timeout_with_priority
Add a timeout to a Future.
getenv
home_dir
host_name
hostname_is_ascii_encoded
hostname_is_ip_address
hostname_is_non_ascii
hostname_to_ascii
hostname_to_unicode
interval_stream
Create a Stream that will provide a value every given number of milliseconds.
interval_stream_seconds
Create a Stream that will provide a value every given number of seconds.
interval_stream_seconds_with_priority
Create a Stream that will provide a value every given number of seconds.
interval_stream_with_priority
Create a Stream that will provide a value every given number of milliseconds.
is_canonical_pspec_name
language_names
language_names_with_categoryv2_58
listenv
locale_from_utf8
locale_to_utf8
locale_variants
log_default_handler
log_remove_handler
log_set_always_fatal
log_set_default_handler
To set back the default print handler, use the log_unset_default_handler function.
log_set_fatal_mask
log_set_handler
log_set_writer_func
log_structured_array
log_unset_default_handler
To set the default print handler, use the log_set_default_handler function.
log_variant
log_writer_default
log_writer_default_set_use_stderr
Sets whether GLib log functions output to stderr or stdout.
log_writer_default_would_drop
log_writer_format_fields
log_writer_is_journald
log_writer_journald
log_writer_standard_streams
log_writer_supports_color
main_current_source
main_depth
markup_escape_text
mkdir_with_parents
mkdtemp
mkdtemp_full
mkstemp
mkstemp_full
monotonic_time
normalize
num_processors
on_error_query
on_error_stack_trace
os_infov2_64
prgname
program_name
Same as get_prgname().
random_double
random_double_range
random_int
random_int_range
random_set_seed
real_name
real_time
reload_user_special_dirs_cache
rust_log_handlerlog
Provides a glib log handler which routes all logging messages to the log crate.
set_application_name
set_prgname
set_print_handler
To set back the default print handler, use the unset_print_handler function.
set_printerr_handler
To set back the default print handler, use the unset_printerr_handler function.
set_program_name
Same as set_prgname().
setenv
shell_parse_argv
shell_quote
shell_unquote
spaced_primes_closest
spawn_async
spawn_async_with_fdsv2_58 and non-Windows
spawn_async_with_pipesNon-Windows
spawn_check_exit_statusDeprecated
spawn_check_wait_statusv2_70
spawn_command_line_asyncUnix
spawn_future
Spawn a new infallible Future on the thread-default main context.
spawn_future_local
Spawn a new infallible Future on the thread-default main context.
system_config_dirs
system_data_dirs
timeout_future
Create a Future that will resolve after the given number of milliseconds.
timeout_future_seconds
Create a Future that will resolve after the given number of seconds.
timeout_future_seconds_with_priority
Create a Future that will resolve after the given number of seconds.
timeout_future_with_priority
Create a Future that will resolve after the given number of milliseconds.
tmp_dir
unix_open_pipe
unix_signal_futureUnix
Create a Future that will resolve once the given UNIX signal is raised
unix_signal_future_with_priorityUnix
Create a Future that will resolve once the given UNIX signal is raised
unix_signal_streamUnix
Create a Stream that will provide a value whenever the given UNIX signal is raised
unix_signal_stream_with_priorityUnix
Create a Stream that will provide a value whenever the given UNIX signal is raised
unlink
unset_print_handler
To set the default print handler, use the set_print_handler function.
unset_printerr_handler
To set the default print handler, use the set_printerr_handler function.
unsetenv
uri_escape_string
uri_parse_scheme
uri_unescape_segment
uri_unescape_string
user_cache_dir
user_config_dir
user_data_dir
user_name
user_runtime_dir
user_special_dir
user_state_dirv2_72
usleep
utf8_to_utf32
utf32_to_utf8
uuid_string_is_valid
uuid_string_random

Type Aliases§

DateDay
DateYear
Time

Attribute Macros§

async_test
An attribute macro for writing asynchronous test functions.
derived_properties
When applied to ObjectImpl
flags
Attribute macro for defining flags using the bitflags crate. This macro will also define a GFlags::type_ function and the glib::Value traits.
object_interface
Macro for boilerplate of ObjectInterface implementations.
object_subclass
Macro for boilerplate of ObjectSubclass implementations.

Derive Macros§

Boxed
Derive macro for defining a BoxedType::type_ function and the glib::Value traits. Optionally, the type can be marked as nullable to get an implementation of glib::value::ToValueOptional.
Downgrade
Macro for deriving implementations of glib::clone::Downgrade and glib::clone::Upgrade traits and a weak type.
Enum
Derive macro to register a Rust enum in the GLib type system and derive the glib::Value traits.
ErrorDomain
Derive macro for defining a GLib error domain and its associated ErrorDomain trait.
Properties
This macro enables you to derive object properties in a quick way.
SharedBoxed
Derive macro for defining a SharedType::get_type function and the glib::Value traits. Optionally, the type can be marked as nullable to get an implementation of glib::value::ToValueOptional.
ValueDelegate
Example
Variant
Derive macro for serializing/deserializing custom structs/enums as glib::Variants.