Browse Source

textedit: add Notepad-like editor and ngui text area

Add the Textedit canvas app on a new ngui_text_area widget: a soft-wrapping multi-line buffer with a caret, mouse/double-click selection, word/page keys, Tab insertion, an overlay scrollbar and 1-based line/column tracking. The toolbar has New/Open/Save/Save As with an in-window path dialog, CRLF normalisation, a 256 KB cap and a discard confirmation for New/Open/quit; Ctrl+N/O/S work anywhere and Ctrl+Q/W or Esc quit.

Replace the start menu/dock "Text editor" entry with Textedit (GNOME Text Editor icon) and make files open text files in it. Show the widget in the gallery Inputs section and update AGENTS.md and the architecture pages.
Johannes Zellner 1 hour ago
parent
commit
9784550190

+ 53 - 19
AGENTS.md

@@ -643,7 +643,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   styled like the netmenu popover: a borderless `theme.bg` surface whose
   styled like the netmenu popover: a borderless `theme.bg` surface whose
   first row is the dim `Applications` caption, `theme.panel_alt` hover rows
   first row is the dim `Applications` caption, `theme.panel_alt` hover rows
   and a rounded Power tile.  It lists every self-contained GUI app in the
   and a rounded Power tile.  It lists every self-contained GUI app in the
-  pack -- Terminal, Files, Web, Gallery, Chat, Clock, Text editor, Colors,
+  pack -- Terminal, Files, Web, Gallery, Chat, Clock, Textedit, Colors,
   Mines, Cards, Disks, Tasks, Services, Settings and Date & Time -- with its
   Mines, Cards, Disks, Tasks, Services, Settings and Date & Time -- with its
   full-colour GNOME app icon and a hover highlight (the coloured letter tile
   full-colour GNOME app icon and a hover highlight (the coloured letter tile
   is only the fallback when the icon bundle is absent), shrinks its row
   is only the fallback when the icon bundle is absent), shrinks its row
@@ -655,7 +655,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (`wm_abi.h`).
   (`wm_abi.h`).
   A macOS-like dock is always visible at the bottom centre, drawn by the WM
   A macOS-like dock is always visible at the bottom centre, drawn by the WM
   as an overlay (not a work-area reservation).  Its 13 pinned slots are
   as an overlay (not a work-area reservation).  Its 13 pinned slots are
-  Terminal, Files, Web, Chat, Text editor, Gallery, Clock, Colors, Mines,
+  Terminal, Files, Web, Chat, Textedit, Gallery, Clock, Colors, Mines,
   Cards, Disks, Tasks and Settings, with a thin separator before Settings;
   Cards, Disks, Tasks and Settings, with a thin separator before Settings;
   Services and Date & Time stay in the start menu.  Icons use a 48 px base
   Services and Date & Time stay in the start menu.  Icons use a 48 px base
   (24 px on very narrow screens) on a translucent rounded panel.  The
   (24 px on very narrow screens) on a translucent rounded panel.  The
@@ -786,7 +786,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   the pre-frame refresh and the frame begin used to unmap the canvas under
   the pre-frame refresh and the frame begin used to unmap the canvas under
   the draw and kill the WM with a #PF.  Closing a window kills its owner;
   the draw and kill the WM with a #PF.  Closing a window kills its owner;
   the reaper frees the canvas.  `clock`, `colors`, `settime`,
   the reaper frees the canvas.  `clock`, `colors`, `settime`,
-  `term`, `files` and the other apps are canvas clients.  The old
+  `term`, `files`, `textedit` and the other apps are canvas clients.  The old
   `SYS_GFX_BEGIN/PRESENT/END` terminal-takeover service and the kernel
   `SYS_GFX_BEGIN/PRESENT/END` terminal-takeover service and the kernel
   text-canvas renderer are removed.  Pointer input: `SYS_WIN_POINTER` reports
   text-canvas renderer are removed.  Pointer input: `SYS_WIN_POINTER` reports
   the content-relative position, buttons and focus, and `SYS_WIN_EVENT` queues
   the content-relative position, buttons and focus, and `SYS_WIN_EVENT` queues
@@ -823,7 +823,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `*` mask (the real text is swapped back only for the edit loop, so caret,
   `*` mask (the real text is swapped back only for the edit loop, so caret,
   selection and clicks follow the mask); Tab returns `NGUI_INPUT_NEXT` with
   selection and clicks follow the mask); Tab returns `NGUI_INPUT_NEXT` with
   `NGUI_INPUT_CANCEL` so forms move the focus themselves.  `NGUI_INPUT_MAX`
   `NGUI_INPUT_CANCEL` so forms move the focus themselves.  `NGUI_INPUT_MAX`
-  is 512 (511 characters).
+  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.
 - **Graphics**: `vga.c/h`, `vga_copy.S`, `blit.c/h`, `gpu.c`, `ati.c`, `nvidia.c`,
 - **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
   `nv50.c`, `pci.h` — VESA LFB + shadow buffer.  Drawing goes into a
   `struct surface` render target: `vga_target()` is the screen's shadow buffer
   `struct surface` render target: `vga_target()` is the screen's shadow buffer
@@ -944,9 +947,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (`uwm_lib`) load faces and leave the 8×16 bitmap fallback when they are
   (`uwm_lib`) load faces and leave the 8×16 bitmap fallback when they are
   absent.  The **browser calls `ngui_font_detach` before `heap_reset()` and
   absent.  The **browser calls `ngui_font_detach` before `heap_reset()` and
   reattaches after `heap_start()`**, because its page heap is reset on every
   reattaches after `heap_start()`**, because its page heap is reset on every
-  navigation.  Terminal and editor cells deliberately keep the 8×16 bitmap
-  grid; ngui text fields use the proportional face with measured caret,
-  selection and horizontal scrolling.  Host test: `make test-font`
+  navigation.  Terminal cells and the old terminal-canvas `edit` command
+  deliberately keep the 8×16 bitmap grid; ngui text fields use the
+  proportional face, and `ngui_text_area` uses the mono face with measured
+  caret, selection and soft wrap.  Host test: `make test-font`
   (`ufont_test.c`, including the WOFF round trip against
   (`ufont_test.c`, including the WOFF round trip against
   `testdata/fonts/sans.woff`, which `tools/mkwoff.py` builds from
   `testdata/fonts/sans.woff`, which `tools/mkwoff.py` builds from
   `fonts/sans.ttf` with stdlib zlib); `make fonts`
   `fonts/sans.ttf` with stdlib zlib); `make fonts`
@@ -1845,19 +1849,36 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `cd` (the shell passes arguments verbatim).  The one argument is passed as a
   `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
   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
   `_start(const char *arg)` needs no crt0.  `ngui.c/h` is the shared userland
-  GUI toolkit linked into `ucmd_files.c`, `ucmd_mines.c`, `ucmd_solitaire.c`,
-  `ucmd_process.c` and the external `gallery.elf` (buttons, menu items, text
-  fields with a disabled state, icons, layout cuts and scroll panes);
+  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);
   `files` opens the selected text file through
   `files` opens the selected text file through
-  `/ramfs/bin/edit`, image files through `/ramfs/bin/view`, and `.htm`/`.html`
+  `/ramfs/bin/textedit`, image files through `/ramfs/bin/view`, and `.htm`/`.html`
   files through `/ramfs/bin/browser`.  `ngui_end_ex()`
   files through `/ramfs/bin/browser`.  `ngui_end_ex()`
   is the variant that runs the bookkeeping without publishing the canvas, for
   is the variant that runs the bookkeeping without publishing the canvas, for
   apps that poll input without redrawing.
   apps that poll input without redrawing.
+- **Textedit**: `ucmd_textedit.c` is the Notepad-like plain-text editor (start
+  menu/dock *Textedit*, or `textedit [path]`, and the target of the `files`
+  text-file action).  The editor area is `ngui_text_area`: soft wrap at word
+  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
+  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
+  buffer asks before it is discarded by New/Open/quit.  The title-bar X still
+  closes without a prompt (the canvas ABI has no close-request event).  The
+  old `edit` command remains the 8x16 terminal-canvas editor for shell-only
+  use.
 - **Gallery**: `gallery.c` is the ngui widget gallery: typography and
 - **Gallery**: `gallery.c` is the ngui widget gallery: typography and
   truncation, the drawing primitives and clip stack, the theme palette, every
   truncation, the drawing primitives and clip stack, the theme palette, every
   icon in `ICON_LIST`, live buttons/icon buttons, text fields (including a disabled,
   icon in `ICON_LIST`, live buttons/icon buttons, text fields (including a disabled,
-  read-only field) with event feedback, 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 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
   ELF ships in the pack as `bin/gallery.app`; `ucmd_gallery.c` is the tiny
   `bin/gallery` launcher, which prefers `/share/GALLERY` (development upload
   `bin/gallery` launcher, which prefers `/share/GALLERY` (development upload
   via `make gallery-dev`), then the pack copy, then the `GALLERY` disk
   via `make gallery-dev`), then the pack copy, then the `GALLERY` disk
@@ -2669,7 +2690,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 `mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
 `mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
 DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
 DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [probe] [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional] [invert on|off]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `seriallog save <path>|show` (write the always-on COM1 capture to a file, or print the whole capture on screen), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [probe] [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional] [invert on|off]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `seriallog save <path>|show` (write the always-on COM1 capture to a file, or print the whole capture on screen), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `service [list|status <name>|start|stop|restart|kill <name>|logs <name>|logtail <name>|--gui]` (init's client; `websrv` is the first service and holds the raw NIC receiver while running), `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher; waits for the app so a terminal launch is foreground), and `chat [config-path]` (Cloudron Chat client).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `service [list|status <name>|start|stop|restart|kill <name>|logs <name>|logtail <name>|--gui]` (init's client; `websrv` is the first service and holds the raw NIC receiver while running), `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `textedit [file]` (Notepad-like plain-text editor; start menu/dock *Textedit*), `browser [url|file]` (disk app launcher; waits for the app so a terminal launch is foreground), and `chat [config-path]` (Cloudron Chat client).
 
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `netdev [name]` (kernel command: show the active NIC driver or
 DHCP client), `netdev [name]` (kernel command: show the active NIC driver or
@@ -2701,7 +2722,7 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `process`, `spin`,
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `process`, `spin`,
-`clock`, `colors`, `settime`, `date`, `files`, `disks`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `settime`, `date`, `files`, `textedit`, `disks`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `websrv`, `curl`, `wifi`, `netmenu`, `settings`, `solitaire` and `hello` are files in `/ramfs/bin`
 `netreset`, `websrv`, `curl`, `wifi`, `netmenu`, `settings`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
@@ -3348,8 +3369,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
    bytes, ~945 KiB gzip; 6000 454,608 bytes, ~204 KiB gzip), the RTL8821A
    firmware and tables (31,898 + 11,668
    firmware and tables (31,898 + 11,668
    bytes), the 15 full-colour app icons and `install/kernel.bin` is
    bytes), the 15 full-colour app icons and `install/kernel.bin` is
-   ~3.16 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 ~744 KB gzip
+   ~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
    and deliberately omits the firmware, the cursor bundle,
    and deliberately omits the firmware, the cursor bundle,
    `install/kernel.bin` and the browser (`BROWSER` on `root.img` is the
    `install/kernel.bin` and the browser (`BROWSER` on `root.img` is the
    floppy copy).  `libdeflate-gzip -12` is still preferred.  Over
    floppy copy).  `libdeflate-gzip -12` is still preferred.  Over
@@ -3671,8 +3692,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     its text uses the built-in faces, and a very text-heavy page can exhaust
     its text uses the built-in faces, and a very text-heavy page can exhaust
     it and fall back to re-rasterizing
     it and fall back to re-rasterizing
     evicted glyphs.  The browser must detach/re-attach its font arena around
     evicted glyphs.  The browser must detach/re-attach its font arena around
-    `heap_reset()`; terminal/editor cell grids stay on the 8×16 bitmap font,
-    while ngui text fields use the proportional face.
+    `heap_reset()`; terminal cells and the old `edit` command stay on the
+    8×16 bitmap font, while ngui text fields use the proportional face and
+    `ngui_text_area` uses the mono face.
 
 
 27. Ring-3 stdio/time/math limits: `FILE` is read-only and whole-file
 27. Ring-3 stdio/time/math limits: `FILE` is read-only and whole-file
     (4 MB cap); there is no `open/read/write/lseek`/fd layer yet, and
     (4 MB cap); there is no `open/read/write/lseek`/fd layer yet, and
@@ -3974,3 +3996,15 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     LPSS UART (`8086:9d27`, ACPI `UA00`) is a 16550 at its MMIO BAR (Linux
     LPSS UART (`8086:9d27`, ACPI `UA00`) is a 16550 at its MMIO BAR (Linux
     `ttyS4`), not the legacy COM1; the legacy port floats at `0xFF`, which
     `ttyS4`), not the legacy COM1; the legacy port floats at `0xFF`, which
     `serial_init()` now detects before the PIT starts polling it.
     `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.

+ 8 - 3
Makefile

@@ -397,7 +397,7 @@ $(UL)/wifi/wpa.o: XFLAGS = $(SECTION_CFLAGS)
 # explicit .elf rule below.
 # explicit .elf rule below.
 UCMDS = cpuinfo ls cat save rm mkdir rmdir \
 UCMDS = cpuinfo ls cat save rm mkdir rmdir \
         meminfo mouseinfo storage top process bootscan \
         meminfo mouseinfo storage top process bootscan \
-        clock colors edit wm term spin \
+        clock colors edit textedit wm term spin \
         netinfo netip netdns host dhcp \
         netinfo netip netdns host dhcp \
         netsend netrecv ping pong netlog \
         netsend netrecv ping pong netlog \
         netconsole netregs netloop netreset net100 netmac curl \
         netconsole netregs netloop netreset net100 netmac curl \
@@ -421,10 +421,11 @@ $(U)/apps/%.elf: $(U)/apps/%.o $(UCMD_LD)
 	$(OBJCOPY) --strip-all $@ $@
 	$(OBJCOPY) --strip-all $@ $@
 
 
 # Objects that were always compiled without the libc headers.
 # Objects that were always compiled without the libc headers.
-$(call app,edit).o $(call app,wm).o $(call app,files).o $(call app,mines).o \
+$(call app,edit).o $(call app,textedit).o $(call app,wm).o \
+$(call app,files).o $(call app,mines).o \
 $(call app,settime).o $(call app,solitaire).o $(U)/apps/gallery/gallery.o \
 $(call app,settime).o $(call app,solitaire).o $(U)/apps/gallery/gallery.o \
 $(U)/apps/hello/hello.o: XFLAGS =
 $(U)/apps/hello/hello.o: XFLAGS =
-$(call app,settime).o $(call app,solitaire).o: OPT = -Os
+$(call app,textedit).o $(call app,settime).o $(call app,solitaire).o: OPT = -Os
 # Both link with --gc-sections; the section-per-function build lets the pack
 # Both link with --gc-sections; the section-per-function build lets the pack
 # drop their unreachable helpers (the rootfs cap is tight).
 # drop their unreachable helpers (the rootfs cap is tight).
 $(call app,wm).o: XFLAGS = $(SECTION_CFLAGS)
 $(call app,wm).o: XFLAGS = $(SECTION_CFLAGS)
@@ -458,6 +459,10 @@ $(call app,term).elf: $(call app,term).o $(UWM) $(FONT16) $(UFONT_OBJS) $(UCMD_L
 $(call app,files).elf: $(call app,files).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 $(call app,files).elf: $(call app,files).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 	$(ULINK)
 
 
+# Textedit: Notepad-like plain text editor built on ngui_text_area().
+$(call app,textedit).elf: $(call app,textedit).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
+	$(ULINK)
+
 # Task manager: process table with CPU, memory and network history graphs.
 # Task manager: process table with CPU, memory and network history graphs.
 $(call app,process).elf: $(call app,process).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 $(call app,process).elf: $(call app,process).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 	$(ULINK)

+ 15 - 10
docs/graphics.html

@@ -213,7 +213,7 @@
 			rows and a rounded Power tile. Every self-contained GUI
 			rows and a rounded Power tile. Every self-contained GUI
 			application in the pack gets a row with its full-colour GNOME app
 			application in the pack gets a row with its full-colour GNOME app
 			icon (the coloured letter tile remains only as a fallback) —
 			icon (the coloured letter tile remains only as a fallback) —
-			Terminal, Files, Web, Gallery, Chat, Clock, Text editor, Colors,
+			Terminal, Files, Web, Gallery, Chat, Clock, Textedit, Colors,
 			Mines, Cards, Disks, Tasks, Services, Settings and Date &amp; Time — the
 			Mines, Cards, Disks, Tasks, Services, Settings and Date &amp; Time — the
 			pointer highlights the hovered row, and an outside press dismisses
 			pointer highlights the hovered row, and an outside press dismisses
 			the panel. Row height shrinks to keep the whole list inside the
 			the panel. Row height shrinks to keep the whole list inside the
@@ -227,7 +227,7 @@
 			A macOS-like dock floats at the bottom centre.  It is a WM-drawn
 			A macOS-like dock floats at the bottom centre.  It is a WM-drawn
 			overlay, not a work-area reservation, so maximized windows keep
 			overlay, not a work-area reservation, so maximized windows keep
 			their full height and simply pass underneath it.  The pinned row
 			their full height and simply pass underneath it.  The pinned row
-			is Terminal, Files, Web, Chat, Text editor, Gallery, Clock,
+			is Terminal, Files, Web, Chat, Textedit, Gallery, Clock,
 			Colors, Mines, Cards, Disks, Tasks and Settings (after a thin
 			Colors, Mines, Cards, Disks, Tasks and Settings (after a thin
 			separator); Services and Date &amp; Time stay in the start menu.
 			separator); Services and Date &amp; Time stay in the start menu.
 			Icons use a 48&nbsp;px base, shrinking to 24&nbsp;px on narrow
 			Icons use a 48&nbsp;px base, shrinking to 24&nbsp;px on narrow
@@ -497,13 +497,14 @@
 			immediate-mode GUI toolkit shared by the ring-3 apps. It provides
 			immediate-mode GUI toolkit shared by the ring-3 apps. It provides
 			clipped RGB565 primitives, buttons, menu items, text fields, the
 			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
 			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>mines</code>,
-			<code>solitaire</code>, <code>process</code>, <code>chat</code>,
-			<code>settings</code>, <code>netmenu</code> and the real
-			<code>gallery.elf</code>.
+			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>.
 		</p>
 		</p>
 		<ul>
 		<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 editor keep the 8×16 cell grid.</li>
+			<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>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>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>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>
 			<li><strong>Clip stack</strong> keeps nested panes and popups inside their parents.</li>
@@ -528,7 +529,7 @@
 			fit beside the built-in set. Missing fonts fall back to the 8×16 bitmap. The browser
 			fit beside the built-in set. Missing fonts fall back to the 8×16 bitmap. The browser
 			detaches the font arena before <code>heap_reset()</code> and
 			detaches the font arena before <code>heap_reset()</code> and
 			reattaches after <code>heap_start()</code>; terminal content and
 			reattaches after <code>heap_start()</code>; terminal content and
-			the editor keep the bitmap cells.
+			the old <code>edit</code> command keep the bitmap cells.
 		</p>
 		</p>
 		<p>
 		<p>
 			UTF-8 text is available through <code>ngui_text_utf8*</code> and
 			UTF-8 text is available through <code>ngui_text_utf8*</code> and
@@ -547,7 +548,11 @@
 		<div class="grid">
 		<div class="grid">
 			<div class="card">
 			<div class="card">
 				<h3>files</h3>
 				<h3>files</h3>
-				<p>File browser on the VFS: opens text in <code>edit</code>, images in <code>view</code> and HTML in <code>browser</code>. The first ngui user.</p>
+				<p>File browser on the VFS: opens text in <code>textedit</code>, images in <code>view</code> and HTML in <code>browser</code>. The first ngui user.</p>
+			</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>
 			</div>
 			</div>
 			<div class="card">
 			<div class="card">
 				<h3>process</h3>
 				<h3>process</h3>
@@ -740,7 +745,7 @@
 			<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.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>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>
 			<li><code>fonts/*.ttf</code> — Arimo / Liberation Mono / Noto Emoji subsets in the pack</li>
-			<li><code>user/apps/files/ucmd_files.c</code>, <code>user/apps/process/ucmd_process.c</code>, <code>user/apps/gallery/gallery.c</code>, <code>user/apps/solitaire/ucmd_solitaire.c</code>, <code>user/apps/chat/ucmd_chat.c</code></li>
+			<li><code>user/apps/files/ucmd_files.c</code>, <code>user/apps/textedit/ucmd_textedit.c</code>, <code>user/apps/process/ucmd_process.c</code>, <code>user/apps/gallery/gallery.c</code>, <code>user/apps/solitaire/ucmd_solitaire.c</code>, <code>user/apps/chat/ucmd_chat.c</code></li>
 			<li><code>user/lib/img/img*.c</code> — image codecs</li>
 			<li><code>user/lib/img/img*.c</code> — image codecs</li>
 			<li><code>kernel/ati.c</code>, <code>kernel/nvidia.c</code>, <code>kernel/intel.c</code>, <code>kernel/nv50.c</code></li>
 			<li><code>kernel/ati.c</code>, <code>kernel/nvidia.c</code>, <code>kernel/intel.c</code>, <code>kernel/nv50.c</code></li>
 			<li><code>kernel/backlight.c</code>, <code>kernel/backlight.h</code> — Cherryview/VLV and Sunrise Point-LP PCH panel PWM</li>
 			<li><code>kernel/backlight.c</code>, <code>kernel/backlight.h</code> — Cherryview/VLV and Sunrise Point-LP PCH panel PWM</li>

+ 1 - 1
docs/index.html

@@ -78,7 +78,7 @@
 
 
 				<rect class="svg-box accent" x="100" y="8" width="720" height="72" rx="9"/>
 				<rect class="svg-box accent" x="100" y="8" width="720" height="72" rx="9"/>
 				<text class="svg-text" x="124" y="35">Ring 3 · commands &amp; GUI apps</text>
 				<text class="svg-text" x="124" y="35">Ring 3 · commands &amp; GUI apps</text>
-				<text class="svg-sub" x="124" y="55">ls · cat · edit · view · files · process · bootscan · browser · chat · gallery · solitaire</text>
+				<text class="svg-sub" x="124" y="55">ls · cat · textedit · view · files · process · bootscan · browser · chat · gallery · solitaire</text>
 				<text class="svg-tiny" x="796" y="35" text-anchor="end">0x40000000</text>
 				<text class="svg-tiny" x="796" y="35" text-anchor="end">0x40000000</text>
 
 
 				<path class="svg-line" d="M460 80v22"/>
 				<path class="svg-line" d="M460 80v22"/>

+ 9 - 6
docs/userland.html

@@ -419,7 +419,7 @@
 		<div class="grid">
 		<div class="grid">
 			<div class="card">
 			<div class="card">
 				<h3>Files &amp; text</h3>
 				<h3>Files &amp; text</h3>
-				<p><code>ls</code> <code>cat</code> <code>save</code> <code>rm</code> <code>mkdir</code> <code>rmdir</code> <code>edit</code> <code>files</code> <code>view</code></p>
+				<p><code>ls</code> <code>cat</code> <code>save</code> <code>rm</code> <code>mkdir</code> <code>rmdir</code> <code>edit</code> <code>textedit</code> <code>files</code> <code>view</code></p>
 			</div>
 			</div>
 			<div class="card">
 			<div class="card">
 				<h3>System</h3>
 				<h3>System</h3>
@@ -431,7 +431,7 @@
 			</div>
 			</div>
 			<div class="card">
 			<div class="card">
 				<h3>GUI</h3>
 				<h3>GUI</h3>
-				<p><code>wm</code> <code>term</code> <code>bootscan</code> <code>files</code> <code>disks</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>process</code> <code>service --gui</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
+				<p><code>wm</code> <code>term</code> <code>bootscan</code> <code>files</code> <code>textedit</code> <code>disks</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>process</code> <code>service --gui</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
 			</div>
 			</div>
 		</div>
 		</div>
 		<p>
 		<p>
@@ -452,7 +452,7 @@
 	<section id="apps">
 	<section id="apps">
 		<h2>GUI applications</h2>
 		<h2>GUI applications</h2>
 		<ul>
 		<ul>
-			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
+			<li><strong>files</strong> — browser for the VFS; opens text in <code>textedit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
 			<li><strong>bootscan</strong> — live tail of the boot storage-scan kernel thread's output (the WM opens it before the terminal, flush right under the top bar). The kernel captures the thread's COM1 trail (mounts, probes, boot traces) into a ring exposed by <code>SYS_BOOTLOG</code>; the window follows the tail while the scan runs, keeps the scrollback afterwards, pauses the follow when scrolled up, and closes with Esc. The deferred USB mount pass runs after the window's ring closes, so its lines appear on COM1/netmon but not in the bootscan scrollback. Also startable from the shell.</li>
 			<li><strong>bootscan</strong> — live tail of the boot storage-scan kernel thread's output (the WM opens it before the terminal, flush right under the top bar). The kernel captures the thread's COM1 trail (mounts, probes, boot traces) into a ring exposed by <code>SYS_BOOTLOG</code>; the window follows the tail while the scan runs, keeps the scrollback afterwards, pauses the follow when scrolled up, and closes with Esc. The deferred USB mount pass runs after the window's ring closes, so its lines appear on COM1/netmon but not in the bootscan scrollback. Also startable from the shell.</li>
 			<li><strong>process</strong> — graphical task manager (start menu <em>Tasks</em> entry or <code>process</code>), the ngui counterpart of <code>top</code>. It samples once per second into 60 s histories of CPU busy (<code>SYS_SCHEDINFO</code> idle ticks summed over all CPUs), physical memory in use (<code>SYS_MEMINFO</code>) and NIC throughput (<code>SYS_NET_INFO.rx_bytes</code>/<code>tx_bytes</code> from the netdev frame counters), then draws the three graphs with ngui rectangles and lines. The table is a process tree: it lists PID, state, CPU%, memory, total CPU time and name, indents children under their <code>parent_pid</code>, and still sorts sibling groups by PID, state, CPU, memory, time or name when a header is clicked; PgUp/PgDn or the wheel scrolls. Selecting a row shows its pid/ppid and details; <em>End task</em> asks for a second click and then calls <code>SYS_KILL</code> (which kills the subtree), while kernel threads (<code>kernel_thread</code> in the process snapshot), the monitor itself and init are protected. Esc closes it.</li>
 			<li><strong>process</strong> — graphical task manager (start menu <em>Tasks</em> entry or <code>process</code>), the ngui counterpart of <code>top</code>. It samples once per second into 60 s histories of CPU busy (<code>SYS_SCHEDINFO</code> idle ticks summed over all CPUs), physical memory in use (<code>SYS_MEMINFO</code>) and NIC throughput (<code>SYS_NET_INFO.rx_bytes</code>/<code>tx_bytes</code> from the netdev frame counters), then draws the three graphs with ngui rectangles and lines. The table is a process tree: it lists PID, state, CPU%, memory, total CPU time and name, indents children under their <code>parent_pid</code>, and still sorts sibling groups by PID, state, CPU, memory, time or name when a header is clicked; PgUp/PgDn or the wheel scrolls. Selecting a row shows its pid/ppid and details; <em>End task</em> asks for a second click and then calls <code>SYS_KILL</code> (which kills the subtree), while kernel threads (<code>kernel_thread</code> in the process snapshot), the monitor itself and init are protected. Esc closes it.</li>
 			<li><strong>disks</strong> — storage manager (start menu <em>Disks</em> entry, or the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
 			<li><strong>disks</strong> — storage manager (start menu <em>Disks</em> entry, or the <em>Disks</em> button in <code>files</code>): devices, MBR partitions and mounts; per-volume mount name, read-only and automount saved to <code>/data/MOUNTS.CFG</code>; Format and Install NebOS dialogs that run <code>format -y</code>/<code>install -y</code> on a private tty and show the log. See <a href="filesystems.html#disks">Filesystems → Storage manager</a>.</li>
@@ -462,7 +462,8 @@
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<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>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>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>edit</strong> — text editor that draws its own text with the 8x16 font.</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>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>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>
 			<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>
 			<li><strong>netmenu</strong> — the top-bar quick-settings popover, opened by clicking anywhere in the right top-bar status area (temperature, date/time, network and AC/battery items). It is a chromeless <code>WIN_F_POPOVER</code> canvas window, anchored flush under the bar at the right screen edge and dismissed by a click outside or <code>Esc</code>. It shows the battery/AC and clock summary, a brightness slider when the panel PWM is present, and six pills: Network, Power, Date &amp; Time, Appearance, Windows and About. A pill is a launcher: it calls <code>SYS_WM_OPEN_SETTINGS(section)</code>, the WM opens or focuses <code>bin/settings</code> at that section, and the popover closes. All editors and lists now live in the Settings window.</li>
 			<li><strong>netmenu</strong> — the top-bar quick-settings popover, opened by clicking anywhere in the right top-bar status area (temperature, date/time, network and AC/battery items). It is a chromeless <code>WIN_F_POPOVER</code> canvas window, anchored flush under the bar at the right screen edge and dismissed by a click outside or <code>Esc</code>. It shows the battery/AC and clock summary, a brightness slider when the panel PWM is present, and six pills: Network, Power, Date &amp; Time, Appearance, Windows and About. A pill is a launcher: it calls <code>SYS_WM_OPEN_SETTINGS(section)</code>, the WM opens or focuses <code>bin/settings</code> at that section, and the popover closes. All editors and lists now live in the Settings window.</li>
@@ -477,9 +478,10 @@
 			the 8×16 bitmap. UTF-8 text APIs additionally fall back to the
 			the 8×16 bitmap. UTF-8 text APIs additionally fall back to the
 			monochrome Noto Emoji subset for common emoji (format-12 cmap);
 			monochrome Noto Emoji subset for common emoji (format-12 cmap);
 			the browser still uses the Latin-1 byte path. Terminal contents and
 			the browser still uses the Latin-1 byte path. Terminal contents and
-			the editor stay bitmap;
+			the old <code>edit</code> command stay bitmap;
 			ngui text fields use the proportional face for text, caret,
 			ngui text fields use the proportional face for text, caret,
-			selection and horizontal scrolling. The browser detaches the font
+			selection and horizontal scrolling, and Textedit's multi-line
+			text area uses the mono face. The browser detaches the font
 			arena before <code>heap_reset()</code> and reattaches after the page
 			arena before <code>heap_reset()</code> and reattaches after the page
 			heap is mapped.
 			heap is mapped.
 		</p>
 		</p>
@@ -562,6 +564,7 @@
 			<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/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>
 			<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>
 			<li><code>user/apps/disks/ucmd_disks.c</code> — storage manager</li>
 			<li><code>user/apps/disks/ucmd_disks.c</code> — storage manager</li>
+			<li><code>user/apps/textedit/ucmd_textedit.c</code> — Notepad-like text editor and its ngui text-area user</li>
 			<li><code>user/apps/process/ucmd_process.c</code> — graphical task manager and its history graphs</li>
 			<li><code>user/apps/process/ucmd_process.c</code> — graphical task manager and its history graphs</li>
 			<li><code>user/apps/bootscan/ucmd_bootscan.c</code> — live boot-scan log window (<code>SYS_BOOTLOG</code>, <code>kernel/bootcon.c</code>)</li>
 			<li><code>user/apps/bootscan/ucmd_bootscan.c</code> — live boot-scan log window (<code>SYS_BOOTLOG</code>, <code>kernel/bootcon.c</code>)</li>
 			<li><code>user/apps/netmenu/ucmd_netmenu.c</code> — top-bar quick-settings popover</li>
 			<li><code>user/apps/netmenu/ucmd_netmenu.c</code> — top-bar quick-settings popover</li>

+ 5 - 5
user/apps/files/ucmd_files.c

@@ -16,7 +16,7 @@
 #define FM_PATH_H       26
 #define FM_PATH_H       26
 #define FM_STATUS_H     18
 #define FM_STATUS_H     18
 #define FM_SIDEBAR_W    140
 #define FM_SIDEBAR_W    140
-#define FM_EDIT_MAX     16384
+#define FM_EDIT_MAX     262144
 #define FM_STATUS_MS    3000
 #define FM_STATUS_MS    3000
 
 
 enum {
 enum {
@@ -534,15 +534,15 @@ static void open_selected(void)
 		return;
 		return;
 	}
 	}
 	if (e->size > FM_EDIT_MAX) {
 	if (e->size > FM_EDIT_MAX) {
-		set_status("File too large for the editor", 1);
+		set_status("File too large for Textedit", 1);
 		return;
 		return;
 	}
 	}
 	path_join(cwd, e->name, path, sizeof(path));
 	path_join(cwd, e->name, path, sizeof(path));
-	pid = u_spawn_detached("/ramfs/bin/edit", path, 0, cwd);
+	pid = u_spawn_detached("/ramfs/bin/textedit", path, 0, cwd);
 	if (pid <= 0)
 	if (pid <= 0)
-		set_status("Cannot launch the editor", 1);
+		set_status("Cannot launch Textedit", 1);
 	else
 	else
-		set_status("Opened in the editor", 0);
+		set_status("Opened in Textedit", 0);
 }
 }
 
 
 static void new_folder(void)
 static void new_folder(void)

+ 74 - 2
user/apps/gallery/gallery.c

@@ -27,7 +27,7 @@
 #define THEME_H         140
 #define THEME_H         140
 #define ICONS_H         100
 #define ICONS_H         100
 #define BUTTONS_H       140
 #define BUTTONS_H       140
-#define INPUTS_H        250
+#define INPUTS_H        440
 #define SCROLL_H        220
 #define SCROLL_H        220
 #define LAYOUT_H        190
 #define LAYOUT_H        190
 #define CURSORS_H       230
 #define CURSORS_H       230
@@ -64,6 +64,7 @@ enum {
 	ID_IN_EMAIL,
 	ID_IN_EMAIL,
 	ID_IN_EVENTS,
 	ID_IN_EVENTS,
 	ID_IN_DISABLED,
 	ID_IN_DISABLED,
+	ID_IN_TEXTAREA,
 	ID_BTN_RESET_FIELDS,
 	ID_BTN_RESET_FIELDS,
 
 
 	ID_NAV_BASE = 0x100,
 	ID_NAV_BASE = 0x100,
@@ -86,7 +87,7 @@ static const char *const sec_descs[SEC_COUNT] = {
 	"the ngui_theme_dark palette",
 	"the ngui_theme_dark palette",
 	"every Adwaita symbolic icon",
 	"every Adwaita symbolic icon",
 	"buttons and icon buttons",
 	"buttons and icon buttons",
-	"single-line text fields",
+	"single-line fields and the multi-line text area",
 	"a nested draggable scroll pane",
 	"a nested draggable scroll pane",
 	"ngui_cut_* layout helpers",
 	"ngui_cut_* layout helpers",
 	"every mouse cursor shape"
 	"every mouse cursor shape"
@@ -114,6 +115,8 @@ static struct ngui_input name_in;
 static struct ngui_input email_in;
 static struct ngui_input email_in;
 static struct ngui_input events_in;
 static struct ngui_input events_in;
 static struct ngui_input disabled_in;
 static struct ngui_input disabled_in;
+static struct ngui_text_area area_in;
+static char area_text[512];
 
 
 static int sec_y[SEC_COUNT];
 static int sec_y[SEC_COUNT];
 static int sec_content_h;
 static int sec_content_h;
@@ -235,6 +238,8 @@ static const char *focus_name(void)
 		return "prefilled";
 		return "prefilled";
 	case ID_IN_EVENTS:
 	case ID_IN_EVENTS:
 		return "events";
 		return "events";
+	case ID_IN_TEXTAREA:
+		return "text area";
 	default:
 	default:
 		return "none";
 		return "none";
 	}
 	}
@@ -775,6 +780,31 @@ static void draw_buttons(struct ngui *g, struct ngui_rect card)
 			   g->theme.border);
 			   g->theme.border);
 }
 }
 
 
+static void area_reset(void)
+{
+	static const char demo[] =
+		"ngui_text_area is a multi-line editor.\n"
+		"\n"
+		"Click to place the caret, drag to select,\n"
+		"double-click a word, or press Ctrl+A.\n"
+		"Tab inserts a tab stop; the arrows, Home,\n"
+		"End and PageUp/PageDown move around.\n"
+		"Long lines soft-wrap at word boundaries.\n";
+
+	s_copy(area_text, demo, sizeof(area_text));
+	area_in.text = area_text;
+	area_in.cap = sizeof(area_text);
+	area_in.len = s_len(area_text);
+	area_in.cursor = 0;
+	area_in.anchor = 0;
+	area_in.dragging = 0;
+	area_in.scroll.offset = 0;
+	area_in.scroll.bar_vis = 0;
+	area_in.scroll.bar_target = 0;
+	area_in.line = 1;
+	area_in.column = 1;
+}
+
 static void draw_inputs(struct ngui *g, struct ngui_rect card)
 static void draw_inputs(struct ngui *g, struct ngui_rect card)
 {
 {
 	int x = card.x + CARD_PAD;
 	int x = card.x + CARD_PAD;
@@ -877,6 +907,7 @@ static void draw_inputs(struct ngui *g, struct ngui_rect card)
 		ngui_input_set(&email_in, "ada@nebos.org");
 		ngui_input_set(&email_in, "ada@nebos.org");
 		ngui_input_set(&events_in, "");
 		ngui_input_set(&events_in, "");
 		ngui_input_set(&disabled_in, "Read-only value");
 		ngui_input_set(&disabled_in, "Read-only value");
+		area_reset();
 		ngui_set_focus(g, 0);
 		ngui_set_focus(g, 0);
 		s_copy(input_feedback, "Fields reset to their defaults.",
 		s_copy(input_feedback, "Fields reset to their defaults.",
 			sizeof(input_feedback));
 			sizeof(input_feedback));
@@ -887,6 +918,46 @@ static void draw_inputs(struct ngui *g, struct ngui_rect card)
 		ngui_text(g, x + 120, top + 192,
 		ngui_text(g, x + 120, top + 192,
 			  "ngui_input_set() rewrites a field.",
 			  "ngui_input_set() rewrites a field.",
 			  g->theme.border);
 			  g->theme.border);
+
+	{
+		int area_y = top + 246;
+		struct ngui_rect ar = rect_make(x, area_y,
+						card.w - 2 * CARD_PAD,
+						card.h -
+						(area_y - card.y) - 14);
+
+		ngui_text_ellipsis(g,
+			rect_make(x, area_y - 20, ar.w, 16),
+			x, area_y - 20,
+			"Multi-line text area (ngui_text_area) - Esc leaves the field",
+			g->theme.accent);
+		if (rect_visible(g, ar)) {
+			int r = ngui_text_area(g, ID_IN_TEXTAREA, ar,
+					       &area_in);
+
+			if (r & NGUI_TEXTAREA_CHANGED) {
+				char b[96];
+				unsigned int n = 0;
+
+				s_append(b, &n, "text area: ", sizeof(b));
+				s_append_uint(b, &n, area_in.len, sizeof(b));
+				s_append(b, &n, " bytes, Ln ", sizeof(b));
+				s_append_uint(b, &n, area_in.line, sizeof(b));
+				s_append(b, &n, " Col ", sizeof(b));
+				s_append_uint(b, &n, area_in.column,
+					      sizeof(b));
+				s_copy(input_feedback, b,
+					sizeof(input_feedback));
+				feedback_error = 0;
+				event_set("text area changed");
+			} else if (r & NGUI_TEXTAREA_CANCEL) {
+				s_copy(input_feedback, "Text area focus left.",
+					sizeof(input_feedback));
+				feedback_error = 0;
+				event_set("text area cancelled");
+			}
+		}
+	}
 }
 }
 
 
 static void draw_scroll(struct ngui *g, struct ngui_rect card)
 static void draw_scroll(struct ngui *g, struct ngui_rect card)
@@ -1327,6 +1398,7 @@ void _start(const char *arg)
 	disabled_in.placeholder = "Cannot edit";
 	disabled_in.placeholder = "Cannot edit";
 	disabled_in.disabled = 1;
 	disabled_in.disabled = 1;
 	ngui_input_set(&disabled_in, "Read-only value");
 	ngui_input_set(&disabled_in, "Read-only value");
+	area_reset();
 
 
 	gallery_layout();
 	gallery_layout();
 	page.content_h = sec_content_h;
 	page.content_h = sec_content_h;

+ 730 - 0
user/apps/textedit/ucmd_textedit.c

@@ -0,0 +1,730 @@
+/* textedit: a Notepad-like plain text editor for a canvas window.
+ *
+ * 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.
+ *
+ * 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,
+ * Ctrl+N new, Ctrl+O open, Ctrl+S save, Ctrl+Q (or Esc) quit.  A modified
+ * buffer gets a discard confirmation before new/open/quit.  The window close
+ * button still ends the process without a prompt (the canvas API has no
+ * close-request event).
+ *
+ * The first argument is a path to open (relative paths resolve against the
+ * inherited cwd); a missing file becomes the document's save path. */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+
+#define TE_MAX        (256u * 1024u)
+#define TE_BUF_SIZE   (TE_MAX + 512u)   /* the FAT read may touch the last sector */
+#define TE_PATH_MAX   64
+#define TE_TOOLBAR_H  38
+#define TE_STATUS_H   24
+#define TE_MARGIN     6
+#define TE_STATUS_MS  4000
+
+enum {
+	ID_AREA = 1,
+	ID_NEW,
+	ID_OPEN,
+	ID_SAVE,
+	ID_SAVEAS,
+
+	ID_DLG_PATH = 0x20,
+	ID_DLG_OK,
+	ID_DLG_CANCEL,
+	ID_CONFIRM_DISCARD,
+	ID_CONFIRM_CANCEL
+};
+
+enum {
+	MODAL_NONE,
+	MODAL_OPEN,
+	MODAL_SAVEAS,
+	MODAL_CONFIRM
+};
+
+enum {
+	ACT_NONE,
+	ACT_NEW,
+	ACT_OPEN,
+	ACT_QUIT
+};
+
+static struct ngui ui;
+static struct ngui_text_area area;
+static struct ngui_input path_input;
+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;
+
+/* ---- small freestanding string helpers ---- */
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void s_append(char *d, unsigned int *n, const char *s,
+		     unsigned int cap)
+{
+	while (s && *s && *n + 1 < cap)
+		d[(*n)++] = *s++;
+	d[*n] = '\0';
+}
+
+static void s_append_uint(char *d, unsigned int *n, unsigned int v,
+			  unsigned int cap)
+{
+	char tmp[12];
+	unsigned int i = 0, j;
+
+	do {
+		tmp[i++] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v && i < sizeof(tmp));
+	for (j = 0; j < i && *n + 1 < cap; j++)
+		d[(*n)++] = tmp[i - 1 - j];
+	d[*n] = '\0';
+}
+
+static const char *base_name(const char *path)
+{
+	const char *b = path;
+	unsigned int i;
+
+	for (i = 0; path && path[i]; i++)
+		if (path[i] == '/')
+			b = path + i + 1;
+	return b;
+}
+
+static void set_status(const char *msg, int error)
+{
+	s_copy(status_text, msg, sizeof(status_text));
+	status_until = u_ticks_ms() + TE_STATUS_MS;
+	status_error = error;
+	ngui_invalidate(&ui);
+}
+
+static const char *read_error(int r)
+{
+	switch (r) {
+	case SYS_ENODEV:
+		return "No such device";
+	case SYS_ENOFS:
+		return "No filesystem on the device";
+	case SYS_ENOENT:
+		return "File not found";
+	case SYS_EIO:
+		return "Disk read error";
+	case SYS_EINVAL:
+		return "Invalid path";
+	default:
+		return "Cannot read the file";
+	}
+}
+
+static const char *write_error(int r)
+{
+	switch (r) {
+	case SYS_ENODEV:
+		return "No such device";
+	case SYS_ENOFS:
+		return "No filesystem on the device";
+	case SYS_ENOENT:
+		return "Path not found";
+	case SYS_EROFS:
+		return "Read-only filesystem";
+	case SYS_EWRITE:
+		return "Disk full or write refused";
+	case SYS_ENOSPC:
+		return "No space left on the filesystem";
+	case SYS_EINVAL:
+		return "Invalid path";
+	case SYS_EIO:
+		return "Disk write error";
+	default:
+		return "Cannot save the file";
+	}
+}
+
+static void reset_view(void)
+{
+	area.len = 0;
+	area.cursor = 0;
+	area.anchor = 0;
+	area.dragging = 0;
+	area.scroll.offset = 0;
+	area.scroll.bar_vis = 0;
+	area.scroll.bar_target = 0;
+	area.line = 1;
+	area.column = 1;
+	text[0] = '\0';
+}
+
+static void new_document(void)
+{
+	reset_view();
+	doc_path[0] = '\0';
+	dirty = 0;
+	set_status("New document", 0);
+	ngui_set_focus(&ui, ID_AREA);
+	ngui_invalidate(&ui);
+}
+
+/* Load a file into the editor.  With allow_new, a missing path becomes the
+ * document's save path instead of an error (a launch argument such as
+ * `textedit notes.txt`).  Returns NULL on success or an error string. */
+static const char *load_file(const char *path, int allow_new)
+{
+	struct sys_stat st;
+	unsigned int i, j;
+	int n, r;
+
+	if (!path || !path[0])
+		return "No path given";
+	if (s_len(path) >= TE_PATH_MAX)
+		return "Path is too long";
+	r = u_stat(path, &st);
+	if (r == SYS_ENOENT) {
+		if (!allow_new)
+			return "File not found";
+		reset_view();
+		s_copy(doc_path, path, sizeof(doc_path));
+		dirty = 0;
+		set_status("New file", 0);
+		return 0;
+	}
+	if (r != 0)
+		return read_error(r);
+	if (st.is_dir)
+		return "That is a directory";
+	if (st.size > TE_MAX)
+		return "File is larger than 256 KB";
+	n = u_read_file(path, text, TE_MAX);
+	if (n < 0)
+		return read_error(n);
+
+	/* Normalize CRLF and lone CR to LF; the editor and save path use LF. */
+	j = 0;
+	for (i = 0; i < (unsigned int)n; i++) {
+		if (text[i] == '\r') {
+			if (i + 1 < (unsigned int)n && text[i + 1] == '\n')
+				continue;
+			text[j++] = '\n';
+		} else {
+			text[j++] = text[i];
+		}
+	}
+	text[j] = '\0';
+	area.len = j;
+	area.cursor = 0;
+	area.anchor = 0;
+	area.dragging = 0;
+	area.scroll.offset = 0;
+	area.scroll.bar_vis = 0;
+	area.scroll.bar_target = 0;
+	area.line = 1;
+	area.column = 1;
+	s_copy(doc_path, path, sizeof(doc_path));
+	dirty = 0;
+	set_status("Opened file", 0);
+	return 0;
+}
+
+static const char *save_file(const char *path)
+{
+	int r;
+
+	if (!path || !path[0])
+		return "No path given";
+	if (s_len(path) >= TE_PATH_MAX)
+		return "Path is too long";
+	r = u_write_file(path, text, area.len);
+	if (r != 0)
+		return write_error(r);
+	s_copy(doc_path, path, sizeof(doc_path));
+	dirty = 0;
+	set_status("Saved", 0);
+	return 0;
+}
+
+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)
+{
+	unsigned int n, a;
+
+	modal = which;
+	modal_error[0] = '\0';
+	if (doc_path[0])
+		ngui_input_set(&path_input, doc_path);
+	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);
+	ngui_invalidate(&ui);
+}
+
+static void do_save(void)
+{
+	if (doc_path[0]) {
+		const char *err = save_file(doc_path);
+
+		if (err)
+			set_status(err, 1);
+		ngui_set_focus(&ui, ID_AREA);
+		ngui_invalidate(&ui);
+	} else {
+		open_dialog(MODAL_SAVEAS);
+	}
+}
+
+static void run_action(int action)
+{
+	switch (action) {
+	case ACT_NEW:
+		new_document();
+		break;
+	case ACT_OPEN:
+		open_dialog(MODAL_OPEN);
+		break;
+	case ACT_QUIT:
+		quit = 1;
+		break;
+	default:
+		break;
+	}
+}
+
+/* New/Open/Quit lose the buffer; ask before discarding a modified one. */
+static void request_action(int action)
+{
+	if (action == ACT_NONE)
+		return;
+	if (dirty) {
+		modal = MODAL_CONFIRM;
+		pending_action = action;
+		modal_error[0] = '\0';
+		ngui_set_focus(&ui, 0);
+		ngui_invalidate(&ui);
+		return;
+	}
+	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;
+	run_action(action);
+	if (modal == MODAL_NONE && !quit)
+		ngui_set_focus(&ui, ID_AREA);
+	ngui_invalidate(&ui);
+}
+
+/* ---- drawing ---- */
+
+static void draw_toolbar(struct ngui_rect r)
+{
+	static const char *const labels[4] = { "New", "Open", "Save", "Save As" };
+	static const unsigned int ids[4] = {
+		ID_NEW, ID_OPEN, ID_SAVE, ID_SAVEAS
+	};
+	int x = r.x + 8;
+	int i;
+
+	ngui_fill_rect(&ui, r, ui.theme.panel);
+	ngui_fill_rect(&ui, (struct ngui_rect){ r.x, r.y + r.h - 1, r.w, 1 },
+		       ui.theme.border);
+	for (i = 0; i < 4; i++) {
+		int w = (int)ngui_text_width_ui(&ui, labels[i]) + 26;
+
+		if (x + w > r.x + r.w - 8)
+			break;
+		if (ngui_button(&ui, ids[i],
+				(struct ngui_rect){ x, r.y + 6, w, 26 },
+				labels[i])) {
+			switch (i) {
+			case 0:
+				request_action(ACT_NEW);
+				break;
+			case 1:
+				open_dialog(MODAL_OPEN);
+				break;
+			case 2:
+				do_save();
+				break;
+			case 3:
+				open_dialog(MODAL_SAVEAS);
+				break;
+			default:
+				break;
+			}
+		}
+		x += w + 6;
+	}
+
+	{
+		const char *name = doc_path[0] ? base_name(doc_path) :
+						 "Untitled";
+		char label[96];
+		unsigned int n = 0;
+		int tw;
+
+		s_append(label, &n, name, sizeof(label));
+		if (dirty)
+			s_append(label, &n, " *", sizeof(label));
+		tw = (int)ngui_text_width_ui(&ui, label);
+		if (i > 0 && x + 12 < r.x + r.w - tw) {
+			ngui_text_ellipsis(&ui,
+				(struct ngui_rect){ x + 8, r.y,
+						    r.x + r.w - x - 16, r.h },
+				x + 8, r.y + (r.h - 16) / 2, label,
+				ui.theme.text_dim);
+		}
+	}
+}
+
+static void draw_status(struct ngui_rect r)
+{
+	char left[128];
+	char right[96];
+	unsigned int n = 0, m = 0;
+	int rw, rx;
+
+	ngui_fill_rect(&ui, r, ui.theme.panel);
+	ngui_fill_rect(&ui, (struct ngui_rect){ r.x, r.y, r.w, 1 },
+		       ui.theme.border);
+
+	if (status_text[0] && status_until &&
+	    (int)(u_ticks_ms() - status_until) < 0) {
+		s_append(left, &n, status_text, sizeof(left));
+	} else {
+		const char *name = doc_path[0] ? base_name(doc_path) :
+						 "Untitled";
+
+		s_append(left, &n, "Ln ", sizeof(left));
+		s_append_uint(left, &n, area.line, sizeof(left));
+		s_append(left, &n, ", Col ", sizeof(left));
+		s_append_uint(left, &n, area.column, sizeof(left));
+		s_append(left, &n, "    ", sizeof(left));
+		s_append_uint(left, &n, area.len, sizeof(left));
+		s_append(left, &n, " bytes    ", sizeof(left));
+		s_append(left, &n, name, sizeof(left));
+		if (dirty)
+			s_append(left, &n, " (modified)", sizeof(left));
+	}
+	/* Right side: the save/open shortcuts. */
+	s_append(right, &m, "Ctrl+S save   Ctrl+O open", sizeof(right));
+	rw = (int)ngui_text_width_ui(&ui, right);
+	rx = r.x + r.w - rw - 10;
+	if (rx > r.x + 20)
+		ngui_text_ellipsis(&ui,
+			(struct ngui_rect){ r.x + 10, r.y, rx - r.x - 16, r.h },
+			r.x + 10, r.y + (r.h - 16) / 2, left,
+			status_error ? ui.theme.error : ui.theme.text);
+	if (rx > r.x + 20)
+		ngui_text(&ui, rx, r.y + (r.h - 16) / 2, right,
+			  ui.theme.text_dim);
+}
+
+static void draw_modal(void)
+{
+	int mw, mh, mx, my;
+	struct ngui_rect panel, input_r;
+	int ok;
+
+	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;
+	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));
+	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 + 16,
+		  modal == MODAL_OPEN ? "Open file" : "Save as",
+		  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,
+			(struct ngui_rect){ mx + mw - 188, my + mh - 44,
+					    84, 28 }, "Cancel"))
+		close_modal();
+	if (ngui_button(&ui, ID_DLG_OK,
+			(struct ngui_rect){ mx + mw - 96, my + mh - 44,
+					    78, 28 },
+			modal == MODAL_OPEN ? "Open" : "Save"))
+		modal_ok();
+}
+
+static void draw(void)
+{
+	struct ngui_rect all = { 0, 0, ui.w, ui.h };
+	struct ngui_rect toolbar, status, edit;
+	int res;
+
+	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);
+	if (modal == MODAL_NONE) {
+		if (edit.w < 1)
+			edit.w = 1;
+		if (edit.h < 1)
+			edit.h = 1;
+		area.scroll.hide_bar = 0;
+		res = ngui_text_area(&ui, ID_AREA, edit, &area);
+		if (res & NGUI_TEXTAREA_CHANGED)
+			dirty = 1;
+	} else {
+		res = 0;
+	}
+	draw_status(status);
+	if (res & NGUI_TEXTAREA_CANCEL)
+		request_action(ACT_QUIT);
+	if (modal != MODAL_NONE)
+		draw_modal();
+}
+
+static void handle_keys(void)
+{
+	int k;
+
+	while ((k = ngui_key(&ui)) != 0) {
+		if (modal == MODAL_CONFIRM) {
+			if (k == NGUI_KEY_ESC)
+				close_modal();
+			else if (k == '\r' || k == '\n')
+				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);
+			break;
+		case 0x0E:              /* Ctrl+N */
+			request_action(ACT_NEW);
+			break;
+		case 0x0F:              /* Ctrl+O */
+			request_action(ACT_OPEN);
+			break;
+		case 0x13:              /* Ctrl+S */
+			do_save();
+			break;
+		case 0x11:              /* Ctrl+Q */
+		case 0x17:              /* Ctrl+W */
+			request_action(ACT_QUIT);
+			break;
+		default:
+			break;
+		}
+	}
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+
+	if (u_win_create(820, 620, "Textedit", &wi) != 0) {
+		u_puts("textedit: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
+
+	area.text = text;
+	area.cap = TE_MAX + 1;
+	area.len = 0;
+	area.cursor = 0;
+	area.anchor = 0;
+	area.dragging = 0;
+	area.read_only = 0;
+	area.line = 1;
+	area.column = 1;
+	text[0] = '\0';
+	doc_path[0] = '\0';
+	dirty = 0;
+	modal = MODAL_NONE;
+	pending_action = ACT_NONE;
+	path_input.placeholder = "/share/FILE.TXT";
+
+	if (arg && arg[0]) {
+		const char *err = load_file(arg, 1);
+
+		if (err)
+			set_status(err, 1);
+	} else {
+		set_status("New document", 0);
+	}
+	ngui_set_focus(&ui, ID_AREA);
+	ngui_invalidate(&ui);
+
+	for (;;) {
+		int want;
+
+		if (status_until &&
+		    (int)(u_ticks_ms() - status_until) >= 0) {
+			status_text[0] = '\0';
+			status_until = 0;
+			status_error = 0;
+			ngui_invalidate(&ui);
+		}
+		want = ngui_begin(&ui);
+		if (quit)
+			break;
+		if (!want) {
+			ngui_end_ex(&ui, 0);
+			u_sleep_ms(10);
+			continue;
+		}
+		draw();
+		handle_keys();
+		if (quit)
+			break;
+		ngui_end(&ui);
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(0);
+}

+ 3 - 3
user/apps/wm/ucmd_wm.c

@@ -246,8 +246,8 @@ struct sm_app {
 };
 };
 
 
 /* Every self-contained GUI application in the pack.  Terminal and Settings
 /* Every self-contained GUI application in the pack.  Terminal and Settings
- * are WM actions (a new terminal canvas and the Settings window); edit gets a
- * scratch file so it can start without a file argument. */
+ * are WM actions (a new terminal canvas and the Settings window); Textedit
+ * starts with an empty Untitled buffer and prompts for a path when saved. */
 static const struct sm_app sm_apps[] = {
 static const struct sm_app sm_apps[] = {
 	{ "Terminal",    "",                    "",                     0x3C8CD2u, 'T', SM_ACT_TERM,     APP_ICON_TERMINAL, "term" },
 	{ "Terminal",    "",                    "",                     0x3C8CD2u, 'T', SM_ACT_TERM,     APP_ICON_TERMINAL, "term" },
 	{ "Files",       "/ramfs/bin/files",    "",                     0xE0A030u, 'F', SM_ACT_SPAWN,    APP_ICON_FILES,    "Files" },
 	{ "Files",       "/ramfs/bin/files",    "",                     0xE0A030u, 'F', SM_ACT_SPAWN,    APP_ICON_FILES,    "Files" },
@@ -255,7 +255,7 @@ static const struct sm_app sm_apps[] = {
 	{ "Gallery",     "/ramfs/bin/gallery",  "",                     0xC864B4u, 'G', SM_ACT_SPAWN,    APP_ICON_GALLERY,  "ngui gallery" },
 	{ "Gallery",     "/ramfs/bin/gallery",  "",                     0xC864B4u, 'G', SM_ACT_SPAWN,    APP_ICON_GALLERY,  "ngui gallery" },
 	{ "Chat",        "/ramfs/bin/chat",     "",                     0x55A055u, 'C', SM_ACT_SPAWN,    APP_ICON_CHAT,     "Chat" },
 	{ "Chat",        "/ramfs/bin/chat",     "",                     0x55A055u, 'C', SM_ACT_SPAWN,    APP_ICON_CHAT,     "Chat" },
 	{ "Clock",       "/ramfs/bin/clock",    "",                     0x8C8C9Cu, 'C', SM_ACT_SPAWN,    APP_ICON_CLOCK,    "clock" },
 	{ "Clock",       "/ramfs/bin/clock",    "",                     0x8C8C9Cu, 'C', SM_ACT_SPAWN,    APP_ICON_CLOCK,    "clock" },
-	{ "Text editor", "/ramfs/bin/edit",     "/share/UNTITLED.TXT",  0xD27850u, 'E', SM_ACT_SPAWN,    APP_ICON_EDITOR,   "edit" },
+	{ "Textedit",    "/ramfs/bin/textedit", "",                     0xD27850u, 'E', SM_ACT_SPAWN,    APP_ICON_EDITOR,   "Textedit" },
 	{ "Colors",      "/ramfs/bin/colors",   "",                     0xC85A5Au, 'P', SM_ACT_SPAWN,    APP_ICON_COLORS,   "colors" },
 	{ "Colors",      "/ramfs/bin/colors",   "",                     0xC85A5Au, 'P', SM_ACT_SPAWN,    APP_ICON_COLORS,   "colors" },
 	{ "Mines",       "/ramfs/bin/mines",    "",                     0x8C6CD2u, 'M', SM_ACT_SPAWN,    APP_ICON_MINES,    "mines" },
 	{ "Mines",       "/ramfs/bin/mines",    "",                     0x8C6CD2u, 'M', SM_ACT_SPAWN,    APP_ICON_MINES,    "mines" },
 	{ "Cards",       "/ramfs/bin/solitaire","",                     0x3CA08Cu, 'S', SM_ACT_SPAWN,    APP_ICON_CARDS,    "Solitaire" },
 	{ "Cards",       "/ramfs/bin/solitaire","",                     0x3CA08Cu, 'S', SM_ACT_SPAWN,    APP_ICON_CARDS,    "Solitaire" },

+ 705 - 0
user/lib/ngui/ngui.c

@@ -2564,3 +2564,708 @@ int ngui_scroll_keys(struct ngui *ui, struct ngui_scroll *s)
 	scroll_clamp(s);
 	scroll_clamp(s);
 	return 1;
 	return 1;
 }
 }
+
+/* ---- multi-line text area ---------------------------------------------- */
+
+#define TA_PAD_X          6
+#define TA_PAD_Y          4
+#define TA_TAB_COLS       4
+#define TA_SCROLL_RESERVE 10
+
+struct ta_metrics {
+	int rows;
+	int caret_row;
+	int caret_pen;               /* 26.6 pixels from the visual-line start */
+	unsigned int seg_start;
+	unsigned int seg_end;
+};
+
+static int ta_word_char(unsigned char c)
+{
+	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+	       (c >= '0' && c <= '9') || c == '_' || c >= 0x80;
+}
+
+/* Advance of one character in 26.6 pixels, matching ngui_text_px()'s
+ * mono face (or its 8 px bitmap fallback).  Tabs are handled separately. */
+static int ta_char_advance(struct ngui *ui, unsigned char c)
+{
+	struct ufont_face *f = ngui_face(ui, 0, 0, 1);
+	int a;
+
+	if (!f)
+		return 8 << 6;
+	a = ufont_advance_cp(f, ui ? ui->font_px : 14, c);
+	return a > 0 ? a : (8 << 6);
+}
+
+static int ta_tab_advance(struct ngui *ui, int pen)
+{
+	int tab = ta_char_advance(ui, ' ') * TA_TAB_COLS;
+
+	if (tab < 1)
+		tab = 8 << 6;
+	return tab - pen % tab;
+}
+
+static int ta_pen_at(struct ngui *ui, const struct ngui_text_area *ta,
+		     unsigned int start, unsigned int pos)
+{
+	int pen = 0;
+	unsigned int p;
+
+	if (pos > ta->len)
+		pos = ta->len;
+	for (p = start; p < pos; p++) {
+		if (ta->text[p] == '\t')
+			pen += ta_tab_advance(ui, pen);
+		else
+			pen += ta_char_advance(ui, (unsigned char)ta->text[p]);
+	}
+	return pen;
+}
+
+static unsigned int ta_line_end(const struct ngui_text_area *ta,
+				unsigned int pos)
+{
+	while (pos < ta->len && ta->text[pos] != '\n')
+		pos++;
+	return pos;
+}
+
+/* End of the visual segment starting at s, wrapping at `avail` (26.6
+ * pixels).  Breaks after the last space/tab that fits; otherwise breaks
+ * before the character that would overflow.  Always consumes >= 1 char when
+ * s < e, so callers cannot loop. */
+static unsigned int ta_seg_end(struct ngui *ui,
+			       const struct ngui_text_area *ta,
+			       unsigned int s, unsigned int e, int avail,
+			       int *used)
+{
+	unsigned int p = s, last_break = s;
+	int pen = 0, last_pen = 0;
+
+	if (avail < 1)
+		avail = 1;
+	while (p < e) {
+		unsigned char c = (unsigned char)ta->text[p];
+		int w;
+
+		if (c == '\t')
+			w = ta_tab_advance(ui, pen);
+		else
+			w = ta_char_advance(ui, c);
+		if (pen + w > avail && p > s) {
+			if (last_break > s) {
+				*used = last_pen;
+				return last_break;
+			}
+			*used = pen;
+			return p;
+		}
+		pen += w;
+		p++;
+		if (c == ' ' || c == '\t') {
+			last_break = p;
+			last_pen = pen;
+		}
+		if (pen >= avail && p < e) {
+			*used = pen;
+			return p;
+		}
+	}
+	*used = pen;
+	return e;
+}
+
+static void ta_sel_bounds(const struct ngui_text_area *ta,
+			  unsigned int *a, unsigned int *b)
+{
+	if (ta->anchor < ta->cursor) {
+		*a = ta->anchor;
+		*b = ta->cursor;
+	} else {
+		*a = ta->cursor;
+		*b = ta->anchor;
+	}
+}
+
+static int ta_delete_range(struct ngui_text_area *ta, unsigned int a,
+			   unsigned int b)
+{
+	unsigned int i;
+
+	if (a >= b || b > ta->len)
+		return 0;
+	for (i = b; i < ta->len; i++)
+		ta->text[i - (b - a)] = ta->text[i];
+	ta->len -= b - a;
+	ta->text[ta->len] = '\0';
+	if (ta->cursor >= b)
+		ta->cursor -= b - a;
+	else if (ta->cursor > a)
+		ta->cursor = a;
+	if (ta->anchor >= b)
+		ta->anchor -= b - a;
+	else if (ta->anchor > a)
+		ta->anchor = a;
+	return 1;
+}
+
+static int ta_delete_selection(struct ngui_text_area *ta)
+{
+	unsigned int a, b;
+
+	ta_sel_bounds(ta, &a, &b);
+	return ta_delete_range(ta, a, b);
+}
+
+static int ta_insert_char(struct ngui_text_area *ta, char c)
+{
+	unsigned int i;
+
+	ta_delete_selection(ta);
+	if (ta->len + 1 >= ta->cap)
+		return 0;
+	i = ta->len + 1;
+	while (i > ta->cursor) {
+		ta->text[i] = ta->text[i - 1];
+		i--;
+	}
+	ta->text[ta->cursor] = c;
+	ta->cursor++;
+	ta->len++;
+	ta->anchor = ta->cursor;
+	return 1;
+}
+
+static unsigned int ta_word_next(const struct ngui_text_area *ta,
+				 unsigned int pos)
+{
+	while (pos < ta->len && ta_word_char((unsigned char)ta->text[pos]))
+		pos++;
+	while (pos < ta->len && !ta_word_char((unsigned char)ta->text[pos]))
+		pos++;
+	return pos;
+}
+
+static unsigned int ta_word_prev(const struct ngui_text_area *ta,
+				 unsigned int pos)
+{
+	while (pos > 0 && !ta_word_char((unsigned char)ta->text[pos - 1]))
+		pos--;
+	while (pos > 0 && ta_word_char((unsigned char)ta->text[pos - 1]))
+		pos--;
+	return pos;
+}
+
+static unsigned int ta_word_delete_end(const struct ngui_text_area *ta,
+				       unsigned int pos)
+{
+	if (pos < ta->len && ta_word_char((unsigned char)ta->text[pos])) {
+		while (pos < ta->len &&
+		       ta_word_char((unsigned char)ta->text[pos]))
+			pos++;
+		while (pos < ta->len &&
+		       !ta_word_char((unsigned char)ta->text[pos]))
+			pos++;
+		return pos;
+	}
+	while (pos < ta->len && !ta_word_char((unsigned char)ta->text[pos]))
+		pos++;
+	while (pos < ta->len && ta_word_char((unsigned char)ta->text[pos]))
+		pos++;
+	return pos;
+}
+
+static void ta_measure(struct ngui *ui, const struct ngui_text_area *ta,
+		       int avail, struct ta_metrics *m,
+		       unsigned int *line_out, unsigned int *column_out)
+{
+	unsigned int pos = 0, line_start = 0, line_no = 1;
+	int row = 0, found = 0;
+
+	m->rows = 0;
+	m->caret_row = 0;
+	m->caret_pen = 0;
+	m->seg_start = 0;
+	m->seg_end = 0;
+	*line_out = 1;
+	*column_out = 1;
+
+	for (;;) {
+		unsigned int le = ta_line_end(ta, pos);
+		unsigned int s = pos;
+
+		for (;;) {
+			unsigned int e;
+			int used = 0;
+
+			if (s >= le) {
+				e = le;
+			} else {
+				e = ta_seg_end(ui, ta, s, le, avail, &used);
+			}
+			if (!found && ta->cursor >= s && ta->cursor <= e) {
+				m->caret_row = row;
+				m->caret_pen = ta_pen_at(ui, ta, s,
+							 ta->cursor);
+				m->seg_start = s;
+				m->seg_end = e;
+				found = 1;
+			}
+			row++;
+			if (e >= le)
+				break;
+			s = e;
+		}
+		if (ta->cursor >= line_start && ta->cursor <= le) {
+			*line_out = line_no;
+			*column_out = ta->cursor - line_start + 1;
+		}
+		if (le >= ta->len)
+			break;
+		pos = le + 1;
+		line_start = pos;
+		line_no++;
+	}
+	m->rows = row;
+}
+
+/* Position at a 26.6 x offset inside [s, e), rounded to the nearest character
+ * boundary. */
+static unsigned int ta_pos_at_pen(struct ngui *ui,
+				  const struct ngui_text_area *ta,
+				  unsigned int s, unsigned int e, int target)
+{
+	unsigned int p = s;
+	int pen = 0;
+
+	if (target < 0)
+		target = 0;
+	while (p < e) {
+		int w = ta->text[p] == '\t' ? ta_tab_advance(ui, pen) :
+			ta_char_advance(ui, (unsigned char)ta->text[p]);
+
+		if (target < pen + (w + 1) / 2)
+			return p;
+		pen += w;
+		p++;
+	}
+	return e;
+}
+
+/* The position on visual row `target_row` closest to `target_pen`. */
+static unsigned int ta_pos_at_row(struct ngui *ui,
+				  const struct ngui_text_area *ta,
+				  int avail, int target_row, int target_pen)
+{
+	unsigned int pos = 0;
+	int row = 0;
+
+	if (target_row < 0)
+		target_row = 0;
+	for (;;) {
+		unsigned int le = ta_line_end(ta, pos);
+		unsigned int s = pos;
+
+		for (;;) {
+			unsigned int e;
+			int used = 0;
+
+			if (s >= le)
+				e = le;
+			else
+				e = ta_seg_end(ui, ta, s, le, avail, &used);
+			if (row == target_row)
+				return ta_pos_at_pen(ui, ta, s, e, target_pen);
+			row++;
+			if (e >= le)
+				break;
+			s = e;
+		}
+		if (le >= ta->len)
+			break;
+		pos = le + 1;
+	}
+	return ta->len;
+}
+
+static unsigned int ta_pos_at_xy(struct ngui *ui,
+				 const struct ngui_text_area *ta,
+				 int avail, const struct ngui_rect *view,
+				 int x, int y)
+{
+	int line_h = ngui_text_line_height(ui, ui->font_px, 1);
+	int row, pen;
+
+	if (line_h < 1)
+		line_h = 16;
+	if (y < view->y)
+		y = view->y;
+	if (y >= view->y + view->h)
+		y = view->y + view->h - 1;
+	row = (y - view->y - TA_PAD_Y + ta->scroll.offset) / line_h;
+	if (row < 0)
+		row = 0;
+	pen = ((x - (view->x + TA_PAD_X)) << 6);
+	if (pen < 0)
+		pen = 0;
+	return ta_pos_at_row(ui, ta, avail, row, pen);
+}
+
+static void ta_move_vertical(struct ngui *ui, struct ngui_text_area *ta,
+			     int avail, const struct ta_metrics *m,
+			     const struct ngui_rect *view, int delta)
+{
+	int line_h = ngui_text_line_height(ui, ui->font_px, 1);
+	int target;
+
+	if (line_h < 1)
+		line_h = 16;
+	target = m->caret_row + delta;
+	if (target < 0)
+		target = 0;
+	if (target >= m->rows)
+		target = m->rows > 0 ? m->rows - 1 : 0;
+	ta->cursor = ta_pos_at_row(ui, ta, avail, target, m->caret_pen);
+	ta->anchor = ta->cursor;
+	ngui_scroll_ensure_visible(&ta->scroll,
+				   TA_PAD_Y + target * line_h, line_h);
+	(void)view;
+}
+
+/* Selected text gets the theme colour; a drag over a tab keeps its cells
+ * highlighted.  Draws one visual segment, splitting the run at tabs so the
+ * glyph positions match the pen used for wrapping and hit-testing. */
+static void ta_draw_segment(struct ngui *ui,
+			    const struct ngui_text_area *ta,
+			    unsigned int s, unsigned int e, int x0, int y,
+			    unsigned int sel_a, unsigned int sel_b)
+{
+	int pen = 0, run_pen = 0;
+	unsigned int p, run_start = s;
+
+	if (sel_b > sel_a) {
+		unsigned int sa = sel_a > s ? sel_a : s;
+		unsigned int sb = sel_b < e ? sel_b : e;
+
+		if (sa < sb) {
+			int pa = ta_pen_at(ui, ta, s, sa);
+			int pb = ta_pen_at(ui, ta, s, sb);
+			struct ngui_rect hr;
+
+			hr.x = x0 + (pa >> 6);
+			hr.y = y;
+			hr.w = ((pb + 32) >> 6) - (pa >> 6);
+			if (hr.w < 1)
+				hr.w = 1;
+			hr.h = ngui_text_line_height(ui, ui->font_px, 1);
+			ngui_fill_rect(ui, hr, ui->theme.selection);
+		}
+	}
+
+	for (p = s; p < e; p++) {
+		if (ta->text[p] == '\t') {
+			if (p > run_start)
+				ngui_text_px(ui, x0 + (run_pen >> 6), y,
+					     ta->text + run_start,
+					     p - run_start, ui->theme.text,
+					     ui->font_px, 0, 0, 1);
+			pen += ta_tab_advance(ui, pen);
+			run_start = p + 1;
+			run_pen = pen;
+		} else {
+			pen += ta_char_advance(ui,
+					       (unsigned char)ta->text[p]);
+		}
+	}
+	if (e > run_start)
+		ngui_text_px(ui, x0 + (run_pen >> 6), y, ta->text + run_start,
+			     e - run_start, ui->theme.text, ui->font_px,
+			     0, 0, 1);
+}
+
+int ngui_text_area(struct ngui *ui, unsigned int id, struct ngui_rect r,
+		   struct ngui_text_area *ta)
+{
+	struct ngui_rect view;
+	struct ta_metrics m;
+	unsigned int line, column, sel_a, sel_b;
+	int focused, avail, line_h, result = 0, k, caret_moved = 0;
+
+	if (!ui || !ta || !ta->text)
+		return 0;
+	if (ta->cap < 1)
+		return 0;
+	if (ta->len >= ta->cap) {
+		ta->len = ta->cap - 1;
+		ta->text[ta->len] = '\0';
+	}
+	if (ta->cursor > ta->len)
+		ta->cursor = ta->len;
+	if (ta->anchor > ta->len)
+		ta->anchor = ta->len;
+
+	focused = ui->focus == id;
+	line_h = ngui_text_line_height(ui, ui->font_px, 1);
+	if (line_h < 1)
+		line_h = 16;
+	view.x = r.x + 1;
+	view.y = r.y + 1;
+	view.w = r.w - 2;
+	view.h = r.h - 2;
+	if (view.w < 1)
+		view.w = 1;
+	if (view.h < 1)
+		view.h = 1;
+	avail = (view.w - 2 * TA_PAD_X - TA_SCROLL_RESERVE) << 6;
+	if (avail < (8 << 6))
+		avail = 8 << 6;
+
+	ngui_fill_rect(ui, r, focused ? ui->theme.panel_alt : ui->theme.panel);
+	ngui_fill_rect(ui, view, ui->theme.bg);
+	ngui_cursor_rect(ui, view, CURSOR_TEXT);
+
+	ta_measure(ui, ta, avail, &m, &line, &column);
+	ta->scroll.view_h = view.h;
+	ta->scroll.content_h = m.rows * line_h + 2 * TA_PAD_Y;
+	ngui_scroll_begin(ui, view, &ta->scroll);
+	if (ngui_scroll_wheel(ui, view, &ta->scroll))
+		ui->dirty = 1;
+
+	if (ui->pressed && ngui_rect_contains(&view, ui->press_x,
+					      ui->press_y)) {
+		unsigned int pos = ta_pos_at_xy(ui, ta, avail, &view,
+						ui->press_x, ui->press_y);
+		unsigned int now = u_ticks_ms();
+		int dbl = ta->last_click_ms &&
+			  (unsigned int)(now - ta->last_click_ms) <= 500;
+
+		ta->cursor = pos;
+		if (dbl && pos < ta->len &&
+		    ta_word_char((unsigned char)ta->text[pos])) {
+			unsigned int a = pos, b = pos;
+
+			while (a > 0 &&
+			       ta_word_char((unsigned char)ta->text[a - 1]))
+				a--;
+			while (b < ta->len &&
+			       ta_word_char((unsigned char)ta->text[b]))
+				b++;
+			ta->anchor = a;
+			ta->cursor = b;
+			ta->dragging = 0;
+		} else {
+			ta->anchor = pos;
+			ta->dragging = 1;
+		}
+		ta->last_click_ms = now;
+		ngui_set_focus(ui, id);
+		ui->focus_claimed = 1;
+		ui->last_blink = now;
+		ui->caret_on = 1;
+		focused = 1;
+		caret_moved = 1;
+	} else if (ui->pressed) {
+		ta->dragging = 0;
+	}
+
+	if (ta->dragging && (ui->buttons & 1) && !ui->released) {
+		ta->cursor = ta_pos_at_xy(ui, ta, avail, &view,
+					  ui->mouse_x, ui->mouse_y);
+		ngui_invalidate(ui);
+		caret_moved = 1;
+	}
+	if (ui->released)
+		ta->dragging = 0;
+
+	if (ui->focus == id) {
+		while ((k = ngui_key_peek(ui)) != 0) {
+			int changed = 0;
+			int handled = 1;
+
+			if (k >= 0x20 && k <= 0x7E) {
+				if (!ta->read_only)
+					changed = ta_insert_char(ta, (char)k);
+			} else if (k == '\n' || k == '\r') {
+				if (!ta->read_only)
+					changed = ta_insert_char(ta, '\n');
+			} else if (k == '\t') {
+				if (!ta->read_only)
+					changed = ta_insert_char(ta, '\t');
+			} else if (k == NGUI_KEY_BACKSPACE || k == 0x7F) {
+				if (!ta->read_only) {
+					if (ta_delete_selection(ta))
+						changed = 1;
+					else if (ta->cursor > 0)
+						changed = ta_delete_range(
+							ta, ta->cursor - 1,
+							ta->cursor);
+				}
+			} else if (k == NGUI_KEY_DELETE) {
+				if (!ta->read_only) {
+					if (ta_delete_selection(ta))
+						changed = 1;
+					else if (ta->cursor < ta->len)
+						changed = ta_delete_range(
+							ta, ta->cursor,
+							ta->cursor + 1);
+				}
+			} else if (k == NGUI_KEY_CTRL_BACKSPACE) {
+				if (!ta->read_only) {
+					if (ta_delete_selection(ta))
+						changed = 1;
+					else
+						changed = ta_delete_range(
+							ta,
+							ta_word_prev(ta,
+								     ta->cursor),
+							ta->cursor);
+				}
+			} else if (k == NGUI_KEY_CTRL_DELETE) {
+				if (!ta->read_only) {
+					if (ta_delete_selection(ta)) {
+						changed = 1;
+					} else {
+						unsigned int a = ta->cursor;
+						unsigned int b =
+							ta_word_delete_end(ta, a);
+
+						if (b == a) {
+							a = ta_word_prev(ta,
+									 ta->cursor);
+							b = ta->cursor;
+						}
+						changed = ta_delete_range(ta,
+									  a, b);
+					}
+				}
+			} else if (k == NGUI_KEY_LEFT) {
+				if (ta->cursor > 0)
+					ta->cursor--;
+				ta->anchor = ta->cursor;
+			} else if (k == NGUI_KEY_RIGHT) {
+				if (ta->cursor < ta->len)
+					ta->cursor++;
+				ta->anchor = ta->cursor;
+			} else if (k == NGUI_KEY_CTRL_LEFT) {
+				ta->cursor = ta_word_prev(ta, ta->cursor);
+				ta->anchor = ta->cursor;
+			} else if (k == NGUI_KEY_CTRL_RIGHT) {
+				ta->cursor = ta_word_next(ta, ta->cursor);
+				ta->anchor = ta->cursor;
+			} else if (k == NGUI_KEY_HOME) {
+				ta->cursor = m.seg_start;
+				ta->anchor = ta->cursor;
+			} else if (k == NGUI_KEY_END) {
+				ta->cursor = m.seg_end;
+				ta->anchor = ta->cursor;
+			} else if (k == NGUI_KEY_UP) {
+				ta_move_vertical(ui, ta, avail, &m, &view, -1);
+			} else if (k == NGUI_KEY_DOWN) {
+				ta_move_vertical(ui, ta, avail, &m, &view, 1);
+			} else if (k == NGUI_KEY_PAGE_UP) {
+				int page = view.h / line_h - 1;
+
+				if (page < 1)
+					page = 1;
+				ta_move_vertical(ui, ta, avail, &m, &view,
+						 -page);
+			} else if (k == NGUI_KEY_PAGE_DOWN) {
+				int page = view.h / line_h - 1;
+
+				if (page < 1)
+					page = 1;
+				ta_move_vertical(ui, ta, avail, &m, &view,
+						 page);
+			} else if (k == 0x01) {   /* Ctrl+A: select all */
+				ta->anchor = 0;
+				ta->cursor = ta->len;
+				ta->dragging = 0;
+			} else if (k == NGUI_KEY_ESC) {
+				ui->focus = 0;
+				result |= NGUI_TEXTAREA_CANCEL;
+			} else {
+				handled = 0;
+			}
+			if (!handled)
+				break;
+			ngui_key(ui);
+			if (changed)
+				result |= NGUI_TEXTAREA_CHANGED;
+			if (k != NGUI_KEY_ESC) {
+				caret_moved = 1;
+				ta_measure(ui, ta, avail, &m, &line, &column);
+			}
+		}
+	}
+
+	/* The edit keys can change both the wrap and the caret row. */
+	ta_measure(ui, ta, avail, &m, &line, &column);
+	ta->line = line;
+	ta->column = column;
+	ta->scroll.view_h = view.h;
+	ta->scroll.content_h = m.rows * line_h + 2 * TA_PAD_Y;
+	if (caret_moved)
+		ngui_scroll_ensure_visible(&ta->scroll,
+					   TA_PAD_Y + m.caret_row * line_h,
+					   line_h);
+
+	ta_sel_bounds(ta, &sel_a, &sel_b);
+	{
+		unsigned int pos = 0;
+		int row = 0;
+
+		for (;;) {
+			unsigned int le = ta_line_end(ta, pos);
+			unsigned int s = pos;
+
+			for (;;) {
+				unsigned int e;
+				int used = 0;
+				int y;
+
+				if (s >= le)
+					e = le;
+				else
+					e = ta_seg_end(ui, ta, s, le, avail,
+						       &used);
+				y = view.y + TA_PAD_Y + row * line_h -
+				    ta->scroll.offset;
+				if (y + line_h > view.y &&
+				    y < view.y + view.h)
+					ta_draw_segment(ui, ta, s, e,
+							view.x + TA_PAD_X, y,
+							sel_a, sel_b);
+				if (row == m.caret_row && ui->focus == id &&
+				    ui->caret_on) {
+					int cx = view.x + TA_PAD_X +
+						 (m.caret_pen >> 6);
+
+					if (cx < view.x)
+						cx = view.x;
+					if (cx >= view.x + view.w)
+						cx = view.x + view.w - 1;
+					ngui_fill_rect(ui,
+						rect_make(cx, y, 1, line_h),
+						ui->theme.accent);
+				}
+				row++;
+				if (e >= le)
+					break;
+				s = e;
+			}
+			if (le >= ta->len)
+				break;
+			pos = le + 1;
+		}
+	}
+
+	ngui_scroll_end(ui, view, &ta->scroll);
+	ngui_frame(ui, r, ui->focus == id ? ui->theme.accent :
+					ui->theme.border);
+	if (ui->inside && ngui_rect_contains(&r, ui->mouse_x, ui->mouse_y))
+		ui->hot = id;
+	return result;
+}

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

@@ -115,6 +115,31 @@ struct ngui_scroll {
 	unsigned int bar_ms;          /* last animation step (u_ticks_ms) */
 	unsigned int bar_ms;          /* last animation step (u_ticks_ms) */
 };
 };
 
 
+/* A multi-line, soft-wrapping plain-text editor.  The caller owns the text
+ * buffer and keeps the state; the widget edits it in place, supports a caret,
+ * mouse drag selection, double-click word selection, Ctrl+A, the arrow /
+ * Home / End / PageUp / PageDown / word-jump keys, Backspace/Delete and
+ * Ctrl+Backspace/Delete, inserts Tab, scrolls to the caret and draws its own
+ * vertical scrollbar.  The NUL at text[len] is maintained.  Esc is consumed:
+ * it clears the focus and returns NGUI_TEXTAREA_CANCEL so the app can close a
+ * dialog or quit.  Other Ctrl shortcuts are left in the key queue for the
+ * app.  line/column are 1-based and updated by every call. */
+struct ngui_text_area {
+	char *text;
+	unsigned int cap;            /* bytes available in text, including NUL */
+	unsigned int len;
+	unsigned int cursor;
+	unsigned int anchor;         /* selection anchor (== cursor: none) */
+	int dragging;
+	int read_only;
+	struct ngui_scroll scroll;
+	unsigned int last_click_ms;  /* previous press, for double-click word select */
+	unsigned int line, column;   /* caret position after the last call */
+};
+
+#define NGUI_TEXTAREA_CHANGED 1
+#define NGUI_TEXTAREA_CANCEL  2
+
 struct ngui_slider {
 struct ngui_slider {
 	int dragging;
 	int dragging;
 };
 };
@@ -322,6 +347,8 @@ int  ngui_slider(struct ngui *ui, unsigned int id, struct ngui_slider *s,
 		 struct ngui_rect r, int *value, int min, int max);
 		 struct ngui_rect r, int *value, int min, int max);
 int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		    struct ngui_input *in);
 		    struct ngui_input *in);
+int ngui_text_area(struct ngui *ui, unsigned int id, struct ngui_rect r,
+		   struct ngui_text_area *ta);
 /* Ask for `shape` (enum cursor_shape) while the pointer is in `r` (and in
 /* 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
  * the current clip); returns 1 when it is.  ngui_set_cursor() sets it
  * unconditionally for the current frame. */
  * unconditionally for the current frame. */