The platform layer
The platform contract in zgui-platform, and the native Wayland, winit, headless and experimental console backends that implement it.
Everything zgui needs from the machine arrives through the traits in zgui-platform: a surface to
draw into, callbacks from the event loop, the time, a way to wake the loop from another thread, and
the desktop's clipboards. This page describes that contract first, then each backend that implements
it. An application reaches the contract as zgui::platform.
| Backend | Crate | Used for |
|---|---|---|
| Native Wayland | zgui-platform-wayland | Wayland sessions on Linux and the BSDs (the default there). |
| winit | zgui-platform-winit | X11, Windows, macOS, and Wayland when forced. |
| Headless | zgui-platform-headless | Tests. No window system. |
| Linux console | zgui-platform-drm | Experimental. A bare console through DRM/KMS. Not published. |
The platform contract
| Trait | Implemented by | Role |
|---|---|---|
AppHandler | the runtime | The callbacks the event loop makes. |
PlatformCx | the backend | What the loop offers during one callback. |
Surface | the backend | Something to draw into that receives input. |
Clock | the backend | The time. |
Waker | the backend | Wakes the loop from another thread. |
Clipboard | the backend | The desktop's clipboards. |
zgui-platform names no windowing library and no graphics API, and is #![forbid(unsafe_code)].
Two unit tests in crates/zgui-platform/src/api.rs enforce this:
no_source_names_a_windowing_library_or_a_graphics_apirejects an import rooted atwinit,wgpu,glutin,vulkano,web_sys,sdl2,gtkorsoftbuffer.every_public_enumeration_is_extensiblerejects apub enumwithout#[non_exhaustive].
The contract does depend on accesskit, the interchange format for accessibility trees.
AppHandler
AppHandler is what a backend calls (crates/zgui-platform/src/app/mod.rs). Three methods are
required.
pub trait AppHandler: 'static {
fn surfaces_available(&mut self, cx: &dyn PlatformCx);
fn surfaces_lost(&mut self, cx: &dyn PlatformCx) { let _ = cx; }
fn surface_event(&mut self, cx: &dyn PlatformCx, surface: SurfaceId, event: SurfaceEvent);
fn wake(&mut self, cx: &dyn PlatformCx, reason: WakeReason);
fn idle(&mut self, cx: &dyn PlatformCx) -> IdlePolicy { let _ = cx; IdlePolicy::Block }
fn deadline_reached(&mut self, cx: &dyn PlatformCx) { let _ = cx; }
fn shutting_down(&mut self, cx: &dyn PlatformCx) { let _ = cx; }
}Box<T> implements AppHandler for any T: AppHandler + ?Sized, so a driver takes
Box<dyn AppHandler>. zgui_runtime::Runtime is the only implementation in the tree.
| Rule | Consequence |
|---|---|
surfaces_available comes first, and may come again. | No surface can be created before it. |
No surface outlives surfaces_lost. | surfaces_lost is suspension, not a close. The runtime keeps its window specifications and recreates the windows on the next surfaces_available. |
idle runs once per loop turn. | It runs on every pointer move, so it must be cheap. |
deadline_reached draws nothing by itself. | Whatever was waiting must call Surface::request_redraw. |
PlatformCx
PlatformCx is what the backend offers for the length of one callback
(crates/zgui-platform/src/cx.rs).
pub trait PlatformCx {
fn create_surface(&self, attributes: &SurfaceAttributes)
-> Result<Arc<dyn Surface>, PlatformError>;
fn destroy_surface(&self, id: SurfaceId);
fn surface(&self, id: SurfaceId) -> Option<Arc<dyn Surface>>;
fn surfaces(&self) -> Vec<Arc<dyn Surface>>;
fn monitors(&self) -> Vec<MonitorInfo>;
fn primary_monitor(&self) -> Option<MonitorInfo>;
fn color_scheme(&self) -> Option<ColorScheme>;
fn clipboard(&self) -> &dyn Clipboard;
fn capabilities(&self) -> &PlatformCapabilities;
fn scroll_settings(&self) -> ScrollSettings { ScrollSettings::default() }
fn clock(&self) -> Arc<dyn Clock>;
fn waker(&self) -> Arc<dyn Waker>;
fn set_app_menu(&self, menu: &AppMenu) { let _ = menu; }
fn request_exit(&self);
fn is_exiting(&self) -> bool;
}- Never store the context. It is valid only inside the callback, and on most platforms it is
neither
SendnorSync. Three things outlive a callback, and their types say so:Arc<dyn Surface>,Arc<dyn Clock>andArc<dyn Waker>. color_schemereturnsNonewhen the desktop cannot be asked. Never guess light: that shows a white flash to every user who chose dark.set_app_menureplaces the application menu. Backends without one ignore it. See Application events and the menu.
PlatformCapabilities starts from PlatformCapabilities::none(), so a capability nobody set reads as
absent. Its fields cover clipboard formats and the primary selection, drop types, IME and purpose
hints, absolute window positions, stacking levels, decorations, native pop-ups, layer surfaces,
drag sources, pointer confinement and lock, native gestures, the system colour scheme, the
application menu (app_menu) and reopen requests (reopen).
Surface
A Surface is something that can be drawn into and receive input
(crates/zgui-platform/src/surface/mod.rs). It is not called a window because the headless
implementation has none.
pub trait Surface: Send + Sync + 'static {
fn id(&self) -> SurfaceId;
fn size(&self) -> Size<DevicePx, Device>;
fn scale_factor(&self) -> f64;
fn refresh_rate_millihertz(&self) -> Option<u32> { None }
fn present_pacing(&self) -> PresentPacing { PresentPacing::Display }
fn presentation_timing(&self) -> Option<PresentationTiming> { None }
fn request_size(&self, size: Size<CssPx, Css>) -> Option<Size<DevicePx, Device>>;
fn set_min_size(&self, size: Option<Size<CssPx, Css>>);
fn set_max_size(&self, size: Option<Size<CssPx, Css>>);
fn request_redraw(&self);
fn pre_present_notify(&self);
fn redraw_declined(&self) {}
fn set_title(&self, title: &str);
fn set_visible(&self, visible: bool);
fn set_decorations(&self, decorations: Decorations);
fn set_resizable(&self, resizable: bool);
fn set_maximized(&self, maximized: bool);
fn set_minimized(&self, minimized: bool);
fn set_fullscreen(&self, mode: Option<FullscreenMode>);
fn set_position(&self, position: Point<CssPx, Css>) {}
fn position(&self) -> Option<Point<CssPx, Css>> { None }
fn is_maximized(&self) -> bool { false }
fn is_minimized(&self) -> Option<bool> { None }
fn fullscreen(&self) -> Option<FullscreenMode> { None }
fn set_window_level(&self, level: WindowLevel) {}
fn set_icon(&self, icon: Option<&WindowIcon>) {}
fn set_theme(&self, theme: Option<ColorScheme>) {}
fn focus(&self) {}
fn request_attention(&self, urgent: bool) {}
fn title_bar_double_click(&self) { self.set_maximized(!self.is_maximized()); }
fn begin_move_drag(&self) -> Result<(), Unsupported> { Err(Unsupported) }
fn begin_resize_drag(&self, edge: ResizeEdge) -> Result<(), Unsupported> { /* Err */ }
fn set_cursor(&self, cursor: CursorStyle);
fn set_pointer_passthrough(&self, passthrough: bool) -> Result<(), Unsupported> { /* Err */ }
fn set_text_input(&self, state: Option<TextInput>);
fn reset_dead_keys(&self) {}
fn push_a11y_update(&self, build: &mut dyn FnMut() -> TreeUpdate);
fn gpu(&self) -> Option<&dyn GpuSurface> { None }
fn gpu_shared(self: Arc<Self>) -> Option<Arc<dyn GpuSurface>> { None }
}sizeis in physical pixels; every size the caller passes is in CSS pixels.scale_factorconverts between them, and it is the surface's own, not the monitor's (see Scale factor).request_redrawcan be called from any thread and coalesces. Many requests before the next frame produce one frame.redraw_declinedreports a delivered redraw that the application refused to run, for example a configure deferred by resize pacing. The backend must commit nothing and owe the compositor nothing; the application asks for the frame again when its own deadline arrives. A redraw that ran and presented nothing is different: the backend keeps its pacing bookkeeping.title_bar_double_clickdoes what a double press on a title bar does. The default toggles maximised. The winit backend on macOS follows the user's System Settings preference (zoom, minimise, or nothing).push_a11y_updatetakes a closure. Building the update costs a tree walk, so a backend with no assistive technology listening never calls it.gpuandgpu_sharedare bothSomeor bothNone.GpuSurfaceis a blanket trait overSurface + HasWindowHandle + HasDisplayHandle.
Presentation pacing
PresentPacing says who waits for the display:
Displaylets the graphics API block during surface acquisition.Platformmeans the backend schedules frames itself, so the renderer uses a non-blocking present mode (see Present).
PresentationTiming can report the last presentation time, the measured interval and the next
predicted refresh. Each field is optional, and unknown is not zero.
Watchdog (also in zgui-platform) bounds how long a paced backend waits for a "frame shown"
report that may never come: four refresh intervals, but at least 200 ms. The next frame after it
expires is a probe, not a blocked acquire.
Creating a surface
SurfaceAttributes holds the role, title, size limits, resizability, decorations, transparency,
application identifier, requested position, maximised and full-screen state, stacking level, icon,
colour-scheme override, and title_buttons (where macOS places its window buttons over a window
with Decorations::NoTitleBar).
SurfaceAttributes::new(title) sets resizable: true and Decorations::Full.
SurfaceAttributes::default() keeps Decorations::Full but leaves resizable false.
Surfaces are always created hidden. There is no visible field, because the accessibility
adapter must be attached before a window is first shown. The order is fixed:
- Create the window hidden.
- Attach the accessibility adapter.
- Draw one frame.
- Call
set_visible(true).
The runtime makes the last call at the end of the first frame that presented
(crates/zgui-runtime/src/window/frame.rs). Two platform quirks are handled around it:
- macOS may report a hidden window's first frame as occluded, because the hidden layer has no drawable. The runtime then shows the already-composed window and asks for another frame.
- Windows sends no paint message to a hidden window. The winit backend therefore delivers a
hidden window's redraw request itself, through its event-loop proxy (
UserEvent::Redraw).
Surface roles
SurfaceRole is Toplevel, Popup(PopupPlacement) or Layer(LayerPlacement). A backend must
refuse an unsupported role with PlatformError::Unsupported; it must not turn a menu or a panel
into an ordinary window.
SurfaceAttributes::popup(placement)creates an undecorated, non-resizable pop-up. The placement names the parent surface, anchor rectangle, anchor and gravity, the allowed slide, flip and resize adjustments, and whether to grab input.PopupPlacement::below(parent, rect)is the grabbing, left-aligned dropdown default.SurfaceAttributes::layer(placement)creates a shell surface:Background,Bottom,ToporOverlay, with anchored edges, margins, an exclusive zone, keyboard interactivity and an optional output name.
Check native_popup_surfaces and layer_surfaces before creating these roles. Only the native
Wayland backend supports them. WindowOptions and the built-in overlay components do not use them
yet; menus, tooltips and dropdowns are drawn inside their owner window.
Surface events
One #[non_exhaustive] enum, SurfaceEvent, carries everything that happens to a surface
(crates/zgui-platform/src/surface/event.rs).
| Variant | Meaning |
|---|---|
Resized(Size<DevicePx, Device>) | The new physical size. |
ScaleFactorChanged { scale_factor, size } | The new ratio and the resulting size, as one event. |
RedrawRequested | Only in answer to a redraw request. |
CloseRequested | The user asked; nothing has closed yet. |
Destroyed | The surface is gone. |
Focused(bool) | Keyboard focus. |
Occluded(bool) | The surface is entirely hidden. |
ResizingChanged(bool) | An interactive resize started or ended. Best effort; currently sent by the Wayland backend. The false edge lets paced resizing settle at once. |
ColorSchemeChanged(ColorScheme) | The desktop's colour scheme changed. |
Pointer { action, event, modifiers, timestamp } | Mouse, touch and stylus, as one stream. |
Wheel { event, modifiers, timestamp } | A wheel or touchpad scroll. |
Key { state, event, modifiers, timestamp } | A key press or release. |
ModifiersChanged(Modifiers) | Sent on every change of the held set, including next to the key event that changed it. |
Ime(ImeEvent) | An input-method event. See IME and text input. |
Drag(DragEvent) | A file drag, carrying the whole set of paths at every stage. |
to_dispatch() turns an event into an (EventKind, Payload) for the input system. It returns
None for ModifiersChanged and for Drag(Entered | Moved | Left), which change state without
being an occurrence. Because ModifiersChanged dispatches nothing, a consumer can track modifiers
from it or from key events without counting twice.
Wheel deltas are positive in the direction the scroll offset grows. A backend whose platform reports the opposite sign converts them (see Wheel sign and phase).
Clock and Waker
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Instant;
fn origin(&self) -> Instant;
fn timestamp(&self) -> Timestamp { /* now - origin */ }
}
pub trait Waker: Send + Sync + 'static {
fn wake(&self, reason: WakeReason);
}Nothing above this seam reads the system clock. VirtualClock
(crates/zgui-platform/src/clock/manual.rs) starts at its origin and moves only when advance(by)
is called. Both the headless backend and zgui-testkit-scene re-export it.
Waker is the only object in the contract that crosses threads. wake never blocks and never
fails; a wake sent to a finished loop is dropped.
#[non_exhaustive]
pub enum WakeReason {
ReactiveWork { surfaces: Box<[SurfaceId]> },
A11yAction(accesskit::ActionRequest),
A11yTreeRequested(SurfaceId),
ClipboardRead { serial: ClipboardSerial, result: Result<ClipboardData, ClipboardError> },
AppWork,
DeviceLost,
ColorSchemeChanged,
App(AppEvent),
SurfaceStateChanged(SurfaceId),
}WakeReason::surfaces() returns the surfaces a wake is for. An empty slice means all of them; a
non-empty one is a restriction the handler must honour. An image decoded for one window is no
reason to redraw another. AppWork tells the handler to drain deferred window opens, closes, quits
and clipboard requests on a turn that has a PlatformCx; it does not mean a window needs a frame.
Clipboard
pub trait Clipboard {
fn read(&self, kind: ClipboardKind, format: ClipboardFormat) -> ClipboardSerial;
fn read_blocking(&self, kind: ClipboardKind, format: ClipboardFormat)
-> Result<ClipboardData, ClipboardError>;
fn write(&self, kind: ClipboardKind, data: ClipboardData, options: ClipboardWriteOptions)
-> Result<(), ClipboardError>;
fn clear(&self, kind: ClipboardKind) -> Result<(), ClipboardError>;
}A read is a request. The content belongs to another process, which may answer late or never.
read returns a ClipboardSerial, and the answer arrives as WakeReason::ClipboardRead.
read_blocking exists because a desktop can often answer at once; it may refuse.
ClipboardKind is Standard or Primary. The primary selection is the X11 and Wayland clipboard
filled by selecting text and pasted with the middle button. It is a separate slot.
Both desktop backends support only ClipboardFormat::Text. Html, FileList and Image fail with
ClipboardError::UnsupportedFormat for both read and write, because a refusal and an empty value
mean different things to a paste command. An empty read is Empty(kind), not Ok("").
The runtime exposes reads through use_clipboard(): it assigns a ClipboardSerial, stores the
callback, and routes WakeReason::ClipboardRead back to it on the UI thread. Writes, clears and
reads are queued until a turn has a PlatformCx. Editable fields handle Copy, Cut and Paste
themselves. See Clipboard for the application API.
Application events and the menu
Some requests are for the application, not one window. They arrive as WakeReason::App(AppEvent):
AppEvent | Sent when |
|---|---|
Reopen | The user asks for the application again: a dock icon click on macOS. |
Menu(MenuId) | The user picks an application action from the menu. |
Role(MenuRole) | The user picks an editing role (Undo, Redo, Cut, Copy, Paste, Select All). |
WakeReason::SurfaceStateChanged(id) reports that the desktop has finished a state change, such
as leaving full screen, after the last resize it caused. The runtime then reads the window state
again.
The menu model is in zgui_platform::menu and re-exported as zgui::desktop. AppMenu holds
Submenus, which hold MenuEntry values (Action(MenuAction), Role(MenuRole), Submenu,
Separator). A MenuAction has an id, a label, an optional Shortcut, and enabled and checked
states. MenuRole covers the standard desktop entries (About, Services, Hide, Hide Others, Show
All, Minimize, Zoom, Full Screen, Bring All to Front) and the editing roles. MenuRole::shortcut()
gives each role its standard chord using Modifiers::PRIMARY, which is Command on macOS and
Control elsewhere.
How the runtime uses the menu:
App::with_menu(build)runsbuildin the application scope afterwith_context, and runs it again whenever a signal it read changes.- When
capabilities().app_menuis true, each new version is passed toset_app_menu. Only the winit backend on macOS sets it. on_menu,on_reopenandon_exit(inzgui::desktop) register callbacks. Each returns anAppHookGuardthat unregisters on drop.on_exitruns on every exit path before windows close.- An editing role is replayed into the focused window as a key press of its shortcut, so text fields and custom editors handle it exactly as they handle the keys.
- A window runs a menu action whose shortcut it received, when nothing in its document claimed the chord.
For the application-level API, see Shipping.
Idling and parking
After each loop turn, AppHandler::idle tells the backend how long it may block:
#[non_exhaustive]
pub enum IdlePolicy { Block, BlockUntil(Instant), Spin }
impl IdlePolicy {
pub fn until(deadline: Instant, now: Instant) -> Self; // Block when deadline <= now
pub fn merge(self, other: Self) -> Self; // Spin wins, else the earliest deadline
pub const fn deadline(self) -> Option<Instant>;
}Three failures at this seam all look like "nothing happens":
| Failure | Cause | Defence |
|---|---|---|
| Stall | A deadline is reached, and nothing turns it into a redraw request. | deadline_reached calls request_redraw. |
| Spin | A deadline already in the past is installed. The loop reports it reached on every turn and uses a full core. | IdlePolicy::until collapses to Block; Runtime::idle asks for a frame instead. |
| Dropped moment | The application names a moment a few microseconds ahead, and it passes before the loop installs it. | The park state machine hands it over instead of dropping it. |
The runtime side of parking (which deadlines a window waits on) is described in
The frame. The backend side is the park state machine,
zgui_platform::app::park, shared by the winit, Wayland and console loops:
#[must_use = "an install that is dropped may be dropping a deadline the application is waiting for"]
#[non_exhaustive]
pub enum Install { Ready(Parked), Overdue(Instant) }
impl Install {
pub const fn overdue(self) -> Option<Instant>;
pub fn park(self, deliver: impl FnOnce(Instant)) -> Parked;
}Park::install never installs a moment that is not strictly in the future and never discards one.
Install::park is the only way from Overdue to Parked, and it requires the delivery callback,
so the obligation cannot be lost. A turn that delivered an overdue moment then parks
Parked::Never, because the policy the application returned earlier is stale.
The headless harness asserts resumes <= frames + 1 after every turn, which separates a spin from a
correct park. A loop turn over a still document measures 0.07 µs on the reference machine and
runs zero frames (idle.turn, idle.frames in docs/performance.md).
Scale factor
The scale factor is physical pixels per CSS pixel. It belongs to the surface, not the monitor:
Wayland sets it per surface through wp-fractional-scale, and X11 has no per-window scale at all.
MonitorInfo::scale_factor exists but is not a substitute for Surface::scale_factor.
The ratio changes when a window moves to another monitor, when desktop scaling changes, and on the
first configure a Wayland compositor sends. Each backend reports
ScaleFactorChanged { scale_factor, size }. The runtime handles it in Window::rescale
(crates/zgui-runtime/src/window/scale.rs):
| State | Unit | Effect of a new ratio |
|---|---|---|
| Computed styles | CSS px | None. |
| Layout cache | device px | Cleared in full with zgui_layout::tree::dirty::mark_all_dirty. |
| Shaped paragraphs | device px | Keyed by ratio, so they miss and reshape. |
| Rasterised glyphs | device px | Keyed by device size, so they miss and re-rasterise. |
| Scroll offsets | device px | Multiplied by new / old. |
| Media device | ratio | Rebuilt, for resolution and dppx queries. |
The layout cache must be cleared explicitly. It is keyed by the question layout asked (run mode, available space, known size), and some questions, such as a min-content width, are identical at every ratio. Without the clear, boxes sized by their own text keep their old size and the document is only partly rescaled.
rescale also passes the new scale to the view host and rebuilds the viewport in CSS pixels,
carrying the colour scheme across. On the accessibility side, only the root node changes: it carries
Affine::scale(scale), and every other node's bounds are in CSS pixels.
Accessibility
AccessKit carries a second, smaller description of the interface to the operating system's
accessibility service: what each control is, its name, its value, and where it was drawn.
Accessibility covers the a11y: attributes and projection rules;
this section covers the platform side.
Publication. Window::publish_a11y (crates/zgui-runtime/src/window/a11y.rs) runs after the
renderer, so reported positions match what was drawn. It always retires the frame's accessibility
marks, even with no listener; otherwise the leftover dirty bits would make every other stage descend
the whole tree. The update itself is built inside the closure passed to push_a11y_update, so with
no assistive technology running the phase costs one match.
Diffing. A11yBuilder::build (crates/zgui-a11y/src/build/) sends a full tree on first
publication or when more than 4096 nodes are owed. Otherwise it sends each changed node with its
parent, and only when its projection differs from what was last sent. Node identity is the
document key: NodeId(key.as_u64()).
Focus is a field of every TreeUpdate. An unprojectable focus target falls back to the root,
because a dangling id crashes the consumer on a thread this process does not own. A
debug_assert! checks every published update with zgui_a11y::dangling.
Requests from the adapter:
| From the adapter | WakeReason | Runtime response |
|---|---|---|
InitialTreeRequested | A11yTreeRequested(surface) | publish_full_a11y_tree() |
ActionRequested(request) | A11yAction(request) | Offered to each window until one accepts it. Action::Click becomes an ordinary click dispatched through capture, target and bubble. |
AccessibilityDeactivated | none | Nothing to do. |
IME and text input
An input method (IME) turns keystrokes into text for scripts with more characters than keys. It shows provisional text and a candidate window while the user composes. The window must be told that text input is wanted, and where the caret is, so the candidate window appears in the right place.
pub struct TextInput {
pub caret_origin: Point<CssPx, Css>, // from the surface's top-left corner
pub caret_size: Size<CssPx, Css>,
pub purpose: TextInputPurpose,
}Surface::set_text_input(Some(state)) sets all three in one call. Both desktop backends send the
caret area and purpose before enabling input, so the input method knows the caret position before
it shows anything.
Incoming events map to zgui_vocab::ImeEvent: Enabled, Preedit { text, cursor },
Commit(text), Disabled. The preedit cursor is a byte range, because input methods select spans
as often as they place a caret.
zgui_input::ime::Ime remembers what the surface was last told and reports only real changes, so
an unmoved caret does not wake the input method every frame. The runtime updates it when focus
moves and after each edit. Focus leaving an editable element abandons the composition.
TextInputPurpose has eight values and both desktop backends can pass them on, but the runtime
always sends TextInputPurpose::Normal (crates/zgui-runtime/src/window/input.rs). A password
field does not yet report itself as secret.
Drivers and backend selection
A driver is a function that runs an AppHandler on some platform. Which driver an application uses
is decided in one place (crates/zgui/src/app/mod.rs):
pub type Driver = fn(Box<dyn AppHandler>) -> Result<(), PlatformError>;
pub fn desktop() -> Driver;
impl App {
pub fn run<F, V>(self, view: F) -> Result<(), AppError>;
pub fn run_on<F, V, D>(self, driver: D, view: F) -> Result<(), AppError>
where
F: FnMut() -> V + 'static,
V: IntoView,
D: FnOnce(Box<dyn AppHandler>) -> Result<(), PlatformError>;
pub fn into_handler<F, V>(self, view: F) -> Result<Handler, AppError>;
}
impl Handler {
pub fn into_runtime(self) -> zgui_runtime::Runtime;
pub fn drive<D>(self, driver: D) -> Result<(), AppError>;
}App::run is run_on(desktop(), view). On Linux and the BSDs, desktop() returns the native
Wayland driver when a Wayland display is available, and the winit driver otherwise. macOS, Windows
and X11 use winit. ZGUI_PLATFORM=winit forces winit; ZGUI_PLATFORM=wayland requires the native
backend. The choice is made before either backend starts, and a failed connection is returned as an
error rather than silently switching backends.
| Linux session and selection | Backend | Properties |
|---|---|---|
Wayland, automatic or ZGUI_PLATFORM=wayland | native Wayland | Native pop-ups, optional layer surfaces, portal colour scheme, platform-paced presentation. |
Wayland with ZGUI_PLATFORM=winit | winit | Comparison path; no special surface roles; display-paced presentation. |
| X11 | winit | Absolute positions and monitor queries work; arboard provides the clipboard. |
Pass a driver yourself for one of two reasons:
- Run somewhere else. A test drives the same application over the headless backend, and the
console entry point passes
zgui_platform_drm::run. - Wrap the real desktop. Pass
|handler| zgui::app::desktop()(Box::new(Wrapper(handler))), whereWrapperis your ownAppHandlerthat forwards to the inner one. It sees every event and can inject its own, while the window and graphics device stay real.
Handler::drive takes the runtime's failure cell before handing the runtime over, so a machine with
no usable graphics adapter returns AppError::GpuUnavailable instead of exiting successfully. After
the driver returns, it drops whatever is left in the task pool.
into_handler decides the renderer factory, metrics source, text engine and glyph rasteriser. App
does not expose the last three, because they come from Fonts. A host that owns its own wgpu device
can supply a renderer factory built on it; see
Adopting a host-opened device.
zgui_runtime::App::run(view, driver) takes its arguments in the opposite order from
zgui::App::run_on(driver, view).
The native Wayland backend
zgui-platform-wayland speaks the Wayland protocols directly, using smithay-client-toolkit for the
common objects and calloop for the loop. It compiles to an empty crate off Linux and the BSDs.
It requires wl_compositor, wl_shm and xdg_wm_base; without them, start-up returns
PlatformError::Backend. Optional protocols add capabilities:
| Protocol | When present | When absent |
|---|---|---|
| fractional scale and viewporter (both) | per-surface fractional scale | whole-number output scale |
| presentation feedback | measured presentation time and interval | output-mode interval when known |
| data device | text clipboard and incoming file drops | neither |
| primary selection | the selection clipboard | standard clipboard only |
| text-input-v3 | IME and purpose hints | no IME |
| server decorations | compositor-drawn frame | application decorations |
| settings portal | live system colour scheme | scheme unknown |
| wlr layer shell | layer surfaces | layer roles refused |
XDG pop-ups are part of the required shell, so native_popup_surfaces is always true. Toplevels
cannot set an absolute position or a stacking level. Keyboard input goes through xkbcommon, and
accessibility through accesskit_unix. The backend has no application menu and no reopen request.
The scale factor combines the preferred fractional scale with the configured size, or uses the whole-number output scale when fractional-scale and viewporter are missing.
The clipboard uses the data-device protocols on the backend's own connection. It offers text when the data device is present, and the primary selection only when that protocol is also present.
A Wayland window cannot read or set its global position, so accessibility bounds use the surface origin. Screen-coordinate features of assistive technology, such as a magnifier following focus, get less information there. This is a protocol limit, not a backend one.
Frame pacing
Wayland sends wl_surface.frame when a surface may draw again, so this backend returns
PresentPacing::Platform and owns the cadence:
- A surface that owes no callback may draw in the current turn.
pre_present_notifyrequests the next frame callback and presentation feedback before the buffer is committed.- A later redraw waits for that callback.
- If the compositor never answers, the
Watchdogreleases the wait after four refresh intervals or 200 ms, whichever is longer.
A redraw that ran but presented nothing still ends in a bufferless commit, because a frame callback
is attached to a commit and the chain would otherwise stop. A declined redraw (redraw_declined)
commits nothing, so the application's own deadline is answered in the same turn.
The backend draws nothing before a surface's first configure. After that, it reports the surface as
occluded while the compositor marks it suspended, after it leaves every output, or after three
unanswered frame callbacks. With presentation feedback, presentation_timing reports the actual
shown time and interval, and moving to another output updates the interval. The xdg-toplevel
resizing state is reported as ResizingChanged.
When ZGUI_LATENCY names a file, the loop writes the latency trace there when it ends.
The winit backend
zgui-platform-winit is the portable backend, and the only crate that names winit.
pub fn event_loop() -> Result<EventLoop<UserEvent>, PlatformError>;
pub fn run(handler: Box<dyn AppHandler>) -> Result<(), PlatformError>;run builds the loop, wraps the handler in WinitApp, and blocks until the application stops.
WinitApp<A> is generic over the handler, so a caller who owns both can read the application back
after the loop ends.
One loop turn
| winit callback | What happens |
|---|---|
new_events | Counts the turn. The first call discovers the theme, settles capabilities, connects the clipboard and installs the macOS reopen hook. ResumeTimeReached resumes the park and calls deadline_reached. |
resumed | surfaces_available |
suspended | surfaces_lost, then every native window is dropped. |
user_event | Wake(reason) → wake; A11y(event) is translated first; Redraw(window) delivers a hidden window's redraw. |
window_event | The accessibility adapter sees the raw event first, then translate, then surface_event. |
about_to_wait | Flush drags, idle, install the park, set the control flow. |
exiting | shutting_down |
Parked::Indefinitely maps to ControlFlow::Wait, Parked::Until(t) to WaitUntil(t), and
Parked::Never to Poll.
Creating a window
WinitCx::create_surface creates the window with .with_visible(false) regardless of the request,
passing every size as a logical size. It numbers the surface (from 1, never reused), creates the
AccessKit adapter in the loop thread's adapter registry, and on macOS installs the per-window hooks
listed under macOS integration.
On Linux and the BSDs, the application identifier is set through both
WindowAttributesExtWayland::with_name and WindowAttributesExtX11::with_name; it becomes the
Wayland app_id or the X11 WM_CLASS. Windows and macOS take identity from the package and ignore
it.
AccessKit adapters are thread-local to the event loop, keyed by SurfaceId, because Windows
accessibility handles and AppKit objects must stay on the thread that created them, while a surface
can be shared with other threads.
Translating events
zgui_platform_winit::app::events::translate is public, so a program that owns its own winit event
loop can still produce zgui events:
pub fn translate(
state: &mut WindowState,
scale_factor: f64,
size: impl FnOnce() -> Size<DevicePx, Device>,
timestamp: Timestamp,
event: WindowEvent,
) -> Option<SurfaceEvent>;Keep one WindowState per window and pass every event of that window in order. size is called
only for a scale change. Dragged files are gathered in WindowState::drag; take them with
Drag::take at the end of each loop turn.
winit WindowEvent | SurfaceEvent |
|---|---|
Resized | Resized |
ScaleFactorChanged | ScaleFactorChanged { scale_factor, size: size() } |
CloseRequested, Destroyed, Focused, Occluded, RedrawRequested | the same variant |
ThemeChanged | ColorSchemeChanged |
ModifiersChanged | ModifiersChanged; the set is stored and attached to later events |
KeyboardInput | Key, unless is_synthetic |
CursorMoved | Pointer { action: Moved }; the position is stored |
CursorEntered / CursorLeft | Pointer { action: Entered / Left } |
MouseInput | Pointer { action: Pressed / Released } |
MouseWheel | Wheel, at the stored pointer position |
Touch | Pointer, on the same stream as the mouse |
Ime | Ime |
HoveredFile, DroppedFile, HoveredFileCancelled | None; gathered into a DragEvent |
| anything else | None |
The cases that need care:
- Synthetic key events are dropped. They report keys already held when the window gained focus; dispatching them would type characters nobody pressed.
- The pointer position is remembered, because wheel events and file drops carry none.
- File drags are gathered. winit reports one path at a time and never says the set is complete,
so the loop flushes whole
DragEvents inabout_to_wait. - On macOS, Control-click is a secondary press. A primary press with Control held reaches the document as a secondary press without Control, and its release follows it.
Wheel sign and phase
crates/zgui-platform-winit/src/input/wheel.rs performs the framework's only wheel sign change.
winit reports positive deltas in the direction the content should move; zgui's convention is
positive in the direction the scroll offset grows.
MouseScrollDelta::LineDelta(x, y) => ScrollDelta::Lines { x: -x, y: -y },
MouseScrollDelta::PixelDelta(p) => ScrollDelta::Pixels(Size::new(
CssPx(-(p.x / scale) as f32),
CssPx(-(p.y / scale) as f32),
)),Lines stay lines, because converting a notch to pixels needs the scrolled element's line height.
A line delta is always ScrollPhase::Discrete. A pixel delta maps winit's touch phase to
Started, Moved or Ended. On macOS, winit merges the finger phase and the momentum phase, so
the backend reads both from AppKit with an event monitor and reports ScrollPhase::Momentum after
the fingers lift.
desktop_scroll_settings() returns lines_per_notch = 3.0, direction = AsReported on every
target (natural scrolling is already applied by the OS input stack), and WheelMotion::Discrete,
except Continuous on macOS.
Capabilities
| Field | winit backend |
|---|---|
clipboard_formats | [Text] |
clipboard_primary_selection | Linux and BSD only |
drop_mime_types | ["text/uri-list"] |
ime, ime_purpose_hints | true |
absolute_window_position, window_levels | false under Wayland, read from the display handle |
decorations | DecorationSource::Platform |
system_color_scheme | true only when a theme was discovered |
app_menu, reopen | macOS only |
native_popup_surfaces, layer_surfaces, drag_source, pointer_confine, pointer_lock, native_gestures | false |
The set is settled once, on the first callback, so capabilities() can return a borrow.
Clipboard
DesktopClipboard (crates/zgui-platform-winit/src/clipboard/mod.rs) picks an implementation
once, from the running loop's display handle:
- Wayland:
smithay-clipboard, on the application's own connection, using the ordinarywl_data_device.arboard's Wayland support uses the privileged data-control protocol, which several compositors do not offer, so it is compiled out withdefault-features = false. - Everything else, including X11:
arboard, opened lazily on first use. An application that never copies opens no connection.
macOS integration
winit does not expose several AppKit objects, so crates/zgui-platform-winit/src/macos/ reaches
them through objc2 and builds the menu with muda. Every call runs on the main thread inside an
event-loop callback.
| Feature | How it works |
|---|---|
| Application menu | set_app_menu builds a muda menu from the AppMenu. Desktop roles are AppKit's own items; editing roles are ordinary items answered by the framework. Picks are sent through the waker as AppEvents. |
| Command chords | Once a menu is installed, a key monitor offers each Command chord to the focused zgui view before the menu sees it, so a text field keeps the chords it handles. The menu answers chords nothing claimed. Chords of desktop roles and window cycling stay with AppKit. |
| Reopen | A method added to winit's application delegate answers applicationShouldHandleReopen:hasVisibleWindows: and sends AppEvent::Reopen. AppKit still restores minimised windows itself. |
| Title-bar buttons | With Decorations::NoTitleBar and title_buttons set, the close, minimise and zoom buttons are moved into the given band. They are placed again after a resize, a key-window change and leaving full screen. Other desktops ignore title_buttons. |
| Title-bar double click | Reads the user's preference (zoom, minimise, or nothing). |
| Full screen | AppKit's end-of-transition notification sends SurfaceStateChanged, so the runtime reads the state after the last resize of the transition. |
| Scroll momentum | An event monitor records AppKit's finger and momentum phases for ScrollPhase::Momentum. |
| Text keys | zgui-edit follows the macOS text-field bindings: Command moves to an edge, Option moves by word, and Control runs the Emacs keys. |
The headless backend
zgui-platform-headless implements the contract with no window system. It is
#![forbid(unsafe_code)], is a dev-dependency of zgui, and is not re-exported: a test names it in
its own [dev-dependencies].
| Type | What it is |
|---|---|
Headless | PlatformCx with a VirtualClock, declared capabilities, monitors and colour scheme. |
OffscreenSurface | A Surface that records calls instead of acting on them. |
MemoryClipboard | Two independent slots, standard and primary. |
RecordingWaker | Queues wake reasons. |
Harness<A: AppHandler> | Runs loop turns by hand, with real parking rules and no blocking. |
Configure what the desktop can do. Headless::with_capabilities, with_monitors,
with_scroll_settings and set_color_scheme declare answers the headless platform cannot perform,
so a component can be tested under each one. OffscreenSurface::resize, set_scale_factor and
set_refresh_rate_millihertz change a surface mid-test.
Read what happened. redraws_requested, has_pending_redraw, take_pending_redraw,
a11y_updates, last_a11y_update, a11y_log, take_a11y_log, text_input_log,
last_text_input, cursor_log, last_cursor, is_visible, title. The accessibility log keeps
the sequence of updates, because each update is a difference against the ones before. It is bounded
at A11Y_LOG_NODES (2²⁰) nodes, dropping the oldest updates first; a long-running driver drains it
with take_a11y_log. push_a11y_update always calls the closure.
Drive the loop. Harness provides deliver, deliver_all, deliver_to_first, pump,
settle, advance, run_for, suspend, resume and shut_down.
deliverapplies an event to the surface first and then delivers it, as a window system does. DeliveringSurfaceEvent::Pointeris how a test gets:hoverand:activeinto a document.advanceclears the parked deadline before notifying the application, then checks the park invariant.assert_park_invariantpanics whenresumes > frames + 1.
The headless backend is never a fallback for a real window. A windowing backend that cannot open a window or a device reports the error.
The Linux console backend (experimental)
The console stack runs an application on a bare Linux console with no display server. It is experimental, lives in the repository, and is not published:
| Crate | Role |
|---|---|
zgui-drm | DRM/KMS: modes, planes, framebuffers, page flips, from bindings generated from vendored kernel headers. |
zgui-evdev | evdev input devices and events. |
zgui-libinput, zgui-seat, zgui-xkb | libinput, libseat and libxkbcommon, each loaded with dlopen at run time. None is needed to build, and a console session starts without them. |
zgui-platform-drm | The platform backend. |
zgui-console | The entry point: RunDrm::run_drm. |
zgui does not depend on any of them. An application names zgui-console beside zgui and calls
run_drm in place of run:
use zgui::prelude::*;
use zgui_console::RunDrm;
fn main() -> Result<(), zgui::Error> {
app().run_drm(|| view! { column() })
}run_drm opens one graphics device, lights every connected display at its preferred mode, and
installs the console backend and its renderer together. Where the device supports exportable scanout
images, frames are composed straight into the buffers the display scans out. Otherwise each frame
is read back and copied, which works on every machine.
Before running it, note:
- Device access. With a seat daemon, libseat opens the card and no privilege is needed. Without one, the process takes DRM master itself, which needs root or a free virtual terminal. It refuses to start while a compositor holds the card.
- Input. Every keyboard and pointer is grabbed. Keys are translated by libxkbcommon when
available, with the layout read from
XKB_DEFAULT_LAYOUT,/etc/vconsole.conf,/etc/default/keyboardor the X11 keyboard config, and otherwise from the kernel's console keymap. Devices plugged in later are picked up; unplugged ones release their keys and buttons. The cursor uses a hardware plane where one exists and is drawn into the frame otherwise. - No built-in quit key.
Ctrl+Cdoes not raiseSIGINT, because the keyboard is grabbed. The application must bind its own exit key. - Terminal switching.
Ctrl+Alt+Fnasks the seat daemon for that terminal; devices are released and reopened around the switch. Without a daemon, the request is refused and logged once. - One pointer, no multi-touch. Touchscreens and tablets drive the same pointer.
examples/tty.rs is a working example. Build it with
cargo build -p zgui-examples --example tty --features drm and run it from a spare virtual
terminal. The console crates need the pinned nightly toolchain (zgui-xkb).
Writing another backend
Each item below is a defence in the shipped backends, and each fails quietly when missed.
| Do not | Because |
|---|---|
Store the PlatformCx | It is valid for one callback and is usually neither Send nor Sync. |
| Create a visible window | The accessibility adapter must attach before the first show. |
| Assume a hidden window gets redraws | Windows sends none; deliver them yourself until the first frame shows the window. |
Answer ColorScheme::Light when the desktop cannot be asked | Dark-mode users get a white flash. Answer None. |
| Install a deadline that is not strictly in the future | The loop spins. |
| Drop a deadline the application named | The loop stalls. |
| Commit after a declined redraw | It puts the application's deadline behind a compositor round trip. |
| Skip the commit after a redraw that ran but drew nothing | The frame-callback chain ends and the surface never draws again. |
| Dispatch synthetic key events | They type characters nobody pressed. |
| Invent a refresh rate | Answer None. The one fallback is zgui_platform::refresh_interval(None), 60 000 mHz. |
Answer gpu() and gpu_shared() differently | Both are Some or both None. |
Share one slot between Standard and Primary | Every copy would overwrite the user's selection. |
| Report wheel deltas in the platform's sign | zgui's deltas are positive in the direction the offset grows. |
| Mark a single-surface wake as global | Every window would redraw. |
Let a surface outlive surfaces_lost | That is a crash, not a leak. |
| Fall back to a buffer when a device cannot be opened | Report the failure instead. |
The mechanical checks are in crates/zgui-platform/src/api.rs. The winit backend compares its real
loop with the contract's test driver in crates/zgui-platform-winit/tests/both_backends.rs, and the
Wayland backend has protocol-harness tests for frame chains, declined redraws, occlusion, input,
clipboard, wakes and parking. Tests against a real loop each run as their own binary with
harness = false, because a process may create only one event loop, usually on its first thread.
Without a display server they print SKIPPED: and pass.
Unsupported features
| Capability | Status |
|---|---|
| Native file dialogs | Absent. |
| Application menu | macOS only, through App::with_menu. Other desktops have no menu outside the window; draw one in the window. |
| Native context menus | Absent. |
| System tray icons | Absent. |
| Desktop notifications | Absent. |
| Overlays as native pop-ups | The Wayland backend supports the pop-up role, but the overlay components still draw inside their owner window. |
| Dragging out to another application | drag_source is false everywhere. Drops into the application work. |
| Pointer confinement or lock | false in every desktop backend. |
Next
The renderer
The Renderer and VectorRaster contracts, the wgpu backend, frame planning, partial redraw, presentation, atlases, and how each visual feature is drawn.
The crate map
Every crate in the workspace with its layer and publication status, the external dependencies, the ledger checks that keep the graph layered, feature flags, and how a release is made.