Răsfoiți Sursa

ngui: add modal file Open/Save dialog

Add ngui_file_dialog: a reusable in-canvas modal browser with the VFS root mount table, Up/Home/Refresh, a scrollable folder/file list with sizes, a file-name field that also accepts paths, and Cancel/Open|Save. It returns an absolute path and stays active so the caller can close it or show an I/O error for another try.

Switch Textedit's Open/Save As from its single-path field to the dialog; a failed load or save now keeps the dialog open with the error, and cancelling Open preserves the modified buffer. Give the gallery a live browse example and update AGENTS.md and the architecture pages.
Johannes Zellner 1 oră în urmă
părinte
comite
2f70962e14
8 a modificat fișierele cu 1114 adăugiri și 172 ștergeri
  1. 38 22
      AGENTS.md
  2. 4 1
      Makefile
  3. 30 6
      docs/graphics.html
  4. 2 2
      docs/userland.html
  5. 40 3
      user/apps/gallery/gallery.c
  6. 93 138
      user/apps/textedit/ucmd_textedit.c
  7. 56 0
      user/lib/ngui/ngui.h
  8. 851 0
      user/lib/ngui/ngui_file.c

+ 38 - 22
AGENTS.md

@@ -826,7 +826,15 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   is 512 (511 characters).  `ngui_text_area` is the multi-line editor built
   on the same event model: soft wrap at word boundaries, caret/selection,
   Ctrl+A, word and page movement, and the scrolling pane above; `textedit`
-  is its user and the gallery shows it.
+  is its user and the gallery shows it.  `ngui_file_dialog` is the modal
+  Open/Save browser: it lists the VFS (the root shows the mount table), with
+  Up/Home/Refresh, a scrollable row list, a file-name field and
+  Cancel/Open|Save.  Clicking a folder enters it, clicking a file selects
+  it, double-click or Enter accepts, and Esc cancels; the file-name field
+  also takes a path.  On accept it returns an absolute result path and stays
+  active so the app can close it or show an I/O error for another try.
+  Textedit uses it for Open/Save As and the gallery's Inputs section has a
+  live demo.
 - **Graphics**: `vga.c/h`, `vga_copy.S`, `blit.c/h`, `gpu.c`, `ati.c`, `nvidia.c`,
   `nv50.c`, `pci.h` — VESA LFB + shadow buffer.  Drawing goes into a
   `struct surface` render target: `vga_target()` is the screen's shadow buffer
@@ -1848,11 +1856,13 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   syscalls resolve relative paths against it, so commands keep working after
   `cd` (the shell passes arguments verbatim).  The one argument is passed as a
   C string on the top of the user stack (`process_create_user(..., arg)`), so
-  `_start(const char *arg)` needs no crt0.  `ngui.c/h` is the shared userland
-  GUI toolkit linked into `ucmd_files.c`, `ucmd_textedit.c`,
+  `_start(const char *arg)` needs no crt0.  `ngui.c/h` and `ngui_file.c`
+  are the shared userland GUI toolkit linked into `ucmd_files.c`,
+  `ucmd_textedit.c`,
   `ucmd_mines.c`, `ucmd_solitaire.c`, `ucmd_process.c` and the external
   `gallery.elf` (buttons, menu items, text fields with a disabled state, the
-  multi-line `ngui_text_area`, icons, layout cuts and scroll panes);
+  multi-line `ngui_text_area`, the modal `ngui_file_dialog`, icons, layout
+  cuts and scroll panes);
   `files` opens the selected text file through
   `/ramfs/bin/textedit`, image files through `/ramfs/bin/view`, and `.htm`/`.html`
   files through `/ramfs/bin/browser`.  `ngui_end_ex()`
@@ -1864,9 +1874,12 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   boundaries, a caret with Home/End/PageUp/PageDown/arrow/word-jump movement,
   mouse and double-click word selection, Ctrl+A, Backspace/Delete and
   Ctrl+Backspace/Delete, Tab insertion and a vertical scrollbar.  The toolbar
-  has New, Open, Save and Save As; Open/Save As use a small in-window path
-  dialog (`ngui_text_input`) and save with `SYS_WRITE_FILE`, so an installed
-  board can edit `/data` files and `/share` always works.  CRLF/CR are
+  has New, Open, Save and Save As; Open/Save As use `ngui_file_dialog` (a
+  directory list with the mounts at `/`, Up/Home/Refresh, a file-name field
+  and Cancel/Open|Save).  A failed load/save puts the error back in the
+  dialog and leaves it open instead of losing the chosen path.  Files are
+  read and written through the VFS, so an installed board can edit `/data`
+  files and `/share` always works.  CRLF/CR are
   normalized to LF on load; files are capped at 256 KB.  The status bar shows
   the 1-based line/column, byte count and the file name with `(modified)`.
   Ctrl+N/O/S work anywhere in the window, Ctrl+Q/W or Esc quit, and a modified
@@ -1877,8 +1890,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 - **Gallery**: `gallery.c` is the ngui widget gallery: typography and
   truncation, the drawing primitives and clip stack, the theme palette, every
   icon in `ICON_LIST`, live buttons/icon buttons, text fields (including a disabled,
-  read-only field) with event feedback, the multi-line text area, a nested
-  draggable scroll pane and the `ngui_cut_*` layout helpers.  The real
+  read-only field) with event feedback, the multi-line text area, a live
+  `ngui_file_dialog` example, a nested draggable scroll pane and the
+  `ngui_cut_*` layout helpers.  The real
   ELF ships in the pack as `bin/gallery.app`; `ucmd_gallery.c` is the tiny
   `bin/gallery` launcher, which prefers `/share/GALLERY` (development upload
   via `make gallery-dev`), then the pack copy, then the `GALLERY` disk
@@ -3369,8 +3383,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    bytes, ~945 KiB gzip; 6000 454,608 bytes, ~204 KiB gzip), the RTL8821A
    firmware and tables (31,898 + 11,668
    bytes), the 15 full-colour app icons and `install/kernel.bin` is
-   ~3.19 MB gzip (~0.8 MB under the cap), inflating to ~7.3 MB, which adds
-   about a second to the boot; the floppy lite pack is ~770 KB gzip
+   ~3.20 MB gzip (~0.8 MB under the cap), inflating to ~7.3 MB, which adds
+   about a second to the boot; the floppy lite pack is ~781 KB gzip
    and deliberately omits the firmware, the cursor bundle,
    `install/kernel.bin` and the browser (`BROWSER` on `root.img` is the
    floppy copy).  `libdeflate-gzip -12` is still preferred.  Over
@@ -3997,14 +4011,16 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `ttyS4`), not the legacy COM1; the legacy port floats at `0xFF`, which
     `serial_init()` now detects before the PIT starts polling it.
 
-44. Textedit/ngui text-area limits: no undo/redo, clipboard, find/replace,
-    line numbers, syntax highlighting or word-count; selection is mouse drag,
-    double-click or Ctrl+A because the kernel key path exposes no Shift+arrow
-    chord.  Open/Save As are a single path field (no file browser; use
-    `files` or the `open` dialog's path field), files are capped at 256 KB,
-    text is Latin-1 and saves always write LF line endings.  The title-bar X
-    kills the process without the discard prompt, and paths are limited to 63
-    characters (`VFS_PATH_MAX`); longer input gets a "Path is too long" error.
-    The widget scans the buffer to
-    wrap and find the caret each frame, so a 256 KB document is noticeably
-    more CPU-hungry than a small one.
+44. Textedit/ngui text-area/file-dialog limits: no undo/redo, clipboard,
+    find/replace, line numbers, syntax highlighting or word-count; selection
+    is mouse drag, double-click or Ctrl+A because the kernel key path exposes
+    no Shift+arrow chord.  `ngui_file_dialog` lists at most 128 entries (then
+    reports truncation), has no new-folder/rename/delete, no file-type
+    filter, no toolbar path completion and no overwrite confirmation; the
+    file-name field accepts a path.  Files are capped at 256 KB, text is
+    Latin-1 and saves always write LF line endings.  The title-bar X kills
+    the process without the discard prompt, and paths are limited to 63
+    characters (`VFS_PATH_MAX`); longer input gets a "Path is too long"
+    error.  The text area scans the buffer to wrap and find the caret each
+    frame, so a 256 KB document is noticeably more CPU-hungry than a small
+    one.

+ 4 - 1
Makefile

@@ -348,7 +348,10 @@ $(UFONT_WOFF): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
 NGUI = $(UL)/ngui/ngui.o
 $(NGUI): OPT = -Os
 $(NGUI): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
-NGUI_APP = $(NGUI) $(FONT16) $(UFONT_OBJS)
+NGUI_FILE = $(UL)/ngui/ngui_file.o
+$(NGUI_FILE): OPT = -Os
+$(NGUI_FILE): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
+NGUI_APP = $(NGUI) $(NGUI_FILE) $(FONT16) $(UFONT_OBJS)
 
 # Window-manager/terminal drawing helpers (wm and term).
 UWM = $(UL)/uwm/uwm_lib.o

+ 30 - 6
docs/graphics.html

@@ -343,7 +343,7 @@
 			repeat. <code>wm_pump_keyboard()</code> consumes the chord so the
 			focused client never receives a Tab and queues
 			<code>WM_CHORD_NEXT</code>/<code>WM_CHORD_PREV</code> in the
-			eight-entry chord ring of <code>struct wm_status</code>, since
+			16-entry input ring of <code>struct wm_status</code>, since
 			the WM has no window key queue of its own. The WM derives the
 			most-recently-focused order from the window <code>focused</code>
 			flags it refreshes every frame, draws a centred icon strip with
@@ -354,6 +354,28 @@
 			up while repeated Tabs walk the list.
 		</p>
 
+		<h3>App runner</h3>
+		<p>
+			Pressing Win/Super toggles the WM's app runner.
+			<span class="file">kernel/io.c</span> reports only the key press
+			(<code>IO_KEY_META</code>, with the keyboard typematic repeats
+			suppressed), and <code>wm_pump_keyboard()</code> flips
+			<code>wm_status.runner_active</code> and routes every following
+			key into the same input ring as <code>WM_CHORD_KEY | key</code>
+			instead of to the focused client. Enter and Esc also release the
+			grab in the kernel, so a dead WM cannot leave the keyboard
+			captured. The WM mirrors the flag and draws a centred query field
+			plus a ranked suggestion list from the <code>sm_apps</code>
+			catalogue: matches are case-insensitive on the app label, the
+			command basename and the window title, with an inline ghost
+			completion of the selected label. Up/Down and PageUp/PageDown
+			move the selection, Tab fills the completion, Left/Right/Home/End
+			edit the query, and Enter launches the selected app through the
+			normal <code>sm_launch()</code> path. The overlay is modal for
+			the pointer; a second Win or Esc closes it. It is drawn by the WM
+			like the Alt+Tab strip, not a canvas window.
+		</p>
+
 		<h3>Compositing cost</h3>
 		<p>
 			The WM keeps a front-to-back order: the focused window first, then
@@ -496,8 +518,9 @@
 			<span class="file">ngui.c</span>/<span class="file">ngui.h</span> is an
 			immediate-mode GUI toolkit shared by the ring-3 apps. It provides
 			clipped RGB565 primitives, buttons, menu items, text fields, the
-			Adwaita symbolic icons (see <a href="#icons">UI icons</a>), a theme palette, layout cut helpers and scrolling
-			panes. It is linked into <code>files</code>, <code>textedit</code>,
+			multi-line text area, the modal file dialog, the Adwaita symbolic
+			icons (see <a href="#icons">UI icons</a>), a theme palette, layout
+			cut helpers and scrolling panes. It is linked into <code>files</code>, <code>textedit</code>,
 			<code>mines</code>, <code>solitaire</code>, <code>process</code>,
 			<code>chat</code>, <code>settings</code>, <code>netmenu</code> and
 			the real <code>gallery.elf</code>.
@@ -505,6 +528,7 @@
 		<ul>
 			<li><strong>Text fields</strong> support drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Backspace word deletion and Ctrl+A. They use the proportional face with measured caret, selection and horizontal scrolling; a field marked <code>disabled</code> ignores pointer and keyboard input, drops the focus and paints its value dimmed in the same proportional face. A field marked <code>secret</code> is measured and painted from a <code>*</code> mask (caret, selection and click positions follow the mask, Ctrl+Left/Right jump to the ends), and Tab returns <code>NGUI_INPUT_NEXT</code> together with <code>NGUI_INPUT_CANCEL</code> so forms can move the focus. Fields hold up to 511 characters (<code>NGUI_INPUT_MAX</code> 512). The terminal and the old <code>edit</code> command keep the 8×16 cell grid; the multi-line text area uses the mono face.</li>
 			<li><strong>Multi-line text area</strong> (<code>ngui_text_area</code>) is the Notepad-like editor used by <code>textedit</code> and shown in the gallery. It edits a caller-owned byte buffer in place with soft wrapping at word boundaries, a blinking caret, mouse drag and double-click word selection, Ctrl+A, arrow/Home/End/PageUp/PageDown and word-jump movement, Backspace/Delete and Ctrl+Backspace/Delete word deletion, Tab insertion and the same overlay vertical scrollbar. It maintains the caret's 1-based line/column, keeps only visible text drawn, and leaves app-level Ctrl shortcuts in the key queue so the window can handle Ctrl+S/O/N/Q. Esc clears the focus and returns <code>NGUI_TEXTAREA_CANCEL</code>.</li>
+			<li><strong>File dialog</strong> (<code>ngui_file_dialog</code>) is a modal Open/Save browser drawn inside the app canvas: a dark backdrop and rounded panel, Up/Home/Refresh, the current folder with the VFS mount table at <code>/</code>, a scrollable list of folders/files with sizes, a file-name field that also accepts a path, and Cancel plus Open/Save. Clicking a folder enters it, clicking a file selects it, double-click or Enter accepts, and Esc cancels. On accept it returns an absolute path but keeps the dialog active so the caller can close it or display an I/O error and stay open. <code>textedit</code> uses it for Open and Save As; the gallery's Inputs section has a live example.</li>
 			<li><strong>Popover components</strong> give a menu panel its surface: <code>ngui_popover_begin()</code> fills the canvas and returns the body and footer rectangles (no title bar or close button); <code>ngui_section()</code> draws a captioned section header with an optional right-aligned action button; <code>ngui_list_row()</code> is a two-line hover/selected row with optional signal bars and trailing text; <code>ngui_tile()</code> is a rounded quick-settings tile and <code>ngui_slider()</code> a draggable horizontal slider. The WM draws no outer chrome, so the app paints the whole window.</li>
 			<li><strong>Scroll panes</strong> keep the wheel and page keys, and draw a Firefox-style overlay pill instead of a permanent track. It is hidden by default, animates in from the pane's right edge while the pointer is over the pane, brightens over the hit strip and turns accent-coloured while dragged. Presses in the strip start a drag (or jump the thumb) and do not reach the rows or buttons beneath it; content uses the full pane width in every app.</li>
 			<li><strong>Clip stack</strong> keeps nested panes and popups inside their parents.</li>
@@ -552,7 +576,7 @@
 			</div>
 			<div class="card">
 				<h3>textedit</h3>
-				<p>Notepad-like plain-text editor (start menu and dock <em>Textedit</em>): a soft-wrapping <code>ngui_text_area</code> with caret, mouse/double-click selection, word and page keys and a vertical scrollbar; New/Open/Save/Save As toolbar with an in-window path dialog; Ln/Col/bytes status and a modified marker. Ctrl+N/O/S work anywhere, Ctrl+Q/W or Esc quit, and New/Open/quit ask before discarding a modified buffer. Files are capped at 256 KB and CRLF is normalized to LF.</p>
+				<p>Notepad-like plain-text editor (start menu and dock <em>Textedit</em>): a soft-wrapping <code>ngui_text_area</code> with caret, mouse/double-click selection, word and page keys and a vertical scrollbar; New/Open/Save/Save As toolbar with the modal <code>ngui_file_dialog</code> (folders, mounts, sizes and a file-name field) for Open/Save As; Ln/Col/bytes status and a modified marker. A failed load/save leaves the dialog open with the error. Ctrl+N/O/S work anywhere, Ctrl+Q/W or Esc quit, and New/Open/quit ask before discarding a modified buffer. Files are capped at 256 KB and CRLF is normalized to LF.</p>
 			</div>
 			<div class="card">
 				<h3>process</h3>
@@ -564,7 +588,7 @@
 			</div>
 			<div class="card">
 				<h3>gallery</h3>
-				<p>Live showcase of every ngui control and primitive. Ships in the pack as <code>bin/gallery.app</code>; a launcher prefers <code>/share/GALLERY</code> for development.</p>
+				<p>Live showcase of every ngui control and primitive, including the multi-line editor and a working file-dialog example. Ships in the pack as <code>bin/gallery.app</code>; a launcher prefers <code>/share/GALLERY</code> for development.</p>
 			</div>
 			<div class="card">
 				<h3>chat</h3>
@@ -741,7 +765,7 @@
 			<li><code>kernel/gfx.c</code>, <code>kernel/gfx.h</code> — RGB565 window canvases</li>
 			<li><code>kernel/sys_wm.c</code>, <code>kernel/sys_wm.h</code> — WM/window ABI</li>
 			<li><code>user/apps/browser/browser.c</code>, <code>user/apps/browser/browser_html.c</code> — HTML/CSS renderer and inline SVG</li>
-			<li><code>user/lib/ngui/ngui.c</code>, <code>user/lib/ngui/ngui.h</code> — toolkit</li>
+			<li><code>user/lib/ngui/ngui.c</code>, <code>user/lib/ngui/ngui_file.c</code>, <code>user/lib/ngui/ngui.h</code> — toolkit and file dialog</li>
 			<li><code>user/lib/ufont/ufont.c</code>, <code>user/lib/ufont/ufont_ttf.c</code>, <code>user/lib/ufont/ufont_draw.c</code> — fixed-point TrueType text</li>
 			<li><code>user/lib/ufont/ufont_woff.c</code> — WOFF 1.0 to sfnt (browser only)</li>
 			<li><code>fonts/*.ttf</code> — Arimo / Liberation Mono / Noto Emoji subsets in the pack</li>

+ 2 - 2
docs/userland.html

@@ -462,7 +462,7 @@
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<li><strong>mines</strong> — second ngui canvas app; shares the toolkit and event model.</li>
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback. Its <em>Background</em> button (or <code>b</code>) cover-scales the image to a screen-aspect RGB565 wallpaper, writes <code>/data/WALLPAPR.BIN</code> when the data volume is mounted (otherwise the RAM-only <code>/share/wallpaper</code>), and signals the WM; the status bar reports the result.</li>
-			<li><strong>textedit</strong> — the Notepad-like plain-text editor (start menu and dock <em>Textedit</em>, or <code>textedit [file]</code>). The editor area is ngui's multi-line <code>ngui_text_area</code>: soft wrapping at word boundaries, a caret with arrow/Home/End/PageUp/PageDown/word movement, mouse and double-click word selection, Ctrl+A, Tab insertion and a vertical scrollbar. The toolbar offers New, Open, Save and Save As; Open/Save As use an in-window path field, CRLF is normalized to LF on load and writes go through <code>SYS_WRITE_FILE</code> (256 KB cap). The status bar shows the 1-based line/column, byte count and the file name with <code>(modified)</code>. Ctrl+N/O/S work anywhere in the window; Ctrl+Q/W or Esc quit, and a modified buffer asks before New/Open/quit discard it. The title-bar X still closes without a prompt, because the canvas ABI has no close-request event.</li>
+			<li><strong>textedit</strong> — the Notepad-like plain-text editor (start menu and dock <em>Textedit</em>, or <code>textedit [file]</code>). The editor area is ngui's multi-line <code>ngui_text_area</code>: soft wrapping at word boundaries, a caret with arrow/Home/End/PageUp/PageDown/word movement, mouse and double-click word selection, Ctrl+A, Tab insertion and a vertical scrollbar. The toolbar offers New, Open, Save and Save As; Open/Save As use ngui's modal <code>ngui_file_dialog</code> (a directory browser with the mount table at <code>/</code>, Up/Home/Refresh, file sizes and a file-name field), CRLF is normalized to LF on load and writes go through the VFS (256 KB cap). The status bar shows the 1-based line/column, byte count and the file name with <code>(modified)</code>. Ctrl+N/O/S work anywhere in the window; Ctrl+Q/W or Esc quit, and a modified buffer asks before New/Open/quit discard it. The title-bar X still closes without a prompt, because the canvas ABI has no close-request event.</li>
 			<li><strong>edit</strong> — terminal-canvas text editor that draws its own text with the 8x16 font; kept for shell-only use.</li>
 			<li><strong>clock</strong> / <strong>colors</strong> — small window canvas demos.</li>
 			<li><strong>settime</strong> — the standalone Date &amp; Time editor (the Settings app has the same editor on its Date &amp; Time page). It reads and writes the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code>; the <em>Sync NTP</em> button asks the kernel's SNTP client (<code>SYS_NTP_SYNC</code>, 106) for UTC and writes the result to the RTC. The two-digit RTC year is expanded over 1970–2069 so dead-battery defaults such as 1980/1990 can be corrected.</li>
@@ -559,7 +559,7 @@
 			<li><code>Makefile</code> — <code>UCMDS</code> and pack rules</li>
 			<li><code>user/apps/&lt;name&gt;/ucmd_&lt;name&gt;.c</code> — commands, one directory each</li>
 			<li><code>user/lib/ufont/ufont.c</code>, <code>user/lib/ufont/ufont_ttf.c</code>, <code>user/lib/ufont/ufont_woff.c</code> — fixed-point TrueType text, WOFF 1.0 unwrapping</li>
-			<li><code>user/lib/ngui/ngui.c</code> — GUI toolkit; <code>fonts/*.ttf</code> — UI and emoji subsets</li>
+			<li><code>user/lib/ngui/ngui.c</code>, <code>user/lib/ngui/ngui_file.c</code> — GUI toolkit and file dialog; <code>fonts/*.ttf</code> — UI and emoji subsets</li>
 			<li><code>user/apps/browser/browser.c</code>, <code>user/apps/browser/browser_html.c</code>, <code>user/apps/browser/svg_raster.c/h</code> (+ <code>user/apps/browser/svg_test.c</code>), <code>user/apps/browser/js_browser.c/h</code>, <code>user/apps/browser/js_prelude.js</code> + <code>user/apps/browser/js_prelude.S</code> (+ <code>tools/jsstrip.c</code>), <code>user/apps/browser/js_mu.c/h</code>, <code>third_party/quickjs/</code>, <code>user/apps/gallery/gallery.c</code></li>
 			<li><code>user/apps/chat/ucmd_chat.c</code>, <code>user/apps/chat/chat_login.c</code>, <code>user/lib/ujson/ujson.c</code>, <code>user/lib/uhttp/uhttp_cookie.c</code> — chat client</li>
 			<li><code>user/apps/wifi/ucmd_wifi.c</code>, <code>user/lib/wifi/wpa.c</code>, <code>user/lib/tls/wpa_crypto.c</code> — <code>wifi</code> command and the WPA2-PSK supplicant</li>

+ 40 - 3
user/apps/gallery/gallery.c

@@ -66,6 +66,7 @@ enum {
 	ID_IN_DISABLED,
 	ID_IN_TEXTAREA,
 	ID_BTN_RESET_FIELDS,
+	ID_BTN_FILE_DIALOG,
 
 	ID_NAV_BASE = 0x100,
 	ID_ICON_BASE = 0x200
@@ -87,7 +88,7 @@ static const char *const sec_descs[SEC_COUNT] = {
 	"the ngui_theme_dark palette",
 	"every Adwaita symbolic icon",
 	"buttons and icon buttons",
-	"single-line fields and the multi-line text area",
+	"single-line fields, the text area and file dialog",
 	"a nested draggable scroll pane",
 	"ngui_cut_* layout helpers",
 	"every mouse cursor shape"
@@ -117,6 +118,7 @@ static struct ngui_input events_in;
 static struct ngui_input disabled_in;
 static struct ngui_text_area area_in;
 static char area_text[512];
+static struct ngui_file_dialog file_dlg;
 
 static int sec_y[SEC_COUNT];
 static int sec_content_h;
@@ -914,9 +916,16 @@ static void draw_inputs(struct ngui *g, struct ngui_rect card)
 		feedback_error = 0;
 		event_set("input fields reset");
 	}
+	if (gallery_button(g, ID_BTN_FILE_DIALOG,
+			   rect_make(x + 114, top + 186, 124, 26),
+			   "Browse files...")) {
+		ngui_file_dialog_open(&file_dlg, NGUI_FILE_OPEN, "/", "",
+				      0x5000);
+		ngui_invalidate(g);
+	}
 	if (help_w >= 150)
-		ngui_text(g, x + 120, top + 192,
-			  "ngui_input_set() rewrites a field.",
+		ngui_text(g, x + 250, top + 192,
+			  "ngui_file_dialog() opens a modal browser.",
 			  g->theme.border);
 
 	{
@@ -1299,6 +1308,29 @@ static void draw(struct ngui *g)
 {
 	struct ngui_rect all = {0, 0, g->w, g->h};
 	struct ngui_rect header, nav, status, body;
+	int r;
+
+	if (file_dlg.active) {
+		r = ngui_file_dialog(g, &file_dlg);
+		if (r == NGUI_FILE_ACCEPTED) {
+			char b[160];
+			unsigned int n = 0;
+
+			s_append(b, &n, "file dialog: ", sizeof(b));
+			s_append(b, &n, ngui_file_dialog_result(&file_dlg),
+				 sizeof(b));
+			s_copy(input_feedback, b, sizeof(input_feedback));
+			feedback_error = 0;
+			event_set("file dialog accepted");
+			ngui_file_dialog_close(&file_dlg);
+		} else if (r == NGUI_FILE_CANCELLED) {
+			s_copy(input_feedback, "File dialog cancelled.",
+				sizeof(input_feedback));
+			feedback_error = 0;
+			event_set("file dialog cancelled");
+		}
+		return;
+	}
 
 	if (g->w < 420 || g->h < 300) {
 		ngui_fill_rect(g, all, g->theme.bg);
@@ -1324,6 +1356,11 @@ static void handle_keys(struct ngui *g)
 {
 	int k;
 
+	if (file_dlg.active) {
+		while (ngui_key(g) != 0)
+			;
+		return;
+	}
 	if (ngui_focus(g)) {
 		/* A focused field consumed its keys; Ctrl+C is never consumed. */
 		while ((k = ngui_key(g)) != 0)

+ 93 - 138
user/apps/textedit/ucmd_textedit.c

@@ -3,8 +3,9 @@
  * The text area is ngui's multi-line editor widget (soft wrap, caret,
  * mouse/double-click/drag selection, Ctrl+A, word jumps, page keys and a
  * vertical scrollbar).  The toolbar offers New, Open, Save and Save As; Open
- * and Save As use a small in-window path dialog.  The status bar shows the
- * caret line/column and the file name with a modified marker.
+ * and Save As use ngui's modal file dialog (directory list, mounts root,
+ * Up/Home/Refresh and a file-name field).  The status bar shows the caret
+ * line/column and the file name with a modified marker.
  *
  * Keys: the printable set, Enter, Tab, Backspace/Delete and the arrows edit;
  * Ctrl+Left/Right and Ctrl+Backspace/Delete work by word, Ctrl+A selects all,
@@ -34,17 +35,12 @@ enum {
 	ID_SAVE,
 	ID_SAVEAS,
 
-	ID_DLG_PATH = 0x20,
-	ID_DLG_OK,
-	ID_DLG_CANCEL,
-	ID_CONFIRM_DISCARD,
+	ID_CONFIRM_DISCARD = 0x20,
 	ID_CONFIRM_CANCEL
 };
 
 enum {
 	MODAL_NONE,
-	MODAL_OPEN,
-	MODAL_SAVEAS,
 	MODAL_CONFIRM
 };
 
@@ -57,14 +53,13 @@ enum {
 
 static struct ngui ui;
 static struct ngui_text_area area;
-static struct ngui_input path_input;
+static struct ngui_file_dialog file_dlg;
 static char text[TE_BUF_SIZE];
 static char doc_path[TE_PATH_MAX];
 static int dirty;
 static int quit;
 static int modal;
 static int pending_action;
-static char modal_error[96];
 static char status_text[128];
 static unsigned int status_until;
 static int status_error;
@@ -281,30 +276,56 @@ static const char *save_file(const char *path)
 static void close_modal(void)
 {
 	modal = MODAL_NONE;
-	modal_error[0] = '\0';
 	ngui_set_focus(&ui, ID_AREA);
 	ngui_invalidate(&ui);
 }
 
-static void open_dialog(int which)
+/* Open the ngui file dialog.  With a current document, start in its folder
+ * with its name selected; a brand-new Save As starts in /share. */
+static void open_file_dialog(int mode)
 {
-	unsigned int n, a;
+	const char *start = "";
+	const char *suggested = "";
+	char base[TE_PATH_MAX];
 
-	modal = which;
-	modal_error[0] = '\0';
-	if (doc_path[0])
-		ngui_input_set(&path_input, doc_path);
+	if (doc_path[0]) {
+		start = doc_path;
+		s_copy(base, base_name(doc_path), sizeof(base));
+		suggested = base;
+	} else if (mode == NGUI_FILE_SAVE) {
+		start = "/share";
+		suggested = "UNTITLED.TXT";
+	}
+	ngui_file_dialog_open(&file_dlg, mode, start, suggested, 0x4000);
+	ngui_invalidate(&ui);
+}
+
+/* The dialog stays active until the app closes it, so a failed load/save can
+ * put its error back into the dialog and let the user adjust the name. */
+static void handle_file_dialog_result(int result)
+{
+	const char *path, *err;
+
+	if (result == NGUI_FILE_CANCELLED) {
+		ngui_file_dialog_close(&file_dlg);
+		ngui_set_focus(&ui, ID_AREA);
+		ngui_invalidate(&ui);
+		return;
+	}
+	if (result != NGUI_FILE_ACCEPTED)
+		return;
+	path = ngui_file_dialog_result(&file_dlg);
+	if (file_dlg.mode == NGUI_FILE_OPEN)
+		err = load_file(path, 0);
 	else
-		ngui_input_set(&path_input, "/share/UNTITLED.TXT");
-	/* Preselect the file name after the last slash, so typing a name
-	 * replaces it while the directory stays. */
-	n = s_len(path_input.text);
-	a = n;
-	while (a > 0 && path_input.text[a - 1] != '/')
-		a--;
-	path_input.anchor = a;
-	path_input.cursor = n;
-	ngui_set_focus(&ui, ID_DLG_PATH);
+		err = save_file(path);
+	if (err) {
+		ngui_file_dialog_error(&file_dlg, err);
+		ngui_invalidate(&ui);
+		return;
+	}
+	ngui_file_dialog_close(&file_dlg);
+	ngui_set_focus(&ui, ID_AREA);
 	ngui_invalidate(&ui);
 }
 
@@ -318,7 +339,7 @@ static void do_save(void)
 		ngui_set_focus(&ui, ID_AREA);
 		ngui_invalidate(&ui);
 	} else {
-		open_dialog(MODAL_SAVEAS);
+		open_file_dialog(NGUI_FILE_SAVE);
 	}
 }
 
@@ -329,7 +350,7 @@ static void run_action(int action)
 		new_document();
 		break;
 	case ACT_OPEN:
-		open_dialog(MODAL_OPEN);
+		open_file_dialog(NGUI_FILE_OPEN);
 		break;
 	case ACT_QUIT:
 		quit = 1;
@@ -347,7 +368,6 @@ static void request_action(int action)
 	if (dirty) {
 		modal = MODAL_CONFIRM;
 		pending_action = action;
-		modal_error[0] = '\0';
 		ngui_set_focus(&ui, 0);
 		ngui_invalidate(&ui);
 		return;
@@ -355,41 +375,17 @@ static void request_action(int action)
 	run_action(action);
 }
 
-static void modal_ok(void)
-{
-	const char *err;
-
-	if (modal == MODAL_OPEN) {
-		err = load_file(path_input.text, 0);
-		if (err) {
-			s_copy(modal_error, err, sizeof(modal_error));
-			ngui_set_focus(&ui, ID_DLG_PATH);
-			ngui_invalidate(&ui);
-			return;
-		}
-		close_modal();
-	} else if (modal == MODAL_SAVEAS) {
-		err = save_file(path_input.text);
-		if (err) {
-			s_copy(modal_error, err, sizeof(modal_error));
-			ngui_set_focus(&ui, ID_DLG_PATH);
-			ngui_invalidate(&ui);
-			return;
-		}
-		close_modal();
-	}
-}
-
 static void discard_and_run(void)
 {
 	int action = pending_action;
 
 	pending_action = ACT_NONE;
 	modal = MODAL_NONE;
-	modal_error[0] = '\0';
-	dirty = 0;
+	/* Do not clear `dirty` here: an Open dialog can still be cancelled,
+	 * and the existing buffer must keep its modified state until a file
+	 * is actually loaded.  New/load/quit update it themselves. */
 	run_action(action);
-	if (modal == MODAL_NONE && !quit)
+	if (!quit)
 		ngui_set_focus(&ui, ID_AREA);
 	ngui_invalidate(&ui);
 }
@@ -421,13 +417,13 @@ static void draw_toolbar(struct ngui_rect r)
 				request_action(ACT_NEW);
 				break;
 			case 1:
-				open_dialog(MODAL_OPEN);
+				open_file_dialog(NGUI_FILE_OPEN);
 				break;
 			case 2:
 				do_save();
 				break;
 			case 3:
-				open_dialog(MODAL_SAVEAS);
+				open_file_dialog(NGUI_FILE_SAVE);
 				break;
 			default:
 				break;
@@ -500,59 +496,20 @@ static void draw_status(struct ngui_rect r)
 			  ui.theme.text_dim);
 }
 
-static void draw_modal(void)
+static void draw_confirm_modal(void)
 {
 	int mw, mh, mx, my;
-	struct ngui_rect panel, input_r;
-	int ok;
+	struct ngui_rect panel;
 
 	ngui_set_cursor(&ui, CURSOR_DEFAULT);
-	if (modal == MODAL_CONFIRM) {
-		mw = ui.w - 40;
-		if (mw > 440)
-			mw = 440;
-		if (mw < 240)
-			mw = 240;
-		mh = 132;
-		mx = (ui.w - mw) / 2;
-		my = (ui.h - mh) / 2;
-		panel = (struct ngui_rect){ mx, my, mw, mh };
-		ngui_fill_rect(&ui, (struct ngui_rect){ 0, 0, ui.w, ui.h },
-			       NGUI_RGB(8, 10, 16));
-		ngui_fill_round_rect(&ui, panel, NGUI_RADIUS, NGUI_RADIUS,
-				     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
-		ngui_frame_round(&ui, panel, NGUI_RADIUS, NGUI_RADIUS,
-				 NGUI_RADIUS, NGUI_RADIUS, 1, ui.theme.border);
-		ngui_text(&ui, mx + 18, my + 18, "Discard unsaved changes?",
-			  ui.theme.text);
-		ngui_text_ellipsis(&ui,
-			(struct ngui_rect){ mx + 18, my + 42, mw - 36, 18 },
-			mx + 18, my + 42,
-			doc_path[0] ? base_name(doc_path) : "Untitled",
-			ui.theme.text_dim);
-		if (ngui_button(&ui, ID_CONFIRM_CANCEL,
-				(struct ngui_rect){ mx + mw - 188, my + mh - 44,
-						    84, 28 }, "Cancel"))
-			close_modal();
-		if (ngui_button(&ui, ID_CONFIRM_DISCARD,
-				(struct ngui_rect){ mx + mw - 96, my + mh - 44,
-						    78, 28 }, "Discard"))
-			discard_and_run();
-		return;
-	}
-
-	mw = ui.w - 60;
-	if (mw > 560)
-		mw = 560;
-	if (mw < 280)
-		mw = 280;
-	mh = 178;
+	mw = ui.w - 40;
+	if (mw > 440)
+		mw = 440;
+	if (mw < 240)
+		mw = 240;
+	mh = 132;
 	mx = (ui.w - mw) / 2;
 	my = (ui.h - mh) / 2;
-	if (mx < 0)
-		mx = 0;
-	if (my < 0)
-		my = 0;
 	panel = (struct ngui_rect){ mx, my, mw, mh };
 	ngui_fill_rect(&ui, (struct ngui_rect){ 0, 0, ui.w, ui.h },
 		       NGUI_RGB(8, 10, 16));
@@ -560,31 +517,21 @@ static void draw_modal(void)
 			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
 	ngui_frame_round(&ui, panel, NGUI_RADIUS, NGUI_RADIUS,
 			 NGUI_RADIUS, NGUI_RADIUS, 1, ui.theme.border);
-	ngui_text(&ui, mx + 18, my + 16,
-		  modal == MODAL_OPEN ? "Open file" : "Save as",
+	ngui_text(&ui, mx + 18, my + 18, "Discard unsaved changes?",
 		  ui.theme.text);
-	ngui_text(&ui, mx + 18, my + 44, "Path", ui.theme.text_dim);
-	input_r = (struct ngui_rect){ mx + 18, my + 62, mw - 36, 28 };
-	ok = ngui_text_input(&ui, ID_DLG_PATH, input_r, &path_input);
-	if (ok & NGUI_INPUT_SUBMIT)
-		modal_ok();
-	else if ((ok & NGUI_INPUT_CANCEL) && !(ok & NGUI_INPUT_NEXT))
-		close_modal();
-
-	if (modal_error[0])
-		ngui_text_ellipsis(&ui,
-			(struct ngui_rect){ mx + 18, my + 96, mw - 36, 18 },
-			mx + 18, my + 96, modal_error, ui.theme.error);
-
-	if (ngui_button(&ui, ID_DLG_CANCEL,
+	ngui_text_ellipsis(&ui,
+		(struct ngui_rect){ mx + 18, my + 42, mw - 36, 18 },
+		mx + 18, my + 42,
+		doc_path[0] ? base_name(doc_path) : "Untitled",
+		ui.theme.text_dim);
+	if (ngui_button(&ui, ID_CONFIRM_CANCEL,
 			(struct ngui_rect){ mx + mw - 188, my + mh - 44,
 					    84, 28 }, "Cancel"))
 		close_modal();
-	if (ngui_button(&ui, ID_DLG_OK,
+	if (ngui_button(&ui, ID_CONFIRM_DISCARD,
 			(struct ngui_rect){ mx + mw - 96, my + mh - 44,
-					    78, 28 },
-			modal == MODAL_OPEN ? "Open" : "Save"))
-		modal_ok();
+					    78, 28 }, "Discard"))
+		discard_and_run();
 }
 
 static void draw(void)
@@ -593,12 +540,22 @@ static void draw(void)
 	struct ngui_rect toolbar, status, edit;
 	int res;
 
+	if (file_dlg.active) {
+		handle_file_dialog_result(ngui_file_dialog(&ui, &file_dlg));
+		return;
+	}
+
 	ngui_fill_rect(&ui, all, ui.theme.bg);
 	toolbar = ngui_cut_top(&all, TE_TOOLBAR_H);
 	status = ngui_cut_bottom(&all, TE_STATUS_H);
 	ngui_inset(&all, TE_MARGIN);
 	edit = all;
 	draw_toolbar(toolbar);
+	/* A toolbar action may have opened the file dialog. */
+	if (file_dlg.active) {
+		handle_file_dialog_result(ngui_file_dialog(&ui, &file_dlg));
+		return;
+	}
 	if (modal == MODAL_NONE) {
 		if (edit.w < 1)
 			edit.w = 1;
@@ -615,13 +572,20 @@ static void draw(void)
 	if (res & NGUI_TEXTAREA_CANCEL)
 		request_action(ACT_QUIT);
 	if (modal != MODAL_NONE)
-		draw_modal();
+		draw_confirm_modal();
 }
 
 static void handle_keys(void)
 {
 	int k;
 
+	if (file_dlg.active) {
+		/* The dialog has already handled its keys; discard any app
+		 * shortcut it deliberately left alone. */
+		while (ngui_key(&ui) != 0)
+			;
+		return;
+	}
 	while ((k = ngui_key(&ui)) != 0) {
 		if (modal == MODAL_CONFIRM) {
 			if (k == NGUI_KEY_ESC)
@@ -630,15 +594,6 @@ static void handle_keys(void)
 				discard_and_run();
 			continue;
 		}
-		if (modal == MODAL_OPEN || modal == MODAL_SAVEAS) {
-			if (k == NGUI_KEY_ESC &&
-			    ngui_focus(&ui) != ID_DLG_PATH)
-				close_modal();
-			else if ((k == '\r' || k == '\n') &&
-				 ngui_focus(&ui) != ID_DLG_PATH)
-				modal_ok();
-			continue;
-		}
 		switch (k) {
 		case NGUI_KEY_ESC:
 			request_action(ACT_QUIT);
@@ -687,7 +642,7 @@ void _start(const char *arg)
 	dirty = 0;
 	modal = MODAL_NONE;
 	pending_action = ACT_NONE;
-	path_input.placeholder = "/share/FILE.TXT";
+	file_dlg.active = 0;
 
 	if (arg && arg[0]) {
 		const char *err = load_file(arg, 1);

+ 56 - 0
user/lib/ngui/ngui.h

@@ -140,6 +140,54 @@ struct ngui_text_area {
 #define NGUI_TEXTAREA_CHANGED 1
 #define NGUI_TEXTAREA_CANCEL  2
 
+/* A modal file Open/Save dialog.  The caller owns the state; open it with a
+ * directory or file path (and optionally a suggested file name), then call
+ * ngui_file_dialog() every frame.  It fills the canvas with a dark modal
+ * backdrop and lists the current directory (the VFS root shows the mount
+ * table), with Up/Home/Refresh, a scrollable list, a file-name field and
+ * Cancel/Open|Save buttons.  Click a folder to enter it, click a file to
+ * select it, double-click a file (or press Enter) to accept, Esc to cancel.
+ *
+ * The returned result path is absolute and shorter than NGUI_FILE_PATH_MAX.
+ * NGUI_FILE_ACCEPTED leaves the dialog active so the app can perform the I/O
+ * and then either ngui_file_dialog_close() it or ngui_file_dialog_error() it
+ * (which keeps it open for another try).  NGUI_FILE_CANCELLED closes it. */
+#define NGUI_FILE_OPEN       0
+#define NGUI_FILE_SAVE       1
+
+#define NGUI_FILE_NONE       0
+#define NGUI_FILE_ACCEPTED   1
+#define NGUI_FILE_CANCELLED  2
+
+#define NGUI_FILE_PATH_MAX   64
+#define NGUI_FILE_NAME_MAX   64
+#define NGUI_FILE_MAX_ENTRIES 128
+
+struct ngui_file_entry {
+	char name[NGUI_FILE_NAME_MAX];
+	unsigned int size;
+	unsigned char is_dir;
+	unsigned char is_mount;
+};
+
+struct ngui_file_dialog {
+	int active;
+	int mode;
+	unsigned int id_base;
+	char path[NGUI_FILE_PATH_MAX];
+	struct ngui_file_entry entries[NGUI_FILE_MAX_ENTRIES];
+	unsigned int count;
+	int selected;
+	int truncated;
+	struct ngui_scroll scroll;
+	struct ngui_input name;
+	char error[96];
+	char result[NGUI_FILE_PATH_MAX];
+	int last_click;
+	unsigned int last_click_ms;
+	int need_focus;
+};
+
 struct ngui_slider {
 	int dragging;
 };
@@ -349,6 +397,14 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		    struct ngui_input *in);
 int ngui_text_area(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		   struct ngui_text_area *ta);
+void ngui_file_dialog_open(struct ngui_file_dialog *fd, int mode,
+			   const char *start_path,
+			   const char *suggested_name,
+			   unsigned int id_base);
+int  ngui_file_dialog(struct ngui *ui, struct ngui_file_dialog *fd);
+void ngui_file_dialog_close(struct ngui_file_dialog *fd);
+void ngui_file_dialog_error(struct ngui_file_dialog *fd, const char *msg);
+const char *ngui_file_dialog_result(const struct ngui_file_dialog *fd);
 /* Ask for `shape` (enum cursor_shape) while the pointer is in `r` (and in
  * the current clip); returns 1 when it is.  ngui_set_cursor() sets it
  * unconditionally for the current frame. */

+ 851 - 0
user/lib/ngui/ngui_file.c

@@ -0,0 +1,851 @@
+/* ngui_file.c: modal file Open/Save dialog for ngui canvas windows.
+ *
+ * The dialog owns a directory listing (the VFS root shows the mount table),
+ * Up/Home/Refresh controls, a scrollable row list, a file-name field and
+ * Cancel/Open|Save.  It is not a separate window: the app draws it on top of
+ * its own canvas and calls ngui_file_dialog() until it returns ACCEPTED or
+ * CANCELLED.  See ngui.h for the caller contract. */
+
+#include "ngui.h"
+#include "ucmd_lib.h"
+
+#define FD_ROW_H 22
+#define FD_PAD   16
+
+#define FD_ID_NAME     1
+#define FD_ID_UP       2
+#define FD_ID_HOME     3
+#define FD_ID_REFRESH  4
+#define FD_ID_CANCEL   5
+#define FD_ID_ACCEPT   6
+#define FD_ID_ROW      0x100
+
+static unsigned int fl_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+/* Copy s into d (always NUL terminated).  Returns 0 when it had to truncate. */
+static int fl_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return 0;
+	while (s && s[i]) {
+		if (i + 1 >= cap) {
+			d[i] = '\0';
+			return 0;
+		}
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+	return 1;
+}
+
+/* Join dir and name into an absolute path.  Returns 0 if it does not fit. */
+static int fl_join(const char *dir, const char *name, char *out,
+		   unsigned int cap)
+{
+	unsigned int i = 0, j;
+
+	if (!dir || !dir[0])
+		dir = "/";
+	if (name && name[0] == '/')
+		return fl_copy(out, name, cap);
+	while (dir[i]) {
+		if (i + 1 >= cap) {
+			out[0] = '\0';
+			return 0;
+		}
+		out[i] = dir[i];
+		i++;
+	}
+	if (i && out[i - 1] != '/') {
+		if (i + 1 >= cap) {
+			out[0] = '\0';
+			return 0;
+		}
+		out[i++] = '/';
+	}
+	for (j = 0; name && name[j]; j++) {
+		if (i + 1 >= cap) {
+			out[0] = '\0';
+			return 0;
+		}
+		out[i++] = name[j];
+	}
+	out[i] = '\0';
+	return 1;
+}
+
+static void fl_parent(const char *in, char *out, unsigned int cap)
+{
+	unsigned int n, i, last = 0;
+
+	fl_copy(out, in && in[0] ? in : "/", cap);
+	n = fl_len(out);
+	if (n > 1 && out[n - 1] == '/')
+		out[--n] = '\0';
+	for (i = 0; i < n; i++)
+		if (out[i] == '/')
+			last = i;
+	if (last == 0) {
+		out[0] = '/';
+		out[1] = '\0';
+	} else {
+		out[last] = '\0';
+	}
+	if (!out[0])
+		fl_copy(out, "/", cap);
+}
+
+static const char *fl_base(const char *path)
+{
+	const char *b = path;
+
+	while (path && *path) {
+		if (*path == '/')
+			b = path + 1;
+		path++;
+	}
+	return b;
+}
+
+static void fl_abs(const char *p, char *out, unsigned int cap)
+{
+	char cwd[NGUI_FILE_PATH_MAX];
+
+	if (!p || !p[0]) {
+		fl_copy(out, "/", cap);
+		return;
+	}
+	if (p[0] == '/') {
+		fl_copy(out, p, cap);
+		return;
+	}
+	if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
+		fl_copy(cwd, "/", sizeof(cwd));
+	if (!fl_join(cwd, p, out, cap))
+		fl_copy(out, "/", cap);
+}
+
+static int fl_ci_cmp(const char *a, const char *b)
+{
+	for (;;) {
+		unsigned char ca = (unsigned char)*a++;
+		unsigned char cb = (unsigned char)*b++;
+
+		if (ca >= 'a' && ca <= 'z')
+			ca = (unsigned char)(ca - 32);
+		if (cb >= 'a' && cb <= 'z')
+			cb = (unsigned char)(cb - 32);
+		if (ca != cb)
+			return (int)ca - (int)cb;
+		if (!ca)
+			return 0;
+	}
+}
+
+static void fl_size_text(unsigned int bytes, char *out, unsigned int cap)
+{
+	char tmp[12];
+	unsigned int n = 0, i = 0, j;
+
+	if (bytes < 1024) {
+		do {
+			tmp[i++] = (char)('0' + bytes % 10);
+			bytes /= 10;
+		} while (bytes && i < sizeof(tmp));
+		for (j = 0; j < i && n + 1 < cap; j++)
+			out[n++] = tmp[i - 1 - j];
+		if (n + 1 < cap)
+			out[n++] = ' ';
+		if (n + 1 < cap)
+			out[n++] = 'B';
+		out[n] = '\0';
+		return;
+	}
+	if (bytes < 1024u * 1024u) {
+		unsigned int kb = bytes / 1024;
+
+		i = 0;
+		do {
+			tmp[i++] = (char)('0' + kb % 10);
+			kb /= 10;
+		} while (kb && i < sizeof(tmp));
+		for (j = 0; j < i && n + 1 < cap; j++)
+			out[n++] = tmp[i - 1 - j];
+		if (n + 1 < cap)
+			out[n++] = ' ';
+		if (n + 1 < cap)
+			out[n++] = 'K';
+		if (n + 1 < cap)
+			out[n++] = 'B';
+	} else {
+		unsigned int mb = bytes / (1024u * 1024u);
+
+		i = 0;
+		do {
+			tmp[i++] = (char)('0' + mb % 10);
+			mb /= 10;
+		} while (mb && i < sizeof(tmp));
+		for (j = 0; j < i && n + 1 < cap; j++)
+			out[n++] = tmp[i - 1 - j];
+		if (n + 1 < cap)
+			out[n++] = ' ';
+		if (n + 1 < cap)
+			out[n++] = 'M';
+		if (n + 1 < cap)
+			out[n++] = 'B';
+	}
+	out[n] = '\0';
+}
+
+static const char *fd_error_text(int r)
+{
+	switch (r) {
+	case SYS_ENODEV:
+		return "No such device";
+	case SYS_ENOFS:
+		return "No filesystem on the device";
+	case SYS_ENOENT:
+		return "Folder not found";
+	case SYS_EINVAL:
+		return "Not a folder";
+	case SYS_EIO:
+		return "Disk read error";
+	default:
+		return "Cannot open the folder";
+	}
+}
+
+static int fd_entry_before(const struct ngui_file_entry *a,
+			   const struct ngui_file_entry *b)
+{
+	if (a->is_dir != b->is_dir)
+		return a->is_dir > b->is_dir;
+	return fl_ci_cmp(a->name, b->name) < 0;
+}
+
+static void fd_sort_entries(struct ngui_file_entry *list, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 1; i < n; i++) {
+		struct ngui_file_entry key = list[i];
+		unsigned int j = i;
+
+		while (j > 0 && fd_entry_before(&key, &list[j - 1])) {
+			list[j] = list[j - 1];
+			j--;
+		}
+		list[j] = key;
+	}
+}
+
+/* Load a directory into the dialog.  The previous path and listing are kept
+ * when listing fails, so the error can be shown without leaving the user in
+ * a dead folder. */
+static int fd_load_dir(struct ngui_file_dialog *fd, const char *path)
+{
+	struct ngui_file_entry tmp[NGUI_FILE_MAX_ENTRIES];
+	char dir[NGUI_FILE_PATH_MAX];
+	unsigned int n = 0, i, dl;
+	int truncated = 0;
+
+	if (!fd)
+		return -1;
+	if (!path || !path[0])
+		path = "/";
+	if (!fl_copy(dir, path, sizeof(dir))) {
+		fl_copy(fd->error, "Path is too long", sizeof(fd->error));
+		return -1;
+	}
+	dl = fl_len(dir);
+	if (dl > 1 && dir[dl - 1] == '/')
+		dir[--dl] = '\0';
+
+	if (dir[0] == '/' && dir[1] == '\0') {
+		struct sys_mount m;
+
+		for (i = 0; ; i++) {
+			if (u_syscall2(SYS_LIST_MOUNTS, (int)i,
+				       (int)&m) != 1)
+				break;
+			if (!m.name[0])
+				continue;
+			if (n >= NGUI_FILE_MAX_ENTRIES) {
+				truncated = 1;
+				break;
+			}
+			fl_copy(tmp[n].name, m.name, sizeof(tmp[n].name));
+			tmp[n].size = 0;
+			tmp[n].is_dir = 1;
+			tmp[n].is_mount = 1;
+			n++;
+		}
+	} else {
+		struct sys_dirent d;
+
+		for (i = 0; ; i++) {
+			int r = u_syscall3(SYS_LIST_DIR, (int)dir, (int)i,
+					   (int)&d);
+
+			if (r != 1) {
+				if (r < 0) {
+					fl_copy(fd->error, fd_error_text(r),
+						sizeof(fd->error));
+					return -1;
+				}
+				break;
+			}
+			if (n >= NGUI_FILE_MAX_ENTRIES) {
+				truncated = 1;
+				break;
+			}
+			{
+				char disp[NGUI_FILE_NAME_MAX];
+
+				if (d.raw_83)
+					u_fat_name(d.name, disp, sizeof(disp));
+				else
+					fl_copy(disp, d.name, sizeof(disp));
+				if (!disp[0] || disp[0] == '.')
+					continue;
+				fl_copy(tmp[n].name, disp, sizeof(tmp[n].name));
+				tmp[n].size = d.size;
+				tmp[n].is_dir = d.is_dir ? 1 : 0;
+				tmp[n].is_mount = 0;
+				n++;
+			}
+		}
+	}
+
+	fd_sort_entries(tmp, n);
+	for (i = 0; i < n; i++)
+		fd->entries[i] = tmp[i];
+	fd->count = n;
+	fd->truncated = truncated;
+	fd->selected = -1;
+	fd->last_click = -1;
+	fd->last_click_ms = 0;
+	fl_copy(fd->path, dir, sizeof(fd->path));
+	fd->scroll.offset = 0;
+	fd->scroll.dragging = 0;
+	fd->scroll.bar_vis = 0;
+	fd->scroll.bar_target = 0;
+	fd->scroll.bar_hot = 0;
+	fd->error[0] = '\0';
+	return 0;
+}
+
+static void fd_set_name(struct ngui_file_dialog *fd, const char *name)
+{
+	ngui_input_set(&fd->name, name ? name : "");
+	if (fd->name.len) {
+		fd->name.anchor = 0;
+		fd->name.cursor = fd->name.len;
+	}
+}
+
+static void fd_default_dir(int mode, char *out, unsigned int cap)
+{
+	struct sys_stat st;
+
+	if (mode == NGUI_FILE_SAVE &&
+	    u_stat("/share", &st) == 0 && st.is_dir) {
+		fl_copy(out, "/share", cap);
+		return;
+	}
+	if (mode == NGUI_FILE_OPEN &&
+	    u_getcwd(out, cap) == 0 && out[0] &&
+	    u_stat(out, &st) == 0 && st.is_dir)
+		return;
+	fl_copy(out, "/", cap);
+}
+
+static void fd_focus_name(struct ngui *ui, struct ngui_file_dialog *fd)
+{
+	unsigned int id = fd->id_base + FD_ID_NAME;
+
+	ngui_set_focus(ui, id);
+	ui->focus_claimed = 1;
+	ui->last_blink = u_ticks_ms();
+	ui->caret_on = 1;
+}
+
+/* Resolve the name field (or the highlighted entry) to an absolute path and
+ * either navigate to a directory or accept it.  Returns 1 on accept. */
+static int fd_accept(struct ngui_file_dialog *fd)
+{
+	char path[NGUI_FILE_PATH_MAX];
+	const char *name = fd->name.text;
+	struct sys_stat st;
+	int r;
+
+	if (!name[0]) {
+		const struct ngui_file_entry *e;
+
+		if (fd->selected < 0 ||
+		    fd->selected >= (int)fd->count) {
+			fl_copy(fd->error, "Enter a file name",
+				sizeof(fd->error));
+			return 0;
+		}
+		e = &fd->entries[fd->selected];
+		if (!fl_join(fd->path, e->name, path, sizeof(path))) {
+			fl_copy(fd->error, "Path is too long",
+				sizeof(fd->error));
+			return 0;
+		}
+		if (e->is_dir) {
+			if (fd_load_dir(fd, path) == 0)
+				fd_set_name(fd, "");
+			return 0;
+		}
+		name = e->name;
+	}
+	if (!fl_join(fd->path, name, path, sizeof(path))) {
+		fl_copy(fd->error, "Path is too long", sizeof(fd->error));
+		return 0;
+	}
+	r = u_stat(path, &st);
+	if (r == 0 && st.is_dir) {
+		if (fd_load_dir(fd, path) == 0)
+			fd_set_name(fd, "");
+		return 0;
+	}
+	if (fd->mode == NGUI_FILE_OPEN) {
+		if (r != 0) {
+			fl_copy(fd->error, "File not found",
+				sizeof(fd->error));
+			return 0;
+		}
+	} else if (r != 0 && r != SYS_ENOENT) {
+		fl_copy(fd->error, fd_error_text(r), sizeof(fd->error));
+		return 0;
+	} else if (r != 0) {
+		/* Saving a new file: make sure the parent exists. */
+		char parent[NGUI_FILE_PATH_MAX];
+
+		fl_parent(path, parent, sizeof(parent));
+		if (u_stat(parent, &st) != 0 || !st.is_dir) {
+			fl_copy(fd->error, "Folder not found",
+				sizeof(fd->error));
+			return 0;
+		}
+	}
+	if (fl_len(path) >= sizeof(fd->result)) {
+		fl_copy(fd->error, "Path is too long", sizeof(fd->error));
+		return 0;
+	}
+	fl_copy(fd->result, path, sizeof(fd->result));
+	return 1;
+}
+
+static void fd_move_selection(struct ngui *ui, struct ngui_file_dialog *fd,
+			      int delta)
+{
+	int i;
+
+	if (!fd->count)
+		return;
+	if (fd->selected < 0)
+		fd->selected = delta > 0 ? 0 : (int)fd->count - 1;
+	else {
+		fd->selected += delta;
+		if (fd->selected < 0)
+			fd->selected = 0;
+		if (fd->selected >= (int)fd->count)
+			fd->selected = (int)fd->count - 1;
+	}
+	i = fd->selected;
+	if (fd->entries[i].is_dir)
+		fd_set_name(fd, "");
+	else
+		fd_set_name(fd, fd->entries[i].name);
+	fd->error[0] = '\0';
+	fd_focus_name(ui, fd);
+	ngui_scroll_ensure_visible(&fd->scroll,
+				   2 + i * FD_ROW_H, FD_ROW_H);
+	ngui_invalidate(ui);
+}
+
+void ngui_file_dialog_open(struct ngui_file_dialog *fd, int mode,
+			   const char *start_path, const char *suggested_name,
+			   unsigned int id_base)
+{
+	char abs[NGUI_FILE_PATH_MAX], dir[NGUI_FILE_PATH_MAX];
+	char nm[NGUI_FILE_NAME_MAX];
+	struct sys_stat st;
+	unsigned int i;
+
+	if (!fd)
+		return;
+	for (i = 0; i < sizeof(*fd); i++)
+		((unsigned char *)fd)[i] = 0;
+	fd->active = 1;
+	fd->mode = mode == NGUI_FILE_SAVE ? NGUI_FILE_SAVE : NGUI_FILE_OPEN;
+	fd->id_base = id_base ? id_base : 0x1000u;
+	fd->last_click = -1;
+	fd->need_focus = 1;
+	fd->name.placeholder = mode == NGUI_FILE_OPEN ?
+		"File name or path" : "File name";
+
+	if (start_path && start_path[0])
+		fl_abs(start_path, abs, sizeof(abs));
+	else
+		abs[0] = '\0';
+	if (!abs[0]) {
+		fd_default_dir(fd->mode, dir, sizeof(dir));
+		fl_copy(nm, suggested_name ? suggested_name : "", sizeof(nm));
+	} else if (u_stat(abs, &st) == 0 && st.is_dir) {
+		fl_copy(dir, abs, sizeof(dir));
+		fl_copy(nm, suggested_name ? suggested_name : "", sizeof(nm));
+	} else {
+		fl_parent(abs, dir, sizeof(dir));
+		fl_copy(nm, suggested_name && suggested_name[0] ?
+			suggested_name : fl_base(abs), sizeof(nm));
+	}
+
+	if (!dir[0] || fd_load_dir(fd, dir) != 0) {
+		if (!dir[0] || fl_ci_cmp(dir, "/") != 0)
+			fd_load_dir(fd, "/");
+	}
+	fd_set_name(fd, nm);
+	for (i = 0; i < fd->count; i++) {
+		if (fl_ci_cmp(fd->entries[i].name, fd->name.text) == 0) {
+			fd->selected = (int)i;
+			break;
+		}
+	}
+}
+
+int ngui_file_dialog(struct ngui *ui, struct ngui_file_dialog *fd)
+{
+	struct ngui_rect panel, list, r, name_r;
+	char size_text[24];
+	int pw, ph, px, py, x, y, w, list_y, list_h, name_y, err_y, btn_y;
+	int event = NGUI_FILE_NONE;
+	int clicked_dir = -1, accept_after = 0;
+	unsigned int id_name, i;
+	int k;
+
+	if (!ui || !fd || !fd->active)
+		return NGUI_FILE_NONE;
+	if (ui->focus == 0)
+		fd_focus_name(ui, fd);
+
+	id_name = fd->id_base + FD_ID_NAME;
+	/* The name field must keep the focus for typing, but ngui_text_input
+	 * consumes every key it sees.  Take the list-navigation keys first so
+	 * they still move the highlight. */
+	for (;;) {
+		int page = fd->scroll.view_h / FD_ROW_H - 1;
+
+		if (page < 1)
+			page = 1;
+		k = ngui_key_peek(ui);
+		if (k == NGUI_KEY_UP) {
+			ngui_key(ui);
+			fd_move_selection(ui, fd, -1);
+		} else if (k == NGUI_KEY_DOWN) {
+			ngui_key(ui);
+			fd_move_selection(ui, fd, 1);
+		} else if (k == NGUI_KEY_PAGE_UP) {
+			ngui_key(ui);
+			fd_move_selection(ui, fd, -page);
+		} else if (k == NGUI_KEY_PAGE_DOWN) {
+			ngui_key(ui);
+			fd_move_selection(ui, fd, page);
+		} else {
+			break;
+		}
+	}
+	pw = ui->w - 40;
+	if (pw > 720)
+		pw = 720;
+	if (pw < 320)
+		pw = ui->w - 20;
+	if (pw < 160)
+		pw = 160;
+	ph = ui->h - 40;
+	if (ph > 480)
+		ph = 480;
+	if (ph < 260)
+		ph = ui->h - 20;
+	if (ph < 160)
+		ph = 160;
+	px = (ui->w - pw) / 2;
+	py = (ui->h - ph) / 2;
+	if (px < 0)
+		px = 0;
+	if (py < 0)
+		py = 0;
+	panel = (struct ngui_rect){ px, py, pw, ph };
+
+	ngui_set_cursor(ui, CURSOR_DEFAULT);
+	ngui_fill_rect(ui, (struct ngui_rect){ 0, 0, ui->w, ui->h },
+		       NGUI_RGB(8, 10, 16));
+	ngui_fill_round_rect(ui, panel, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui->theme.panel);
+	ngui_frame_round(ui, panel, NGUI_RADIUS, NGUI_RADIUS,
+			 NGUI_RADIUS, NGUI_RADIUS, 1, ui->theme.border);
+	ngui_text(ui, px + FD_PAD, py + 14,
+		  fd->mode == NGUI_FILE_OPEN ? "Open file" : "Save as",
+		  ui->theme.text);
+
+	x = px + FD_PAD;
+	y = py + 40;
+	r = (struct ngui_rect){ x, y, 28, 26 };
+	if (ngui_icon_button(ui, fd->id_base + FD_ID_UP, r, NGUI_ICON_UP)) {
+		char parent[NGUI_FILE_PATH_MAX];
+
+		fl_parent(fd->path, parent, sizeof(parent));
+		if (fd_load_dir(fd, parent) == 0)
+			fd_set_name(fd, "");
+		fd_focus_name(ui, fd);
+	}
+	x += 32;
+	r.x = x;
+	if (ngui_icon_button(ui, fd->id_base + FD_ID_HOME, r,
+			     NGUI_ICON_HOME)) {
+		if (fd_load_dir(fd, "/") == 0)
+			fd_set_name(fd, "");
+		fd_focus_name(ui, fd);
+	}
+	x += 32;
+	r.x = x;
+	if (ngui_icon_button(ui, fd->id_base + FD_ID_REFRESH, r,
+			     NGUI_ICON_REFRESH)) {
+		fd_load_dir(fd, fd->path);
+		fd_focus_name(ui, fd);
+	}
+	x += 38;
+	w = px + pw - FD_PAD - x;
+	if (w < 10)
+		w = 10;
+	ngui_text_ellipsis(ui, (struct ngui_rect){ x, y, w, 26 },
+			   x, y + 5, fd->path, ui->theme.text_dim);
+
+	list_y = py + 96;
+	btn_y = py + ph - 44;
+	err_y = btn_y - 22;
+	name_y = err_y - 36;
+	list_h = name_y - 10 - list_y;
+	if (list_h < 40)
+		list_h = 40;
+	list = (struct ngui_rect){ px + FD_PAD, list_y, pw - 2 * FD_PAD,
+				  list_h };
+	ngui_text(ui, list.x + 6, list_y - 18, "Name", ui->theme.text_dim);
+	{
+		int sw = (int)ngui_text_width_ui(ui, "Size");
+
+		ngui_text(ui, list.x + list.w - sw - 10, list_y - 18,
+			  "Size", ui->theme.text_dim);
+	}
+	ngui_fill_rect(ui, list, ui->theme.bg);
+	ngui_frame(ui, list, ui->theme.border);
+	fd->scroll.view_h = list.h;
+	fd->scroll.content_h = (int)fd->count * FD_ROW_H + 4;
+	ngui_scroll_begin(ui, list, &fd->scroll);
+	if (ngui_scroll_wheel(ui, list, &fd->scroll))
+		ui->dirty = 1;
+	if (!fd->count) {
+		ngui_text(ui, list.x + 10, list.y + 8,
+			  fd->truncated ? "No entries" :
+			  "This folder is empty", ui->theme.text_dim);
+	}
+	for (i = 0; i < fd->count; i++) {
+		struct ngui_rect rr = { list.x + 2,
+			list.y + 2 + (int)i * FD_ROW_H - fd->scroll.offset,
+			list.w - 4, FD_ROW_H };
+		const struct ngui_file_entry *e = &fd->entries[i];
+		int hot, selected;
+		int name_w;
+
+		if (rr.y + rr.h <= list.y || rr.y >= list.y + list.h)
+			continue;
+		hot = ui->inside &&
+		      ngui_rect_contains(&rr, ui->mouse_x, ui->mouse_y);
+		selected = (int)i == fd->selected;
+		if (selected)
+			ngui_fill_rect(ui, rr, ui->theme.selection);
+		else if (hot)
+			ngui_fill_rect(ui, rr, ui->theme.panel_alt);
+
+		ngui_icon(ui, (struct ngui_rect){ rr.x + 5, rr.y + 3, 16, 16 },
+			  e->is_dir ? NGUI_ICON_FOLDER : NGUI_ICON_FILE,
+			  e->is_dir ? ui->theme.icon_folder :
+				      ui->theme.icon_file);
+		if (e->is_dir)
+			fl_copy(size_text, e->is_mount ? "Mount" : "Folder",
+				sizeof(size_text));
+		else
+			fl_size_text(e->size, size_text, sizeof(size_text));
+		{
+			int sw = (int)ngui_text_width_ui(ui, size_text);
+			int tx = rr.x + rr.w - sw - 10;
+
+			if (tx < rr.x + 28)
+				tx = rr.x + 28;
+			ngui_text(ui, tx, rr.y + 3, size_text,
+				  selected ? ui->theme.text :
+					     ui->theme.text_dim);
+
+			name_w = tx - (rr.x + 28) - 6;
+		}
+		if (name_w < 10)
+			name_w = 10;
+		ngui_text_ellipsis(ui,
+			(struct ngui_rect){ rr.x + 28, rr.y, name_w, rr.h },
+			rr.x + 28, rr.y + 3, e->name, ui->theme.text);
+		if (hot)
+			ui->hot = fd->id_base + FD_ID_ROW + i;
+
+		if (ui->pressed && ngui_rect_contains(&rr, ui->press_x,
+						      ui->press_y)) {
+			unsigned int now = u_ticks_ms();
+			int dbl = fd->last_click == (int)i &&
+				  fd->last_click_ms &&
+				  (unsigned int)(now - fd->last_click_ms) <= 500;
+
+			fd->selected = (int)i;
+			fd->last_click = (int)i;
+			fd->last_click_ms = now;
+			fd->error[0] = '\0';
+			fd_focus_name(ui, fd);
+			if (e->is_dir) {
+				clicked_dir = (int)i;
+			} else {
+				fd_set_name(fd, e->name);
+				if (dbl)
+					accept_after = 1;
+			}
+			ngui_invalidate(ui);
+		}
+	}
+	ngui_scroll_end(ui, list, &fd->scroll);
+
+	name_r = (struct ngui_rect){ px + FD_PAD + 86, name_y,
+				     pw - 2 * FD_PAD - 86, 28 };
+	if (name_r.w < 80)
+		name_r.w = 80;
+	ngui_text(ui, px + FD_PAD, name_y + 6, "File name",
+		  ui->theme.text_dim);
+	{
+		int input_result = ngui_text_input(ui, id_name, name_r,
+						   &fd->name);
+
+		if (input_result & NGUI_INPUT_CHANGED)
+			fd->error[0] = '\0';
+		if (input_result & NGUI_INPUT_SUBMIT) {
+			if (fd_accept(fd))
+				event = NGUI_FILE_ACCEPTED;
+			else
+				ngui_invalidate(ui);
+		}
+		if ((input_result & NGUI_INPUT_CANCEL) &&
+		    !(input_result & NGUI_INPUT_NEXT)) {
+			event = NGUI_FILE_CANCELLED;
+			fd->active = 0;
+		}
+		if (input_result & NGUI_INPUT_NEXT)
+			fd_focus_name(ui, fd);
+	}
+
+	if (clicked_dir >= 0) {
+		char path[NGUI_FILE_PATH_MAX];
+
+		if (fl_join(fd->path, fd->entries[clicked_dir].name,
+			    path, sizeof(path)) &&
+		    fd_load_dir(fd, path) == 0)
+			fd_set_name(fd, "");
+		clicked_dir = -1;
+	}
+	if (accept_after && event == NGUI_FILE_NONE) {
+		if (fd_accept(fd))
+			event = NGUI_FILE_ACCEPTED;
+		else
+			ngui_invalidate(ui);
+	}
+
+	if (event == NGUI_FILE_NONE && ui->focus != id_name) {
+		k = ngui_key_peek(ui);
+		if (k == '\r' || k == '\n') {
+			ngui_key(ui);
+			if (fd_accept(fd))
+				event = NGUI_FILE_ACCEPTED;
+			else
+				ngui_invalidate(ui);
+		} else if (k == NGUI_KEY_ESC) {
+			ngui_key(ui);
+			event = NGUI_FILE_CANCELLED;
+			fd->active = 0;
+		}
+	}
+
+	if (fd->error[0])
+		ngui_text_ellipsis(ui,
+			(struct ngui_rect){ px + FD_PAD, err_y,
+					    pw - 2 * FD_PAD, 18 },
+			px + FD_PAD, err_y, fd->error, ui->theme.error);
+	else if (fd->truncated)
+		ngui_text(ui, px + FD_PAD, err_y,
+			  "Showing the first 128 entries", ui->theme.text_dim);
+
+	if (ngui_button(ui, fd->id_base + FD_ID_CANCEL,
+			(struct ngui_rect){ px + pw - 16 - 84 - 8 - 84,
+					    btn_y, 84, 28 }, "Cancel")) {
+		event = NGUI_FILE_CANCELLED;
+		fd->active = 0;
+	}
+	if (ngui_button(ui, fd->id_base + FD_ID_ACCEPT,
+			(struct ngui_rect){ px + pw - 16 - 84, btn_y,
+					    84, 28 },
+			fd->mode == NGUI_FILE_OPEN ? "Open" : "Save")) {
+		if (fd_accept(fd))
+			event = NGUI_FILE_ACCEPTED;
+		else
+			ngui_invalidate(ui);
+		fd_focus_name(ui, fd);
+	}
+
+	if (fd->need_focus) {
+		fd->need_focus = 0;
+		fd_focus_name(ui, fd);
+		if (fd->selected >= 0)
+			ngui_scroll_ensure_visible(&fd->scroll,
+				2 + fd->selected * FD_ROW_H, FD_ROW_H);
+	}
+	return event;
+}
+
+void ngui_file_dialog_close(struct ngui_file_dialog *fd)
+{
+	if (!fd)
+		return;
+	fd->active = 0;
+	fd->error[0] = '\0';
+}
+
+void ngui_file_dialog_error(struct ngui_file_dialog *fd, const char *msg)
+{
+	if (!fd)
+		return;
+	fl_copy(fd->error, msg ? msg : "Cannot use that path",
+		sizeof(fd->error));
+	fd->active = 1;
+	fd->need_focus = 1;
+}
+
+const char *ngui_file_dialog_result(const struct ngui_file_dialog *fd)
+{
+	return fd ? fd->result : "";
+}