JFLib

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> records Edits (apply / revert / label, optionally merge so a drag is one step); Snapshot::new(label, before, after) is the edit for small Clone states, .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_end for compound steps, mark_saved() / dirty() for "save changes?" (mark_unsaved(): a recovered copy counts as unsaved). ui.undo_keys() gives Some(true) for Ctrl+Z and Some(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) return true to keep the window, open your "save?" dialog, and call ui.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_ACT when 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.md describes 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(); // always

    Flags WF_TOOL, WF_DIALOG (+ WF_MODAL; dialog_buttons then make the footer), WF_RESIZABLE, WF_NOCLOSE, WF_AUTOHEIGHT, ...; the library writes the user's placement back into the WinRect. 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_TOOL without WF_DIALOG) are child windows there: a subsurface of the owner, placed where the WinRect says, 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 or window_activate -- as on Windows (plat::WST_CHILD; jfgui_WL_TOOLWIN=toplevel keeps 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 with titlebar_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 (no WM_TRANSIENT_FOR, type normal / an xdg_toplevel without 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 a WinRect with 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/viewtest tests/appwin.uis; real windows on X11 and Wayland: python tools/x11check.py appwin --backend x11|wayland (viewtest --app-window opens it at the start).

  • One instance: with AF_SINGLE_INSTANCE in the AppDesc, 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), and App::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 from PACKAGE (PACKAGING.md).

  • Notification area and notifications: ui.tray_set(icon, tooltip, &MENU) shows a symbol (None: the program's own icon) whose menu is Mi rows of the command table; a chosen row arrives as App::command(cmd, 0), a click on the symbol as UIC_TRAY (TRAY_ACTIVATE / TRAY_SECONDARY). ui.notify(title, body, icon) sends a system notification and returns its id; a click on it sends UIC_NOTE (arg = id), and UIC_NOTE_GONE arrives when it closes unclicked. Call tray_set again after cmd_state changes. ui.bring_to_front() restores the window. Windows uses Shell_NotifyIconW (the notification is the symbol's balloon, which Windows 10 / 11 show as a toast); Linux uses StatusNotifierItem + dbusmenu and org.freedesktop.Notifications. The browser and Android have notifications but no symbol (tray_set answers false): 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 for POST_NOTIFICATIONS at the first note, which the manifest must list); a tap opens the activity. The app's PERMISSIONS has no rule for notifications on any platform: the system's permission is the gate. Headless runs only print what they would show. apps/traydemo shows 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_TITLEBAR in the AppDesc, 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's gtk-decoration-layout in settings.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 what action-double-click-titlebar, action-middle-click-titlebar and action-right-click-titlebar say: 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) or none (default of the middle click); a left press moves the window. Changes apply at once (UIC_SETTINGS with SET_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_CORNER corners) 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 and expect 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_ACT when a file (FD_FOLDER: a folder) was chosen; path then 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, with FD_BUILTIN (the app's choice, below) or with jfgui_FILEDLG=builtin (every dialog of the run); FD_FOLDER uses 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): path becomes a content:// name (VFS.md, "Android"), readable and writable with the ordinary file functions and kept across restarts; show the user plat::display_name(&path), not the name itself. In a browser with the File System Access API (Chromium) FD_OPEN / FD_SAVE show the system's pickers too: path becomes /handles/ID/NAME, the user's own file (an opened one already read in); write_file on it writes the file back (plat::web::persist confirms it), plat::web::reopen reads 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 calling filedlg every frame as usual. Keep chosen files in ui.recent_add (a Flatpak's documents of the portal stay reachable after a restart, Android's grants and the browser's handles are kept). Ids id .. id + 0x3FFF belong to it. i preselects a file type of exts:

    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): path gets the first, ui.filedlg_paths() every chosen file in the dialog's order (after a dialog without FD_MULTI the one file, after an FD_FOLDER dialog 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), where jfgui_FILEDLG=builtin only switches a whole run. It lists what plat'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 a DragData (files, text, urls, html, image = a PNG file, bmp, the app's own app kind DT_USER0 << k with bytes, a label, effects); its kinds are DT_FILES, DT_TEXT, DT_URL, DT_HTML, DT_IMAGE and the app's own bits, the effects DE_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 reports DS_HOVER while a matching drag is over it and DS_DROP once, in the first pass after the drop; the source reports DS_ACTIVE and DS_END once. A drop changes what this pass already drew: apply it after the widgets (end of frame) and call ui.repass().

    • When the pointer leaves the window with content other programs know, the platform takes the drag over: Windows DoDragDrop with our IDataObject (CF_UNICODETEXT, CF_HDROP, HTML Format, UniformResourceLocator, PNG, CF_DIBV5), X11 as an XDND source, Wayland wl_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, Wayland wl_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 get DS_HOVER and ui.drag_over() returns its kinds and position. A drop goes to the target at the point; outside every target ui.drop_accept(types) decides (default DT_FILES, as before) and it arrives as UIC_DROP with drop_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 after drop_target says which of DE_COPY | DE_MOVE | DE_LINK that 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_actions on Wayland, the drag operation on macOS. 0 refuses 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, as dropEffect) sets it every pass while DS_HOVER holds, for the point of drag_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: no DS_DROP, no UIC_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 the DE_* effects of the drag over the window as its source offers them -- Windows the effects of its DoDragDrop, X11 the source's XdndActionList with the action it asks for (without a list: all), Wayland its source_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 its DragData::allowed(); DE_ALL where 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 of IDropTarget::Drop, X11 the list with the last XdndPosition's action, Wayland the offer's source_actions, macOS the operation mask of performDragOperation:; without them (the browser's and Android's drops) those of the hover before it, else DE_ALL. drag_allowed() says them from the drop's E_DROP to the end of the passes it starts (DS_DROP, App::command's UIC_DROP) and, after ui.drop_defer(), until its answer went (drop_finish, DROP_DEFER_MS, a newer drop) -- in every window over which no drag is; drop_finish answers within them. 0 otherwise: no drag over the window, no drop in its passes or waiting. A page that maps a web page's effectAllowed and dropEffect picks from it for drop_effect_set and hands it on with the drop.

    • 0 means "not said" wherever the effects a source allows are given: DragData::effects of the app's own drag (drag_set, drag_out), the effects of another program's hover and drop, the allowed of plat::drag_query and plat::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_COPY above). Files are never moved, whatever the source says. (Up to 0.2, a 0 meant copy and move everywhere but in drag_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 in App::command's UIC_DROP) and answers with ui.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). Without drop_finish the answer goes after DROP_DEFER_MS (3 s) as the drop was delivered, with a UIWARN; 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; then drop_finish does nothing. What the source sees:

      Platformdeferred (drop_defer true)takennot taken
      X11alwaysXdndFinished accepted, the effect's actionXdndFinished not accepted, no action (an XDND 5 source; older ones see only that it ended)
      Waylandalwayswl_data_offer.finish: dnd_finished with 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 source cancelled)
      Windowsonly a source whose data object offers IDataObjectAsyncCapability in 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's drop event 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)alwaysDS_ACTIVE until the answer, then DS_END with drag_effect() the effect, UIC_DRAG_ENDDS_END, drag_effect() 0

      The app's own drags inside its window go the same way. Without drop_defer the source's DS_END (and UIC_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's DS_DROP, still before the frame is drawn. With drop_defer it comes after drop_finish with that effect. While the answer waits, drag_allowed() says the source's effects and dragging() 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() and drag_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) takes drop_pos_px() / drag_over_px(): px of the window like last_rect, so (x - inp.rect[0], y - inp.rect[1]) is the pixel of the canvas (UiInput's own x, y are px too).

    • Mirrored windows (RTL): targets and positions stay logical, as every pointer event.

    • Tests: drag S1 S2 and down / move / key esc / up for widget drags; dragover, dragleave and drop 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's drop_effect_set); dragover X Y text copy link sets the effects the source allows (drop ... allows copy link: the effects a drop gives itself, as Windows' Drop does; without, those of the dragover before it, else all); drop expect copy|move|link|none|pending for the answer the source of the last drop got (drop ... sync: a platform that answers at the drop); dragout expect ... / dragout end move for a drag that left the window (headless, the platform is not involved); see apps/dndtest (tests/later.uis: the answer after the drop). plattest --test dnd checks 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.py XDND both ways under WSLg (also XdndActionList and XdndFinished after drop_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).

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