7. Dialogs, windows, title bar, files#
Content dialogs are drawn on the window (smoke layer, modal). The library keeps the open
flag (Shared<i32>: closing by Esc or a button clears it):
// state: dlg_open: Shared<i32> (Shared::new(0)); open it with self.dlg_open.set(1)
let dlg = self.dlg_open.clone();
if ui.dialog_begin(ID_DLG, "Änderungen speichern?", &dlg) {
ui.text(TS_BODY | TX_WRAP, "Möchten Sie die Änderungen speichern?");
match ui.dialog_buttons(Some("Speichern"), Some("Nicht speichern"), Some("Abbrechen")) {
DLG_PRIMARY => ui.cmd_run(CMD_SAVE, 0), // do the work in App::command
DLG_SECONDARY => ui.quit(),
_ => {} // DLG_NONE, DLG_CLOSE
}
}
ui.dialog_end(); // always
Emit dialogs and windows at the end of
frame(on top of everything else).ui.modal_active()tells whether a dialog is open (for shortcuts of your own).Undo / redo of the app's own state:
ui::History<S>recordsEdits (apply / revert / label, optionallymergeso a drag is one step);Snapshot::new(label, before, after)is the edit for smallClonestates,.merging(key)joins steps with the same key.h.apply(&mut state, Box::new(edit)),h.undo(&mut state),h.redo(..),undo_label()for the menu ("Rückgängig: …"),undo_value()/redo_value()(the step as data,Edit::value: an app can see what kind of edit it is before it runs),group_begin/group_endfor compound steps,mark_saved()/dirty()for "save changes?" (mark_unsaved(): a recovered copy counts as unsaved).ui.undo_keys()givesSome(true)for Ctrl+Z andSome(false)for Ctrl+Y / Ctrl+Shift+Z unless a text field (which has its own undo) has the keyboard.Unsaved changes: in
App::command(UIC_CLOSE)returntrueto keep the window, open your "save?" dialog, and callui.quit()when done:UIC_CLOSE => { if !self.modified { return false; // not handled: the window closes } self.dlg_open.set(1); // ask first; true keeps the window open }Info bars:
infobar(id, IB_INFO | IB_SUCCESS | IB_WARNING | IB_ERROR, title, msg)->EV_ACTwhen its close button was clicked. Status bar:statusbar_begin()... texts,separator()...statusbar_end()at the end of the main box.Secondary windows (tool windows, dialog windows) are real OS windows, built by the same
frame, each with its own UI state (legacy/ASMLIB/docs/modules/WINDOWS.mddescribes the model; the API is the same):// state: win_open: Shared<i32>, win_rect: Shared<WinRect> (WinRect::new(0, 0, 260, 0, 0)) let (wo, wr) = (self.win_open.clone(), self.win_rect.clone()); if ui.window_begin(ID_WIN, "Werkzeuge", Some(&wo), WF_TOOL | WF_AUTOHEIGHT, Some(&wr)) { ui.box_begin(0, BOX_V | PAD_12, 8); ui.slider(ID_WIN_SIZE, &mut self.size, &RG_SIZE); ui.box_end(); } ui.window_end(); // alwaysFlags
WF_TOOL,WF_DIALOG(+WF_MODAL;dialog_buttonsthen make the footer),WF_RESIZABLE,WF_NOCLOSE,WF_AUTOHEIGHT, ...; the library writes the user's placement back into theWinRect.window_place,window_state,window_activate,window_destroy. On Wayland a client cannot place its own toplevels (GNOME, KDE and WSLg centre an owned one on its owner), so tool windows (WF_TOOLwithoutWF_DIALOG) are child windows there: a subsurface of the owner, placed where theWinRectsays, kept inside the owner and moved, minimized and stacked with it; the library moves and resizes them itself, and the keyboard goes to one only after a click on a text box orwindow_activate-- as on Windows (plat::WST_CHILD;jfgui_WL_TOOLWIN=toplevelkeeps separate toplevels). Dialogs stay toplevels and are centred by the compositor.Independent app windows (
WF_APP: a browser's second or private window): on Windows a top-level window of its own -- its own taskbar button, not minimized, hidden or kept above the main window as owned windows are -- and without the library's title bar: the app draws its own withtitlebar_begin/titlebar_end(its widgets in it, a tab strip, the caption buttons at its end acting on that window), as in the main window. X11 and Wayland give it a top-level window as well (noWM_TRANSIENT_FOR, type normal / anxdg_toplevelwithout a parent; the window manager places it, Wayland tells no position). macOS has one top-level window per app in the window layer yet: it gives it an owned window (the same code works, the window has no taskbar button of its own). Give it aWinRectwith its size; closing the main window still ends the app.let (open, rect) = (self.private_open.clone(), self.private_rect.clone()); if ui.window_begin(ID_PRIVATE, "Privates Fenster", Some(&open), WF_APP | WF_RESIZABLE, Some(&rect)) { ui.titlebar_begin("Privates Fenster", IC_PRIVATE); self.tabs(ui); // the title bar's own widgets ui.titlebar_end(); // minimize, maximize, close of this window self.page(ui); } ui.window_end();apps/viewtesttests/appwin.uis; real windows on X11 and Wayland:python tools/x11check.py appwin --backend x11|wayland(viewtest --app-windowopens it at the start).One instance: with
AF_SINGLE_INSTANCEin theAppDesc, a later start of the app hands its working folder and command line to the running window and ends (plat::instance: a pipe / an abstract socket per user and app; only for real windows, not for--shot/--script). The window comes forward, the files are the user's (PERMISSIONS.md,fs.user), andApp::command(UIC_OPEN, count)arrives:UIC_OPEN => { for r in ui.open_take() { // plat::instance::Request { cwd, args } for path in r.paths() { // the arguments that are no options, absolute self.open(ui, &path); } } }The first start reads its own
plat::args()as before. File types and URL schemes that open the app come fromPACKAGE(PACKAGING.md).Notification area and notifications:
ui.tray_set(icon, tooltip, &MENU)shows a symbol (None: the program's own icon) whose menu isMirows of the command table; a chosen row arrives asApp::command(cmd, 0), a click on the symbol asUIC_TRAY(TRAY_ACTIVATE/TRAY_SECONDARY).ui.notify(title, body, icon)sends a system notification and returns its id; a click on it sendsUIC_NOTE(arg = id), andUIC_NOTE_GONEarrives when it closes unclicked. Calltray_setagain aftercmd_statechanges.ui.bring_to_front()restores the window. Windows usesShell_NotifyIconW(the notification is the symbol's balloon, which Windows 10 / 11 show as a toast); Linux uses StatusNotifierItem + dbusmenu andorg.freedesktop.Notifications. The browser and Android have notifications but no symbol (tray_setanswersfalse): the browser uses the Notification API (web/notify.js) -- not asked yet, the page asks for the permission when the first notification comes (it comes from the user's click, inside the click's activation), refused the note goes away at once (UIC_NOTE_GONE) and later ones answer 0; a click focuses the tab. Android uses the NotificationManager with the channel "jfgui" (android/GalleryNotify.java; API 33+ asks forPOST_NOTIFICATIONSat the first note, which the manifest must list); a tap opens the activity. The app'sPERMISSIONShas no rule for notifications on any platform: the system's permission is the gate. Headless runs only print what they would show.apps/traydemoshows all of it. An installed app runs under its explicit AppUserModelID (section 21, "The app's identity on Windows"): Windows files its notifications under that id, and the setup's start menu shortcut carries it -- the shortcut Windows wants for the notifications of an explicit id.Title bar:
AF_CUSTOM_TITLEBARin theAppDesc, then as the first row of the main box (caption buttons, dragging, snap layouts on Windows, resize grips on Linux):let t = String::from(ui.title()); // title() borrows ui ui.titlebar_begin(&t, IC_BRUSH); // optional widgets in the title bar (search box, buttons) ui.titlebar_end();ui.set_title(s)changes the window title.On Linux the library's title bars (this one and the one it draws itself on Wayland without server-side decorations) follow the desktop's settings as GTK does: GNOME's
button-layout(org.gnome.desktop.wm.preferences, read from the settings portal; without the portal GTK'sgtk-decoration-layoutinsettings.ini) puts the caption buttons at the left and / or the right end ("close,minimize,maximize:", GNOME's default"appmenu:close"shows only the close button; names other than close, minimize and maximize are skipped), and right-to-left mirrors the whole bar. A double click, a middle and a right click on the empty part do whataction-double-click-titlebar,action-middle-click-titlebarandaction-right-click-titlebarsay:toggle-maximize(default of the double click),minimize,lower(X11; Wayland has no such request),menu(the window manager's window menu: default of the right click) ornone(default of the middle click); a left press moves the window. Changes apply at once (UIC_SETTINGSwithSET_OTHER). Secondary windows with the library frame keep their close button at the side the layout puts close. Without these settings (Windows, other desktops) the style decides as before. Overrides:jfgui_BUTTON_LAYOUT=close,minimize,maximize:,jfgui_TITLEBAR_DOUBLE_CLICK,_MIDDLE_CLICK,_RIGHT_CLICK(GNOME's names). The resize band of a window without a system frame (SM_GRIP, about 5 DIP,SM_GRIP_CORNERcorners) lies inside the window, under the caption buttons: there the buttons win (their top row and the close button's corner click the button), elsewhere the band resizes; it is off while the window is maximized or in full screen and on the tiled edges of a tiled window (GTK puts the band outside the visible frame, in its shadow; the library's windows have no shadow margin). Scripts test it with the forced title bar:system env jfgui_CSD 1, then presses at the edges andexpect wm resize ne/expect wm close(headless runs only record what they would ask the window manager for).File dialog:
filedlg(id, FD_OPEN | FD_SAVE | FD_FOLDER | i << FD_EXT_SHIFT, &open, &mut path, cap, exts)->EV_ACTwhen a file (FD_FOLDER: a folder) was chosen;paththen holds an absolute path with/separators (Windows accepts them). It shows the system dialog (Explorer on Windows, the desktop's file chooser through xdg-desktop-portal on Linux) and falls back to the library's own dialog when there is none, in headless runs, withFD_BUILTIN(the app's choice, below) or withjfgui_FILEDLG=builtin(every dialog of the run);FD_FOLDERuses the own dialog on Windows (folders only, the selected or shown folder is the answer). On Android it is the system's picker (Storage Access Framework):pathbecomes acontent://name (VFS.md, "Android"), readable and writable with the ordinary file functions and kept across restarts; show the userplat::display_name(&path), not the name itself. In a browser with the File System Access API (Chromium)FD_OPEN/FD_SAVEshow the system's pickers too:pathbecomes/handles/ID/NAME, the user's own file (an opened one already read in);write_fileon it writes the file back (plat::web::persistconfirms it),plat::web::reopenreads it again after a reload (VFS.md, "The browser"). Firefox and Safari keep the library's own dialog over the browser's virtual files. These pickers answer a few frames later (nothing is drawn meanwhile), so keep callingfiledlgevery frame as usual. Keep chosen files inui.recent_add(a Flatpak's documents of the portal stay reachable after a restart, Android's grants and the browser's handles are kept). Idsid .. id + 0x3FFFbelong to it.ipreselects a file type ofexts:static EXTS: [&str; 2] = ["png=PNG-Bild", "jpg;jpeg=JPEG-Bild"]; const ID_FILEDLG: u32 = 0x0010_0000; // .. + 0x3FFF // in frame: let open = self.fd_open.clone(); if ui.filedlg(ID_FILEDLG, self.fd_mode, &open, &mut self.path, 1040, &EXTS) & EV_ACT != 0 { ui.cmd_run(CMD_FILE_DONE, self.fd_mode); // load / save in App::command } // CMD_OPEN in App::command: self.fd_mode = FD_OPEN; self.fd_open.set(1);Several files at once (
FD_OPEN | FD_MULTI, e.g. an upload field that takes several):pathgets the first,ui.filedlg_paths()every chosen file in the dialog's order (after a dialog withoutFD_MULTIthe one file, after anFD_FOLDERdialog the folder). Windows' dialog (Ctrl / Shift in Explorer) and Linux's portal (multiple) choose several; the library's own dialog marks rows with Ctrl+click and Shift+click (or Shift+arrows; marked rows show a check mark, the name box"a.txt" "c.txt") and takes quoted names typed there, each one an existing file of the shown folder or an absolute path. The pickers of macOS, iOS, Android and the browser choose one file for now (filedlg_paths()holds that one).plat::file_dialog_paths()is the platform's side. Every chosen file is the user's (fs.user).if ui.filedlg(ID_FILEDLG, FD_OPEN | FD_MULTI, &open, &mut self.path, 4096, &EXTS) & EV_ACT != 0 { for p in ui.filedlg_paths() { self.upload.push(p); } }The library's own dialog by choice (
FD_BUILTIN): the app's dialog looks and behaves the same on every system and in every style (a browser's "Save as", a dialog the app's tests drive in real windows), wherejfgui_FILEDLG=builtinonly switches a whole run. It lists whatplat's file functions see: on Windows, Linux and macOS the file system, in the browser and on Android the app's own folders (not the system's documents or the user's files outside them). The other flags keep their meaning (apps/viewtest/tests/builtin.uis):let flags = FD_SAVE | FD_BUILTIN | 1 << FD_EXT_SHIFT; // the own dialog, the second type selected if ui.filedlg(ID_FILEDLG, flags, &open, &mut self.path, 1040, &EXTS) & EV_ACT != 0 { /* save */ }Drag and drop (
ui/dnd.rs,plat/dnd.rs): what a drag carries is aDragData(files,text,urls,html,image= a PNG file,bmp, the app's ownappkindDT_USER0 << kwithbytes, alabel,effects); its kinds areDT_FILES,DT_TEXT,DT_URL,DT_HTML,DT_IMAGEand the app's own bits, the effectsDE_COPY,DE_MOVE,DE_LINK.const DT_ROW: u32 = DT_USER0; // the app's own kind // a source: after the widget, with the widget's EV_* let ev = ui.button(ID_ITEM + i, &name); match ui.drag_source(ID_ITEM + i, ev) { DS_START => { let mut d = DragData::of_app(DT_ROW, &[i as u8]); d.text = Some(name.clone()); // other programs (and text targets) take the text d.effects = DE_MOVE | DE_COPY; ui.drag_set(d); // in the same pass, else nothing is dragged } DS_END if ui.drag_effect() == DE_MOVE => { /* it was moved: remove it here */ } _ => {} } // a target: right after the widget or box_begin (it takes last_rect) ui.box_begin(ID_BASKET, BOX_V | BOX_CARD | PAD_8, 6); if ui.drop_target(ID_BASKET, DT_ROW | DT_TEXT) == DS_DROP { let d = ui.drop_data(); // and ui.drop_effect(), ui.drop_pos() self.pending = Some(d.clone()); // apply after the widgets were drawn, then ui.repass() }Inside the app a widget's drag follows the pointer with a label (the style's tooltip), the drop target under it is highlighted (
StyleBasic::drop_highlight, by default an accent frame), Esc cancels, the release drops onto the innermost matching target of the topmost layer (a plain drag moves when the source allows it, Ctrl copies, Shift moves, Ctrl+Shift links). A target reportsDS_HOVERwhile a matching drag is over it andDS_DROPonce, in the first pass after the drop; the source reportsDS_ACTIVEandDS_ENDonce. A drop changes what this pass already drew: apply it after the widgets (end offrame) and callui.repass().When the pointer leaves the window with content other programs know, the platform takes the drag over: Windows
DoDragDropwith ourIDataObject(CF_UNICODETEXT, CF_HDROP, HTML Format, UniformResourceLocator, PNG, CF_DIBV5), X11 as an XDND source, Waylandwl_data_device.start_drag. Dropped back onto the app it arrives with the app's own kind and bytes again.ui.drag_out(data)starts such a drag at once (the left button held). Paths should be absolute files (a file written for the drag:plat::temp_dir()).Other programs' drags: every window is a drop target (Windows
IDropTarget, X11 XDND 5, Waylandwl_data_device); the platform asks the targets of the last pass synchronously for its answer to the source. While such a drag is over a window the matching targets getDS_HOVERandui.drag_over()returns its kinds and position. A drop goes to the target at the point; outside every targetui.drop_accept(types)decides (defaultDT_FILES, as before) and it arrives asUIC_DROPwithdrop_list()/drop_data(). Files are never moved (their source would delete them): Shift gives a copy. Dropped files may be read and written (fs.user).The effect per target:
ui.drop_effect_set(effects)right afterdrop_targetsays which ofDE_COPY | DE_MOVE | DE_LINKthat target takes in this pass (default all). The platform answers the source with one of them (the modifier keys choose, else copy, move, link), so the system's pointer shows it:IDropTarget::DragOver's effect on Windows, the XdndStatus action on X11,wl_data_offer.set_actionson Wayland, the drag operation on macOS.0refuses the drag there: no drop, no highlight, the pointer shows "no". A canvas that takes drops only in some places (a web page's drop zones, asdropEffect) sets it every pass whileDS_HOVERholds, for the point ofdrag_over_px(); the answers follow the passes, one pass late while the drag moves. The app's own drags inside the window pick from them too. A drop keeps the effect the platform picked when the target takes it, else it gets the first of the target's effects that the source allows (copy, move, link; a scripted drop, or one that raced the pass); with none in common it is refused as the platform refuses such a drag over the target: noDS_DROP, noUIC_DROP, the source is answered "not taken".ui.drop_effect()is always an effect the source allows.if ui.drop_target(ID_PAGE, DT_FILES | DT_URL | DT_TEXT) == DS_HOVER { let (kinds, x, y) = ui.drag_over_px(); ui.drop_effect_set(self.page_effect_at(kinds, x, y)); // e.g. DE_COPY, or 0: not here }What the source allows:
ui.drag_allowed()gives theDE_*effects of the drag over the window as its source offers them -- Windows the effects of itsDoDragDrop, X11 the source'sXdndActionListwith the action it asks for (without a list: all), Wayland itssource_actions(copy and move; Wayland has no link), macOS the drag's operation mask (AppKit narrows it by the modifier keys), the app's own drag itsDragData::allowed();DE_ALLwhere the platform does not say. They are forgotten when the drag leaves the window or ends. A drop carries its own (plat::drop_allowed()): Windows the effects ofIDropTarget::Drop, X11 the list with the lastXdndPosition's action, Wayland the offer'ssource_actions, macOS the operation mask ofperformDragOperation:; without them (the browser's and Android's drops) those of the hover before it, elseDE_ALL.drag_allowed()says them from the drop'sE_DROPto the end of the passes it starts (DS_DROP,App::command'sUIC_DROP) and, afterui.drop_defer(), until its answer went (drop_finish,DROP_DEFER_MS, a newer drop) -- in every window over which no drag is;drop_finishanswers within them. 0 otherwise: no drag over the window, no drop in its passes or waiting. A page that maps a web page'seffectAllowedanddropEffectpicks from it fordrop_effect_setand hands it on with the drop.0 means "not said" wherever the effects a source allows are given:
DragData::effectsof the app's own drag (drag_set,drag_out), the effects of another program's hover and drop, theallowedofplat::drag_queryandplat::drag_decide. Every effect is allowed then (DE_ALL): inside the app a plain drag moves and Ctrl+Shift links, a target that only links takes it, a drag out offers linking to other programs too. A source that names effects limits its drag to them (d.effects = DE_MOVE | DE_COPYabove). Files are never moved, whatever the source says. (Up to 0.2, a 0 meant copy and move everywhere but indrag_allowed()and the effects of a drop.)The answer after the drop: by default the source learns the effect the drop was delivered with after its passes. A target that learns later whether it took the drop (a web page's drop handler in another process) calls
ui.drop_defer()in the pass of the drop (DS_DROP, or inApp::command'sUIC_DROP) and answers withui.drop_finish(effect)when it knows: the effect it took the drop with, 0 = not taken (an effect the source does not allow becomes the first it does;drag_allowed()says them until then). Withoutdrop_finishthe answer goes afterDROP_DEFER_MS(3 s) as the drop was delivered, with aUIWARN; so does a deferred drop the next drop overtakes, and one that waits when the app ends.drop_defer()returns false where the answer went at the drop already; thendrop_finishdoes nothing. What the source sees:Platform deferred ( drop_defertrue)taken not taken X11 always XdndFinishedaccepted, the effect's actionXdndFinishednot accepted, no action (an XDND 5 source; older ones see only that it ended)Wayland always wl_data_offer.finish:dnd_finishedwith the action negotiated before the drop (it cannot change after it)the offer destroyed without finish(the protocol has no other answer after a drop; Weston then sends the sourcecancelled)Windows only a source whose data object offers IDataObjectAsyncCapabilityin async modeEndOperation(S_OK, effect)EndOperation(E_ABORT, DROPEFFECT_NONE)Windows, other sources; macOS; the browser (file drops) never: IDropTarget::Drop,performDragOperation:and the page'sdropevent answer at oncethe effect at the drop (as taken: the source learns nothing more) the app's own drag onto its own target (every platform, headless too) always DS_ACTIVEuntil the answer, thenDS_ENDwithdrag_effect()the effect,UIC_DRAG_ENDDS_END,drag_effect()0The app's own drags inside its window go the same way. Without
drop_deferthe source'sDS_END(andUIC_DRAG_END) comes with the effect the drop was delivered with, in passes right after the drop's: no longer in the same pass as the target'sDS_DROP, still before the frame is drawn. Withdrop_deferit comes afterdrop_finishwith that effect. While the answer waits,drag_allowed()says the source's effects anddragging()is false; a new drag of the app overtakes it (answered as delivered), as a newer drop does (apps/dndtest/tests/own_later.uis).match ui.drop_target(ID_PAGE, DT_FILES | DT_URL | DT_TEXT) { DS_DROP => { let deferred = ui.drop_defer(); // the page decides later self.engine.drop(ui.drop_data().clone(), deferred); } _ => {} } // later, when the engine says DropDone { taken, effect }: ui.drop_finish(if taken { effect } else { 0 });Positions:
drop_pos()anddrag_over()are DIP of the window, rounded; at 150 % three pixels share two DIP. A canvas that draws at the display's resolution (a web page) takesdrop_pos_px()/drag_over_px(): px of the window likelast_rect, so(x - inp.rect[0], y - inp.rect[1])is the pixel of the canvas (UiInput's ownx,yare px too).Mirrored windows (RTL): targets and positions stay logical, as every pointer event.
Tests:
drag S1 S2anddown/move/key esc/upfor widget drags;dragover,dragleaveanddrop X Y text "s" html "s" url U image F files F...for other programs;dragover expect copy|move|link|none [ctrl] [shift]for what the platform would answer the drag that hovers (the target'sdrop_effect_set);dragover X Y text copy linksets the effects the source allows (drop ... allows copy link: the effects a drop gives itself, as Windows'Dropdoes; without, those of thedragoverbefore it, else all);drop expect copy|move|link|none|pendingfor the answer the source of the last drop got (drop ... sync: a platform that answers at the drop);dragout expect .../dragout end movefor a drag that left the window (headless, the platform is not involved); seeapps/dndtest(tests/later.uis: the answer after the drop).plattest --test dndchecks the shared part and Windows' OLE objects without a user (also the answer after the drop with a data object in async mode),tools/platshared/dnd_x11.pyXDND both ways under WSLg (alsoXdndActionListandXdndFinishedafterdrop_finish;--app: with the real dndtest window). By hand only: dragging with a real mouse to and from Explorer, a browser, a file manager, and everything on Wayland (a compositor gives the drag to the client of a real button press).