New release
It’s now time for a new gtk-rs release!
As you might’ve noticed, the gtk3-rs
projects are getting less and less attention and we intend to deprecate them in one of the future releases. Therefore, we recommend to anyone who didn’t upgrade to GTK4 to do it now. gtk3-rs
will get further releases in the foreseeable future to keep up with gtk-rs-core
, but no development effort is going to be directed towards it. This is already the de-facto situation for more than a year. Additionally, the GTK3 versions of various externally maintained bindings will most likely not get any further releases.
In addition to gtk-rs
, various externally maintained bindings also had a new release. For gstreamer-rs
you can find the CHANGELOG of the 0.20 release here. Most bindings maintained as part of GNOME were also updated.
On this note, time to go through the major changes of this release. Enjoy!
Increase of the minimum supported Rust version (MSRV) §
With this release, Rust 1.64 is the minimum version required to compile and use the bindings.
New #[properties]
macro to make using properties in glib::Object
subclasses simpler §
The glib::Properties
macro is now available! It can be used to define object properties straight from the implementation struct definition. The macro will:
- define all the necessary
ParamSpec
s, with the required flags - generate, for each property, a default getter/setter on the wrapper type
- generate, for each property, a
notify_$property
method on the wrapper type - generate the methods
derived_properties
derived_property
andderived_set_property
, which can be directly called inside your overrides forObjectImpl
methodsproperties
,property
andset_property
.
Quick example §
#[derive(Properties)]
#[properties(wrapper_type = super::Author)]
pub struct Author {
#[property(get, set)]
name: RefCell<String>,
}
This is the result of months of work, and will greatly improve the gtk-rs ecosystem by reducing some of the most prevalent boilerplate and making the platform more welcoming.
Be sure to check out the documentation for more info.
Direct conversions to glib::Value
and glib::Variant
via From
§
Previously conversions required using the custom ToValue
and ToVariant
traits, which is not very intuitive. Now it’s possible to directly use the From
trait, i.e. 123i32.to_value()
could become 123i32.into()
.
In addition to improving usability this also avoids copies of the values in a few cases.
gdk_pixbuf
subclassing support §
Support for subclassing various gdk_pixbuf
types was added. This allows writing custom pixbuf loaders in Rust and hopefully opens the way for replacing the old C-based PNG/JPEG/GIF pixbuf loaders with Rust versions to improve image loading in all GTK/GNOME applications.
New glib::CastNone
convenience trait §
In many cases casting failures of Option
al values should be treated as None
. For this purpose a new convenience trait was introduced, which provides an and_downcast()
method.
let widget: Option<Widget> = list_item.child();
// Without using `CastNone`
let label = widget.unwrap().downcast::<gtk::Label>().unwrap();
// Using `CastNone` we can avoid the first `unwrap()` call
let label = widget.and_downcast::<gtk::Label>().unwrap();
New glib::function_name!
macro §
While a huge hack, until Rust supports this directly, this macro will allow to get the name of the current function as a &'static str
. Or to be more exact, the whole path to the current function.
This is now used in the GLib structured logging API to provide the function name (in addition to the file name, line number and other metadata) and glib::BoolError
to provide better location information.
glib::GStr
, glib::List
, glib::PtrSlice
, glib::Slice
, glib::StrV
and related native GLib types §
New API was added to all the aforementioned types to make dealing with them more natural in Rust. Using them instead of the native Rust types, e.g. Vec
, allows for fewer copies when passing the FFI boundary.
Various bindings were also switched to these types for the same reason, and it is planned for the next release(s) to move even more API to it.
In addition two new traits were introduced for dealing with GLib strings and string arrays more efficiently: IntoGStr
and IntoStrV
. Both allow passing a plain &str
or an already NUL
-terminated &GStr
, or a Vec<String>
or an already NUL
-terminated glib::StrV
to functions and internally the function would either do a copy or directly pass the value to the C function. Up to a certain size the copy would by done on the stack, afterwards a temporary heap copy is made. Compared to the before, when temporary heap copies were made unconditionally, this allows for a lot fewer temporary heap allocations.
And lastly, glib::GString
is now storing strings up to a certain size inline without requiring a heap allocation. New GString
s can be created via the gformat!
macro similar to the format!
macro from std
.
Various code generation improvements §
All over the bindings, various small code generation improvements were applied which reduced the size of the generated code and/or improved the performance.
For example:
- Various trivial functions were explicitly marked as
#[inline]
to give the compiler yet another hint to actually inline them, and improve inlining across crate boundaries, which then causes the bindings to be completely optimized away in most cases. - In many places, where it made sense, assertions were converted to
debug_assert!
s to reduce the number of places where stack unwinding could happen in release builds. - The representation of various types was improved, e.g. by removing unnecessary
Option
wrapping around values or replacing unneeded references withPhantomData
with the same lifetime. - Memory initialized by C functions was converted from using zero-initialization to
MaybeUninit
. - The number of redundant checks was reduced and
unsafe
variants of functions that skip the checks were added. - All object builder types were changed to use
glib::Object::builder()
, which reduces stack usage dramatically in addition to requiring fewer value copies.
New glib::Object
constructors §
The old Object::new()
constructor that took a slice of property name / value pairs was removed. Instead, Object::new()
takes no parameters and creates a new object with default property values.
For creating a new object with non-default property values, use Object::builder()
. It provides a much nicer API and also allows for better code generation and fewer value copies.
// before
let obj = glib::Object::new::<MyObject>(&[("a", &123i32), ("b", &"some string")]);
// after
let obj = glib::Object::builder::<MyObject>()
.property("a", 123i32)
.property("b", "some string")
.build();
gio::Application::run()
returns an ExitCode
§
Instead of returning a plain i32
, gio::Application::run()
now returns an ExitCode
type. This can be directly returned from the main()
function as it implements the Termination
trait, making it much easier to correctly propagate application exit codes.
GTK4 4.10 API additions §
The GTK4 bindings were updated to include all the new APIs introduced by the upcoming GTK 4.10 release. These new APIs are available via the v4_10
feature flag. Note that they are not stable and are subject to change if the underlying C API happens to change before the 4.10.0 release.
The minimum supported GTK version stays at 4.0.0.
Add Blueprint UI definition support §
Blueprint is a new markup language for defining GTK4 UIs. The #[template]
macro can now accept Blueprint UI definitions in addition to the old XML-based UI definitions. Doing so requires blueprint-compiler
to be available during compilation.
#[derive(Debug, Default, gtk::CompositeTemplate)]
#[template(string = "
template MyWidget : Widget {
Label label {
label: 'foobar';
}
Label my_label2 {
label: 'foobaz';
}
}
")]
pub struct MyWidget {
#[template_child]
pub label: TemplateChild<gtk::Label>,
#[template_child(id = "my_label2")]
pub label2: gtk::TemplateChild<gtk::Label>,
}
You can also copy the example from https://github.com/gtk-rs/gtk4-rs/releases/tag/0.6.0.
Better mapping of C ownership transfer §
Previously various functions that took ownership of their parameters still used references in the bindings. This required an unnecessary copy to be made in the worst case, and in the best case made it less clear that ownership of the object is given away.
In this release, functions are taking various arguments by value in more places.
Spawning of blocking functions on the glib::MainContext
§
gio::spawn_blocking()
was added, which allows to spawn blocking functions on an internal threadpool and retrieve their results as a Future
from the glib::MainContext
. This is useful for doing blocking / CPU intensive work in the background and when the results are available to handle them on the application’s main thread.
As part of this work, JoinHandle
-style types were also added to glib::MainContext::spawn()
and related functions for spawning Future
s on the main context, and to glib::ThreadPool
for spawning functions on a custom thread pool and collecting their results.
Changes §
For those who are interested, here is the list of the merged pull requests:
- Fixed clippy lints and warnings
- cairo: Fix rectangle getter
- glib: Add helpers for setting property bindings flags
- glib: Add a getter for
ObjectBuilder::type_
- glib: Add unsafe bindings to
g_object_run_dispose()
- gio: Add
set_only
/get_only
helpers to BindingBuilder - gio: Add helpers for setting SettingBinding flags
- Correct outdated references to
subclass::simple
- glib: Add
ObjectSubclass::obj()
as a shorter alias forinstance()
- image: Rebuild once every week
- Fix new clippy lints
- fix CI for 1.65/1.66
- Fix new clippy lints
- Move from
imp.instance()
toimp.obj()
- Move
g_cancellable_set_error_if_cancelled()
to manual - pango: Auto generate Language
- pango: Make
pango::Language::from_string()
infallible - Implement
From<T>
for Value, Variant - glib: fix undefined behavior in
types::register_type
- gdk-pixbuf: Add subclassing support
- glib: Document the value guarantees for
ObjectImpl::set_property()
andproperty()
- glib: Add a doc string for
as_ptr
generated impls - Fix ABI tests
- cairo: fix some misc warnings
- gio: socket/stream extras
- cairo: Update to freetype 0.32
- Add
CastNone
trait - pango: Backport Language changes
- gio: Make GioFuture handle infaliable futures
- gio: Add a GioInfaliableFuture
- Add a changelog file
- glib: Implement
IntoGlibPtr
forOption<T>
- glib: Use actual function name in
glib::BoolError
and include function name/source file/line number in structured logs - glib: Add
GStr::from_ptr_lossy()
andGString::from_ptr_lossy()
and implementFrom<GStr>
andFrom<GString>
forCow<GStr>
- glib: Implement
GStringBuilder
asBoxedInline
to avoid a useless additional heap allocation - glib: Minor
GStringBuilder
improvements - Group imports and use prelude
- glib: Bind more
g_utf8
APIs - gio: fix clippy lints for rust 1.64
- gio: add
spawn_blocking()
- Fix various new beta clippy warnings
- examples: spawn async gio task on the current thread context
- Various
Stash
/to_glib_none()
related optimizations and bugfixes - GString refactor
- ActionEntry: take proper types instead of strings
- Inline various trivial functions
- Suggest kebab-case for the error domain
- gio: simplify async initable
- Improve
glib::collections
API and make it more versatile - glib: Minor optimization for
List
/SList
withCopy
types - glib: Fix
glib::wrapper!
forBoxedInline
with generic parameters - glib: Optimize various from/to
Vec
FFI translation functions - Use
IntoGlibPtr
instead ofto_glib_full()
in more places - glib: Add
Value::from_type_unchecked()
- glib: Use
IntoGStr
trait in a couple of places - Generate string constants as
&'static GStr
/[u8]
- glib: Fix usage of
gformat!
macro ifGString
is not in scope - build tools: fix documentation link
- Enable introspection
- pango: use the new List api to simplify
reorder_items
- glib: implement
ToGlibPtr<*mut _>
for boxed types - settings: implement strv setter and getter manually
- gio: use StrV for the simple proxy resolver API
- glib: Add
ParamSpec::is()
helper function - gdk-pixbuf: Trust return value nullability
- glib: Deprecate
ObjectSubclass::instance()
/from_instance()
in favour of the shorter versions - build-tools: Fix reporting of errors
- Do not hard-code path separator
- glib: Implement enum paramspec builder variant that builds the default value automatically
- glib: Deprecate paramspec
new()
functions in favour of the builder - glib: Add new object constructor for constructing an object with default property values
- glib: Add
MainContext::spawn_from_within()
for spawning non-Send
futures from another thread - mark suboptimal
Object
constructors as deprecated - glib: Implement more From traits for StrV
- build-tools: Allow passing multiple source dirs to
compile_resources
- gio: use GStr for the manual extension point implenentation
- glib: Implement various traits on
GStr
manually - gio: bind GFileDescriptorBased
- glib: Manually implement
TimeZone::adjust_time()
instead of ignoring it - application: Return ExitCode
- Properties macro
- gdk-pixbuf: check if either width/height is null before assignment in
animation_get_size()
- glib: Rename
Object::new_default()
toObject::new()
and remove deprecated API - Add TransparentPtr marker trait to List, SList and StrVItem
- Rename StrVItem to GStrPtr and make it clonable and transparent
- Remove
construct_cell
, too experimental - Use
PtrSlice<GStrPtr>
forKeyFile
methods - gio: Don’t require a
'static
&str
inFile::enumerate_children_async()
andenumerate_children_future()
- gdk-pixbuf: Ensure that transfer-none return values in subclassing are staying alive long enough
- gdk-pixbuf: Fix time related types
- Add doc for ConstructCell, improve doc Boxed, Enum
- macros: further tweak docs
- glib: Add
NULL
debug assertion tofrom_glib_full()
and others for GObjects - Rename GStrPtr to GStringPtr
- properties: Update syntax for custom flags and other builder fields
- gio: implement FromIterator for ListStore
- properties: correctly type check value returned by the getter fn
- Use strcmp for GStringPtr comparisons
- Support
default = ...
in the properties macro - macros: support overrides in the properties macro
- gio: make ListModel::iter() infallible
- Greatly improve
clone!
proc macro error output - clippy cleanup
- Refactor properties macro, improve errors
- impl PropertyGet for T:
HasParamSpec
- Improve properties macro docs
- glib: Implement
ValueArray
Value
traits manually because of the custom paramspec - add
ParamSpecEnumBuilder::default_value()
- Update link
- Base Dockerfile on gtk-rs-core image
- Move from
imp.instance()
toimp.obj()
- widget: support
window_state_event
when subclassing - Skip init assertion for
gdk::set_allowed_backends
- gtk: implement
From<ResponseType>
for Value - examples: Fix compilation after
gio::SimpleAction
constructor took the state by value - examples: Adapt to glib-build-tools breaking change
- Allow subclassing ToggleButton and MenuButton
- Update wayland-client version to 0.30
- examples/glium: lookup libepoxy-0.dll first
- book: Migrate to
glib-build-tools
- Base Dockerfile on gtk-rs-core image
- image: Rebuild once every week
- gtk: Generate new v4.10 APIs
- Move from
imp.instance()
toimp.obj()
- gtk: Add gnome_43 feature
- book: Use
Object::builder()
instead ofObject::new()
- Add gdk4-win32
- Win32 fixes
- Fix latest clippy warnings
- book: Fix typo in xtask code
- gdk-win32: implement
Win32Display.add_filter()
(part 2) - gdk-win32: implement
Win32Display.add_filter()
(part 1) - Fixed a typo
- Release 0.5.2
- Fix clippy lints
- Skip init assertion for
gdk::set_allowed_backends
- book: Fix typo
- Added Libxml, Librsvg, Gettext and Libadwaita demo
- use
Into<Value>
andInto<Variant>
where possible - book: Small windows instructions fix
- examples: Use NoneCast trait where possible
- macros: Allow using re-exports of gtk
- gsk: Export builders module
- gtk4: use
impl_offset()
for calculating template child offset - gtk: Fix missing version guards
- Add a changelog file
- gtk: Cleanup template related functions
- Group imports
- Generate AlertDialog::choose
- Release 0.5.4
- Relax version requirement
- gtk: Subclass BuilderCScope for the BuilderRustScope
- Fix clippy warnings
- Fix compilation after
Stash
PhantomData
usage in glib install_action_async
: Use owned Variant in closurefile_chooser
: Fixadd_choice
- Mark new dialog api as not nullable
- book: Link to “Rust Atomics and Lock”
- Add blueprint-compiler dependency into Dockerfile
- no need to move in the hello world exercise
- Book: make memory management conclusion clearer.
- Use wrapper macros where possible
- Various improvements
- Allocations improvements
- gtk: Make use of
Value::from_type_unchecked
- book: warn about precedence over pkg-config-lite
- Recommend (with instructions) building with
gvsbuild
- book: Simplify instructions on Windows
- Make use of IntoGStr/IntoStrV
- Enable introspection for gtk
- gtk4-macros: Add blueprint support
- Update for
glib::Boxed
ToGlibPtr<*mut _>
trait impl addition - book: remove
try_property
- book: Move listings to feature 4_8
- book: fix panic in
list_widgets_4,5,6
- Builder related fixes
- book: Rephrase a sentence
- Remove unneeded cfg(dox) condition
- book: Add alt text to images and videos
- Fix nightly clippy warnings
- Use glib::ExitStatus
- Update per Properties macro merge
- gtk-macros: Mention the failed to retrieve template child name
- Prepare for 0.6
- Implement HasParamSpec for Expression types
- Clippy cleanups
- book: Adapt to glib-build-tools breaking change
All this was possible thanks to the gtk-rs/gir project as well:
- Fix new clippy lints
- nameutil: correct dll link name
- Add
#[allow(clippy::should_implement_trait)]
if method is nameddefault
- Fix new clippy lint in generated abi and sys test files
- analysis/special_functions: fix missing import
- codegen: implement
From<T>
for Value for enums/flags - Fix up special functions in traits correctly
- Fix incorrect ‘missing from library’ warning when generating in sys mode
- Add init assertions to the enum/flags
From<T> for glib::Value
impls - codegen: silence deprecation warnings in impls for deprecated types/functions
- analysis: handle C array pointer casts to void
- fix the layout tests
- codegen: Handle
_finish
functions not taking a GError input param - Backport: codegen: Handle
_finish
functions not taking a GError input param - analysis: Use the new move trait for in transfer-full params
- analysis: Don’t use IntoGlibPtr for
Vec<T>
parameters - analysis: Generate correct bounds when move is used for nullable types
- analysis: Prefer using
glib::prelude::*
- codegen: Group imports by crate
- Various cleanups
- Fix generation without any shared libraries
- Inline various enum/flags functions
- Generate string constants as
&'static GStr
/[u8]
- Generate static
to_str()
/name()
functions withGStr
instead ofstr
- docs: Generate properties/signals docs
- Handle user_data renaming
- Optimize builders
- Implement object builders around
glib::object::ObjectBuilder
- Fix missing check in case a type cannot be generated in builders
- Add configuration for exhaustive enums
- Fix new clippy warnings
- codegen: Generate HasParamSpec for enums/flags
- Use
Object::new()
instead ofObject::new_default()
- Generate less clippy warnings code
- Reworked the book/tutorial
Thanks to all of our contributors for their (awesome!) work on this release:
- @A6GibKm
- @AaronErhardt
- @andy128k
- @aruiz
- @bilelmoussaoui
- @cgwalters
- @delight-aug
- @elmarco
- @gdesmott
- @GuillaumeGomez
- @harshshredding
- @Hofer-Julian
- @Jedsek
- @jf2048
- @lucab
- @luckylat
- @Megadash452
- @mitchhentges
- @nacho
- @nardoor
- @nt8r
- @pbor
- @pentamassiv
- @ranfdev
- @RealKC
- @sdroege
- @veera-sivarajan
- @vikram-kangotra
- @vlinkz
- @wroyca
- @yuraiz