JFLib

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_button and an accelerator all queue App::command(cmd, 0). & marks the mnemonic (&& = a literal &). Keys are VK_* (Win32 numbering on every OS, ui::keys), modifiers MOD_CTRL | MOD_SHIFT | MOD_ALT.

  • On a Mac the menus of the AppDesc go 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_CTRL is 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 no menubar(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=0 too (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 call capture_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 return false. 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. Each TextSurfaceLine supplies 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 after EV_ACT. apps/jfWord/rich_ui.rs shows integration with doc_layout source ranges. The buffer may span an entire story, with paragraph offsets from doc_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_RTF and CLIP_DOCX. It returns 0 on success and -1 on 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_has probes and clip_get retrieves each format. CLIP_DOCX carries doc_io's versioned document fragment, not an arbitrary DOCX file. doc_core::Document::copy_story_range and Editor::replace_story_fragment preserve formatting, sources and note bodies with atomic document history. doc_io also provides the bounded RTF reader/writer and HTML writer. See apps/jfWord/rich_ui.rs for 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 explicit TextboxPresentation. 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; ordinary textbox calls retain their existing style and rendering.

  • RibbonGroup::new(id, caption, preferred_width, compact_width) describes a command group in DIP; reserve id..=id+3. Start with ribbon_begin(id, &groups), then call ribbon_group_begin(&layout, index, &group) for each group. Emit controls only when it returns Some(mode), followed by ribbon_group_end(mode, caption). Finish with ribbon_end(). Groups first shrink, then collapse into labeled flyouts from the right. ribbon_button provides compact icon actions; ribbon_tile adds typography previews. The app still provides real command availability and actions. See apps/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 returns EV_OPEN, sel stays), 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_ACT when sel changed. Registers are K_TAB records (click tab:"Start"), ids id + 1 + i. The selected register opens toward the ribbon (Style::ribbon_tab, ribbon_tabs_strip; a style that paints the band itself returns 0 from ribbon_box_flags and draws it in ribbon_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 call keytip(2, label), quick access buttons keytip_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, the BackstageItems (BS_FOOTER at its bottom, BS_ACTION for an action that is no page, BS_SEP) and a scrolling area the app fills until backstage_end(); it returns Some(-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. See apps/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); then flyout_begin(id, FL_*) -> true: emit menu_item(id, label), menu_cmd(cmd), menu_sep() or any widgets; always flyout_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 widget

    A widget without context_menu gets the menu key as a right click (EV_RCLICK); a menu_popup in 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 with flyout_begin(id, ..) as usual) at the point (x, y), px of the window as last_rect (a canvas: UiInput::rect plus its x, 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 popup id and the popups opened inside it, the flyout around it stays (a date_picker in 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 its flyout_begin stands: put a drop-down (a date_picker, a combobox) 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 of date_picker's popup without a popup and returns EV_ACT when the user picked. CAL_DAY picks a day (DateRange::DAYS: any day of the years 1 to 9999), CAL_WEEK an ISO week (rows from Monday with the week's number; the date becomes its Monday), CAL_MONTH a month of a year's twelve (the 1st); what lies before min or after max (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 are jflib::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 with capture_shortcut) shows them with menu_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 part EV_ACT, chevron opens popup id), 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 an xdg_popup that 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 UIWARN names 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).

Source: docs/GUIDE.md in the JFLib repository.