Saving Window State
Quite often, we want the window state to persist between sessions.
If the user resizes or maximizes the window, they might expect to find it in the same state the next time they open the app.
GTK does not provide this functionality out of the box, but luckily it is not too hard to manually implement it.
We basically want two integers (height
& width
) and a boolean (is_maximized
) to persist.
We already know how to do this by using gio::Settings
.
Filename: listings/saving_window_state/1/org.gtk_rs.SavingWindowState1.gschema.xml
<?xml version="1.0" encoding="utf-8"?>
<schemalist>
<schema id="org.gtk_rs.SavingWindowState1" path="/org/gtk_rs/SavingWindowState1/">
<key name="window-width" type="i">
<default>-1</default>
<summary>Default window width</summary>
</key>
<key name="window-height" type="i">
<default>-1</default>
<summary>Default window height</summary>
</key>
<key name="is-maximized" type="b">
<default>false</default>
<summary>Default window maximized behaviour</summary>
</key>
</schema>
</schemalist>
Since we don't care about intermediate state, we only load the window state when the window is constructed and save it when we close the window. That can be done by creating a custom window. First, we create one and add convenience methods for accessing settings as well as the window state.
Filename: listings/saving_window_state/1/custom_window/mod.rs
We set the property "application" by passing it to
glib::Object::new
. You can even set multiple properties that way. When creating new GObjects, this is nicer than calling the setter methods manually.
The implementation struct holds the settings
.
You can see that we embed Settings
in std::cell::OnceCell
.
This is a nice alternative to RefCell<Option<T>>
when you know that you will initialize the value only once.
We also override the constructed
and close_request
methods, where we load or save the window state.
Filename: listings/saving_window_state/1/custom_window/imp.rs
That is it! Now our window retains its state between app sessions.