UI / WebView
For iOS and Android project generation, see the mobile app guide and the #ui/phone API.
#ui owns windows, events and desktop services; #ui/draw records drawing frames; #ui/layout computes layout; #ui/chart renders native charts and data visualizations; #ui/widgets manages controls, interaction and retained scenes; #ui/webview hosts web content and request bridging.
#ui · #ui/draw · #ui/layout · #ui/chart · #ui/widgets · #ui/webview
Browser canvas and native / WebView boundaries
Browser canvas: Start with the playground counter project. Its WASM interpreter and canvas adapter implement a subset of drawing and widget interactions. Native windows, desktop services, OS dialogs, native IME behavior and ui/webview hosting are outside that browser path; browser output does not establish desktop parity.
Native / WebView: Run with the local SDK and the target OS libraries: AppKit / WebKit on macOS, the Windows host / WebView2 on Windows, and GTK4 / WebKitGTK 6.0 on Linux. Use xu doctor --desktop --target <target> before packaging. A successful cross build is code-generation evidence; GUI interaction, IME, disposal and WebView behavior still need acceptance on the target machine. Those platform results remain unverified here.
See download platform boundaries and status before choosing a target.
Browser playground
Open the playground without installing the SDK, choose one of 46 component experiences from the template library, then edit and rerun its Xu source. Every component experience executes Xu/WASM. Some use composed or bounded implementations, such as a DatePicker date strip, a WebView placeholder and basic key editing; each template describes its scope. The three-page control gallery is another starting point.
| Task | Operation |
|---|---|
| Phone workspace | Switch between Files, Editor, Preview and Output while keeping code and widget state. UI examples open Preview; ordinary programs open Output. Return from template details to keep your search. |
| Inspect the canvas | Fit shows the whole canvas; 100% keeps its original size. When the canvas exceeds the viewport, enable Pan and drag the view, then disable Pan before clicking or dragging controls. Expand is also available on desktop. |
| Select and check | ComboBox opens a candidate menu; arrows and Enter select an item. Open MultiSelect to toggle individual checkboxes; Escape closes the menu and keeps the selection. |
| Popovers and dialogs | Apply in Popover saves preferences; Cancel, an outside press or Escape discards unsaved changes. Modal blocks background interaction, keeps Tab focus inside the dialog and restores trigger focus when closed. |
| Adjust a color | Drag the channel sliders in ColorPicker; arrow keys remain available after release. The canvas and output show the color value. Disable Pan to interact with the sliders. |
| Keyboard controls | Click the canvas or reach it with Tab first. Tab / Shift+Tab move focus, Enter / Space activate and arrows adjust supported controls. Single Escape is handled first by Xu controls to close menus or overlays; press Escape twice or Shift+Escape to leave canvas focus. |
The workspace and examples use a pinned XUUI design reference. Focus uses one cinnabar boundary, selected controls use theme colors, and control labels align vertically using visible glyph bounds. Xu paints widget focus on the canvas. Examples keep a fixed XUUI theme while the surrounding preview panel follows the site theme. The browser playground supports throttled idle hover, wheel zoom/scroll, and browser-assisted text selection, clipboard copy/paste, and IME or mobile soft-keyboard input in editable text demos. Browser text layout still uses estimated metrics; native OS text shaping, desktop TextInput sessions, native windows, ui/webview, and per-widget DOM screen-reader semantics still require the local SDK.
Reading documentation or opening the homepage does not preload WASM. Running code or opening an explicit example loads it on demand, so the first run can take longer. Run again after a failed download or initialization; Stop terminates the current worker. Linear memory grows dynamically on demand up to 256 MiB, with Copy-on-Write (CoW) checkpoint preview for fast interactive replay. Ordinary programs have a 10-second execution budget; Widgets examples have 30 seconds. Use the local SDK for networking, system services, desktop TextInput sessions, ui/webview, or native windows.
Build and examples
An application has main.xu, xu.xun and brand/ containing a PNG icon, with optional www/ resources. macOS uses AppKit/WebKit, Windows uses the native host and WebView2, and Linux uses GTK4 with WebKitGTK 6.0 for web content. Check the target toolchain before packaging.
# Run from the matching Xu source root; the application must contain xu.xun
bin/xu doctor --desktop --target macos-arm64
XU_UI_PACK=1 bin/xu build /path/to/examples/examples/16_ui_webview/style_gallery \
--target macos-arm64 --desktop -o /tmp/XuStyles
The examples repository provides python3 scripts/ui_examples.py check all and run style_gallery; set XU_ROOT to the matching release SDK. Outputs go to build/ui/<target>/: .app on macOS, .exe on Windows and ELF on Linux. Cross compilation does not establish target-machine interaction support.
| Learning order | Examples | Focus |
|---|---|---|
| Drawing | draw, draw_gallery | Frames, paths, gradients, text, resources and caching |
| Controls and input | widgets, text_input, editor_workbench | Layout, focus, IME, Input / TextArea |
| Styles | style_gallery | Themes, text scaling, density, scopes, states, icons and scrollbars |
| Desktop applications | desktop_services, multiwindow, workbench | Async services, window identity and integration |
| Web content | webview_requests, open, shaped, remote | Request lifetime, web shells, transparent windows and remote content |
| Extended controls | controls_gallery | Switch / Radio / Slider / Stepper / Tabs / Select / ListBox / Badge / Divider / Card / StyleSwitcher |
| Charts & visualization | chart, component_workshop | 30 chart types including line, area, bar, donut, scatter, heatmap, sankey, radar, boxplot, plus viewport interaction |
The example launcher sets XU_UI_PACK=1 to select the larger UI task stack when compiling with the release SDK. Set the same build profile when invoking the packager directly.
Drawing frames and resources
One worker consumes App.event_ch. Wait for canvas_ready, then obtain a Context with draw.context_of. Contexts and resources belong to a canvas_id / generation and expire when the window closes. Start each recording with Context.new_frame / Frame.begin, record a complete frame and call present once; use cancel on failure. Keep the previous frame while idle. Coalesce queued input events before presenting.
Frame coordinates are floating-point logical pixels with the origin at the top left. Frame.scale(1.0, 1.0) is identity; the compatible package-level draw.scale(100, 100) uses percentages. push / pop preserve transforms, clipping and pen state and must balance. A frame is bounded to 4 MiB, 100000 commands and 256 state levels. DisplayList reuses commands; Surface / SurfaceCache reuse raster results.
Canvas panning is off by default. On macOS, Windows and Linux, call draw.set_pan_enabled(1) after canvas readiness to enable built-in drag / wheel panning. Disabling resets the offset. Applications still receive drag and wheel events. Widget attach enables input and disables the camera.
Image, TextLayout, DisplayList, Surface, caches and input sessions have explicit disposal methods. Keep referenced resources alive until the recording is accepted by present, freeze or snapshot; accepted records retain their resource versions. Copying a resource handle does not create an independent resource; follow each clone / dispose contract.
Retained layout and events
Constraints flow from parent to child and measured sizes return upward. The layout tree supports row / column / stack / padding, with at most 4096 nodes and depth 64. View maintains stable node IDs, dirty flags, hit testing and repaint boundaries. It does not build virtual-list items on demand.
Route keyboard and pointer events through dispatch_event, and send native text events and clipboard results to Editor.event. Callback paint rectangles and pointer positions are node-local; node_bounds / Editor.place use canvas coordinates. After layout or ancestor scrolling, call place_editor before painting to synchronize hit testing and IME geometry. Enable set_capture_outside for scroll nodes so thumb dragging continues outside the viewport.
Control styles
dark_styles, light_styles and contrast_styles create complete Styles. font and text_scale control typography; density scales geometry. A ControlStyle can select a local font with inherit_font = false. Appearance includes colors, radius, borders, focus rings, padding, minimum size, alignment and shadows.
@main
#ui/draw
#ui/widgets
fn main() int {
$styles := widgets.light_styles()
styles.text_scale = 1.4
styles.density = 0.85
styles.button.radius = 10.0
styles.button.icon_placement = widgets.ICON_TRAILING
$rule := widgets.state_paint(widgets.STATE_FOCUSED | widgets.STATE_INVALID)
rule.unless = widgets.STATE_DISABLED
rule.fields = widgets.PAINT_BORDER | widgets.PAINT_FOCUS
rule.border = draw.rgb(220, 38, 38)
rule.focus = draw.rgb(251, 113, 133)
styles.button.states.push(rule)
styles.validate() >>> (err) {
eprintln(err.msg())
<< 1
}
<< 0
}| Control | Style options and entry points |
|---|---|
| Button | measure_styled / paint_styled; measure_icon_styled / paint_icon_styled for images, four placements, spacing and disabled opacity |
| Checkbox | Font, spacing, indicator size and mark width; separate colors for the selected mark and label |
| Input / TextArea | Font, line height, padding, placeholder, selection foreground / background, caret, preedit underline, read-only and invalid states |
| Progress | Track, indicator, size, radius, disabled and invalid states |
| Scroll | Scrollbar width, padding, minimum thumb size, focus and states; paint_scrollbar in overlay_styled |
State bits are disabled=1, hovered=2, pressed=4, focused=8, selected=16, invalid=32 and read_only=64. Default background precedence is disabled → invalid → read-only → selected → pressed → hovered → normal. A StatePaint matches all when bits and none of the unless bits. Rules apply in array order; the last matching override wins for the colors / icon opacity selected by fields. Each control permits at most 32 rules.
Scopes, measurement and caching
View.set_styles sets the root theme. set_style_scope stores a complete snapshot inherited until another scope; later global changes preserve explicit local themes. clear_style_scope restores inheritance; styles_for returns an owned clone. Palette and decoration changes invalidate painting; font and geometry changes also remeasure nodes registered with set_style_measure.
@main
#ui/widgets
fn configure(view $&widgets.View, brand_node int, label_node int) int {
styles := widgets.light_styles()
view.set_styles(&styles) >>>
$local := styles.clone()
local.button.radius = 12.0
view.set_style_scope(brand_node, &local) >>>
view.set_style_measure(label_node, true) >>>
view.mark_measure(label_node) >>>
<< 0
}
fn main() int { << 0 }StyledPainter's measure_styled / paint_styled / overlay_styled borrow the effective theme. Call layout_styled, synchronize editor placement, then present_styled, which returns false when clean. Use snapshot_styled for offscreen output. StyledLabel caches text layout; call set_text and mark_measure after changing a label. Callbacks must not mutate View or its topology. Dispose resources when their window closes.
The existing eight-field Theme and paint APIs remain compatible. Applications switch themes explicitly. Native menus / dialogs follow platform appearance, while WebView content uses CSS. Shadows use a bounded approximation of at most eight layers. Additional controls are described below; custom controls can implement StyledPainter.
Editors and IME
widgets.input and text_area create a persistent Editor. While focused, native TextInput owns editing and composition; Editor retains committed text between focus lifetimes. Controls support dragged selection, arrow keys, Home / End, Shift selection and system copy / cut / paste shortcuts. Enter submits a single line or inserts a newline in TextArea. Async clipboard edits apply only to the session revision that requested them.
set_read_only(true) releases the native input session while preserving local selection, navigation and copying. It rejects typing, cut and paste, including late IME commits. enable(false) disables interaction. Text is at most 16384 UTF-8 bytes without NUL; large text and font combinations also face native shaping budgets. Selection offsets are UTF-8 byte positions. Windows hit testing requires DirectWrite; older Wine lacks the implementation.
Structured menus and screens
Window.set_menu_entries atomically replaces a per-window menu tree. Root entries have parent=-1 and must be submenus; other parents are earlier submenu array indexes. Limits are 256 entries and depth 8. Only menu_check can be checked, and only action / check entries can have shortcuts. menu_primary maps to Command on macOS and Control on Windows / GTK. Clicks produce ev_menu_clicked; the application owns subsequent check state. macOS adds a standard Edit menu when absent.
@main
#ui
fn configure_menu(window &ui.Window) int {
$entries := []ui.MenuEntry{}
entries.push(ui.submenu("document", "Document", -1))
$reset := ui.menu_action("reset", "Reset", 0)
reset.key = 82
reset.modifiers = ui.MENU_PRIMARY | ui.MOD_SHIFT
entries.push(reset)
entries.push(ui.menu_separator(0))
entries.push(ui.menu_check("readonly", "Read only", 0, false))
window.set_menu_entries(entries) >>>
<< 0
}
fn main() int { << 0 }Window.screens_async returns a Request. Decode a completed result with screen_result for bounds, work_area, scale and primary / current. Check primary_known / work_area_known first. Windows desktop rectangles use physical pixels; macOS / GTK use logical desktop coordinates, identified by physical_coordinates. Neither is canvas-local.
Extended controls and style switching
Switch, Radio, Slider, Stepper, Tabs, Select, Badge, Divider, Card and ListBox share Styles, combined-state paint rules, shadows and icon placement. Create widgets.style_switcher() to select dark, light or contrast presets. Use use_preset, set_text_scale and set_density, then apply to the retained View; cycle advances and applies a preset. These methods can fail, so handle their errors. Each View receives a complete style snapshot; explicit control overrides remain in effect.
フォーカスセマンティクス(:focus-visible)
Xu 0.14.4 以降、#ui/widgets の非テキストウィジェット(Button、Tabs、Select、ListBox、Slider、Stepper、Scroll、Checkbox、Switch、Radio および複合ラッパーを含む)は、ポインタ押下とキーボードの ROUTE_FOCUS ナビゲーションを区別するため、論理フォーカスとは別に is_focus_visible() を追跡します。フォーカスリングと STATE_FOCUSED スタイルは is_focus_visible() が true を返す場合のみ描画され、セグメント化された Tabs では二重フォーカスリングを回避し、Button と Checkbox は揃った focus_inset ジオメトリを共有します。
Async desktop requests
Clipboard, file selection, prompts, screens and native WebView queries return ui.Request. Decode ev_request with request_of, then validate complete identity with result.matches. Submission means admission, not completion. Status values are completed=0, cancelled=1, failed=2, unsupported=3 and timed_out=4. An empty string can be a successful result.
@main
#ui
fn handle_result(event &ui.Event, pending &ui.Request) int {
if event.kind != ui.EV_REQUEST { << 0 }
result := ui.request_of(event) >>>
if !result.matches(pending) { << 0 }
if result.status == ui.REQUEST_COMPLETED { println(result.value) }
<< 0
}
fn main() int { << 0 }RequestOptions.timeout_ms=0 selects 5000 ms; explicit timeouts range from 1 to 3600000 ms. Prompts default to 300000 ms. Request.cancel reports cancellation admission and cannot undo an already performed clipboard write. Keep the event consumer running and discard requests and resources belonging to closed window generations.
WebView request lifecycle
Run bind_ipc_requests_www on a Xu worker separate from App.run to receive InvokeRequest with id, window_id, generation, name and payload. The page API returns a Promise with id and cancel(). JavaScript defaults to 30000 ms, allows 1–3600000 ms and supports AbortSignal. listen returns an unsubscribe function.
const controller = new AbortController();
const pending = window.__XU__.invoke("echo", "Hello 世界", {
timeoutMs: 5000,
signal: controller.signal
});
pending.then(value => console.log(pending.id, value))
.catch(error => console.log(error.name, error.message));
// pending.cancel(); // or controller.abort()An invoke request including its header, or a response, is at most 1 MiB. There are at most 64 active dispatch leases and an 8 MiB shared queued body / result budget. Names are at most 256 UTF-8 bytes. Cancellation, navigation and closure discard late results. Cancellation does not interrupt running user code; its lease remains occupied until the callback returns. Concurrent requests may complete out of order.
WebView.eval_async, find_async, cookies_async, set_cookie_async and clear_cookies_async share the ui.Request / ev_request lifecycle with results bounded to 64 KiB. Native completion callbacks run on the UI thread; application dispatch runs on Xu workers. Compatibility wait APIs do not drain the public App event queue. Window and document ownership prevent old results from reaching a newly navigated page.
Desktop tutorial · Release API index
Drawing and game engines
This is a desktop 2D drawing layer suitable for tools, editors and modest prototypes. Its platform backends use CoreGraphics, Cairo and GDI+. The public API does not provide a game-engine GPU pipeline, shaders, draw batching or a display-synchronized frame-pacing contract. DisplayList and surface caches help reuse work, but are not evidence of a game frame-time budget; measure the intended workload on each target before committing to it.