zgui

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_stylesheet is 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 ColorScheme that with_theme takes is zgui::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() and maximized(), that your views can read reactively.
  • Commands, such as set_title, request_size and close, 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:

PolicyExits when
WhenAllWindowsClosethe last window closes
WhenPrimaryClosesthe window passed to run closes
Explicitcode 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:

ValueThe desktop drawsThe application supplies
Fulltitle bar and framenothing
Nonenothingtitle bar, move and resize gestures, window controls
NoTitleBaron macOS: the frame, shadow, resize edges and window buttons, without the title bara 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 calls title_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 a ResizeEdge. Put one on each edge and corner strip.
  • no_drag_handler() goes on controls inside the title bar.
  • Hide resize strips while maximized() or fullscreen() 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

MethodSets
new, with_titletitle
with_size, with_min_size, with_max_sizesize and size limits, in CSS pixels
with_resizablewhether the user can resize the window
with_decorationsDecorations::Full, None or NoTitleBar
with_title_buttonswhere macOS places its window buttons with NoTitleBar
with_transparentwhether the window can show what is behind it
with_positionrequested position on the desktop
with_maximized, with_fullscreeninitial display state
with_levelrequested stacking level
with_iconwindow icon, where the desktop accepts one
with_themelight or dark preference for this window
with_stylesheeta style sheet for this window only
on_close_requesta close callback for the window's whole life

Window state signals

WindowHandle methodValue
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 methodEffect
set_titleChanges the title.
request_size, set_min_size, set_max_sizeRequests a size or size limits, in CSS pixels.
set_position, positionMoves the window, or reads where it is.
set_resizable, set_decorationsChanges resizability or the desktop frame.
set_maximized, toggle_maximized, minimize, set_fullscreenChanges the display state.
title_bar_double_clickDoes what a double click on a title bar does on this desktop.
set_visibleHides or shows the window. A hidden window keeps its document, so showing it again costs one frame.
set_levelRequests a stacking level.
set_icon, set_theme, set_cursorChanges the icon, colour scheme or cursor.
focus, request_attentionAsks for keyboard focus (the desktop may refuse), or asks the desktop to flag the window.
begin_move_drag, begin_resize_dragHands a move or resize gesture to the desktop.
closeCloses the window without running close callbacks.

Windows methods

use_windows() methodResult
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

On this page