6. Commands, menus, accelerators, popups#
Put repeated actions into a command table and reference them from menus, buttons and accelerators; the library then does shortcuts, disabled / checked states and tooltips:
const CMD_OPEN: u32 = 1;
const CMD_SAVE: u32 = 2;
const CMD_UNDO: u32 = 3;
const CMD_GRID: u32 = 4;
const CMD_RESET: u32 = 5;
const CMD_RECENT0: u32 = 20; // .. 27
static CMDS: [Command; 4] = [
// id label icon mods key CF_* state
Command::new(CMD_OPEN, "Ö&ffnen…", IC_OPEN_FILE, MOD_CTRL, b'O' as u32, 0),
Command::new(CMD_SAVE, "&Speichern", IC_SAVE, MOD_CTRL, b'S' as u32, 0),
Command::new(CMD_UNDO, "&Rückgängig", IC_UNDO, MOD_CTRL, b'Z' as u32, CF_DISABLED),
Command::new(CMD_GRID, "&Raster", IC_GRID, MOD_CTRL, b'G' as u32, 0),
];
static MENUBAR: [Mi; 2] = [Mi::Menu("&Datei", &M_FILE), Mi::Menu("&Ansicht", &M_VIEW)];
static M_FILE: [Mi; 5] = [
Mi::Cmd(CMD_OPEN),
Mi::Cmd(CMD_SAVE),
Mi::Sep,
Mi::Sub("&Zuletzt geöffnet", &M_RECENT), // a submenu
Mi::Item(CMD_RESET, "&Zurücksetzen", 0), // a plain row: App::command(id, 0)
];
static M_RECENT: [Mi; 1] = [Mi::List(CMD_RECENT0, 8, "Keine Dateien")];
static M_VIEW: [Mi; 1] = [Mi::Cmd(CMD_GRID)];
const DESC: AppDesc = AppDesc { title: "Mein Werkzeug", flags: AF_RESIZABLE, w: 900, h: 640,
cmds: &CMDS, menubar: &MENUBAR, ..AppDesc::NONE };
// in frame, before the widgets:
ui.cmd_state(CMD_GRID, if self.grid { CF_CHECKED } else { 0 });
ui.menu_list(CMD_RECENT0, &self.recent); // the rows of Mi::List (Vec<String>)
ui.menubar(None); // the menu bar of the AppDesc
A chosen menu row, a
cmd_buttonand an accelerator all queueApp::command(cmd, 0).&marks the mnemonic (&&= a literal&). Keys areVK_*(Win32 numbering on every OS,ui::keys), modifiersMOD_CTRL | MOD_SHIFT | MOD_ALT.On a Mac the menus of the
AppDescgo into the menu bar of macOS, between the app menu and the Window menu, as every Mac app has them:ui.menubar(None)of the main window draws no row then, a row chosen up there runs as from the window's bar,MOD_CTRLis the Command key. On an iPad they go into the menu bar of iPadOS as well (between the application menu and Window; the rows with a key also show while Command is held), and the window keeps its row: iPadOS shows its bar only after a swipe down from the top or with the pointer at the top edge, the row stays the way for the finger. A pass that draws nomenubar(None)takes the menus out of the system's bar again (a page without the bar). Headless runs (scripts) keep the row in the window,jfgui_SYSMENU=0too (plat::sysmenu).cmd_state(cmd, CF_DISABLED | CF_CHECKED | CF_HIDDEN)is persistent; set it every frame from your model. Accelerators fire only when no widget consumed the key first (ui.key(VK_*)).accel_text(cmd)gives the shortcut as shown in menus ("Strg+S"). An editor that owns the whole document history can callcapture_shortcut(vk, mods)before its widgets to reserve an exact chord, including one normally owned by a textbox. Guard modal draft/file dialogs so their text-editing shortcuts retain priority. jfWord uses this opt-in API for document undo/redo and inserting a paragraph.textbox_selection(id)returns the focused textbox's UTF-8 byte offsets(anchor, caret). Read it after emitting that textbox.textbox_select(id, text, anchor, caret)restores a selection on an already focused textbox; pass its exact current text. Invalid byte boundaries and inactive fields returnfalse. Document editors can use these opt-in APIs to format a selection or highlight a search result without changing ordinary textbox undo.textbox_surface(id, &mut text, cap_flags, &lines)adds input over externally rendered rich text. EachTextSurfaceLinesupplies UTF-8 start/end offsets, an absolute pixel rectangle and one caret stop per scalar boundary. Lines can span multiple pages and have different alignment and font metrics. The caller draws text and owns scrolling; the widget draws selection/caret and provides keyboard, clipboard and IME handling.textbox_surface_change()returns the original replacement range and inserted text, including the actual insertion position when neighboring characters repeat. Apply this to the document model atomically, reject protected fields there, and rebuild layout afterEV_ACT.apps/jfWord/rich_ui.rsshows integration withdoc_layoutsource ranges. The buffer may span an entire story, with paragraph offsets fromdoc_core::StoryText. Surface paste normalises CRLF and lone CR to LF; the model decides which inserted breaks create paragraphs. Surface replacements exceeding capacity are rejected before deletion, not truncated. Set capacity for the displayed projection, including expanded fields and the terminator. These opt-in rules leave ordinary textbox behaviour unchanged.clip_set_many(&[(format, bytes), ...])publishes up to four representations of one selection:CLIP_TEXT,CLIP_HTML,CLIP_RTFandCLIP_DOCX. It returns0on success and-1on failure; only remove a cut selection after success. Text and HTML must be NUL-free UTF-8; RTF and the private document payload are binary. Combined data is bounded to 64 MiB. The platform handles CF_HTML framing on Windows and MIME offers on Linux; callers supply raw HTML fragments.clip_hasprobes andclip_getretrieves each format.CLIP_DOCXcarriesdoc_io's versioned document fragment, not an arbitrary DOCX file.doc_core::Document::copy_story_rangeandEditor::replace_story_fragmentpreserve formatting, sources and note bodies with atomic document history.doc_ioalso provides the bounded RTF reader/writer and HTML writer. Seeapps/jfWord/rich_ui.rsfor shortcut interception and format preference. Ordinary textboxes continue to paste plain text; plain-text/image writes clear older rich representations. Scripts use an isolated in-process clipboard and never change the user's system clipboard.textbox_presented(id, placeholder, &mut text, cap_flags, presentation)uses the same native editing, selection, clipboard and IME path with an explicitTextboxPresentation. It draws a borderless field with the supplied font, physical-pixel font size (24.8), line height, baseline, foreground/background and underline. The app owns page geometry and document history; ordinarytextboxcalls retain their existing style and rendering.RibbonGroup::new(id, caption, preferred_width, compact_width)describes a command group in DIP; reserveid..=id+3. Start withribbon_begin(id, &groups), then callribbon_group_begin(&layout, index, &group)for each group. Emit controls only when it returnsSome(mode), followed byribbon_group_end(mode, caption). Finish withribbon_end(). Groups first shrink, then collapse into labeled flyouts from the right.ribbon_buttonprovides compact icon actions;ribbon_tileadds typography previews. The app still provides real command availability and actions. Seeapps/jfWord/ribbon_ui.rs.The window parts around a ribbon (
ribbon_shell.rs):ribbon_tabs(id, &mut sel, &tabs)is the register row above it, as wide as its box.RibbonTab::file(label)is the File register (activating it returnsEV_OPEN,selstays),RibbonTab::new(label)a register,RibbonTab::context(label, set, argb)a register of a context set (a coloured edge, the set's name in its tooltip) that the app lists only while its selection asks for it;EV_ACTwhenselchanged. Registers areK_TABrecords (click tab:"Start"), idsid + 1 + i. The selected register opens toward the ribbon (Style::ribbon_tab,ribbon_tabs_strip; a style that paints the band itself returns 0 fromribbon_box_flagsand draws it inribbon_band). The row also runs the access keys (key tips): a tap of Alt or F10 shows a badge on every register, a register's keys show a badge on every command of its ribbon (the ribbon's buttons register themselves; other controls callkeytip(2, label), quick access buttonskeytip_keys(1, "1")), a command's keys activate it in the next pass like a click, Esc steps back, a click ends the mode (keytips_level(),keytips_off()). Keys come from the labels of the current language: the first free letter (accents dropped), then "0A".."0Z".backstage_begin(id, back, &items, &mut sel, nav_w)is the File register's page: a navigation pane with a back item, theBackstageItems (BS_FOOTERat its bottom,BS_ACTIONfor an action that is no page,BS_SEP) and a scrolling area the app fills untilbackstage_end(); it returnsSome(-1)for back (and Esc),Some(i)for an activated item.settings_section(id, &mut settings, section)shows one section of a settings schema, for an options page per section. Seeapps/JFDiagrammer/src/shell.rs,ribbon.rs,backstage.rs.Flyouts of your own: a button's
EV_ACT->popup_open(id)(drop-down buttons do this themselves); thenflyout_begin(id, FL_*)->true: emitmenu_item(id, label),menu_cmd(cmd),menu_sep()or any widgets; alwaysflyout_end():ui.combobox(ID_SHAPE, &mut self.shape, &["Kreis", "Quadrat", "Dreieck"]); ui.dropdown_button(ID_MORE, "Mehr"); if ui.flyout_begin(ID_MORE, FL_BELOW) { if self.more != 0 { ui.next_flags(ST_CHECKED); } if ui.menu_item(ID_MORE_A, "Option A") & EV_ACT != 0 { self.more ^= 1; } ui.menu_sep(); ui.menu_cmd(CMD_SAVE); } ui.flyout_end(); // always, also when flyout_begin returned false ui.button(ID_RCLICK, "Rechtsklick hier"); ui.context_menu(&M_CTX); // right click / menu key / Shift+F10 on the last widgetA widget without
context_menugets the menu key as a right click (EV_RCLICK); amenu_popupin answer to it opens at the widget (§27). At a point the app learns later (a web engine answers a right click with the menu's rows and place a moment after it):menu_popup_at(menu, x, y)opens a menu,popup_open_at(id, x, y)a flyout of the app's own (drawn withflyout_begin(id, ..)as usual) at the point (x, y), px of the window aslast_rect(a canvas:UiInput::rectplus itsx,y), in the frame the answer comes:if inp.ev & EV_RCLICK != 0 { self.page.context_menu(inp.x, inp.y); // the engine answers later } if let Some(info) = self.page.take_context_menu() { // a later frame ui.menu_popup_at(&M_PAGE, inp.rect[0] + info.x, inp.rect[1] + info.y); }apps/viewtest(tests/menus.uis) does both.popup_close()closes every popup;popup_close_id(id)only popupidand the popups opened inside it, the flyout around it stays (adate_pickerin a flyout of the app's own closes its calendar this way when a day is picked). A popup opened inside a flyout is drawn where itsflyout_beginstands: put a drop-down (adate_picker, acombobox) last in the flyout, or its list lies under the flyout's later widgets. A calendar in place (a web page's date input, a panel):calendar(id, &mut y, &mut m, &mut d, &DateRange::new(mode, min, max))draws the month ofdate_picker's popup without a popup and returnsEV_ACTwhen the user picked.CAL_DAYpicks a day (DateRange::DAYS: any day of the years 1 to 9999),CAL_WEEKan ISO week (rows from Monday with the week's number; the date becomes its Monday),CAL_MONTHa month of a year's twelve (the 1st); what lies beforeminor aftermax(in weeks: their weeks, in months: their months) is disabled, and so are the arrows beyond them. The calendar shows the date's month again when the app changes the date. The civil helpers arejflib::datetime's:days_in_month,weekday(0 = Monday),iso_week(y, m, d) -> (year, week),iso_weeks_in_year,iso_week_monday(year, week):let range = DateRange::new(CAL_WEEK, (2026, 11, 5), (2027, 2, 10)); if ui.calendar(ID_WEEK, &mut self.y, &mut self.m, &mut self.d, &range) & EV_ACT != 0 { let (year, week) = datetime::iso_week(self.y, self.m as u8, self.d as u8); // "2026-W48" self.page.set_value(&format!("{year}-W{week:02}")); }apps/viewtest(tests/calendar.uis) has both in a flyout at a point of its page. A row whose keys the app handles itself (no command of the table, e.g. inside a pane that captures them withcapture_shortcut) shows them withmenu_item_keys(id, label, &ui.key_text(VK_F5, MOD_CTRL)):key_text(vk, mods)writes a key as the accelerator texts do ("Strg+F5", the UI language's names). JFNetworker's IDE builds its menus this way.Drop-downs:
dropdown_button,split_button(main partEV_ACT, chevron opens popupid),combobox(id, &mut sel, list);menu_popup(menu)opens a menu at the pointer.Popups (flyouts, menus, combo lists, the calendar of
date_picker, context menus, tooltips) are not limited to their window: on Windows and X11 they may use the work area of the monitor -- below / to the right of their anchor when there is room, above it / to the left (submenus, context menus) when not -- and what lies outside the window becomes a borderless popup window of the platform (owned, never activated, input comes back as the window's events, so nothing changes for the app). Wayland does not tell where a window is: a popup that fits stays inside the window, a larger one becomes anxdg_popupthat the compositor keeps on the screen; the UI lays it out where the compositor put it. Popups close on a press elsewhere in the app, with Esc, and when the app loses the keyboard. Headless runs keep the main window's popups inside it unless a script sets a virtual screen (screen X Y W H, §12).Timers:
ui.timer(id, ms)->App::command(UIC_TIMER, id)once; start it again for a periodic timer (the same id replaces the waiting one). Library timers (caret, tooltips) arrive as well: ignore ids you did not start. Any number may wait (up to 4096 ids); due timers fire by their deadlines, equal deadlines in the order they were set.Limits: the queues and stacks of a pass grow as needed (keys of one pass, commands, timers, pointer positions, hit boxes, widget records, clips, tabs, canvases); their ceilings only stop runaway memory. Where a ceiling or a fixed nesting depth (windows, popups, menus inside each other) holds something back, a
UIWARNnames it once (scripts:expect_warn). The platform's event ring holds 256 events; a larger burst (synthetic keys, a flooding client) waits behind it in order, up to 65536 events (plat::evq_dropped()counts what is lost beyond).