Windows
Open and control windows, share state between them, handle close requests, choose when the application exits, and draw your own title bar.
An application starts with one window, the primary window, which is the one passed to
App::run. You can open more with use_windows(), control any window through its WindowHandle,
and share reactive state between them.
Each window has its own document, view scope, layout state and paint caches. All windows in an application share one graphics device.
Open a window
Call use_windows() in a component body, and use the returned handle in a listener, effect, timer
or other UI-thread callback:
use zgui::prelude::*;
#[component]
fn Settings() -> impl IntoView {
view! { label() {"Settings"} }
}
#[component]
fn Main() -> impl IntoView {
let windows = use_windows();
view! {
control(
tabindex = Focus::Sequential,
on:click = {
let windows = windows.clone();
move |_| {
windows.open(
WindowOptions::new("Settings")
.with_size(480.0, 600.0)
.with_resizable(false),
|| view! { Settings() },
);
}
}
) {"Open settings"}
}
}open returns a WindowHandle at once. The platform creates the window on the next event-loop
turn, so handle.is_open() is false until then. Calls on a pending or closed handle do nothing.
Because creation is deferred, open cannot return a platform error. If a window fails to open,
zgui logs the error under the zgui::app target, leaves the handle unopened, and keeps the other
windows running. A failure to open the primary window is returned by App::run.
The view closure is FnMut. When the platform suspends, native surfaces go away; on resume, zgui
recreates the windows and builds their views again.
Configure a window
WindowOptions sets a new window's title, size, decorations, position and other properties before
it opens. The primary window is configured on app() with the same methods, from with_title to
with_theme. All WindowOptions methods are listed at the end of this
page.
- Style sheets. The application style sheet applies to every window. A sheet set with
with_stylesheetis cascaded after it, so use it for changes local to one window. - Application identifier. Set it once with
App::with_application_id. It applies to every window, and the desktop uses it for grouping, icons and window rules. - Transparency. A window with
with_transparent(true)is composed as premultiplied colour: pixels nothing paints have zero alpha, so the desktop shows through rounded corners and gaps. Text in a transparent window uses greyscale antialiasing instead of subpixel antialiasing. - Colour scheme. The
ColorSchemethatwith_themetakes iszgui::platform::ColorScheme; the prelude uses that name for view theming.
WindowOptions creates ordinary top-level windows only. Menus, tooltips and dropdowns are drawn
inside their owner window; see Overlays and portals.
Control the current window
use_window() returns a handle to the window the calling component runs in:
#[component]
fn WindowStatus() -> impl IntoView {
let window = use_window();
let size = {
let window = window.clone();
move || {
let size = window.size().get();
format!("{:.0} × {:.0}", size.width.0, size.height.0)
}
};
view! {
label() {{size}}
control(
tabindex = Focus::Sequential,
on:click = {
let window = window.clone();
move |_| window.toggle_maximized()
}
) {"Maximize or restore"}
}
}try_use_window() and try_use_windows() return None instead of panicking outside a window or
application scope.
A WindowHandle has two kinds of methods:
- State signals, such as
size(),focused()andmaximized(), that your views can read reactively. - Commands, such as
set_title,request_sizeandclose, that ask the desktop to change the window.
A command is a request, not a result. To resize, call request_size, then read size() to see
what the desktop accepted. Desktops differ: unsupported commands and commands on closed windows do
nothing. Read WindowHandle::capabilities() when you need to hide a command the desktop cannot
perform. For example, Wayland compositors place windows themselves, so set_position does nothing
there and position() returns None.
The signals live as long as the handle, not as long as the component that opened the window. A component can open a window, store its handle, and unmount while the window stays open.
WindowHandle belongs to the UI thread. Do not send it to background work; post the action back to
the UI thread instead.
Window state signals and window commands are listed in full at the end of this page.
Share state between windows
A context provided inside a window belongs to that window. To share state, provide it in the
application scope with App::with_context:
use zgui::prelude::*;
#[derive(Clone, Copy)]
struct SharedCount(RwSignal<i32>);
fn main() -> Result<(), zgui::Error> {
app()
.with_context(|| provide_context(SharedCount(RwSignal::new(0))))
.run(|| view! { Main() })
}Every window is mounted below this scope, so expect_context::<SharedCount>() returns the same
signal in all of them. A write in one window schedules frames for the other windows that read it.
Each window has its own document. A NodeRef, a node identifier or a window-local context from one
window cannot address another window. Share model state, not document handles.
Application-scope state survives platform suspension. Window-scope state does not, because the window's view is rebuilt on resume.
Find open windows
use_windows().all() returns a snapshot of the open windows, and watch() returns a signal
containing them. WindowHandle::id() stays the same for the window's whole life, including
suspension and resume. Compare ids when a command must skip the current window.
Handle close requests
When the user asks to close a window, zgui runs every registered close callback. If any returns
CloseResponse::Veto, the window stays open.
Register a callback for the window's whole life when you open it:
use std::{cell::Cell, rc::Rc};
let dirty = Rc::new(Cell::new(true));
let check_dirty = dirty.clone();
let editor = windows.open(
WindowOptions::new("Editor").on_close_request(move || {
if check_dirty.get() {
CloseResponse::Veto
} else {
CloseResponse::Close
}
}),
|| view! { Editor() },
);Give the editor another clone of dirty so it can clear the flag after saving. The callback in
WindowOptions survives suspension, so it must not capture state that belongs to the window scope.
Application-scope state from App::with_context is safe.
For a check that applies only while a component is mounted, call on_close_request inside the
component. It returns a CloseGuard; dropping the guard unregisters the callback. To keep it for
the component's life:
let guard = on_close_request(move || CloseResponse::Veto);
on_cleanup_local(move || drop(guard));WindowHandle::close() does not run close callbacks. Use it when the application has already
decided to close the window.
When a window closes, zgui unmounts its view. Every scope the view created is disposed in tree
order, so on_cleanup_local callbacks and scoped tasks end with the window, while application-scope
state is still alive.
Choose when the application exits
The default is ExitPolicy::WhenAllWindowsClose. Set another on the application builder with
with_exit_policy:
| Policy | Exits when |
|---|---|
WhenAllWindowsClose | the last window closes |
WhenPrimaryCloses | the window passed to run closes |
Explicit | code calls use_windows().quit() |
Use WhenPrimaryCloses when inspectors or palettes should not outlive the main window. Use
Explicit when the application should keep running with no windows, as many macOS applications do.
To hide a window instead of closing it, veto the close request and call set_visible(false), then
show it again from on_reopen when the user clicks the dock icon.
on_exit, on_reopen and the macOS application menu (with_menu, on_menu) are covered in
shipping on macOS.
Draw your own title bar
Decorations chooses how much frame the desktop draws:
| Value | The desktop draws | The application supplies |
|---|---|---|
Full | title bar and frame | nothing |
None | nothing | title bar, move and resize gestures, window controls |
NoTitleBar | on macOS: the frame, shadow, resize edges and window buttons, without the title bar | a title bar around the desktop's buttons |
Desktops other than macOS cannot keep the frame without the title bar, so they treat NoTitleBar
as None. Request NoTitleBar when the window is created; macOS cannot apply it afterwards, so a
later set_decorations(Decorations::NoTitleBar) gives a full frame there.
Use the handle's drag handlers on your own title bar:
use zgui::prelude::*;
#[component]
fn TitleBar() -> impl IntoView {
let window = use_window();
view! {
row(class = "titlebar", on:pointer_down = window.move_drag_handler()) {
label() {"Notes"}
control(
class = "close",
tabindex = Focus::Sequential,
a11y:label = "Close",
// Stops the press from reaching the title bar and starting a move.
on:pointer_down = window.no_drag_handler(),
on:click = {
let window = window.clone();
move |_| window.close()
}
) {"✕"}
}
}
}move_drag_handler()starts a desktop-driven move on press. A double press callstitle_bar_double_click(), which maximizes or restores the window, or on macOS does what the user chose in System Settings.resize_drag_handler(edge)starts a resize from aResizeEdge. Put one on each edge and corner strip.no_drag_handler()goes on controls inside the title bar.- Hide resize strips while
maximized()orfullscreen()says they cannot apply.
The handlers do not borrow the WindowHandle, so you can call them directly in view! without
cloning the handle first. They also work on Wayland, where a window cannot move itself by setting
coordinates. examples/csd.rs is a complete client-side-decorated window.
Place the macOS window buttons
With NoTitleBar, macOS still draws its close, minimize and zoom buttons over the top-left of the
content. TitleButtons places them so they line up with your own bar:
app()
.with_decorations(Decorations::NoTitleBar)
// Buttons start 16 px from the left edge, centred in a 40 px band along the top.
.with_title_buttons(TitleButtons::new(16.0, 40.0))
.run(|| view! { Main() })Make your title bar the same height as the band, and leave room on the left for the buttons. macOS
re-applies the placement after resizes and when leaving full screen. Other desktops ignore
with_title_buttons.
WindowOptions methods
| Method | Sets |
|---|---|
new, with_title | title |
with_size, with_min_size, with_max_size | size and size limits, in CSS pixels |
with_resizable | whether the user can resize the window |
with_decorations | Decorations::Full, None or NoTitleBar |
with_title_buttons | where macOS places its window buttons with NoTitleBar |
with_transparent | whether the window can show what is behind it |
with_position | requested position on the desktop |
with_maximized, with_fullscreen | initial display state |
with_level | requested stacking level |
with_icon | window icon, where the desktop accepts one |
with_theme | light or dark preference for this window |
with_stylesheet | a style sheet for this window only |
on_close_request | a close callback for the window's whole life |
Window state signals
WindowHandle method | Value |
|---|---|
size() | content size in CSS pixels |
scale() | device pixels per CSS pixel |
focused() | whether the window has keyboard focus |
occluded() | whether the desktop reports the whole window as hidden |
maximized() | whether the window is maximized |
fullscreen() | the current FullscreenMode, if any |
Window commands
WindowHandle method | Effect |
|---|---|
set_title | Changes the title. |
request_size, set_min_size, set_max_size | Requests a size or size limits, in CSS pixels. |
set_position, position | Moves the window, or reads where it is. |
set_resizable, set_decorations | Changes resizability or the desktop frame. |
set_maximized, toggle_maximized, minimize, set_fullscreen | Changes the display state. |
title_bar_double_click | Does what a double click on a title bar does on this desktop. |
set_visible | Hides or shows the window. A hidden window keeps its document, so showing it again costs one frame. |
set_level | Requests a stacking level. |
set_icon, set_theme, set_cursor | Changes the icon, colour scheme or cursor. |
focus, request_attention | Asks for keyboard focus (the desktop may refuse), or asks the desktop to flag the window. |
begin_move_drag, begin_resize_drag | Hands a move or resize gesture to the desktop. |
close | Closes the window without running close callbacks. |
Windows methods
use_windows() method | Result |
|---|---|
open(options, view) | a handle for the requested window |
all() | a snapshot of the open windows |
watch() | a signal containing the open windows |
capabilities() | what the desktop can do with windows |
quit() | asks the application to exit |
Next
Overlays and portals
Render a popover, menu or dialog above the page with Portal, place it next to its trigger, close it on an outside press or Escape, and keep focus inside a modal.
Animation
CSS transitions and keyframe animations, which properties are cheap to animate, animation events, enter and exit animations, and per-frame animation from Rust with request_frame.