10 Revize 852e70701c ... 8513cec844

Autor SHA1 Zpráva Datum
  Johannes Zellner 8513cec844 Run ES modules, fetch and Web Storage in the browser před 1 týdnem
  Johannes Zellner 47aeb06a63 Use one font size in the network popover před 1 týdnem
  Johannes Zellner 484756be4d Turn the network menu into a flat popover před 1 týdnem
  Johannes Zellner 3527e786f9 Clip chat avatars to circles před 1 týdnem
  Johannes Zellner cce9edb987 Add Cherryview panel backlight and a brightness OSD před 1 týdnem
  Johannes Zellner 397b6a6b31 Render chat message images and profile avatars před 1 týdnem
  Johannes Zellner 52a09e7bc6 Give buttons a raised bevel and text fields an inset edge před 1 týdnem
  Johannes Zellner 6f2a56df99 Show the terminal before probing USB, the NIC and disks před 1 týdnem
  Johannes Zellner c7fcd79baf Keep a list of saved WiFi networks in /data před 1 týdnem
  Johannes Zellner 156bac7fc6 Persist the chat session in /data when available před 1 týdnem
54 změnil soubory, kde provedl 5945 přidání a 734 odebrání
  1. 1 0
      .gitignore
  2. 194 62
      AGENTS.md
  3. 33 13
      Makefile
  4. 241 0
      backlight.c
  5. 44 0
      backlight.h
  6. 42 21
      boot.S
  7. 510 37
      browser.c
  8. 68 7
      browser_html.c
  9. 1 0
      browser_html.h
  10. 21 0
      cpu.c
  11. 5 0
      cpu.h
  12. 17 9
      docs/boot.html
  13. 6 2
      docs/development.html
  14. 5 1
      docs/drivers.html
  15. 2 1
      docs/filesystems.html
  16. 49 8
      docs/graphics.html
  17. 47 20
      docs/network.html
  18. 3 3
      docs/userland.html
  19. 1 1
      gallery.c
  20. 2 0
      gpu.c
  21. 90 2
      io.c
  22. 12 0
      io.h
  23. 248 10
      js_browser.c
  24. 25 0
      js_browser.h
  25. 155 0
      js_mu.c
  26. 12 0
      js_mu.h
  27. 8 0
      js_prelude.S
  28. 1132 0
      js_prelude.js
  29. 58 37
      kernel.c
  30. 241 3
      ngui.c
  31. 35 0
      ngui.h
  32. 7 0
      sys_net.c
  33. 3 0
      sys_wm.c
  34. 4 0
      sys_wm.h
  35. 204 0
      terminal.c
  36. 91 15
      tools/mock_chat.py
  37. 4 0
      tools/qmp_chat_test.py
  38. 10 0
      touchpad.c
  39. 677 11
      ucmd_chat.c
  40. 76 7
      ucmd_curl.c
  41. 18 2
      ucmd_lib.h
  42. 488 219
      ucmd_netmenu.c
  43. 195 160
      ucmd_wifi.c
  44. 282 39
      ucmd_wm.c
  45. 48 7
      uhttp.c
  46. 8 3
      usb.c
  47. 6 2
      usbhid.c
  48. 24 7
      wifi_cfg.h
  49. 157 0
      wifi_store.c
  50. 28 0
      wifi_store.h
  51. 205 0
      wifi_store_test.c
  52. 89 25
      wm.c
  53. 1 0
      wm.h
  54. 12 0
      wm_abi.h

+ 1 - 0
.gitignore

@@ -32,4 +32,5 @@ uhttp_cookie_test
 chat_login_test
 chat-test-out/
 wpa_test
+wifi_store_test
 firmware/

+ 194 - 62
AGENTS.md

@@ -84,6 +84,7 @@ make test-font-asan  # ASan/UBSan variant
 make test-svg   # host tests for the inline-SVG rasterizer (ASan/UBSan)
 make test-touchpad  # host tests for the contact gesture engine
 make test-wpa   # host tests for the WPA2-PSK supplicant (SHA-1/PBKDF2/PRF/AES, 4-way)
+make test-wifi-store  # host tests for the saved-network list file
 make test-chat  # host tests: JSON parser, cookie jar, chat login parsers (ASan)
 make test-chat-e2e  # QEMU + tools/mock_chat.py chat end-to-end (CHAT_E2E=--totp...)
 make compat-serve  # serve the browser A/B ladder on port 8000
@@ -141,9 +142,13 @@ make clean
 ## Boot chain
 
 1. `boot.S` — 512-byte boot sector (FAT16 BPB). Loads contiguous kernel sectors
-   to `0x7E00` (CHS for floppy, one sector per call; INT 13h AH=42h LBA for
-   hard disk, up to 64 sectors per call into `ES:0` with `ES` advanced, so the
-   offset never wraps), jumps there with the boot drive still in DL.
+   to `0x7E00`, one INT 13h per run of sectors into `ES:0` with `ES`
+   advanced (the offset never wraps): EDD LBA for hard disks, up to 64
+   sectors; CHS for floppies, up to the end of the track and never across a
+   64 KB physical ISA DMA boundary.  Errors get three tries per run, then one
+   sector per call (the old behaviour), three tries, then `Disk read error`.
+   Jumps to the stage with the boot drive still in DL (do not clobber DX).
+   The 512-byte sector has only a few bytes left before the partition table.
 2. `vesa_stage.S` — real-mode VESA stage. Probes INT 15h E820 into `0x1000`,
    enables A20, reads the `NBROOT1` rootfs header at the boot sector's
    `pack_lba` field and copies the gzip pack directly to `PACK_HIGH_ADDR`
@@ -169,14 +174,20 @@ make clean
    used); fixed disks use EDD LBA.
 3. `kernel.c` — `kernel_main` zeroes BSS then inits serial → memory/paging →
    ACPI/MADT → I/O → power → idle → processes → timer (PIT; 1 kHz busy,
-   100 Hz idle + IDT) → SMP AP bring-up → mouse/USB → VGA shadow buffer →
-   ramfs inflate → WM → NIC probe → kworker → the `bootscan` kernel thread
-   (storage scan + FAT mounts, then the `/data` WiFi autoconnect once the
-   boot DHCP finished) → `wm_server_boot_ready()` immediately, so the first
-   terminal starts while the disks are still probed → DHCP.  COM1 prints
-   `wm: first window frame (term) at N ms` (uptime) when the first app
-   window presents: the end point of a boot-time measurement (~0.65 s after
-   the kernel starts on QEMU's USB image).
+   100 Hz idle + IDT) → SMP AP bring-up → PS/2 mouse (the I2C touchpad
+   probe only on Airmont) → VGA shadow buffer → ramfs inflate → WM →
+   publish `vfs_scan_busy` → `wm_server_boot_ready()` → wait (idle `hlt`,
+   1 s cap) until the first terminal has presented → USB bring-up and scan
+   (non-preemptible, as before the WM existed: reset/SOF timing) → NIC probe
+   → kworker → the `bootscan` kernel thread (storage scan + FAT mounts, then
+   the `/data` WiFi autoconnect once the boot DHCP finished) → DHCP.  So
+   the terminal is on screen before USB, NIC and disks are probed; USB
+   input, USB NICs and USB disks attach right after.  The WM's
+   `SYS_NET_INFO` does not trigger the NIC probe (it reports "no NIC" until
+   `kernel_main` probed), so the first frame never waits for a PHY reset.
+   COM1 prints `wm: first window frame (term) at N ms` (uptime) when the
+   first app window presents: the end point of a boot-time measurement
+   (~0.35-0.4 s after the kernel starts on QEMU's USB image).
 4. `mbr.S` — MBR (USB/HDD boot); loads the active partition's boot sector
    (partition 1 at LBA 63).
 5. **UEFI (`efi/`)** — an x86-64 PE32+ `BOOTX64.EFI` loads from the ESP. It
@@ -354,8 +365,16 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   network status icon: a cable for a wired netdev, signal bars for an
   associated WiFi link, a USB mark for RNDIS tethering, and a red X otherwise.
   The WM polls `SYS_NET_INFO` (and `SYS_WIFI_STATUS` only while WiFi is active)
-  at 1 Hz; clicking the network icon spawns one `/ramfs/bin/netmenu` window and
-  anchors it under the icon once its window exists (`u_wm_set_geom`).
+  at 1 Hz; clicking the network icon opens one `/ramfs/bin/netmenu` popover and
+  anchors it under the icon (`u_wm_set_geom`).  A popover is a chromeless
+  `WIN_F_POPOVER` canvas window (`u_win_create_popover`): the WM skips the
+  title bar/close/resize chrome and treats it as always topmost in painting
+  and hit-testing.  The canvas fills the whole window rectangle: there is no
+  outer shadow, rim or rounded corner, so it reads as a flat menu panel.  The
+  kernel uses the window origin for content-relative pointer and scroll
+  coordinates (a normal window uses the 1 px border plus title bar).  An
+  outside press dismisses the popover and then continues with the normal
+  click handling; a second click on the network icon toggles it.
   The last launcher, `Chat`, spawns `/ramfs/bin/chat`; `WM_BTN_END_X`
   (`wm_abi.h`) is the launchers' right edge, and the bar notice and the
   right-aligned status never draw left of it.
@@ -396,7 +415,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   live showcase of every control and primitive the toolkit exports.  Buttons
   fire on the release edge and keep `active` until `ui->released`: inferring
   release from the sampled `ui->buttons` races the WM event queue and drops
-  clicks.  Text fields use the proportional font with measured caret,
+  clicks.  The popover component (`ngui_popover_begin`/`footer`, a flat
+  surface with a body and footer, no title bar or close button) is the shell
+  of `netmenu`; `ngui_section` draws captioned section headers with an
+  optional action button, `ngui_list_row` is a two-line hover/selected row
+  with optional signal bars and trailing text, and `ngui_signal_bars` draws
+  the four-bar strength icon.  The WM draws no outer chrome, so a popover
+  fills its whole window.  Text fields use the proportional font with
+  measured caret,
   selection and horizontal scrolling, and support mouse drag-selection,
   double-click select-all, Ctrl+Left/Right word jumps,
   Ctrl+Delete/Ctrl+Backspace word deletion and Ctrl+A select-all; typing or
@@ -451,6 +477,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   DMA channels never fetch until nouveau's full takeover (which re-programs the
   mode itself), the cursor staging registers are engine-only, and a channel
   that has run cannot be restarted — see the header of `nv50.c`.
+- **Panel backlight**: `backlight.c/h` — the Intel Cherryview/VLV display PWM
+  for the internal panel (the HP Chromebook 11 G5's `google/setzer` VBT
+  declares PWM controller 0, 200 Hz, active high).  It matches Intel
+  `8086:22b0`/`22b1`, maps the graphics MMIO BAR, reads `BLC_PWM_CTL2`
+  (`0x1E1250`, +`0x100` for pipe B) and `BLC_PWM_CTL` (`0x1E1254`), follows the
+  pipe the firmware enabled and falls back to controller 0; the period comes
+  from the firmware (`6000` = 19.2 MHz / (200 Hz × 16) when it reads zero).
+  The 10% steps clamp at 5..100% and the level is not persisted across a cold
+  boot.  `io.c` maps F6/F7 (the ChromeOS EC action row) and `E0 14`/`E0 15`
+  (standard brightness scancodes) to `backlight_step()` and consumes them.
+  The `backlight [0-100|up|down|probe]` kernel command is the other interface.
+  `struct wm_status` carries the level and a change counter
+  (`backlight_seq()`); the ring-3 WM shows a centered 3 s bubble with a
+  sun icon, the percentage and a bar after each change, and redraws it on
+  every pass while visible so a window cannot cover it.
+  The `keytest` kernel command drains the raw scancode tap in `io.c`
+  (E0/make/break/decoded) for key mapping.
 - **Text console**: `fbtext.c`, `font_8x8.c/h`, `io.c/h`, `screen.c/h` — 8×8 font,
   framebuffer glyph blitting (`fbtext_draw_cells`) and the boot-console cell
   buffer (`screen.c`, used by `io.c`'s fallback screen and `bootcon`).  The
@@ -628,8 +671,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   the selected driver's probe and leaves the current driver untouched on
   failure.  The top-bar network icon opens `ucmd_netmenu.c`, which lists every
   present driver through `SYS_NET_DEVLIST` (111), selects one through
-  `SYS_NET_SELECT` (112) and runs DHCP; the same window lists scanned WiFi
-  networks and asks for the WPA2 passphrase.  Hidden SSIDs are omitted, and
+  `SYS_NET_SELECT` (112) and runs DHCP; the same popover lists scanned WiFi
+  networks, marks the ones in `/data/WIFI.CFG` as saved, joins them with the
+  stored passphrase, and has a Saved view that forgets individual networks.
+  The panel is an ngui popover (a device status card, a scrollable
+  Devices/Wi-Fi/Connection content area with `ngui_section` and
+  `ngui_list_row`, and a footer status line); it opens as a `WIN_F_POPOVER`
+  canvas window anchored under the icon, not as a titled window.
+  Hidden SSIDs are omitted, and
   BSSIDs that share an SSID/security collapse to the strongest entry (the
   active BSSID wins while connected).  `wifi.c` (the Intel
   7265D/3165 netdev, see the WiFi bullet) is
@@ -707,27 +756,37 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   7265D-29 firmware does not use correctly installed `ADD_STA_KEY` keys for
   RX even though TX (which embeds the TK in `TX_CMD`) works; there is no
   software replay window yet.
-  The firmware is loaded on the first `wifi` command, not at boot.
+  The firmware is loaded on first use (`wifi` or the boot autoconnect
+  helper), not during kernel init.
   `netdev_shutdown()` always calls `wifi_shutdown()` before a kexec (the RX
   ring would keep writing into reused pages).  The ring-3 side is
   `ucmd_wifi.c` (`wifi`, `wifi up|scan|connect <ssid> [pass]|disconnect`,
   `wifi connectfile <path>` for the network menu's staged SSID/pass/BSSID
-  record, `wifi autoconnect` for the boot helper and `wifi forget`),
+  record, `wifi saved` to list the saved networks, `wifi autoconnect` for the
+  boot helper and `wifi forget [ssid]`),
   `wpa.c/h` (4-way + group handshake, key descriptor v2) and
   `wpa_crypto.c/h` (SHA-1, HMAC, PBKDF2, PRF, AES-128, RFC 3394 unwrap; host
   test `make test-wpa`).  After the handshake `wifi connect` installs the
   TK/GTK, calls `SYS_WIFI_AUTHORIZE` (data port open + `netdev_select
   ("wifi")`), runs DHCP and leaves `wifi __keep` running for group rekeys.
-  A successful menu/CLI connect also writes the SSID and passphrase to
-  `/data/WIFI.CFG` (8.3, plaintext, BSSID zeroed so a mesh/repeater AP works);
-  after the storage scan and the boot DHCP attempt the `bootscan` thread spawns
+  A successful menu/CLI connect stores the SSID and passphrase through
+  `wifi_store.c/h` in `/data/WIFI.CFG` (8.3, plaintext), a
+  most-recently-used list of up to `WIFI_CFG_MAX` (16) fixed records behind
+  a list header; the old one-record file is still read.  Re-connecting a
+  known SSID replaces its record and moves it to the front, and a full list
+  drops the least recently used network.  Each record leaves the BSSID zero
+  so a mesh/repeater AP with the same SSID still works.  After the storage
+  scan and the boot DHCP attempt the `bootscan` thread spawns
   `/ramfs/bin/wifi autoconnect` when that file exists.  Autoconnect leaves a
-  wired link that is physically up alone and only tries WiFi when no wired
-  link is present; an already-linked WiFi card is also left alone.  `/data`
-  is the persistent FAT volume from the installer.
-  `wifi forget` removes the saved record.  A FAT read may write a final
-  partial sector past the requested length, so the credential reader keeps
-  512 bytes of slack on the stack.
+  wired link that is physically up alone, and an already-linked WiFi card
+  too.  Otherwise it scans once and joins the strongest network present whose
+  SSID is in the saved list, moves on to the other saved networks found if
+  one fails, and rescans after three seconds for a second pass.  `/data` is
+  the persistent FAT volume from the installer.  `wifi forget` without an
+  SSID removes the whole list, `wifi forget <ssid>` one record; the network
+  menu marks saved SSIDs and its Saved view forgets them individually.  A FAT
+  read may write a final partial sector past the requested length, so the
+  credential reader keeps 512 bytes of slack on the stack.
   The helper's PTK and EAPOL replay counter are kept in the kernel
   (`SYS_WIFI_SET_PTK`/`SYS_WIFI_GET_PTK`) and fetched by connection ID, so
   the 64-byte `SYS_SPAWN` argument limit cannot truncate the rekey state.
@@ -841,7 +900,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   for the Braswell LPSS blocks (fast mode, component-type probe, explicit
   LPSS reset-release so the FIFO drains); `touchpad.c/h` — Elan
   HID-over-I2C touchpad on LPSS I2C6 at `0xD1327000`, slave `0x15`.
-  `touchpad_init()` runs from `mouse_init()` at boot (it maps the I2C
+  `touchpad_init()` runs from `mouse_init()` at boot, only when
+  `cpu_family_model()` is Airmont `0x64C` (elsewhere the fixed-address LPSS
+  scan would reset-cycle 32 MMIO windows that belong to nobody, ~64 ms, or
+  to another device); it maps the I2C
   window before processes clone the page directory), resets the device,
   consumes the 2-byte acknowledgement, reads the HID descriptor, selects
   absolute mode (`0x0300 = 1`), wakes it (`0x0800`) and then queries the
@@ -1093,7 +1155,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   copy, then `BROWSER` on `root.img`/IDE/SATA fat mounts.  The launcher
   forwards its argument and cwd.
   `uhttp.c/h` is the shared ring-3 HTTP client extracted from curl: URL
-  parsing/resolution, redirects, chunked decoding, timeouts and TLS; curl,
+  parsing/resolution (unsafe path bytes are percent-encoded; path
+  normalization stops at `?`/`#`), redirects, chunked decoding, timeouts
+  and TLS; curl,
   the browser and chat use it.  `browser_html.c/h` is a tolerant HTML tree + the
   CSS subset: external `<link rel=stylesheet>` sheets (in document order,
   inline `<style>` last), one selector engine shared by the cascade,
@@ -1219,7 +1283,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   arena, so a large image no longer reserves a fixed 24 MB.  `<script>`
   blocks are collected by `browser_html.c`; inline bodies run directly and
   `<script src>` bodies are fetched through the same local/network path as
-  pages and CSS (512 KB cap), in document order, through the vendored QuickJS
+  pages and CSS (2 MB cap), in document order, through the vendored QuickJS
   engine (`third_party/quickjs/`, 2026-06-04, ES2025: classes, arrow
   functions, `let`/`const`, template literals, destructuring, spread,
   async/await, Promise, Map/Set, BigInt, optional chaining; linked only
@@ -1267,7 +1331,41 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   libc math/time layers.  The parsed page is painted before scripts are
   fetched and run, and remote `<script src>` bodies are cached under
   `/share/bjs-*` for the current boot.  Classic scripts run sloppy by
-  default (`"use strict"` and private class fields work).  `cloneNode`
+  default (`"use strict"` and private class fields work).
+  `<script type="module">` runs as an ES module (`js_browser_run_module`,
+  `js_ploadmodule`): QuickJS's module loader resolves each specifier to an
+  absolute URL (module name = URL, so every module is evaluated once) and
+  loads it synchronously through `host.load_script` (the boot script cache,
+  else one blocking helper fetch with input pumping off, since the loader
+  runs inside JavaScript); `import()` and `import.meta.url` work, `nomodule`
+  scripts are skipped, and the page's `<link rel="modulepreload">` targets
+  are downloaded on all helpers in parallel into the script cache before any
+  script runs.  The 20 s budget restarts after every blocking fetch, so it
+  measures script time, not the network.  Unhandled promise rejections are
+  reported (`JS_SetHostPromiseRejectionTracker`), as Vite apps boot from an
+  async IIFE.  `js_prelude.js` (embedded by `js_prelude.S`, run once per
+  state before the page's scripts) implements the Web APIs in JavaScript on
+  three C primitives (`__nb_http`, `__nb_storage`, `__nb_resolve`):
+  `fetch`/`Request`/`Response`/`Headers`, `XMLHttpRequest`, `URL`/
+  `URLSearchParams`, `TextEncoder`/`TextDecoder`, `btoa`/`atob`, `Blob`/
+  `File`/`FormData` (urlencoded only), `AbortController`,
+  `localStorage`/`sessionStorage` (a Proxy, so `localStorage.token = x`
+  works), `crypto.getRandomValues`/`randomUUID`/`subtle.digest("SHA-256")`
+  (PKCE), inert `MutationObserver`/`ResizeObserver`/`IntersectionObserver`,
+  `instanceof`-able DOM classes (`HTMLElement`, `Node`, ...), and Element
+  methods (`closest`, `append`/`prepend`/`before`/`after`, `replaceWith`,
+  `insertAdjacentHTML`, `toggleAttribute`, `*AttributeNS`) on the node
+  wrappers' own prototype.  fetch()/XHR are synchronous inside a Promise:
+  `js_host_http` submits `X <method> <len> <ctype> <url>` to a helper and
+  returns the status and body whatever the HTTP status (2 MB response, 16 KB
+  request body).  Web Storage is stored in `/share/bls<origin-hash>`
+  (local, per boot) and `/share/bss<pid>-<origin-hash>` (session, per
+  window), outside the page heap that navigation resets.  `console.*` print
+  Error stacks.  `location.assign`/`replace`/`reload` navigate.  The
+  Cloudron dashboard (`my.<domain>`: a Vite/Vue 3 app, 12 modules / 3.5 MB)
+  boots, builds its PKCE request, and its OIDC login form renders, submits
+  through `fetch()` with the interaction cookie and shows the server's
+  verdict; the `authcallback.html` code exchange runs the same way.  `cloneNode`
   copies attributes to the clone (it used to stamp them onto the previous
   node, which broke every `ng-repeat`).
   `addEventListener`/`removeEventListener`/`dispatchEvent` dispatch real DOM
@@ -1288,14 +1386,22 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   since the floppy needs IRQ 6.
 - **Chat client**: `ucmd_chat.c` (`chat [config-path]`, top-bar `Chat`
   button) is a native Cloudron Chat client on ngui: channel/DM sidebar with
-  unread badges, presence dots and previews; a timeline with initial-letter
-  avatars, author grouping, UTC times, day headers, reply snippets and an
-  attachments/thread/reaction line; a composer; browse/join and new-DM
-  pickers.  It talks to the Chat REST API (`/api/me`, `/api/channels`,
-  `/api/dms`, `/api/channels/public`, `/api/users`, messages with
-  `?limit=50`, `&before=` and `&after=`, POST messages with a `clientId`,
-  `/read`, `/join`, `/api/dms`) through one `struct uhttp` with a cookie
-  jar.  No WebSocket: the open conversation is polled every 2 s (5 s
+  unread badges, presence dots and previews; a timeline with circular
+  profile-picture avatars (initials until the picture loads, or when there is
+  none), author grouping, UTC times, day headers, reply snippets, inline
+  image attachments/link-preview images and an attachments/thread/reaction
+  line; a composer; browse/join and new-DM pickers.  It talks to the Chat REST
+  API (`/api/me`, `/api/channels`, `/api/dms`, `/api/channels/public`,
+  `/api/users`, messages with `?limit=50`, `&before=` and `&after=`, POST
+  messages with a `clientId`, `/read`, `/join`, `/api/dms`) through one
+  `struct uhttp` with a cookie jar.  Message images and avatars use the same
+  uhttp connection and cookie jar, are fetched one per main-loop pass, and
+  are decoded by the in-tree image library (PNG/JPEG/GIF first
+  frame/BMP/TGA/PNM/ICO/PAM).  They live in a 16-entry, 6 MB message-image
+  LRU plus a 64-entry avatar cache.  The fetch is capped at 4 MB and the
+  decoder at 4 MP / 12 MB of scratch.
+
+  No WebSocket: the open conversation is polled every 2 s (5 s
   unfocused), the directory every 12 s (20 s), polling waits 1 s after
   input, and errors back off 2/5/10/30 s.  An open TCP socket pauses the
   netkexec watcher (`tcp_client_count()`), so keep-alive is kept only while
@@ -1312,8 +1418,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   is parsed and posted) and validating with `/api/me`.  External
   SSO and passkey accounts use the pasted-cookie screen.  The password is
   wiped after each attempt and never stored; the Chat host's cookie header
-  and the server go to `/share/chat.cfg` (or the given path) and are
-  re-saved when the server rolls the cookie.  `uhttp_cookie.c/h` is the jar
+  and the server go to `/data/CHAT.CFG` when the persistent `/data` mount
+  exists, otherwise `/share/chat.cfg` (or the given path), and are
+  re-saved when the server rolls the cookie.  A session left in the old
+  `/share/chat.cfg` is copied to `/data` once.  `uhttp_cookie.c/h` is the jar
   (24 host-only cookies, Path prefix match, Secure, Max-Age/1970-Expires
   deletion); uhttp stores every `Set-Cookie` (redirects too), sends matching
   cookies on each hop, splits requests/bodies into 1024-byte TLS records or
@@ -1328,8 +1436,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `img_png.c`, `img_bmp.c`, `img_gif.c`, `img_jpeg.c`, `img_tga.c`,
   `img_pnm.c`, `img_file.c/h` — freestanding RGB565 decoders with an optional
   8-bit alpha plane.  The codecs are independent of the OS and ngui: they take
-  an input buffer plus a caller-provided `struct img_mem` arena, so a browser
-  can link the same objects and decode HTTP bodies.  `inflate.c/h` (DEFLATE,
+  an input buffer plus a caller-provided `struct img_mem` arena, so the browser
+  and the chat client can link the same objects and decode HTTP bodies.  `inflate.c/h` (DEFLATE,
   zlib, gzip, CRC32/Adler32) is shared with the boot pack.  Its whole-buffer
   helpers (`inflate_gzip_mem`/`_zlib_mem`/`_raw_mem`, used by `ramfs_init`
   and the image decoders) are a separate fast path: 10-bit Huffman lookup
@@ -1339,12 +1447,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   with a source/sink and progress hook) keeps the bit-at-a-time decoder.  `img_sniff()` is a
   cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
   is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
-  over a checkerboard or over the destination (for a browser).  Progressive
+  over a checkerboard or over the destination (for the browser and chat).  Progressive
   JPEG (successive approximation), EXIF orientation, ICO/CUR, PAM and
   animated GIF frames are supported as well; arithmetic JPEG/CMYK are not.
   The viewer, `ucmd_view.c`, owns a canvas window and reads its file through
   `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size,
-  animates GIFs, and gives a clear error for unsupported variants.  Host
+  animates GIFs, and gives a clear error for unsupported variants.  The chat
+  client decodes fetched message images and avatars into a 480x320 / 32x32
+  cache and draws them with `img_draw()`.  Host
   tests: `make test-images` (`img_test.c`, corpus in `testdata/images/`,
   generator `tools/gen_img_tests.py`).
 - **Network service**: `sys_net.c/h` — the NIC and the stack stay in the
@@ -1408,7 +1518,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk), `install <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]`, `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), 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]`, `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
 
 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
@@ -1920,7 +2030,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 7. `display` (needs a GPU snapshot) and `lsusb` (a 45-byte wrapper around
    the USB tree printer) are the last non-privileged commands still living in
    the kernel, plus the privileged ones (`peek`, `poke`, `dbg`, `serial`,
-   `kexec`, `reboot`, `poweroff`, `format`, `install`, `ps`/`kill`).
+   `kexec`, `reboot`, `poweroff`, `format`, `install`, `ps`/`kill`,
+   `backlight`/`keytest`).
 8. The rootfs pack is inflated into one contiguous page-allocated run at
    boot, capped by `RAMFS_MAX_DECOMPRESSED` (8 MB); a larger pack fails to
    load (the USB rootfs partition is 8 MB, so this only bites if the cap is
@@ -1932,11 +2043,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    with `--gc-sections`; the current full pack with the UI fonts, both
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
-   bytes) and `install/kernel.bin` is ~1.75 MiB gzip (1,832,893
-   bytes, ~264 KB under the cap), inflating to ~3.6 MB, which adds about
+   bytes) and `install/kernel.bin` is ~1.75 MiB gzip (~260 KB under the
+   cap), inflating to ~3.6 MB, which adds about
    half a second to the boot; the floppy lite pack is ~930 KiB gzip and
    deliberately omits the firmware and `install/kernel.bin`.  `libdeflate-gzip -12` is still preferred.  Over
-   115200 serial a raw `cmds-dev` pack (2.6 MB) now takes about three
+   115200 serial a raw `cmds-dev` pack (3.5 MiB) now takes about four
    minutes; use `net-cmds`.
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
     board that exposes only MP tables stays UP (deliberate; there is no test
@@ -2007,9 +2118,20 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `once`/`passive` options.  POST uses
     `application/x-www-form-urlencoded`; a redirected POST follows as GET,
     and `enctype=multipart/form-data` plus file inputs are unsupported.
-    Also missing: `type="module"`,
-    `defer`/`async`, `MutationObserver`/`IntersectionObserver`,
-    `XMLHttpRequest`/`fetch`, `DOMParser`, canvas/2D contexts, user-state
+    ES modules, `fetch`/`XMLHttpRequest` and Web Storage work (see the
+    browser bullet) with these limits: fetch()/XHR block the page while they
+    run (no streaming bodies, no upload progress), `FormData` is sent
+    urlencoded (no multipart/files), only `Content-Type` is forwarded from
+    request headers, response headers other than `Content-Type` are not
+    exposed, bodies are text (Latin-1/UTF-8, no binary `arrayBuffer`),
+    CORS is not enforced, and the observers never fire.  Module loading is
+    sequential apart from the modulepreload pass.  `crypto` entropy is the
+    weak Math.random/clock mix (fine for PKCE nonces, like the TLS DRBG).
+    On QEMU's NE2000 the four parallel module downloads can overrun its
+    small RX ring and stall TLS handshakes into a 10 s timeout; use e1000.
+    Also missing: `defer`/`async` ordering, `DOMParser`/
+    `document.implementation.createDocument` (DOMPurify throws, so the
+    Cloudron login footer is not rendered), canvas/2D contexts, user-state
     pseudo-classes (`:hover`, `:focus`, ...), `:nth-child(... of S)` and
     pseudo-elements other than `::before`/`::after`; generated content is
     text only (no box, background, counters or `url()` images, and
@@ -2240,10 +2362,13 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     TOTP; passkeys and external SSO need the pasted `connect.sid` cookie.
     The login depends on Cloudron's `cloudron-config` login API
     (`chat_login.c` isolates it).  TLS is not verified (the login screen
-    says so), and the saved cookie in `/share/chat.cfg` is a bearer
-    credential (RAM-only unless a FAT path is chosen; concurrent chat
-    windows share the file).  No threads, reactions, polls, search,
-    attachments/images/GIFs, edits or deletes beyond what a reload shows;
+    says so), and the saved cookie in `/data/CHAT.CFG` (or
+    `/share/chat.cfg` without a `/data` mount) is a bearer credential
+    (persistent on `/data`, RAM-only on `/share`; concurrent chat windows
+    share the file).  No threads, reactions, polls, search, edits or deletes
+    beyond what a reload shows; image attachments and link-preview images
+    render inline up to the 4 MB fetch / 4 MP decode caps (first GIF frame;
+    WebP/AVIF/SVG are not decoded), file attachments are still text-only,
     messages over 4 KB are truncated, history holds 240 messages, times are
     UTC and text is Latin-1.  Network calls block the UI for their duration.
 
@@ -2279,16 +2404,23 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 36. Network menu limits (`ucmd_netmenu.c`): building the device list probes
     every driver, so opening the menu on a machine with an unconfigured USB
     NIC can take a moment (USB control transfers) and may initialize a device
-    that was not the boot-time winner.  The list shows at most six device
-    rows, one menu instance is kept open by the WM, and WiFi scanning is
-    refused while associated (use Disconnect first).  The staged
+    that was not the boot-time winner.  The panel shows at most four device
+    rows plus a "+N more devices" line, one menu instance is kept open by the
+    WM, and WiFi scanning is refused while associated (use Disconnect first).
+    The popover is a 404x520 canvas (with 380x440 and 340x360 fallbacks); the
+    content area scrolls, the connection card can be scrolled away in a long
+    Wi-Fi list, and closing the panel with an outside click kills the netmenu
+    process without cancelling an already started `wifi` helper.  The staged
     `/share/netmenu.wifi` record contains the WPA2 passphrase until the
     `wifi` helper reads and unlinks it; the path is fixed, so two concurrent
     netmenu instances (e.g. one launched from a terminal) would overwrite
     each other.  The `wifi` helper is asynchronous: closing the menu does not
     cancel a connection attempt.  Saved credentials live in plaintext
-    `/data/WIFI.CFG` (8.3), hold one network, and are retried at boot; use
-    `wifi forget` to remove them.  There is no menu button for forgetting yet.
+    `/data/WIFI.CFG` (8.3), hold up to 16 networks, and are retried at boot;
+    `wifi saved` lists them, `wifi forget [ssid]` removes one and the menu's
+    Saved view has a Forget button per network.  A network saved with a wrong
+    passphrase is tried again at every boot until it is forgotten (Saved view
+    or `wifi forget <ssid>`) and joined again with the correct passphrase.
 
 37. `/data` limits: the data partition is a plain FAT volume, so file names
     are 8.3 until `fat.c` gains LFN write support; there is no fsck, resize or

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 33 - 13
Makefile


+ 241 - 0
backlight.c

@@ -0,0 +1,241 @@
+/* Intel Cherryview/VLV display PWM panel backlight.
+ *
+ * Braswell/Cherryview (and Bay Trail/Valleyview) drive the internal panel
+ * backlight from the display engine, not from the Chrome EC.  The VBT
+ * (block 43, LFP backlight) on google/setzer selects PWM controller 0 at
+ * 200 Hz, active high.  Linux drives the same registers from i915
+ * (vlv_setup_backlight()/vlv_set_backlight()):
+ *
+ *   BLC_PWM_CTL2  pipe A  VLV_DISPLAY_BASE + 0x61250  (0x1E1250)
+ *   BLC_PWM_CTL   pipe A  VLV_DISPLAY_BASE + 0x61254  (0x1E1254)
+ *   pipe B adds 0x100.
+ *
+ * BLC_PWM_CTL2 bit 31 enables the PWM, bit 28 is the polarity.
+ * BLC_PWM_CTL bits 31:16 are the period and bits 15:0 the duty cycle.
+ *
+ * The PWM clock is 19.2 MHz with a fixed /16 increment on Cherryview, so
+ * 200 Hz is a period of 6000.  At probe time the period the firmware left
+ * in the register wins; 6000 is only the fallback when it reads as zero.
+ */
+#include "backlight.h"
+#include "paging.h"
+#include "pci.h"
+#include "serial.h"
+
+#define INTEL_CHV_GFX_B0	0x22b0
+#define INTEL_CHV_GFX_C0	0x22b1
+
+#define VLV_DISPLAY_BASE	0x180000u
+#define VLV_BLC_PWM_CTL2(pipe)	(VLV_DISPLAY_BASE + 0x61250u + \
+				 ((pipe) ? 0x100u : 0u))
+#define VLV_BLC_PWM_CTL(pipe)	(VLV_DISPLAY_BASE + 0x61254u + \
+				 ((pipe) ? 0x100u : 0u))
+
+#define BLM_PWM_ENABLE		(1u << 31)
+#define BLC_DUTY_MASK		0xFFFFu
+#define BLC_MIN_PERCENT		5
+#define BLC_STEP_PERCENT	10
+#define BLC_DEFAULT_PERIOD	6000u	/* 19.2 MHz / (200 Hz * 16) */
+
+static unsigned int blc_bar;
+static unsigned int blc_pipe;
+static unsigned int blc_period;
+static unsigned int blc_duty;
+static int blc_level;
+static int blc_present;
+static int blc_enabled;
+static unsigned int blc_seq;	/* bumped on every user-visible change */
+
+static unsigned int blc_read(unsigned int reg)
+{
+	return *(volatile unsigned int *)(blc_bar + reg);
+}
+
+static void blc_write(unsigned int reg, unsigned int val)
+{
+	*(volatile unsigned int *)(blc_bar + reg) = val;
+}
+
+void backlight_init(unsigned int bus, unsigned int dev, unsigned int device_id)
+{
+	unsigned int bar0, ctl2[2], ctl[2], period, duty, i;
+	int pipe, a_ok, b_ok;
+
+	blc_bar = 0;
+	blc_pipe = 0;
+	blc_period = 0;
+	blc_duty = 0;
+	blc_level = 0;
+	blc_present = 0;
+	blc_enabled = 0;
+
+	if (device_id != INTEL_CHV_GFX_B0 && device_id != INTEL_CHV_GFX_C0)
+		return;
+
+	bar0 = pci_cfg_read32(bus, dev, 0, 0x10);
+	if (bar0 & 1)
+		return;			/* I/O BAR, not MMIO */
+	if (!(bar0 & 0xFFFFFFF0u))
+		return;
+	if ((bar0 & 0x6) == 0x4 &&
+	    pci_cfg_read32(bus, dev, 0, 0x14) != 0)
+		return;			/* 64-bit BAR above 4 GB */
+
+	/* The backlight registers live below 2 MB in the display MMIO BAR. */
+	blc_bar = bar0 & 0xFFFFFFF0u;
+	paging_map_mmio(blc_bar, 0x200000);
+
+	for (i = 0; i < 2; i++) {
+		ctl2[i] = blc_read(VLV_BLC_PWM_CTL2(i));
+		ctl[i] = blc_read(VLV_BLC_PWM_CTL(i));
+	}
+
+	a_ok = !(ctl2[0] == 0xFFFFFFFFu && ctl[0] == 0xFFFFFFFFu);
+	b_ok = !(ctl2[1] == 0xFFFFFFFFu && ctl[1] == 0xFFFFFFFFu);
+	if (!a_ok && !b_ok) {
+		serial_puts(SERIAL_COM1, "backlight: no display MMIO\n");
+		return;
+	}
+
+	/* Follow the pipe the firmware enabled; when both or neither are
+	 * enabled, use the active display plane; otherwise fall back to the
+	 * VBT's controller 0 (pipe A).  The internal panel is normally on A. */
+	pipe = 0;
+	if (!a_ok) {
+		pipe = 1;
+	} else if (b_ok &&
+		   (ctl2[0] & BLM_PWM_ENABLE) == (ctl2[1] & BLM_PWM_ENABLE)) {
+		unsigned int dspa = blc_read(VLV_DISPLAY_BASE + 0x70180);
+		unsigned int dspb = blc_read(VLV_DISPLAY_BASE + 0x71180);
+
+		if (!(dspa & (1u << 31)) && (dspb & (1u << 31)))
+			pipe = 1;
+	} else if (b_ok && (ctl2[1] & BLM_PWM_ENABLE)) {
+		pipe = 1;
+	}
+
+	period = ctl[pipe] >> 16;
+	if (!period)
+		period = BLC_DEFAULT_PERIOD;
+	duty = ctl[pipe] & BLC_DUTY_MASK;
+	if (duty > period)
+		duty = period;
+
+	blc_pipe = (unsigned int)pipe;
+	blc_period = period;
+	blc_duty = duty;
+	blc_level = (int)((duty * 100u + period / 2u) / period);
+	if (blc_level > 100)
+		blc_level = 100;
+	if (blc_level < BLC_MIN_PERCENT)
+		blc_level = BLC_MIN_PERCENT;
+	blc_enabled = (ctl2[pipe] & BLM_PWM_ENABLE) != 0;
+	blc_present = 1;
+
+	serial_puts(SERIAL_COM1, "backlight: CHV PWM pipe ");
+	serial_puts(SERIAL_COM1, pipe ? "B" : "A");
+	serial_puts(SERIAL_COM1, ", period ");
+	serial_putdec(SERIAL_COM1, period);
+	serial_puts(SERIAL_COM1, ", duty ");
+	serial_putdec(SERIAL_COM1, duty);
+	serial_puts(SERIAL_COM1, " (");
+	serial_putdec(SERIAL_COM1, (unsigned int)blc_level);
+	serial_puts(SERIAL_COM1, "%), ");
+	serial_puts(SERIAL_COM1, blc_enabled ? "enabled" : "disabled");
+	serial_puts(SERIAL_COM1, ", ctl2 ");
+	serial_puthex(SERIAL_COM1, ctl2[0]);
+	serial_puthex(SERIAL_COM1, ctl2[1]);
+	serial_puts(SERIAL_COM1, ", ctl ");
+	serial_puthex(SERIAL_COM1, ctl[0]);
+	serial_puthex(SERIAL_COM1, ctl[1]);
+	serial_puts(SERIAL_COM1, "\n");
+}
+
+int backlight_present(void)
+{
+	return blc_present;
+}
+
+int backlight_percent(void)
+{
+	return blc_present ? blc_level : -1;
+}
+
+unsigned int backlight_seq(void)
+{
+	return blc_seq;
+}
+
+void backlight_set_percent(int percent)
+{
+	unsigned int ctl2, duty;
+
+	if (!blc_present)
+		return;
+	if (percent < BLC_MIN_PERCENT)
+		percent = BLC_MIN_PERCENT;
+	if (percent > 100)
+		percent = 100;
+	blc_seq++;
+
+	duty = (blc_period * (unsigned int)percent + 50u) / 100u;
+	if (duty > blc_period)
+		duty = blc_period;
+	if (percent && !duty)
+		duty = 1;
+
+	if (!blc_enabled) {
+		ctl2 = blc_read(VLV_BLC_PWM_CTL2(blc_pipe));
+		blc_write(VLV_BLC_PWM_CTL2(blc_pipe), ctl2 & ~BLM_PWM_ENABLE);
+		blc_write(VLV_BLC_PWM_CTL(blc_pipe),
+			  (blc_period << 16) | duty);
+		(void)blc_read(VLV_BLC_PWM_CTL(blc_pipe));
+		blc_write(VLV_BLC_PWM_CTL2(blc_pipe),
+			  (ctl2 & ~BLM_PWM_ENABLE) | BLM_PWM_ENABLE);
+		(void)blc_read(VLV_BLC_PWM_CTL2(blc_pipe));
+		blc_enabled = 1;
+	} else {
+		blc_write(VLV_BLC_PWM_CTL(blc_pipe),
+			  (blc_period << 16) | duty);
+		(void)blc_read(VLV_BLC_PWM_CTL(blc_pipe));
+	}
+
+	blc_duty = duty;
+	blc_level = percent;
+}
+
+void backlight_step(int dir)
+{
+	int level;
+
+	if (!blc_present)
+		return;
+	level = blc_level + (dir > 0 ? BLC_STEP_PERCENT : -BLC_STEP_PERCENT);
+	backlight_set_percent(level);
+}
+
+int backlight_status(struct backlight_status *out)
+{
+	unsigned int i;
+
+	if (!out)
+		return -1;
+	for (i = 0; i < sizeof(*out); i++)
+		((unsigned char *)out)[i] = 0;
+	out->present = blc_present;
+	if (!blc_present)
+		return -1;
+
+	out->level = blc_level;
+	out->enabled = blc_enabled;
+	out->pipe = blc_pipe;
+	out->period = blc_period;
+	out->duty = blc_duty;
+	out->bar = blc_bar;
+	/* Keep the two pipe snapshots live for the `backlight probe` dump. */
+	out->ctl2[0] = blc_read(VLV_BLC_PWM_CTL2(0));
+	out->ctl2[1] = blc_read(VLV_BLC_PWM_CTL2(1));
+	out->ctl[0] = blc_read(VLV_BLC_PWM_CTL(0));
+	out->ctl[1] = blc_read(VLV_BLC_PWM_CTL(1));
+	return 0;
+}

+ 44 - 0
backlight.h

@@ -0,0 +1,44 @@
+/* Intel Cherryview/VLV display-engine panel backlight.
+ *
+ * The internal panel's PWM lives in the graphics MMIO BAR, not on the
+ * Chrome EC: BLC_PWM_CTL2 enables it and BLC_PWM_CTL holds the period and
+ * duty cycle.  The HP Chromebook 11 G5 (google/setzer, Braswell) VBT
+ * declares PWM controller 0, 200 Hz, active high.
+ */
+#ifndef BACKLIGHT_H
+#define BACKLIGHT_H
+
+struct backlight_status {
+	int present;
+	int level;              /* percent, 5..100 */
+	int enabled;
+	unsigned int pipe;      /* 0 = A, 1 = B */
+	unsigned int period;    /* raw PWM period from BLC_PWM_CTL */
+	unsigned int duty;      /* raw duty from BLC_PWM_CTL */
+	unsigned int bar;       /* graphics MMIO BAR0 base */
+	unsigned int ctl2[2];   /* raw BLC_PWM_CTL2 for pipes A and B */
+	unsigned int ctl[2];    /* raw BLC_PWM_CTL for pipes A and B */
+};
+
+/* Called from gpu_init() for the active Intel adapter; no-op elsewhere. */
+void backlight_init(unsigned int bus, unsigned int dev, unsigned int device_id);
+
+int backlight_present(void);
+
+/* Current brightness in percent, or -1 when no panel PWM was found. */
+int backlight_percent(void);
+
+/* Monotonic change counter, bumped by every successful set/step.  The WM
+ * uses it to pop the brightness OSD without polling the registers. */
+unsigned int backlight_seq(void);
+
+/* Clamped to 5..100. */
+void backlight_set_percent(int percent);
+
+/* Step by 10 percent; dir > 0 is brighter. */
+void backlight_step(int dir);
+
+/* Fill the status snapshot used by the `backlight` command. */
+int backlight_status(struct backlight_status *out);
+
+#endif

+ 42 - 21
boot.S

@@ -69,24 +69,27 @@ load_kernel:
 	movw  $0x07e0, %ax
 	movw  %ax, %es
 
-	/* EDD reads up to 64 sectors per INT 13h into ES:0 and then advances
-	 * ES, so the offset never wraps (one call per sector made the kernel
-	 * load ~700 BIOS calls).  CHS (floppy) stays at one sector: a longer
-	 * transfer could cross a 64 KB ISA DMA boundary. */
+	/* One INT 13h per run of sectors into ES:0, then ES advances, so the
+	 * offset never wraps.  EDD reads up to 64 sectors; CHS (floppy) reads
+	 * up to the end of the track and never across a 64 KB physical ISA
+	 * DMA boundary (the buffer starts 512-byte aligned at 0x7E00).  One
+	 * call per sector made the kernel load ~700 BIOS calls, each of which
+	 * can cost a full floppy revolution.  Errors: three tries per run,
+	 * then one sector per call (the old behaviour), three tries again,
+	 * then "Disk read error". */
 load_loop:
 	testw %cx, %cx
 	jz    load_done
 	pushw %cx
 	pushw %si
-	movw  $1, %ax
-	movb  boot_drive, %dl
-	cmpb  $0x80, %dl
-	jb    read_chs
 	movw  %cx, %ax
 	cmpw  chunk_max, %ax
 	jbe   1f
 	movw  chunk_max, %ax
-1:	movw  %ax, cur_count
+1:	movb  boot_drive, %dl
+	cmpb  $0x80, %dl
+	jb    read_chs
+	movw  %ax, cur_count
 	movw  %ax, 0x502
 	xorw  %ax, %ax
 	movw  %ax, 0x504
@@ -101,11 +104,24 @@ load_loop:
 	movb  $0x42, %ah
 	jmp   do_int13
 read_chs:
-	movw  %ax, cur_count
-	movw  %si, %ax
+	movw  %ax, %bx            /* bx = sectors to read */
+	movw  %es, %ax
+	shlw  $4, %ax             /* low 16 bits of the physical address */
+	negw  %ax                 /* bytes to the next 64 KB boundary */
+	shrw  $9, %ax
+	jz    3f                  /* 0: a whole 64 KB window is free */
+	cmpw  %ax, %bx
+	jbe   3f
+	movw  %ax, %bx
+3:	movw  %si, %ax
 	xorw  %dx, %dx
 	movw  $18, %di
-	divw  %di
+	divw  %di                 /* ax = track index, dx = sector - 1 */
+	subw  %dx, %di            /* sectors left on this track */
+	cmpw  %di, %bx
+	jbe   4f
+	movw  %di, %bx
+4:	movw  %bx, cur_count
 	movb  %dl, %cl
 	incb  %cl
 	xorw  %dx, %dx
@@ -115,23 +131,26 @@ read_chs:
 	movb  %al, %ch
 	movb  boot_drive, %dl
 	movb  $0x02, %ah
-	movb  $1, %al
+	movb  %bl, %al
 	xorw  %bx, %bx
 do_int13:
 	int   $0x13
 	popw  %si
 	popw  %cx
 	jnc   2f
-	/* A BIOS that refuses a multi-sector EDD read: reset the drive and
-	 * continue one sector per call (the old behaviour). */
-	cmpw  $1, cur_count
-	je    read_error
-	movw  $1, chunk_max
-	movb  boot_drive, %dl
+	movb  boot_drive, %dl     /* reset the drive, then retry */
 	xorw  %ax, %ax
 	int   $0x13
+	incb  tries
+	cmpb  $3, tries
+	jb    load_loop
+	movb  $0, tries
+	cmpw  $1, chunk_max
+	je    read_error
+	movw  $1, chunk_max       /* multi-sector refused: old behaviour */
 	jmp   load_loop
-2:	movw  cur_count, %ax
+2:	movb  $0, tries
+	movw  cur_count, %ax
 	addw  %ax, %si
 	subw  %ax, %cx
 	shlw  $5, %ax
@@ -155,6 +174,8 @@ chunk_max:
 	.word 64
 cur_count:
 	.word 0
+tries:
+	.byte 0
 
 /* INT 13h error: say so instead of halting silently. */
 read_error:
@@ -185,7 +206,7 @@ boot_msg:
 loading_msg:
 	.asciz "Loading kernel...\r\n"
 loaded_msg:
-	.asciz "Kernel loaded, starting...\r\n"
+	.asciz "Kernel loaded\r\n"
 disk_err_msg:
 	.asciz "Disk read error\r\n"
 

+ 510 - 37
browser.c

@@ -51,14 +51,16 @@ static unsigned int decode_arena_size;
 #define BR_IMG_JOB_TIMEOUT_MS 30000u
 #define BR_CSS_MAX      (832u * 1024u)
 #define BR_CSS_COMP_MAX (192u * 1024u)
-#define BR_SCRIPT_MAX   (512u * 1024u)
+/* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
+ * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
+#define BR_SCRIPT_MAX   (2u * 1024u * 1024u)
 #define FETCH_ABORT     (-2)
 /* Session cache for remote stylesheets (per launch; cleared at startup). */
 #define CSS_CACHE_MAX      16
 #define CSS_CACHE_FILE_MAX (256u * 1024u)
 #define CSS_CACHE_PREFIX   "bcss-"
-#define SCRIPT_CACHE_MAX      16
-#define SCRIPT_CACHE_FILE_MAX (512u * 1024u)
+#define SCRIPT_CACHE_MAX      24
+#define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
 #define SCRIPT_CACHE_PREFIX   "bjs-"
 #define BR_MAX_SHEETS   6
 #define BR_HISTORY      16
@@ -164,6 +166,9 @@ static char pending_url[BR_URL_MAX];
 #define BR_POST_MAX 4096
 static char pending_post[BR_POST_MAX];
 static unsigned int pending_post_len;
+/* The pending navigation is a POST even when its body is empty (a form
+ * without fields, e.g. the OIDC consent auto-submit). */
+static int pending_post_is;
 static unsigned int pending_action;
 static int cancel_fetch;
 static int quit;
@@ -1163,9 +1168,25 @@ static int fetch_worker_read_body(struct fetch_worker *w,
 				  int *truncated, char *err,
 				  unsigned int errcap);
 static void fetch_workers_stop_all(void);
+static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
+				   unsigned int cap, const char *method,
+				   const char *ctype, const char *post,
+				   unsigned int post_len, unsigned int node,
+				   int bg, char *err, unsigned int errcap);
 static int script_cache_has(const char *url);
 static void script_cache_put(const char *url, const unsigned char *data,
 			     unsigned int len);
+static unsigned int script_cache_hash(const char *s);
+static int fetch_worker_poll(struct fetch_worker *w, char *err,
+			     unsigned int errcap);
+static void fetch_workers_cancel_busy(void);
+static void worker_wait_ui(void);
+static int fetch_worker_status(const struct fetch_worker *w);
+
+/* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
+ * module load: the wait must not pump input, or a click would dispatch DOM
+ * events into the middle of the running script. */
+static int fetch_wait_passive;
 
 static void script_error(const char *what, const char *url, const char *why)
 {
@@ -1184,6 +1205,206 @@ static void script_error(const char *what, const char *url, const char *why)
 	js_host_report(msg);
 }
 
+/* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
+
+/* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
+ * body (FETCH_POST_MAX in ucmd_curl.c). */
+#define JS_HTTP_MAX      (2u * 1024u * 1024u)
+#define JS_HTTP_POST_MAX (16u * 1024u)
+
+/* struct fetch_meta / fetch_worker internals come later in the file. */
+static int js_worker_http(const char *method, const char *url,
+			  const char *ctype, const char *body,
+			  unsigned int body_len, struct js_http_resp *r,
+			  char *err, int errcap);
+
+static int js_host_http(const char *method, const char *url,
+			const char *ctype, const char *body,
+			unsigned int body_len, struct js_http_resp *r,
+			char *err, int errcap)
+{
+	if (pending_action) {
+		s_copy(err, "page is navigating", (unsigned int)errcap);
+		return -1;
+	}
+	if (url[0] == '/') {
+		/* Local file: GET only. */
+		unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
+		int rv;
+
+		if (!buf) {
+			s_copy(err, "out of memory", (unsigned int)errcap);
+			return -1;
+		}
+		rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
+				(int)JS_HTTP_MAX);
+		r->status = rv < 0 ? 404 : 200;
+		r->len = rv < 0 ? 0 : (unsigned int)rv;
+		buf[r->len] = '\0';
+		r->body = (char *)buf;
+		s_copy(r->url, url, sizeof(r->url));
+		if (contains_ci(url, ".json"))
+			s_copy(r->ctype, "application/json", sizeof(r->ctype));
+		return 0;
+	}
+	if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
+		s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
+		return -1;
+	}
+	if (body_len > JS_HTTP_POST_MAX) {
+		s_copy(err, "request body too large", (unsigned int)errcap);
+		return -1;
+	}
+	return js_worker_http(method, url, ctype, body, body_len, r, err,
+			      errcap);
+}
+
+/* Module source for the engine's loader: the boot script cache first, then
+ * one blocking fetch with input pumping disabled (the loader runs inside
+ * JavaScript). */
+static char *js_host_load_script(const char *url, unsigned int *len)
+{
+	unsigned char *data = 0;
+	char err[64];
+	int rv;
+
+	fetch_wait_passive++;
+	set_status("Loading module...", 0, 0);
+	rv = fetch_script_text(url, &data, len, err, sizeof(err));
+	fetch_wait_passive--;
+	if (rv != 0) {
+		script_error("Cannot load module", url,
+			     rv == FETCH_ABORT ? "navigation" : err);
+		return 0;
+	}
+	return (char *)data;
+}
+
+/* Web Storage lives in /share, outside the page heap that every navigation
+ * resets: localStorage per origin for the boot, sessionStorage per origin
+ * and browser window. */
+static void js_storage_path(int kind, char *out, unsigned int cap)
+{
+	char origin[160];
+	unsigned int n = 0, i = 0, slashes = 0;
+
+	while (page_url[i] && i + 1 < sizeof(origin)) {
+		if (page_url[i] == '/' && ++slashes == 3)
+			break;
+		origin[i] = page_url[i];
+		i++;
+	}
+	origin[i] = '\0';
+	s_append(out, &n, kind ? "/share/bss" : "/share/bls", cap);
+	if (kind) {
+		s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
+		s_append(out, &n, "-", cap);
+	}
+	s_append_dec(out, &n, script_cache_hash(origin), cap);
+}
+
+static int js_host_storage(int kind, const char *set, char *out, int cap)
+{
+	char path[48];
+	int rv;
+
+	js_storage_path(kind, path, sizeof(path));
+	if (set) {
+		if (!set[0] || !strcmp(set, "{}")) {
+			u_syscall1(SYS_UNLINK, (int)path);
+			return 0;
+		}
+		return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
+				  (int)strlen(set)) < 0 ? -1 : 0;
+	}
+	rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
+	if (rv < 0)
+		return -1;
+	out[rv] = '\0';
+	return rv;
+}
+
+/* <link rel="modulepreload">: download the page's module graph on all
+ * helpers at once into the boot script cache, before any script runs.  The
+ * engine's module loader is sequential (one blocking fetch per import), so
+ * without this a Vite app with a dozen chunks pays every round trip in a
+ * row.  Failures are ignored; the loader fetches what is missing. */
+#define MODULE_PRELOAD_MAX 24
+
+static void prefetch_module_preloads(void)
+{
+	static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
+	struct fetch_worker *slot[MODULE_PRELOAD_MAX];
+	unsigned int count = 0, next = 0, done = 0, i;
+	char err[64];
+
+	for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
+		struct br_node *nd = &doc.nodes[i];
+		const char *rel, *href;
+
+		if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
+			continue;
+		rel = br_rel(&doc, i);
+		href = br_href(&doc, i);
+		if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
+			continue;
+		if (resolve_link(page_url, href, urls[count],
+				 sizeof(urls[count])) != 0 ||
+		    urls[count][0] == '/' || script_cache_has(urls[count]))
+			continue;
+		slot[count++] = 0;
+	}
+	if (!count)
+		return;
+	set_status("Loading modules...", 0, 0);
+	while (done < count) {
+		struct fetch_worker *w;
+
+		while (next < count && (w = fetch_worker_alloc()) != 0) {
+			if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
+						0, 0, 0, err,
+						sizeof(err)) != 0) {
+				fetch_worker_release(w);
+				done++;
+			} else {
+				slot[next] = w;
+			}
+			next++;
+		}
+		worker_wait_ui();
+		if (cancel_fetch || pending_action) {
+			fetch_workers_cancel_busy();
+			return;
+		}
+		for (i = 0; i < next; i++) {
+			unsigned char *body;
+			int rv, tr = 0;
+
+			if (!slot[i])
+				continue;
+			rv = fetch_worker_poll(slot[i], err, sizeof(err));
+			if (rv == 0)
+				continue;
+			body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
+			       (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
+			if (body) {
+				rv = fetch_worker_read_body(slot[i], body,
+					BR_SCRIPT_MAX, image_io_buf,
+					BR_PAGE_COMP_MAX, &tr, err,
+					sizeof(err));
+				if (rv > 0 && !tr)
+					script_cache_put(urls[i], body,
+							 (unsigned int)rv);
+				free(body);
+			}
+			fetch_worker_release(slot[i]);
+			slot[i] = 0;
+			done++;
+		}
+		u_sleep_ms(10);
+	}
+}
+
 /* Script prefetch state: one entry per <script> block.  Remote bodies are
  * submitted to helper workers ahead of time, but scripts still execute in
  * document order. */
@@ -1248,6 +1469,9 @@ static void run_page_scripts(void)
 	host.form_reset = js_host_form_reset;
 	host.click = js_host_click;
 	host.computed = js_host_computed;
+	host.http = js_host_http;
+	host.load_script = js_host_load_script;
+	host.storage = js_host_storage;
 	host.page_url = page_url;
 	host.width = ui.w;
 	host.height = ui.h;
@@ -1255,6 +1479,7 @@ static void run_page_scripts(void)
 		js_host_status("JavaScript: out of memory", 1);
 		return;
 	}
+	prefetch_module_preloads();
 
 	for (i = 0; i < doc.nscripts; i++) {
 		struct br_script *script = &doc.scripts[i];
@@ -1297,7 +1522,21 @@ static void run_page_scripts(void)
 			for (k = 0; k < len; k++)
 				src[k] = doc.script_src[off + k];
 			src[len] = '\0';
-			js_browser_run(src, page_url);
+			if (script->module) {
+				/* A distinct module name per inline module
+				 * (QuickJS registers modules by name); the
+				 * fragment keeps relative imports resolving
+				 * against the page. */
+				char mname[BR_URL_MAX + 16];
+				unsigned int mn = 0;
+
+				s_append(mname, &mn, page_url, sizeof(mname));
+				s_append(mname, &mn, "#module", sizeof(mname));
+				s_append_dec(mname, &mn, i, sizeof(mname));
+				js_browser_run_module(src, mname);
+			} else {
+				js_browser_run(src, page_url);
+			}
 			free(src);
 		} else if (script->src_off) {
 			const char *src_attr = doc.attrs + script->src_off;
@@ -1324,11 +1563,17 @@ static void run_page_scripts(void)
 						     script_urls[i], err);
 					continue;
 				}
-				js_browser_run((const char *)data,
-					       script_urls[i]);
+				if (script->module)
+					js_browser_run_module(
+						(const char *)data,
+						script_urls[i]);
+				else
+					js_browser_run((const char *)data,
+						       script_urls[i]);
 				free(data);
 			} else {
 				struct fetch_worker *w = script_slot[i];
+				unsigned char *body = 0;
 				int tr = 0, rv;
 
 				if (!w) {
@@ -1356,14 +1601,22 @@ static void run_page_scripts(void)
 					fetch_workers_stop_all();
 					break;
 				}
-				if (rv == 0)
-					rv = fetch_worker_read_body(w,
-						image_io_buf, BR_SCRIPT_MAX,
-						image_io_buf + BR_SCRIPT_MAX,
-						BR_IMG_FILE_MAX, &tr, err,
+				/* The body gets its own buffer (scripts are up
+				 * to 2 MB); image_io_buf takes the gzip
+				 * stream. */
+				body = rv == 0 ? (unsigned char *)malloc(
+					BR_SCRIPT_MAX + 1) : 0;
+				if (body)
+					rv = fetch_worker_read_body(w, body,
+						BR_SCRIPT_MAX, image_io_buf,
+						BR_PAGE_COMP_MAX, &tr, err,
 						sizeof(err));
-				else
+				else {
+					if (rv == 0)
+						s_copy(err, "out of memory",
+						       sizeof(err));
 					rv = -1;
+				}
 				fetch_worker_release(w);
 				script_slot[i] = 0;
 				script_submit_window(&next, ferr, sizeof(ferr));
@@ -1376,14 +1629,19 @@ static void run_page_scripts(void)
 						     script_urls[i],
 						     "script is too large");
 				else {
-					image_io_buf[rv] = '\0';
-					script_cache_put(script_urls[i],
-							 image_io_buf,
+					body[rv] = '\0';
+					script_cache_put(script_urls[i], body,
 							 (unsigned int)rv);
-					js_browser_run(
-						(const char *)image_io_buf,
-						script_urls[i]);
+					if (script->module)
+						js_browser_run_module(
+							(const char *)body,
+							script_urls[i]);
+					else
+						js_browser_run(
+							(const char *)body,
+							script_urls[i]);
 				}
+				free(body);
 			}
 		}
 		if (pending_action)
@@ -2308,12 +2566,36 @@ static struct fetch_worker *fetch_worker_alloc(void)
 	return 0;
 }
 
+static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
+				   unsigned int cap, const char *method,
+				   const char *ctype, const char *post,
+				   unsigned int post_len, unsigned int node,
+				   int bg, char *err, unsigned int errcap);
+
 static int fetch_worker_submit(struct fetch_worker *w, const char *url,
 			       unsigned int cap, const char *post,
 			       unsigned int post_len, unsigned int node,
 			       int bg, char *err, unsigned int errcap)
 {
-	static char req[768];
+	/* A body pointer with no bytes is still a POST: the classic request
+	 * line would turn it into a GET. */
+	if (post && !post_len)
+		return fetch_worker_submit_req(w, url, cap, "POST",
+			"application/x-www-form-urlencoded", post, 0, node,
+			bg, err, errcap);
+	return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
+				       node, bg, err, errcap);
+}
+
+/* `method` NULL keeps the classic GET / form-POST request line; otherwise
+ * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
+static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
+				   unsigned int cap, const char *method,
+				   const char *ctype, const char *post,
+				   unsigned int post_len, unsigned int node,
+				   int bg, char *err, unsigned int errcap)
+{
+	static char req[1024];
 	unsigned int n = 0;
 
 	fetch_seq++;
@@ -2332,7 +2614,24 @@ static int fetch_worker_submit(struct fetch_worker *w, const char *url,
 	s_append(req, &n, " ", sizeof(req));
 	s_append_dec(req, &n, cap, sizeof(req));
 	s_append(req, &n, " ", sizeof(req));
-	if (post_len) {
+	if (method) {
+		unsigned int k;
+
+		s_append(req, &n, "X ", sizeof(req));
+		s_append(req, &n, method, sizeof(req));
+		s_append(req, &n, " ", sizeof(req));
+		s_append_dec(req, &n, post_len, sizeof(req));
+		s_append(req, &n, " ", sizeof(req));
+		if (!ctype || !ctype[0])
+			s_append(req, &n, "-", sizeof(req));
+		/* One token on the request line: drop the spaces
+		 * ("application/json; charset=utf-8" stays valid). */
+		for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
+			if (ctype[k] != ' ')
+				req[n++] = ctype[k];
+		req[n] = '\0';
+		s_append(req, &n, " ", sizeof(req));
+	} else if (post_len) {
 		s_append(req, &n, "POST ", sizeof(req));
 		s_append_dec(req, &n, post_len, sizeof(req));
 		s_append(req, &n, " ", sizeof(req));
@@ -2509,6 +2808,7 @@ static void fetch_worker_release(struct fetch_worker *w)
 	w->image_job = 0;
 }
 
+
 /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
 static int fetch_worker_wait(struct fetch_worker *w, char *err,
 			     unsigned int errcap)
@@ -2516,7 +2816,8 @@ static int fetch_worker_wait(struct fetch_worker *w, char *err,
 	for (;;) {
 		int rv;
 
-		worker_wait_ui();
+		if (!fetch_wait_passive)
+			worker_wait_ui();
 		if (cancel_fetch || pending_action) {
 			fetch_workers_cancel_busy();
 			return FETCH_ABORT;
@@ -2567,6 +2868,68 @@ static int fetch_remote(const char *url, unsigned int cap,
 	return rv;
 }
 
+static int fetch_worker_status(const struct fetch_worker *w)
+{
+	return w->m.status;
+}
+
+/* fetch()/XHR through a helper: one request, the status and body come back
+ * whatever the HTTP status (a 401 is an answer, not a network error). */
+static int js_worker_http(const char *method, const char *url,
+			  const char *ctype, const char *body,
+			  unsigned int body_len, struct js_http_resp *r,
+			  char *err, int errcap)
+{
+	struct fetch_worker *w = fetch_worker_alloc();
+	unsigned char *plain;
+	int rv, tr = 0;
+
+	if (!w) {
+		s_copy(err, "network busy", (unsigned int)errcap);
+		return -1;
+	}
+	if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
+				    body_len, 0, 0, err,
+				    (unsigned int)errcap) != 0) {
+		fetch_worker_release(w);
+		return -1;
+	}
+	fetch_wait_passive++;
+	rv = fetch_worker_wait(w, err, (unsigned int)errcap);
+	fetch_wait_passive--;
+	if (rv != 0) {
+		if (rv == FETCH_ABORT)
+			s_copy(err, "page is navigating", (unsigned int)errcap);
+		fetch_worker_release(w);
+		return -1;
+	}
+	r->status = w->m.status;
+	s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
+	s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
+	plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
+	if (!plain) {
+		fetch_worker_release(w);
+		s_copy(err, "out of memory", (unsigned int)errcap);
+		return -1;
+	}
+	if (w->m.len == 0) {
+		rv = 0;     /* 204, an empty 200: no body file */
+	} else {
+		rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
+					    image_io_buf, BR_PAGE_COMP_MAX,
+					    &tr, err, (unsigned int)errcap);
+	}
+	fetch_worker_release(w);
+	if (rv < 0) {
+		free(plain);
+		return -1;
+	}
+	plain[rv] = '\0';
+	r->body = (char *)plain;
+	r->len = (unsigned int)rv;
+	return 0;
+}
+
 /* ---- HTTP / file fetch ---- */
 
 static int read_url(const char *url, unsigned int cap, unsigned char **out,
@@ -3647,7 +4010,7 @@ static void load_page(const char *url, int local, int push)
 	char final[BR_URL_MAX];
 	char err[80];
 	const char *detail = 0;
-	const char *post = pending_post_len ? pending_post : 0;
+	const char *post = pending_post_is ? pending_post : 0;
 	unsigned int post_len = pending_post_len;
 	unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
 	/* Phase timings for the status line: where a slow load spends it. */
@@ -3660,6 +4023,7 @@ static void load_page(const char *url, int local, int push)
 	nav_https_upgraded = 0;
 	final[0] = '\0';
 	pending_post_len = 0;
+	pending_post_is = 0;
 	cancel_fetch = 0;
 	preload_active = 0;
 	preload_pending = 0;
@@ -3877,6 +4241,7 @@ static void load_page(const char *url, int local, int push)
 static void load_home(int push)
 {
 	pending_post_len = 0;
+	pending_post_is = 0;
 	cancel_fetch = 0;
 	preload_active = 0;
 	preload_pending = 0;
@@ -4754,34 +5119,77 @@ static void flush_line(struct lay *l)
 								l->ui->theme.accent);
 					}
 				} else {
+					int editable =
+						r->form_kind == FORM_TEXT ||
+						r->form_kind == FORM_PASSWORD ||
+						r->form_kind == FORM_TEXTAREA;
+					int scroll = 0;
+					/* Editable fields draw the live value
+					 * (r->lit is a short copy). */
+					static char shown[FORM_VALUE_MAX + 1];
+					const char *txt = r->lit;
+					unsigned int tl = s_len(r->lit);
+
+					if (editable && fs && fs->len) {
+						unsigned int k;
+
+						if (r->form_kind == FORM_PASSWORD) {
+							for (k = 0; k < fs->len; k++)
+								shown[k] = '*';
+							shown[k] = '\0';
+							txt = shown;
+						} else {
+							txt = fs->value;
+						}
+						tl = fs->len;
+					}
+					/* The box is drawn in theme colours, so
+					 * the text is too: the page's CSS colour
+					 * (dark on a light page) would vanish on
+					 * the dark field. */
+					if (!disabled)
+						fg = editable && fs && !fs->len ?
+						     l->ui->theme.text_dim :
+						     l->ui->theme.text;
 					ngui_fill_rect(l->ui, box, bg);
 					ngui_frame(l->ui, box,
 						   focused ? l->ui->theme.accent :
 						   l->ui->theme.border);
+					/* A value wider than the field shows its
+					 * tail (where typing happens). */
+					if (editable && w > 12) {
+						int tw = (int)run_text_width(l->ui,
+							r, txt, tl);
+
+						if (tw > w - 12)
+							scroll = tw - (w - 12);
+					}
+					ngui_push_clip(l->ui, (struct ngui_rect){
+						x + 1, ry + 1,
+						w > 2 ? w - 2 : 1,
+						hh > 2 ? hh - 2 : 1 });
 					ngui_text_px_face(l->ui, run_face(r),
-							  x + 6, ry + 2,
-							  r->lit, s_len(r->lit),
-							  fg, r->font_px, r->bold,
-							  r->italic, r->mono);
-					if (focused && fs &&
-					    (r->form_kind == FORM_TEXT ||
-					     r->form_kind == FORM_PASSWORD ||
-					     r->form_kind == FORM_TEXTAREA)) {
+							  x + 6 - scroll,
+							  ry + (hh - r->font_px) / 2 - 1,
+							  txt, tl, fg, r->font_px,
+							  r->bold, r->italic, r->mono);
+					if (focused && fs && editable) {
 						int cw = 0;
 
 						if (fs->len && fs->caret)
 							cw = (int)run_text_width(
-								l->ui, r, r->lit,
+								l->ui, r, txt,
 								fs->caret < fs->len ?
 								fs->caret : fs->len);
 						ngui_fill_rect(l->ui,
 							(struct ngui_rect){
-								x + 6 + cw,
+								x + 6 + cw - scroll,
 								ry + 4, 1,
 								hh > 8 ? hh - 8 : 1
 							},
 							l->ui->theme.accent);
 					}
+					ngui_pop_clip(l->ui);
 					if (r->form_kind == FORM_SELECT) {
 						ngui_text_px(l->ui, x + w - 12,
 							     ry + 2, "v", 1, fg,
@@ -5382,6 +5790,11 @@ static void list_marker_text(char *m, unsigned int cap, int style, int idx)
 	m[n] = '\0';
 }
 
+/* Set by the layout when the control is stretched to its line: a flex item
+ * (its box width was assigned by the flex row) or a child of a flex column,
+ * whose default align-items: stretch makes inputs full width. */
+static int form_fill_line;
+
 static void add_form_run(struct lay *l, unsigned int node,
 			 const struct br_style *st, unsigned short href)
 {
@@ -5436,7 +5849,20 @@ static void add_form_run(struct lay *l, unsigned int node,
 			w = 64;
 		h = 22;
 	} else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
-		w = st->width_kind == 1 ? st->width : 120;
+		int line_w = l->line_right - l->line_left;
+
+		if (st->width_kind == 1)
+			w = st->width;
+		else if (st->width_kind == 2)
+			w = css_size(st->width_kind, st->width, line_w);
+		else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
+			w = line_w - (l->line_x - l->line_left);
+		else
+			w = 120;
+		/* Taller fields for large text (min-height/padding on login
+		 * pages): keep the box around the glyphs. */
+		if (st->font_px + 8 > h)
+			h = st->font_px + 8;
 	} else if (kind == FORM_SELECT) {
 		w = st->width_kind == 1 ? st->width : 120;
 	}
@@ -6448,9 +6874,14 @@ static void layout_block(struct lay *l, unsigned int node,
 		if (doc.nodes[node].tag == BR_TAG_INPUT &&
 		    s_eq(br_type(&doc, node), "hidden"))
 			return;
+		/* Reached as a block-level box (a flex item): the control
+		 * fills the box the caller assigned, and its line is flushed
+		 * here; flex layout resets the run list for the next item, so
+		 * a queued run would never be drawn. */
+		form_fill_line = 1;
 		add_form_run(l, node, st, link);
-		l->y += doc.nodes[node].tag == BR_TAG_TEXTAREA ? 40 :
-		       doc.nodes[node].tag == BR_TAG_BUTTON ? 22 : 20;
+		form_fill_line = 0;
+		flush_line(l);
 		return;
 	}
 	flush_line(l);
@@ -8581,8 +9012,13 @@ static void layout_children(struct lay *l, unsigned int parent,
 		if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
 		    nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
 			if (!(nd->tag == BR_TAG_INPUT &&
-			      s_eq(br_type(&doc, n), "hidden")))
+			      s_eq(br_type(&doc, n), "hidden"))) {
+				form_fill_line = pst->display ==
+						 BR_DISPLAY_FLEX &&
+						 pst->flex_col;
 				add_form_run(l, n, &cs, lk);
+				form_fill_line = 0;
+			}
 			n = nd->next;
 			continue;
 		}
@@ -9274,8 +9710,10 @@ static int form_submit_form(unsigned int node, int fire_event)
 			memcpy(pending_post, query, qn);
 		pending_post[qn] = '\0';
 		pending_post_len = qn;
+		pending_post_is = 1;
 	} else {
 		pending_post_len = 0;
+		pending_post_is = 0;
 		if (qn) {
 			unsigned int an = s_len(action);
 
@@ -9530,6 +9968,31 @@ static void form_key(int k)
 	ngui_invalidate(&ui);
 }
 
+/* The innermost laid-out box under a screen point: the smallest valid box
+ * that contains it (the last one wins a tie, i.e. the later/deeper node).
+ * Used to deliver clicks to elements that are neither links nor controls
+ * (a Vue <div role="button">, a card with a click listener). */
+static unsigned int find_box_hit(int x, int y)
+{
+	unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
+
+	for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
+		const struct br_layout_box *b = &layout_boxes[i];
+		unsigned int area;
+
+		if (!b->valid || b->w <= 0 || b->h <= 0 ||
+		    x < b->x || y < b->y || x >= b->x + b->w ||
+		    y >= b->y + b->h)
+			continue;
+		area = (unsigned int)b->w * (unsigned int)b->h;
+		if (area <= best_area) {
+			best = i;
+			best_area = area;
+		}
+	}
+	return best;
+}
+
 static void handle_page_click(unsigned int *action)
 {
 	int node;
@@ -9543,8 +10006,18 @@ static void handle_page_click(unsigned int *action)
 	    ui.press_y >= page_rect.y + page_rect.h)
 		return;
 	node = find_hit(ui.press_x, ui.press_y);
-	if (!node)
+	if (!node) {
+		unsigned int box;
+
+		if (!js_browser_active())
+			return;
+		box = find_box_hit(ui.press_x, ui.press_y);
+		if (box) {
+			form_blur();
+			js_browser_event(box, "click", 1, 1);
+		}
 		return;
+	}
 	if (form_is_control((unsigned int)node)) {
 		form_click((unsigned int)node);
 		return;

+ 68 - 7
browser_html.c

@@ -937,6 +937,33 @@ static unsigned int append_text(struct br_doc *d, unsigned int parent,
 	return idx;
 }
 
+/* Raw text child (no entity decoding, whitespace kept): the body of a
+ * data-block <script> such as type="application/json", which scripts read
+ * through textContent.  Bodies longer than a text node holds are dropped. */
+static unsigned int append_raw_text(struct br_doc *d, unsigned int parent,
+				    const char *s, unsigned int len)
+{
+	unsigned int idx, i;
+
+	if (len == 0 || len > 0xFFFFu)
+		return 0;
+	if (d->text_used + len + 1 >= BR_TEXT_SIZE) {
+		d->truncated = 1;
+		return 0;
+	}
+	idx = node_append(d, parent, BR_NODE_TEXT, 0);
+	if (!idx)
+		return 0;
+	for (i = 0; i < len; i++)
+		d->text[d->text_used + i] = s[i];
+	d->text[d->text_used + len] = '\0';
+	d->nodes[idx].text_off = d->text_used;
+	d->nodes[idx].text_len = (unsigned short)len;
+	d->nodes[idx].flags = BR_NODE_PREFORMAT;
+	d->text_used += len + 1;
+	return idx;
+}
+
 /* ---- runtime DOM helpers (JavaScript bindings) ---- */
 
 static int same_string(const char *a, const char *b)
@@ -1522,6 +1549,25 @@ static void attr_note_known(struct br_doc *d, struct br_node *n,
 			    const char *name, const char *value,
 			    unsigned int len)
 {
+	int control = n->tag == BR_TAG_INPUT || n->tag == BR_TAG_BUTTON ||
+		      n->tag == BR_TAG_SELECT || n->tag == BR_TAG_TEXTAREA;
+
+	/* Form controls keep type/value/placeholder in the rel/src/alt slots,
+	 * exactly like parse_attrs(); script-built inputs (Vue sets
+	 * type="password" after createElement) must land there too. */
+	if (control && same_string(name, "type")) {
+		n->rel_off = len ? store_attr(d, value, len, 40) : 0;
+		return;
+	}
+	if (control && same_string(name, "value")) {
+		n->src_off = len ? store_attr(d, value, len, 220) : 0;
+		return;
+	}
+	if ((n->tag == BR_TAG_INPUT || n->tag == BR_TAG_TEXTAREA) &&
+	    same_string(name, "placeholder")) {
+		n->alt_off = len ? store_attr(d, value, len, 120) : 0;
+		return;
+	}
 	if (same_string(name, "id"))
 		n->id_off = len ? store_attr(d, value, len, 64) : 0;
 	else if (same_string(name, "class"))
@@ -8107,9 +8153,13 @@ static unsigned int script_src_attr(struct br_doc *d, const char *s,
 
 /* JavaScript only: skip structured-data/template script blocks (JSON-LD,
  * application/json, text/template, ...) and non-JS type values.  External
- * src scripts are allowed; the browser fetches them separately. */
+ * src scripts are allowed; the browser fetches them separately.  Returns 1
+ * for a classic script, 2 for type="module", 0 to skip (also for a
+ * `nomodule` fallback, since module scripts run). */
 static int script_is_javascript(const char *s, unsigned int len)
 {
+	int kind = 1;
+
 	unsigned int i = 0;
 
 	while (i < len) {
@@ -8149,22 +8199,28 @@ static int script_is_javascript(const char *s, unsigned int len)
 		} else if (i == ne) {
 			i++;
 		}
-		if (ne > ns && ci_eq_n(s + ns, "type", ne - ns)) {
+		if (ne - ns == 8 && ci_eq_n(s + ns, "nomodule", 8))
+			return 0;
+		if (ne - ns == 4 && ci_eq_n(s + ns, "type", 4)) {
 			unsigned int vn = has_val ? ve - vs : 0;
 
 			if (vn == 0)
-				return 1;
+				continue;
+			if (vn == 6 && ci_eq_n(s + vs, "module", 6)) {
+				kind = 2;
+				continue;
+			}
 			if ((vn == 15 && ci_eq_n(s + vs, "text/javascript", 15)) ||
 			    (vn == 22 &&
 			     ci_eq_n(s + vs, "application/javascript", 22)) ||
 			    (vn == 15 && ci_eq_n(s + vs, "text/ecmascript", 15)) ||
 			    (vn == 22 &&
 			     ci_eq_n(s + vs, "application/ecmascript", 22)))
-				return 1;
+				continue;
 			return 0;
 		}
 	}
-	return 1;
+	return kind;
 }
 
 int br_parse(struct br_doc *d, const char *html, unsigned int len)
@@ -8309,12 +8365,15 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 				unsigned int end = p >= 0 ? (unsigned int)p : len;
 				unsigned int idx;
 
-				if (script_is_javascript(html + attr_start,
-							 attr_end - attr_start)) {
+				int kind = script_is_javascript(html + attr_start,
+							attr_end - attr_start);
+
+				if (kind) {
 					if (d->nscripts < BR_MAX_SCRIPTS) {
 						struct br_script *script =
 							&d->scripts[d->nscripts++];
 
+						script->module = kind == 2;
 						script->off = i;
 						script->len = end > i ? end - i : 0;
 						script->src_off = script_src_attr(
@@ -8334,6 +8393,8 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 					parse_attrs(d, &d->nodes[idx],
 						    html + attr_start,
 						    attr_end - attr_start);
+				if (idx && !kind && end > i)
+					append_raw_text(d, idx, html + i, end - i);
 				i = p >= 0 ? (unsigned int)p + 8 : len;
 				while (i < len && html[i] != '>')
 					i++;

+ 1 - 0
browser_html.h

@@ -266,6 +266,7 @@ struct br_script {
 	unsigned int off;       /* inline body, or empty for src scripts */
 	unsigned int len;
 	unsigned int src_off;   /* src attribute in the attr arena, 0 if inline */
+	unsigned int module;    /* type="module": run as an ES module */
 };
 
 struct br_doc {

+ 21 - 0
cpu.c

@@ -16,6 +16,27 @@ int cpu_has_cpuid(void)
 	return ((a ^ b) & (1u << 21)) != 0;
 }
 
+unsigned int cpu_family_model(void)
+{
+	unsigned int a, b, c, d, family, model;
+
+	if (!cpu_has_cpuid())
+		return 0;
+	a = 0;
+	__asm__ volatile ("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d));
+	if (a < 1)
+		return 0;
+	a = 1;
+	__asm__ volatile ("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d));
+	family = (a >> 8) & 0xFu;
+	model = (a >> 4) & 0xFu;
+	if (family == 0xFu)
+		family += (a >> 20) & 0xFFu;
+	if (family == 0x6u || family == 0xFu)
+		model |= ((a >> 16) & 0xFu) << 4;
+	return (family << 8) | model;
+}
+
 void cpu_enable_sse(void)
 {
 	unsigned int eax, ebx, ecx, edx, cr4;

+ 5 - 0
cpu.h

@@ -9,6 +9,11 @@
 /* 1 when CPUID is available (has the ID bit in EFLAGS). */
 int cpu_has_cpuid(void);
 
+/* (display family << 8) | display model from CPUID leaf 1 (extended
+ * family/model folded in the Intel way), or 0 without CPUID.  Used as a
+ * platform allowlist for probes that poke fixed MMIO addresses. */
+unsigned int cpu_family_model(void);
+
 /* 1 when the CPU supports SSE2 (the ION does, the Pentium targets do not). */
 int cpu_has_sse2(void);
 

+ 17 - 9
docs/boot.html

@@ -145,11 +145,15 @@
 		<p>
 			The boot sector carries a FAT16 BPB, loads the contiguous kernel
 			directly after itself to <code>0x7E00</code>, and jumps there.
-			Floppy drives use CHS, one sector per call; fixed disks use
-			<code>INT 13h AH=42h</code> (EDD LBA) with up to 64 sectors per call
-			into <code>ES:0</code>, advancing <code>ES</code> so the offset never
-			wraps (one call per sector used to make the kernel load ~700 BIOS
-			calls). The sector count and the rootfs LBA are patched into the
+			Each <code>INT 13h</code> reads a run of sectors into
+			<code>ES:0</code> and then advances <code>ES</code>, so the offset
+			never wraps: fixed disks use EDD LBA (<code>AH=42h</code>) with up to
+			64 sectors, floppies use CHS up to the end of the track and never
+			across a 64 KB physical ISA DMA boundary. One call per sector used
+			to make the kernel load ~700 BIOS calls, each of which can cost a
+			floppy revolution. A failing run is tried three times, then the
+			loader drops to one sector per call (the old behaviour) before it
+			reports <code>Disk read error</code>. The sector count and the rootfs LBA are patched into the
 			boot sector by the Makefile.
 		</p>
 		<p>
@@ -401,14 +405,18 @@
 			<li>Parse ACPI/MADT; initialise I/O, power, idle, thermal and board sensors.</li>
 			<li>Create the process table, then start the PIT and verify it ticks.</li>
 			<li>Start APs through INIT-SIPI-SIPI (they idle until scheduling is enabled).</li>
-			<li>Initialise PS/2, USB HID and the VGA shadow buffer.</li>
+			<li>Initialise PS/2 (the I2C touchpad probe only on Airmont) and the VGA shadow buffer.</li>
 			<li>Inflate the command pack into <code>/ramfs</code> (table-driven whole-buffer inflate); start the WM and the first frame.</li>
-			<li>Probe the NIC, restore retained network config, start the kworker.</li>
-			<li>Start the <code>bootscan</code> kernel thread (storage probe + FAT mounts, then the <code>/data</code> WiFi autoconnect once the boot DHCP is done) and publish <code>vfs_scan_busy</code>; call <code>wm_server_boot_ready()</code> at once so the WM spawns the first terminal while the disks are probed; run DHCP if needed.</li>
+			<li>Publish <code>vfs_scan_busy</code> and call <code>wm_server_boot_ready()</code>; idle (1 s cap) until the first terminal has presented a frame.</li>
+			<li>Bring up USB (controllers, HID, USB NICs/WiFi/disks) non-preemptibly, as before the WM existed; probe the NIC, restore retained network config, start the kworker.</li>
+			<li>Start the <code>bootscan</code> kernel thread (storage probe + FAT mounts, then the <code>/data</code> WiFi autoconnect once the boot DHCP is done); run DHCP if needed.</li>
 			<li>Enable scheduling on the APs and enter the kernel idle loop.</li>
 		</ol>
 		<p>
-			The terminal no longer waits for storage: <code>/ramfs</code> and
+			The terminal no longer waits for USB, the NIC or storage.  The
+			WM's network status poll does not trigger the NIC probe (it reports
+			no NIC until <code>kernel_main</code> has probed), so the first frame
+			never waits for a PHY reset.  <code>/ramfs</code> and
 			<code>/share</code> operations (including spawning commands from
 			<code>/ramfs/bin</code>) skip the scan wait, a disk path waits for it,
 			and the scan thread sleeps through its long probe timeouts.  The

+ 6 - 2
docs/development.html

@@ -182,6 +182,7 @@
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
 					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
 					<tr><td><code>make test-wpa</code></td><td>Host vectors for the WPA2 supplicant: SHA-1, RFC 6070 PBKDF2, the 802.11 PSK and PRF examples, FIPS-197 AES, RFC 3394 unwrap, plus a simulated 4-way handshake, group rekey, replay and wrong-passphrase case.</td></tr>
+					<tr><td><code>make test-wifi-store</code></td><td>Host test for the saved-network file: newest-first ordering, passphrase update, LRU eviction at the 16-entry cap, per-SSID forget, the old one-record format and malformed or duplicate lists.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
 					<tr><td><code>make test-js</code></td><td>Host tests (ASan/UBSan) for the vendored QuickJS engine through the <code>js_mu</code> stack API: modern syntax (classes, arrows, templates, destructuring, spread, async/await, BigInt, named regex groups), Promise jobs, C functions and <code>new</code>, thrown TypeErrors, userdata hooks and expandos, registry refs and the wall-clock interrupt.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
@@ -287,7 +288,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Installer.</strong> <code>make test-install</code> boots the dual image with its USB mass-storage source and a blank target, types <code>install ide1</code> through QMP, verifies the clone and boots the target in BIOS and (under OVMF) UEFI.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
-			<li><strong>WPA2.</strong> <code>make test-wpa</code> runs <span class="file">wpa_test.c</span> against <span class="file">wpa_crypto.c</span> and <span class="file">wpa.c</span>. The WiFi driver itself has no QEMU model: test it on the Chromebook over <code>make net-dev</code> with the RNDIS phone or ASIX dongle as the management link and <code>make netmon</code> for the <code>iwl:</code>/<code>wifi:</code> trail.</li>
+			<li><strong>WPA2.</strong> <code>make test-wpa</code> runs <span class="file">wpa_test.c</span> against <span class="file">wpa_crypto.c</span> and <span class="file">wpa.c</span>. <code>make test-wifi-store</code> runs the saved-network list against an in-memory FAT file: ordering, update, eviction, forget and the legacy/malformed formats. The WiFi driver itself has no QEMU model: test it on the Chromebook over <code>make net-dev</code> with the RNDIS phone or ASIX dongle as the management link and <code>make netmon</code> for the <code>iwl:</code>/<code>wifi:</code> trail.</li>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (64 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
@@ -302,9 +303,10 @@ make net-cmds                   # replace /ramfs only</code></pre>
 		<h2>Debugging</h2>
 		<ul>
 			<li><strong>Serial log.</strong> <code>make monitor</code> shows the boot trace and printf-style driver output. The <code>NebOS v… booted</code> line is written before the framebuffer is ready.</li>
-			<li><strong>Boot time.</strong> Timestamp COM1 on the host (QEMU <code>-serial stdio</code>): the kernel starts at <code>NebOS v… booted</code>, the desktop at <code>wm: first frame</code>, and the terminal is on screen at <code>wm: first window frame (term) at N ms</code> (kernel uptime).  On QEMU the USB image reaches it about 0.65 s after the kernel starts.</li>
+			<li><strong>Boot time.</strong> Timestamp COM1 on the host (QEMU <code>-serial stdio</code>): the kernel starts at <code>NebOS v… booted</code>, the desktop at <code>wm: first frame</code>, and the terminal is on screen at <code>wm: first window frame (term) at N ms</code> (kernel uptime).  On QEMU the USB image reaches it about 0.4 s after the kernel starts; USB, the NIC and the disks are probed after that (<code>[boot] usb/net/storage</code> lines).</li>
 			<li><strong>Network console.</strong> <code>make netmon</code> listens to UDP 19290 for serial and terminal output; <code>netconsole host &lt;ip&gt;</code> narrows the target.</li>
 			<li><strong>dbg.</strong> The ring-0 serial monitor accepts <code>r addr len</code>, <code>w addr b0 …</code>, <code>i port</code>, <code>o port val</code>, <code>h</code> and <code>q</code>.</li>
+			<li><strong>Keys.</strong> <code>keytest</code> drains the raw scancode tap in <span class="file">io.c</span> and prints every byte with its E0-prefix state, make/break kind and decoded <code>IO_KEY_*</code>/ASCII value; Ctrl+C stops it.  It sees releases and keys the decoder ignores, so an unknown action-row key is easy to identify.</li>
 			<li><strong>Panic.</strong> A ring-0 fault dumps vector, error code, registers, CRs, EIP bytes and stack candidates to the LFB and COM1. Resolve addresses with <code>nm kernel.elf</code> / <code>addr2line -e kernel.elf</code>.</li>
 			<li><strong>Profiling.</strong> <code>gfxbench</code> times fill/copy/cell/canvas/flush; <code>top</code>, <code>sched</code>, <code>sensors</code>, <code>powerinfo</code>, <code>power</code> and <code>lspci</code>/<code>lsusb</code> expose live state.</li>
 			<li><strong>Memory.</strong> <code>peek addr len</code> hex-dumps identity-mapped memory (MMIO too); <code>poke addr val</code> writes one dword and prints the read-back.</li>
@@ -369,10 +371,12 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><code>netkexec.c</code>, <code>netkexec_send.c</code> — network reload</li>
 			<li><code>netlog.c</code>, <code>netmonitor.c</code> — UDP console</li>
 			<li><code>dbg.c</code> — serial debug monitor</li>
+			<li><code>io.c</code>, <code>terminal.c</code> — scancode decoder/tap and the kernel command registry</li>
 			<li><code>panic.c</code> — fatal exception dump</li>
 			<li><code>kernel.ld</code>, <code>ucmd.ld</code> — link limits</li>
 			<li><code>tools/</code> — QMP USB and installer tests</li>
 			<li><code>wpa_test.c</code> — WPA2 supplicant host test (<code>make test-wpa</code>)</li>
+			<li><code>wifi_store_test.c</code> — saved WiFi list host test (<code>make test-wifi-store</code>)</li>
 			<li><code>AGENTS.md</code> — developer notes and maintenance rule</li>
 		</ul>
 	</section>

+ 5 - 1
docs/drivers.html

@@ -87,6 +87,7 @@
 					<tr><td>Network</td><td><span class="file">e1000e.c</span> <span class="file">r8168.c</span> <span class="file">ne2000.c</span> <span class="file">asix.c</span> <span class="file">rndis.c</span></td><td>PCI or USB</td><td>Polled, one active receiver</td></tr>
 					<tr><td>WiFi</td><td><span class="file">iwl_trans.c</span> <span class="file">iwl_mvm.c</span> <span class="file">iwl_dvm.c</span> <span class="file">wifi.c</span></td><td>PCIe, Intel 7265D/3165 (<code>8086:095a/095b/3165/3166</code>) and 6200/6300 (<code>8086:4239/422c</code>, <code>4238/422b</code>)</td><td>Polled RX ring; firmware from <code>/ramfs/firmware</code>, loaded on first use</td></tr>
 					<tr><td>USB WiFi</td><td><span class="file">rtl8821au.c</span> <span class="file">wifi.c</span></td><td>USB 2.0 high speed, Realtek RTL8821AU/8811AU (TP-Link Archer T2U Nano <code>2357:011f</code> and the other Linux <code>rtw88_8821au</code> IDs)</td><td>Vendor control requests for registers, one bulk-IN/one bulk-OUT endpoint; firmware + register tables from <code>/ramfs/firmware</code></td></tr>
+					<tr><td>Panel backlight</td><td><span class="file">backlight.c</span></td><td>Intel Braswell/Cherryview graphics MMIO, PCI <code>00:02.0</code> (<code>8086:22b0/22b1</code>)</td><td>Polled register writes; F6/F7 and <code>E0 14</code>/<code>E0 15</code> step 10%</td></tr>
 					<tr><td>PS/2</td><td><span class="file">mouse.c</span>, <span class="file">io.c</span></td><td>i8042</td><td>IRQ 1 keyboard, IRQ 12 mouse; polling fallback</td></tr>
 					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span>, <span class="file">touchpad_gesture.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; software tap and two-finger scroll gestures; no GPIO interrupt driver</td></tr>
 					<tr><td>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
@@ -510,7 +511,9 @@
 			The HP Chromebook 11 G5 EE has no PS/2 port: its Elan touchpad is a
 			HID-over-I2C device on LPSS I2C6. The LPSS I2C functions are hidden
 			from PCI in ACPI mode, so <span class="file">touchpad.c</span> scans
-			the two firmware BAR windows for a DesignWare component and
+			the two firmware BAR windows for a DesignWare component (only on an
+			Airmont CPU, family 6 model <code>0x4C</code>: elsewhere the scan
+			would reset-cycle 32 fixed MMIO windows for ~64 ms of boot) and
 			<span class="file">i2c.c</span> drives that controller in fast mode,
 			polled and without interrupts.
 		</p>
@@ -690,6 +693,7 @@
 			<li><code>wifi.c</code>, <code>wifi.h</code> — 802.11 station, <code>wifi</code> netdev, <code>SYS_WIFI</code></li>
 			<li><code>ccmp.c</code>, <code>ccmp.h</code> — software CCMP (AES-CCM): RX fallback, RTL8821AU TX</li>
 			<li><code>install.c</code> — live-image clone installer</li>
+			<li><code>backlight.c</code>, <code>backlight.h</code> — Cherryview/Braswell panel PWM</li>
 			<li><code>usbhid.c</code>, <code>mouse.c</code>, <code>io.c</code> — input</li>
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>
 			<li><code>touchpad.c</code>, <code>touchpad.h</code> — Elan HID-over-I2C touchpad</li>

+ 2 - 1
docs/filesystems.html

@@ -311,7 +311,8 @@
 			<li><strong>Persistent.</strong> A reinstall or <code>install &lt;target&gt; self</code> replaces the OS partitions (P1 kernel, P2 rootfs pack, P3 ESP) and keeps P4. <code>net-install</code> writes only P1/P2.</li>
 			<li><strong>First install is destructive.</strong> Creating P4 formats the rest of the target disk; an existing <code>NEBOSDATA</code> volume is detected and left untouched.</li>
 			<li><strong>8.3 names.</strong> The FAT driver creates and reads short names only; long names need VFAT LFN write support.</li>
-			<li><strong>WiFi credentials.</strong> A successful WiFi connect stores the SSID/passphrase in <code>WIFI.CFG</code>; the boot-time <code>wifi autoconnect</code> helper reads it. The file is plaintext and 8.3, like the rest of the volume.</li>
+			<li><strong>WiFi credentials.</strong> A successful WiFi connect adds the network to a most-recently-used list of up to 16 SSID/passphrase records in <code>WIFI.CFG</code>; the boot-time <code>wifi autoconnect</code> helper scans and joins the strongest saved network it finds. <code>wifi saved</code> lists them and <code>wifi forget [ssid]</code> removes one. The file is plaintext and 8.3, like the rest of the volume.</li>
+			<li><strong>Chat session.</strong> The Chat client stores its server and session cookie in <code>CHAT.CFG</code> when this volume is mounted; without it the client falls back to the RAM-only <code>/share/chat.cfg</code>. The cookie is a bearer credential, and the password is never stored.</li>
 			<li><strong>Fixed start.</strong> P4 starts at LBA 34816. A BIOS-only install leaves the space between P2 and P4 unpartitioned, and a later disk clone does not resize P4.</li>
 			<li><strong>No fsck.</strong> Like the other FAT mounts, the volume has no journal, repair tool or permissions; it is writable by every process.</li>
 		</ul>

+ 49 - 8
docs/graphics.html

@@ -61,6 +61,7 @@
 			<li><a href="#apps">Applications</a></li>
 			<li><a href="#images">Image library</a></li>
 			<li><a href="#gpu">GPU quirks</a></li>
+			<li><a href="#backlight">Panel backlight</a></li>
 			<li><a href="#sources">Source map</a></li>
 		</ul>
 	</nav>
@@ -149,13 +150,27 @@
 			icon, a network status icon shows a
 			cable for wired Ethernet, signal bars for a connected WiFi link, a
 			USB mark for RNDIS tethering, or a red X when no link is up;
-			clicking it opens the anchored <code>bin/netmenu</code> window.
+			clicking it opens the anchored <code>bin/netmenu</code> popover.
 			Present NICs can be selected (then DHCP runs), and scanned WiFi
 			networks can be joined, asking for the WPA2 passphrase first when
 			the AP requires one. The right-aligned date/time text sits to the
 			icon's left and is also a target: it highlights on hover and opens
 			the Date &amp; Time editor (<code>bin/settime</code>) on a click.
 		</p>
+		<p>
+			A popover is a chromeless canvas window created with
+			<code>u_win_create_popover()</code> (<code>WIN_F_POPOVER</code>).
+			The WM anchors it under the status icon, treats it as always
+			topmost in painting and hit-testing, and draws no chrome at all:
+			the canvas fills the whole window rectangle, with no title bar,
+			shadow, rim or rounded outer corners, so it reads as a flat menu
+			panel. The kernel uses the window origin for content-relative
+			pointer and scroll coordinates. An outside press dismisses the
+			popover and the click then continues normally; a second click on
+			the network icon toggles it. The panel itself is drawn with the
+			ngui popover components: a flat body with section captions and
+			two-line list rows, and a footer status line.
+		</p>
 		<p>
 			The WM is the ring-3 process loaded from
 			<code>/ramfs/bin/wm</code>; there is no kernel WM fallback. The
@@ -239,9 +254,13 @@
 			counters, so the WM cannot lose one.
 		</p>
 		<p>
-			<code>SYS_WIN_CREATE</code> creates a generic canvas window. Input is
-			exposed through <code>SYS_WIN_POINTER</code> (content-relative
-			position, button mask, focus), <code>SYS_WIN_EVENT</code>, which
+			<code>SYS_WIN_CREATE</code> creates a generic canvas window.
+			<code>struct win_create.flags</code> can request
+			<code>WIN_F_POPOVER</code>, a chromeless overlay: the canvas fills
+			the window and the WM supplies only the topmost placement.
+			Input is exposed through <code>SYS_WIN_POINTER</code>
+			(content-relative position, button mask, focus),
+			<code>SYS_WIN_EVENT</code>, which
 			queues press/release edges and a capture window, and
 			<code>SYS_WIN_SCROLL</code>, which returns wheel/touchpad scroll
 			accumulated for the window under the pointer in pixels
@@ -299,6 +318,7 @@
 		</p>
 		<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>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. The WM draws no outer chrome, so the app paints the whole window.</li>
 			<li><strong>Clip stack</strong> keeps nested panes and popups inside their parents.</li>
 			<li><strong>Layout cuts</strong> split a rectangle into rows, columns and fixed margins without a constraint solver.</li>
 			<li><strong>No retained widget tree.</strong> Apps redraw from state every frame, which keeps the toolkit small and predictable.</li>
@@ -369,13 +389,14 @@
 			The codecs are independent of the OS and the toolkit: each takes an
 			input buffer plus a caller-provided <code>struct img_mem</code> arena
 			and returns an RGB565 image with an optional 8-bit alpha plane. The
-			browser links the same objects and decodes HTTP bodies in memory.
+			browser and the chat client link the same objects and decode HTTP
+			bodies in memory.
 		</p>
 		<ul>
 			<li><strong>Formats.</strong> PNG, baseline and progressive JPEG, animated GIF, BMP, TGA, PNM, ICO/CUR and PAM.</li>
 			<li><strong>Drawing.</strong> <code>img_draw()</code> is a clipped, scaled RGB565 blit: box-filter downscale, bilinear upscale, alpha over a checkerboard or over the destination.</li>
 			<li><strong>Orientation.</strong> EXIF orientation is applied; arithmetic JPEG and CMYK are rejected.</li>
-			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint.</li>
+			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint; the chat client caches up to 480x320 message images and 32x32 circular avatars.</li>
 		</ul>
 	</section>
 
@@ -384,11 +405,30 @@
 		<ul>
 			<li><strong>ATI Mach64.</strong> A CRTC fixup is applied after mode set. The legacy CRTC is skipped under UEFI.</li>
 			<li><strong>NVIDIA.</strong> VBE-only. The legacy VGA CRTC is never touched. On the ION, the framebuffer is stolen DRAM behind a BAR3 aperture; <span class="file">nvidia.c</span> finds the stolen range and writes through a cached alias once a WC MTRR covers it.</li>
-			<li><strong>Intel.</strong> The Ironlake-era path supports a hardware cursor where available; the software cursor is the common fallback.</li>
+			<li><strong>Intel.</strong> The Ironlake-era path supports a hardware cursor where available; the software cursor is the common fallback. Cherryview/Braswell also exposes the panel backlight (below).</li>
 			<li><strong>UEFI.</strong> <code>vga.c</code> honours the RGBX flag and skips the VBE-only ATI CRTC reset and NVIDIA stolen-VRAM alias. <span class="file">mouse.c</span> forces the software cursor.</li>
 		</ul>
 	</section>
 
+	<section id="backlight">
+		<h2>Panel backlight</h2>
+		<p>
+			The HP Chromebook 11 G5 (<code>google/setzer</code>, Braswell)
+			drives its internal panel PWM from the display engine, not from
+			the Chrome EC. The board VBT (<code>data.vbt</code>, block 43)
+			declares PWM controller 0 at 200 Hz, active high. Linux uses the
+			same Valleyview/Cherryview registers through
+			<code>intel_backlight</code>.
+		</p>
+		<ul>
+			<li><strong>Registers.</strong> <code>BLC_PWM_CTL2</code> at GPU BAR0 + <code>0x1E1250</code> (pipe A; pipe B is <code>+0x100</code>): bit 31 enables, bit 28 is polarity. <code>BLC_PWM_CTL</code> at <code>0x1E1254</code>: period in bits 31:16, duty in bits 15:0. The Cherryview PWM clock is 19.2 MHz with a fixed /16 increment, so 200 Hz is a period of 6000.</li>
+			<li><strong>Probe.</strong> <span class="file">backlight.c</span> matches Intel <code>8086:22b0</code>/<code>22b1</code>, maps the graphics MMIO BAR, reads both pipes, follows the one the firmware enabled and falls back to controller 0. It logs the chosen pipe, period, duty and raw registers to COM1.</li>
+			<li><strong>Use.</strong> The <code>backlight</code> command prints the percentage and PWM state; <code>backlight up|down</code> steps by 10%, <code>backlight 0-100</code> sets a level (clamped to 5..100), and <code>backlight probe</code> dumps both pipes' registers. F6/F7 (the ChromeOS EC action-row brightness keys) and the standard <code>E0 14</code>/<code>E0 15</code> brightness scancodes adjust it; the keys are consumed in <span class="file">io.c</span> and never reach a window.</li>
+			<li><strong>Overlay.</strong> <code>SYS_WM_POLL</code> also reports the backlight percentage and a change counter. After each change the ring-3 WM (<span class="file">ucmd_wm.c</span>) draws a centered <em>Brightness</em> bubble with a sun icon, the percentage and a level bar, keeps it up for 3 s, and composits it above the windows on every pass while it is visible.</li>
+			<li><strong>Limits.</strong> Only the Cherryview/Braswell native PWM (<code>8086:22b0</code>/<code>22b1</code>) is driven. The level is not persisted; a cold boot returns to the firmware's duty.</li>
+		</ul>
+	</section>
+
 	<section id="sources">
 		<h2>Source map</h2>
 		<ul class="filelist">
@@ -398,7 +438,7 @@
 			<li><code>cpu.c</code> — SSE2 probing</li>
 			<li><code>wm.c</code>, <code>wm.h</code>, <code>wm_abi.h</code> — kernel window server and shared ABI</li>
 			<li><code>ucmd_wm.c</code>, <code>uwm_lib.c</code> — ring-3 WM</li>
-			<li><code>ucmd_netmenu.c</code> — top-bar network menu (NIC selection, DHCP, WiFi scan/passphrase)</li>
+			<li><code>ucmd_netmenu.c</code> — top-bar network popover (NIC selection, DHCP, WiFi scan/passphrase)</li>
 			<li><code>ucmd_settime.c</code>, <code>rtc.c</code>, <code>ntp.c</code> — Date &amp; Time editor, RTC access and SNTP sync</li>
 			<li><code>gfx.c</code>, <code>gfx.h</code> — RGB565 window canvases</li>
 			<li><code>sys_wm.c</code>, <code>sys_wm.h</code> — WM/window ABI</li>
@@ -409,6 +449,7 @@
 			<li><code>ucmd_files.c</code>, <code>gallery.c</code>, <code>ucmd_solitaire.c</code>, <code>ucmd_chat.c</code></li>
 			<li><code>img*.c</code> — image codecs</li>
 			<li><code>ati.c</code>, <code>nvidia.c</code>, <code>intel.c</code>, <code>nv50.c</code></li>
+			<li><code>backlight.c</code>, <code>backlight.h</code> — Cherryview/VLV panel PWM</li>
 		</ul>
 	</section>
 </main>

+ 47 - 20
docs/network.html

@@ -149,7 +149,7 @@
 			<code>SYS_NET_DEVLIST</code> (111), so an RNDIS phone or a USB
 			Ethernet dongle that was not the boot-time winner still appears.
 			Selecting one calls <code>SYS_NET_SELECT</code> (112) and then runs
-			DHCP. The same window lists scanned WiFi networks; selecting a WPA2
+			DHCP. The same popover lists scanned WiFi networks; selecting a WPA2
 			network asks for the passphrase and starts the existing
 			<code>wifi</code> supplicant, which opens the data port and runs DHCP
 			itself. Mesh/repeater BSSIDs sharing one SSID are collapsed to the
@@ -193,17 +193,29 @@
 			after reading it.
 		</p>
 		<p>
-			A successful <code>wifi connect</code> (from the CLI or the menu) also saves
-			the SSID and passphrase to <code>/data/WIFI.CFG</code> on the
-			persistent <code>NEBOSDATA</code> partition. After the boot DHCP
-			attempt and the storage scan, the <code>bootscan</code> thread spawns
-			<code>wifi autoconnect</code> when that file exists. It samples the
-			active NIC's <code>link_up()</code> state: a wired cable that is
-			physically up keeps the Ethernet path, while no wired link lets
-			WiFi associate and run DHCP. An existing WiFi link is left alone.
-			<code>wifi forget</code> removes the saved record.
-			The file is a plaintext 8.3 FAT file with the BSSID zeroed so the
-			strongest AP advertising that SSID is used.
+			A successful <code>wifi connect</code> (from the CLI or the menu) adds
+			the network to a most-recently-used list of up to
+			<code>WIFI_CFG_MAX</code> (16) SSID/passphrase records in
+			<code>/data/WIFI.CFG</code> on the persistent <code>NEBOSDATA</code>
+			partition. The network menu marks every scanned SSID that is in the
+			list as <em>saved</em>, joins it with the stored passphrase without
+			asking again, and its <em>Saved</em> view lists the records with a
+			<em>Forget</em> button each. The <code>wifi saved</code> command
+			prints the same list and <code>wifi forget [ssid]</code> removes one
+			network (or all of them without an SSID).
+		</p>
+		<p>
+			After the boot DHCP attempt and the storage scan, the
+			<code>bootscan</code> thread spawns <code>wifi autoconnect</code>
+			when that file exists. It samples the active NIC's
+			<code>link_up()</code> state: a wired cable that is physically up
+			keeps the Ethernet path, while no wired link lets WiFi scan and
+			join the strongest network present whose SSID is in the saved list,
+			trying the other saved networks found if one fails and rescanning
+			once after three seconds. An existing WiFi link is left alone. The
+			file is a plaintext 8.3 FAT file (one list header plus fixed-size
+			records, most recently used first); no BSSID is stored, so the
+			strongest AP advertising a saved SSID is used.
 		</p>
 		<div class="table-wrap">
 			<table>
@@ -396,9 +408,9 @@
 		<h2>HTTP clients</h2>
 		<ul>
 			<li><strong>curl</strong> — <code>http://</code> or <code>https://</code> GET with DNS, ARP, redirects (up to five hops), chunked decoding, status/headers/body dump and a TLS warning.</li>
-			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl, the browser and chat: URL parsing, redirects (up to eight hops; 1 KB paths and 1.5 KB header lines, enough for OIDC URLs), chunked decoding, timeouts and TLS.  Requests and bodies of any size are split into pieces the transport accepts (1024-byte TLS records, one peer MSS for plain TCP).  Optional per-request fields set the <code>Accept</code> header, extra header lines and a cookie jar; 1xx/204/304 responses are treated as bodyless so keep-alive does not wait for an idle timeout.</li>
+			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl, the browser and chat: URL parsing (spaces, controls, quotes and non-ASCII bytes in the path are percent-encoded, and <code>//</code>/<code>.</code>/<code>..</code> normalization stops at the query, which may carry a URL such as <code>redirect_uri=https://…</code>), redirects (up to eight hops; 1 KB paths and 1.5 KB header lines, enough for OIDC URLs), chunked decoding, timeouts and TLS.  Requests and bodies of any size are split into pieces the transport accepts (1024-byte TLS records, one peer MSS for plain TCP).  Optional per-request fields set the <code>Accept</code> header, extra header lines and a cookie jar; 1xx/204/304 responses are treated as bodyless so keep-alive does not wait for an idle timeout.</li>
 			<li><strong>uhttp_cookie</strong> — the cookie jar (<span class="file">uhttp_cookie.c</span>, 24 cookies of up to 768 bytes).  Every <code>Set-Cookie</code>, including those on redirect responses, is stored; matching cookies are sent on every request and redirect hop.  Cookies are host-only (<code>Domain</code> is ignored), <code>Path</code> is a prefix match, <code>Secure</code> cookies only go over https, and <code>Max-Age&lt;=0</code> or a 1970 <code>Expires</code> deletes a cookie.  The jar outlives the connection, so a cross-origin redirect that reconnects keeps the session.</li>
-			<li><strong>browser</strong> — runs network fetches in up to four headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share/bf&lt;session&gt;_&lt;slot&gt;*</code>.  The session id comes from the browser pid, so multiple browser windows do not share queue files.  Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order; one image starts before the script phase, and the remaining images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection; idle helpers stay warm across navigations (a cross-origin job just drops the old connection, and only busy helpers are killed), and helpers also exit after ten idle seconds or when the window loses focus.  A DNS failure is retried once after tearing the helpers down.  The helpers' DNS/TLS log lines go to a private tty that the browser drains and discards from every poll loop; a full tty ring blocks its writers, so an undrained one used to hang every helper after about sixteen TLS connections.  The status bar reports the page's total, header and first-byte times.</li>
+			<li><strong>browser</strong> — runs network fetches in up to four headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share/bf&lt;session&gt;_&lt;slot&gt;*</code>.  A request line is <code>&lt;seq&gt; &lt;cap&gt; [POST &lt;len&gt;] &lt;url&gt;</code> for page/form loads or <code>&lt;seq&gt; &lt;cap&gt; X &lt;method&gt; &lt;len&gt; &lt;content-type|-&gt; &lt;url&gt;</code> for script <code>fetch()</code>/XHR and empty-body form POSTs.  All helpers share one cookie jar in <code>/share/bcookies</code> (read before and written after every request that changed it), so a login session survives helper restarts and the parallel workers; it is RAM only and cleared at reboot.  The session id comes from the browser pid, so multiple browser windows do not share queue files.  Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order; one image starts before the script phase, and the remaining images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection; idle helpers stay warm across navigations (a cross-origin job just drops the old connection, and only busy helpers are killed), and helpers also exit after ten idle seconds or when the window loses focus.  A DNS failure is retried once after tearing the helpers down.  The helpers' DNS/TLS log lines go to a private tty that the browser drains and discards from every poll loop; a full tty ring blocks its writers, so an undrained one used to hang every helper after about sixteen TLS connections.  The status bar reports the page's total, header and first-byte times.</li>
 			<li><strong>websrv</strong> — the server side, speaking HTTP/1.1 + WebDAV over the TCP listener; see <a href="filesystems.html#webdav">Filesystems → WebDAV</a>.</li>
 		</ul>
 		<p>
@@ -427,13 +439,28 @@
 		<p>
 			The password lives only in the form field and the request buffer;
 			both are wiped after the attempt.  The Chat host's cookie header is
-			saved with the server address in <code>/share/chat.cfg</code>
-			(RAM-only; another path can be given as the argument or on the login
-			screen) and is re-saved when the server rolls the cookie.  The saved
+			saved with the server address in <code>/data/CHAT.CFG</code> when
+			the persistent <code>/data</code> volume is mounted, or
+			<code>/share/chat.cfg</code> (RAM-only) otherwise; another path can
+			be given as the argument or on the login screen, and a session left
+			in the old <code>/share</code> file is copied over once.  The
+			config is re-saved when the server rolls the cookie.  The saved
 			cookie is a bearer credential.  Passkey and external-SSO accounts
 			paste a <code>connect.sid</code> cookie from a signed-in browser
 			instead.
 		</p>
+		<p>
+			Message image attachments, link-preview images and profile
+			pictures are fetched through the same uhttp connection and
+			cookie jar, one per main-loop pass, and decoded by the in-tree
+			image library (PNG, JPEG, GIF first frame, BMP, TGA, PNM, ICO
+			and PAM).  Message images are scaled to at most 480x320 and
+			cached in a 16-entry, 6 MB LRU; avatars are 32x32 with a
+			64-entry cache and a circular alpha mask, and fall back to
+			initials until they load or when the account has no picture.
+			The fetch is capped at 4 MB and the decoder at 4 MP / 12 MB
+			of scratch.
+		</p>
 		<p>
 			There is no WebSocket: the open conversation is polled with
 			<code>GET /api/channels/:id/messages?after=&lt;newest&gt;</code> every
@@ -460,9 +487,9 @@
 					<tr><td>TLS certificates</td><td>Not verified</td><td>Encryption without authentication; MITM is undetected.</td></tr>
 					<tr><td>TLS DRBG</td><td>Weak (RDTSC/ticks/MAC)</td><td>Not suitable for high-value secrets.</td></tr>
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
-					<tr><td>Chat session</td><td>Cookie saved in <code>/share/chat.cfg</code></td><td>A bearer credential in RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
+					<tr><td>Chat session</td><td>Cookie saved in <code>/data/CHAT.CFG</code>, or <code>/share/chat.cfg</code> without a <code>/data</code> mount</td><td>A bearer credential on disk while <code>/data</code> is mounted, otherwise RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
 					<tr><td>WiFi WPA2</td><td>PSK/CCMP, handshake in ring 3</td><td>The SNonce comes from the weak TLS DRBG. The PTK/replay are kept in the kernel (<code>SYS_WIFI_SET_PTK</code>/<code>SYS_WIFI_GET_PTK</code>) and fetched by the <code>wifi __keep</code> helper by connection ID for group rekeys; no WPA3/PMF.</td></tr>
-					<tr><td>Saved WiFi credentials</td><td>Plaintext <code>/data/WIFI.CFG</code></td><td>The SSID and passphrase are stored in an 8.3 FAT file so <code>wifi autoconnect</code> can reconnect at boot; anyone who can read the disk can read the passphrase. <code>wifi forget</code> removes it.</td></tr>
+					<tr><td>Saved WiFi credentials</td><td>Plaintext <code>/data/WIFI.CFG</code></td><td>Up to 16 SSID/passphrase pairs are stored in an 8.3 FAT file (most recently used first) so <code>wifi autoconnect</code> can join any known network at boot; anyone who can read the disk can read the passphrases. <code>wifi forget [ssid]</code> and the menu's <em>Saved</em> view remove records.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
 					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>
@@ -478,7 +505,7 @@
 			<li><code>e1000e.c</code>, <code>r8168.c</code>, <code>ne2000.c</code>, <code>asix.c</code>, <code>rndis.c</code></li>
 			<li><code>wifi.c</code>, <code>wifi_fw.c</code>, <code>iwl_mvm.c</code>, <code>iwl_dvm.c</code>, <code>iwl_trans.c</code>, <code>rtl8821au.c</code> — Intel 7265D/3165 and 6200/6300 WiFi, Realtek RTL8821AU USB WiFi</li>
 			<li><code>wpa.c</code>, <code>wpa_crypto.c</code>, <code>ucmd_wifi.c</code> — WPA2-PSK supplicant and the <code>wifi</code> command (<code>make test-wpa</code>)</li>
-			<li><code>ucmd_netmenu.c</code>, <code>wifi_cfg.h</code> — top-bar network menu and its staged WiFi connect request</li>
+			<li><code>ucmd_netmenu.c</code>, <code>wifi_cfg.h</code>, <code>wifi_store.c/h</code> — top-bar network popover, staged WiFi connect request and the saved-network list</li>
 			<li><code>net.c</code>, <code>net.h</code> — ARP cache/ICMP/UDP/IP</li>
 			<li><code>netcore.c</code>, <code>netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 3 - 3
docs/userland.html


+ 1 - 1
gallery.c

@@ -766,7 +766,7 @@ static void draw_buttons(struct ngui *g, struct ngui_rect card)
 	ngui_text_ellipsis(g, rect_make(x, card.y + 72, card.w - 2 * CARD_PAD,
 					16),
 			   x, card.y + 72,
-			   "Buttons fire on release inside; hover paints an accent frame.",
+			   "Buttons fire on release inside; hover lights the raised edge.",
 			   g->theme.text_dim);
 	ngui_text_ellipsis(g, rect_make(x, card.y + 94, card.w - 2 * CARD_PAD,
 					16),

+ 2 - 0
gpu.c

@@ -2,6 +2,7 @@
 
 #include "gpu.h"
 #include "pci.h"
+#include "backlight.h"
 #include "ati.h"
 #include "cirrus.h"
 #include "intel.h"
@@ -100,6 +101,7 @@ void gpu_init(unsigned int lfb_base)
 	} else if (active_vendor == PCI_VENDOR_INTEL) {
 		gpu_vendor_id = GPU_VENDOR_INTEL;
 		intel_init(active_bus, active_dev, (active_id >> 16) & 0xFFFF);
+		backlight_init(active_bus, active_dev, (active_id >> 16) & 0xFFFF);
 	} else if (active_vendor == PCI_VENDOR_CIRRUS) {
 		gpu_vendor_id = GPU_VENDOR_CIRRUS;
 		cirrus_init();

+ 90 - 2
io.c

@@ -3,10 +3,13 @@
    slot 0 / boot fall back to a static screen the WM does not render. */
 
 #include "io.h"
+#include "backlight.h"
+#include "cros_ec.h"
 #include "fbtext.h"
 #include "mouse.h"
 #include "process.h"
 #include "screen.h"
+#include "spinlock.h"
 #include "timer.h"
 #include "tty.h"
 
@@ -67,6 +70,57 @@ static unsigned int repeat_at;
 static volatile unsigned char kbd_buf[KBD_BUF_SIZE];
 static volatile unsigned int kbd_head, kbd_tail;
 
+/* Raw decoder tap for `keytest`; independent of the decoded key queue so it
+ * also records releases, E0 prefixes and keys the decoder ignores. */
+#define KBD_TAP_SIZE 64
+static struct io_keytap kbd_tap[KBD_TAP_SIZE];
+static unsigned int kbd_tap_head, kbd_tap_tail;
+static spinlock_t kbd_tap_lock;   /* producer/consumer can run on different CPUs */
+
+static void kbd_tap_push(unsigned char raw, unsigned char ext,
+			 unsigned char kind, int key)
+{
+	unsigned int flags;
+	unsigned int next;
+
+	spin_lock_irqsave(&kbd_tap_lock, &flags);
+	next = (kbd_tap_head + 1) % KBD_TAP_SIZE;
+	kbd_tap[kbd_tap_head].raw = raw;
+	kbd_tap[kbd_tap_head].ext = ext;
+	kbd_tap[kbd_tap_head].kind = kind;
+	kbd_tap[kbd_tap_head].key = key;
+	kbd_tap_head = next;
+	if (next == kbd_tap_tail)
+		kbd_tap_tail = (kbd_tap_tail + 1) % KBD_TAP_SIZE;
+	spin_unlock_irqrestore(&kbd_tap_lock, flags);
+}
+
+void io_keytap_reset(void)
+{
+	unsigned int flags;
+
+	spin_lock_irqsave(&kbd_tap_lock, &flags);
+	kbd_tap_head = kbd_tap_tail = 0;
+	spin_unlock_irqrestore(&kbd_tap_lock, flags);
+}
+
+int io_keytap_read(struct io_keytap *out)
+{
+	unsigned int flags;
+	int ok = 0;
+
+	if (!out)
+		return 0;
+	spin_lock_irqsave(&kbd_tap_lock, &flags);
+	if (kbd_tap_tail != kbd_tap_head) {
+		*out = kbd_tap[kbd_tap_tail];
+		kbd_tap_tail = (kbd_tap_tail + 1) % KBD_TAP_SIZE;
+		ok = 1;
+	}
+	spin_unlock_irqrestore(&kbd_tap_lock, flags);
+	return ok;
+}
+
 /* Fallback screen for slot 0 / boot / exception output (not rendered by WM). */
 static struct text_screen io_fallback;
 
@@ -274,8 +328,8 @@ static int kbd_repeat_poll(void)
 	return repeat_key;
 }
 
-/* Process one scancode byte; shared by io_poll_key and io_poll_key_with_hw. */
-static int kbd_process_byte(unsigned char sc)
+/* Decode one scancode byte; shared by io_poll_key and io_poll_key_with_hw. */
+static int kbd_process_byte_inner(unsigned char sc)
 {
 	int key;
 
@@ -295,6 +349,13 @@ static int kbd_process_byte(unsigned char sc)
 			ctrl_pressed = 1;
 			return 0;
 		}
+		if (sc == 0x14 || sc == 0x15) {
+			/* Standard AT brightness down/up (E0 14 / E0 15);
+			 * ChromeOS EC action-key boards send these. */
+			if (backlight_present())
+				backlight_step(sc == 0x14 ? -1 : 1);
+			return 0;
+		}
 		if (sc == 0x4B)
 			key = ctrl_pressed ? IO_KEY_CTRL_LEFT : IO_KEY_LEFT;
 		else if (sc == 0x4D)
@@ -324,6 +385,14 @@ static int kbd_process_byte(unsigned char sc)
 		kbd_repeat_stop(0, sc & 0x7F);
 		return 0;
 	}
+	/* A ChromeOS EC keyboard sends the action-row brightness keys as plain
+	 * F6/F7 (the older standard table).  Only claim them when a Chrome EC
+	 * is present, so a regular Braswell laptop keeps its function keys. */
+	if ((sc == 0x40 || sc == 0x41) && backlight_present() &&
+	    cros_ec_present()) {
+		backlight_step(sc == 0x40 ? -1 : 1);
+		return 0;
+	}
 	if (sc == 0x2A || sc == 0x36) {
 		shift_pressed = 1;
 		return 0;
@@ -357,6 +426,25 @@ static int kbd_process_byte(unsigned char sc)
 	return 0;
 }
 
+/* Tap every byte after decoding, so `keytest` sees the raw wire sequence
+ * (including E0 prefixes, releases and keys the decoder ignores). */
+static int kbd_process_byte(unsigned char sc)
+{
+	unsigned char ext = (unsigned char)kbd_extended;
+	unsigned char kind;
+	int key;
+
+	key = kbd_process_byte_inner(sc);
+	if (sc == 0xE0)
+		kind = 2;
+	else if (sc & 0x80)
+		kind = 1;
+	else
+		kind = 0;
+	kbd_tap_push(sc, ext, kind, key);
+	return key;
+}
+
 int io_poll_key(void)
 {
 	unsigned char sc;

+ 12 - 0
io.h

@@ -46,6 +46,18 @@ int io_keyboard_irq_masked(void);
    it is then decoded by the normal io_poll_key path. */
 void io_inject_scancode(unsigned char sc);
 
+/* Raw scancode tap for diagnostics (the `keytest` kernel command).  Every
+   byte fed to the set-1 decoder is recorded with the E0-prefix state, the
+   make/break/prefix kind and the decoded key (0 when nothing is produced). */
+struct io_keytap {
+	unsigned char raw;
+	unsigned char ext;
+	unsigned char kind;      /* 0 make, 1 break, 2 0xE0 prefix */
+	int key;
+};
+void io_keytap_reset(void);
+int io_keytap_read(struct io_keytap *out);
+
 /* While set, the WM stops draining the keyboard ring: an inline command
    (e.g. `format`'s confirmation) is polling for keys itself.  The WM still
    runs and the USB backend still queues scancodes. */

+ 248 - 10
js_browser.c

@@ -20,7 +20,7 @@
  * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a
  * slow CPU, so the budget is generous. */
 #define JS_RUN_LIMIT 20000
-#define JS_TIMERS 16
+#define JS_TIMERS 64
 
 struct js_timer {
 	int used;
@@ -71,6 +71,7 @@ static int node_put(js_State *state, void *p, const char *name);
 static int node_delete(js_State *state, void *p, const char *name);
 static void push_element_url(js_State *state, unsigned int node,
 			     const char *name);
+static void rellist_supports(js_State *state);
 
 /* One wrapper per DOM node: the same element must have the same object
  * identity on every access, or library caches (jQuery expando data, Sizzle)
@@ -91,7 +92,7 @@ static void push_node(js_State *state, unsigned int handle)
 	/* js_newuserdatax() pops a prototype from the top.  Wrappers inherit
 	 * from Object.prototype like real DOM nodes (toString/hasOwnProperty;
 	 * Angular calls node.toString() to sniff SVG). */
-	js_getregistry(state, "wrapproto");
+	js_getregistry(state, "nodeproto");
 	js_newuserdatax(state, "node", (void *)(uintptr_t)handle,
 			node_has, node_put, node_delete, 0);
 	js_copy(state, -1);
@@ -190,7 +191,7 @@ static unsigned int node_name(unsigned int node, char *buf, unsigned int cap)
  * per dispatch in a small event-state table and mirrored onto the event
  * object, so a submit handler can cancel the browser's default action. */
 
-#define JS_LISTENERS        64
+#define JS_LISTENERS       256
 #define JS_EVENT_SLOTS       8
 #define JS_EVENT_TEMPLATES  16
 
@@ -1993,6 +1994,51 @@ static int node_has(js_State *state, void *p, const char *name)
 		js_getglobal(state, "document");
 		return 1;
 	}
+	if (!strcmp(name, "localName")) {
+		unsigned int i;
+
+		if (n->type != BR_NODE_ELEM) {
+			js_pushnull(state);
+			return 1;
+		}
+		node_name(node, buf, sizeof(buf));
+		for (i = 0; buf[i]; i++)
+			if (buf[i] >= 'A' && buf[i] <= 'Z')
+				buf[i] = (char)(buf[i] - 'A' + 'a');
+		js_pushstring(state, buf);
+		return 1;
+	}
+	if (!strcmp(name, "namespaceURI")) {
+		unsigned int a;
+
+		if (n->type != BR_NODE_ELEM) {
+			js_pushnull(state);
+			return 1;
+		}
+		for (a = node; a && a < D->nnode; a = D->nodes[a].parent)
+			if (D->nodes[a].type == BR_NODE_ELEM &&
+			    D->nodes[a].tag == BR_TAG_SVG)
+				break;
+		js_pushstring(state, a && a < D->nnode ?
+			      "http://www.w3.org/2000/svg" :
+			      "http://www.w3.org/1999/xhtml");
+		return 1;
+	}
+	if (!strcmp(name, "isConnected")) {
+		unsigned int a = node;
+
+		while (a && a < D->nnode && D->nodes[a].parent)
+			a = D->nodes[a].parent;
+		js_pushboolean(state, a == 0 || a == D->root);
+		return 1;
+	}
+	if (!strcmp(name, "relList")) {
+		/* Only supports(): Vite's modulepreload polyfill asks it and
+		 * otherwise refetches every preloaded module through fetch(). */
+		js_newobject(state);
+		def_func(state, "supports", rellist_supports, 1);
+		return 1;
+	}
 	if (!strcmp(name, "getAttribute"))
 		{ push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
 	if (!strcmp(name, "setAttribute"))
@@ -2331,6 +2377,26 @@ static void location_set(js_State *state)
 		host.navigate(url);
 }
 
+/* assign()/replace(): navigate (the history entry is not replaced yet). */
+static void location_assign(js_State *state)
+{
+	if (host.navigate)
+		host.navigate(js_tostring(state, 1));
+	js_pushundefined(state);
+}
+
+static void location_reload(js_State *state)
+{
+	if (host.navigate && current_url)
+		host.navigate(current_url);
+	js_pushundefined(state);
+}
+
+static void location_tostring(js_State *state)
+{
+	js_pushstring(state, current_url ? current_url : "");
+}
+
 static void win_noop(js_State *state);
 
 struct loc_parts {
@@ -2431,13 +2497,13 @@ static void push_location(js_State *state)
 	LOC_FIELD(origin);
 #undef LOC_FIELD
 
-	js_newcfunction(state, win_noop, "reload", 0);
+	js_newcfunction(state, location_reload, "reload", 0);
 	js_setproperty(state, -2, "reload");
-	js_newcfunction(state, win_noop, "assign", 1);
+	js_newcfunction(state, location_assign, "assign", 1);
 	js_setproperty(state, -2, "assign");
-	js_newcfunction(state, win_noop, "replace", 1);
+	js_newcfunction(state, location_assign, "replace", 1);
 	js_setproperty(state, -2, "replace");
-	js_newcfunction(state, win_noop, "toString", 0);
+	js_newcfunction(state, location_tostring, "toString", 0);
 	js_setproperty(state, -2, "toString");
 }
 
@@ -2476,7 +2542,7 @@ static void url_put(char *out, unsigned int cap, unsigned int *n,
 /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
 static void url_normalize(char *url)
 {
-	char tmp[512];
+	char tmp[1024];
 	char *path;
 	unsigned int n = 0, i = 0;
 
@@ -2490,13 +2556,15 @@ static void url_normalize(char *url)
 	}
 	if (path[0] != '/')
 		return;
-	while (path[i]) {
+	/* The path only: ?query and #fragment are copied verbatim below. */
+	while (path[i] && path[i] != '?' && path[i] != '#') {
 		unsigned int start;
 
 		while (path[i] == '/')
 			i++;
 		start = i;
-		while (path[i] && path[i] != '/')
+		while (path[i] && path[i] != '/' && path[i] != '?' &&
+		       path[i] != '#')
 			i++;
 		if (i == start)
 			continue;
@@ -2517,6 +2585,10 @@ static void url_normalize(char *url)
 	}
 	if (n == 0)
 		tmp[n++] = '/';
+	else if (i > 0 && path[i - 1] == '/' && n + 1 < sizeof(tmp))
+		tmp[n++] = '/';     /* keep "dir/" a directory */
+	while (path[i] && n + 1 < sizeof(tmp))
+		tmp[n++] = path[i++];
 	tmp[n] = '\0';
 	memcpy(path, tmp, n + 1);
 }
@@ -2777,6 +2849,113 @@ static void win_matchmedia(js_State *state)
 	def_func(state, "removeEventListener", win_noop, 2);
 }
 
+static void rellist_supports(js_State *state)
+{
+	const char *t = js_tostring(state, 1);
+
+	js_pushboolean(state, !strcmp(t, "modulepreload") ||
+		       !strcmp(t, "preload") || !strcmp(t, "stylesheet"));
+}
+
+/* ---- primitives for js_prelude.js ---- */
+
+/* __nb_http(method, url, contentType, body) -> [status, ctype, url, text].
+ * Synchronous: the host fetches through its helpers while the script
+ * waits.  A network failure throws (fetch() turns it into a TypeError). */
+static void nb_http(js_State *state)
+{
+	struct js_http_resp r;
+	const char *method = js_tostring(state, 1);
+	const char *url = js_tostring(state, 2);
+	const char *ctype = js_tostring(state, 3);
+	const char *body = js_tostring(state, 4);
+	char err[96];
+	int rv;
+
+	memset(&r, 0, sizeof(r));
+	err[0] = '\0';
+	rv = host.http ? host.http(method, url, ctype, body,
+				   (unsigned int)strlen(body), &r, err,
+				   (int)sizeof(err)) : -1;
+	/* The budget covers running JavaScript, not the network wait. */
+	js_setlimit(state, JS_RUN_LIMIT, 0);
+	if (rv != 0) {
+		free(r.body);
+		js_typeerror(state, "network error: %s",
+			     err[0] ? err : "fetch failed");
+	}
+	js_newarray(state);
+	js_pushnumber(state, r.status);
+	js_setindex(state, -2, 0);
+	js_pushstring(state, r.ctype);
+	js_setindex(state, -2, 1);
+	js_pushstring(state, r.url);
+	js_setindex(state, -2, 2);
+	js_pushlstring(state, r.body ? r.body : "", (int)r.len);
+	js_setindex(state, -2, 3);
+	free(r.body);
+}
+
+#define JS_STORAGE_MAX (32u * 1024u)
+
+/* __nb_storage(kind) -> text, __nb_storage(kind, text) stores it. */
+static void nb_storage(js_State *state)
+{
+	int kind = js_tointeger(state, 1);
+	char *buf;
+	int n;
+
+	if (js_isstring(state, 2)) {
+		if (host.storage)
+			host.storage(kind, js_tostring(state, 2), 0, 0);
+		js_pushundefined(state);
+		return;
+	}
+	buf = (char *)malloc(JS_STORAGE_MAX);
+	n = buf && host.storage ?
+	    host.storage(kind, 0, buf, (int)JS_STORAGE_MAX) : -1;
+	if (n > 0)
+		js_pushlstring(state, buf, n);
+	else
+		js_pushstring(state, "");
+	free(buf);
+}
+
+static void url_resolve(const char *base, const char *rel,
+			char *out, unsigned int cap);
+
+static void nb_resolve(js_State *state)
+{
+	char out[512];
+
+	url_resolve(js_tostring(state, 1), js_tostring(state, 2), out,
+		    sizeof(out));
+	js_pushstring(state, out);
+}
+
+extern const char js_prelude_source[];
+
+static void install_prelude(js_State *state)
+{
+	js_newcfunction(state, nb_http, "__nb_http", 4);
+	js_defglobal(state, "__nb_http", 0);
+	js_newcfunction(state, nb_storage, "__nb_storage", 2);
+	js_defglobal(state, "__nb_storage", 0);
+	js_newcfunction(state, nb_resolve, "__nb_resolve", 2);
+	js_defglobal(state, "__nb_resolve", 0);
+	js_getregistry(state, "nodeproto");
+	js_defglobal(state, "__nb_nodeproto", 0);
+	if (js_ploadstring(state, "[prelude]", js_prelude_source)) {
+		report_top(state);
+		return;
+	}
+	js_pushundefined(state);
+	if (js_pcall(state, 0))
+		report_top(state);
+	else
+		js_pop(state, 1);
+}
+
 static void install_globals(js_State *state)
 {
 	unsigned int h;
@@ -2784,6 +2963,10 @@ static void install_globals(js_State *state)
 	/* Shared prototype of the node/style/dataset wrappers. */
 	js_newobject(state);
 	js_setregistry(state, "wrapproto");
+	/* DOM node wrappers: their own prototype, so the prelude can add the
+	 * Element methods there without touching style/dataset objects. */
+	js_newobject(state);
+	js_setregistry(state, "nodeproto");
 	js_newobject(state);
 	def_func(state, "getElementById", doc_getelementbyid, 1);
 	def_func(state, "createElement", doc_create_element, 1);
@@ -2914,6 +3097,32 @@ static void install_globals(js_State *state)
 	js_pop(state, 1);
 }
 
+static int module_resolve(const char *base, const char *name, char *out,
+			  unsigned int cap)
+{
+	url_resolve(base && base[0] ? base :
+		    (current_url ? current_url : ""), name, out, cap);
+	return 0;
+}
+
+static char *module_load(const char *url, unsigned int *len)
+{
+	char *src;
+
+	if (!host.load_script)
+		return 0;
+	src = host.load_script(url, len);
+	if (J)
+		js_setlimit(J, JS_RUN_LIMIT, 0);
+	if (!src && host.report) {
+		char msg[600];
+
+		snprintf(msg, sizeof(msg), "Cannot load module %s", url);
+		host.report(msg);
+	}
+	return src;
+}
+
 int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
 {
 	if (!doc || !h)
@@ -2934,7 +3143,10 @@ int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
 		return -1;
 	js_setreport(J, report_cb);
 	js_atpanic(J, panic_cb);
+	js_setmodulehost(J, module_resolve, module_load);
 	install_globals(J);
+	js_setlimit(J, JS_RUN_LIMIT, 0);
+	install_prelude(J);
 	return 0;
 }
 
@@ -3061,3 +3273,29 @@ int js_browser_run(const char *source, const char *url)
 	panic_armed = 0;
 	return 0;
 }
+
+/* Run a <script type="module">: imports are resolved against `url` and
+ * loaded through host.load_script. */
+int js_browser_run_module(const char *source, const char *url)
+{
+	if (!J || !D)
+		return -1;
+	js_setlimit(J, JS_RUN_LIMIT, 0);
+	panic_armed = 1;
+	if (setjmp(panic_env)) {
+		panic_armed = 0;
+		if (host.report)
+			host.report("uncaught JavaScript exception");
+		J = 0;
+		D = 0;
+		return -1;
+	}
+	if (js_ploadmodule(J, url ? url : "[module]", source)) {
+		report_top(J);
+		panic_armed = 0;
+		return -1;
+	}
+	js_pop(J, 1);
+	panic_armed = 0;
+	return 0;
+}

+ 25 - 0
js_browser.h

@@ -9,6 +9,16 @@
 
 struct br_doc;
 
+/* One synchronous HTTP exchange for fetch()/XMLHttpRequest.  `body` is a
+ * malloc()ed buffer owned by the caller after the call (may be NULL). */
+struct js_http_resp {
+	int status;
+	char ctype[64];
+	char url[512];          /* final URL after redirects */
+	char *body;
+	unsigned int len;
+};
+
 struct js_browser_host {
 	void (*status)(const char *msg, int error);
 	void (*report)(const char *msg);
@@ -32,6 +42,17 @@ struct js_browser_host {
 	/* Computed style for getComputedStyle(); return 1 when known. */
 	int (*computed)(unsigned int node, const char *property, char *buf,
 			int cap);
+	/* fetch()/XHR: returns 0 and fills `r`, or -1 with `err` set. */
+	int (*http)(const char *method, const char *url, const char *ctype,
+		    const char *body, unsigned int body_len,
+		    struct js_http_resp *r, char *err, int errcap);
+	/* Module source for an absolute URL, malloc()ed and NUL-terminated
+	 * (the caller frees it); NULL when it cannot be loaded. */
+	char *(*load_script)(const char *url, unsigned int *len);
+	/* Web Storage for this page's origin; kind 0 = local, 1 = session.
+	 * With `set` the text is stored (returns 0); otherwise it is read into
+	 * out (returns its length, or -1). */
+	int (*storage)(int kind, const char *set, char *out, int cap);
 	const char *page_url;   /* location.href for every script on the page */
 	unsigned int width;     /* viewport size for window.inner* */
 	unsigned int height;
@@ -44,6 +65,10 @@ void js_browser_stop(void);
 /* Run one script.  `url` is used in error messages and by location.href. */
 int js_browser_run(const char *source, const char *url);
 
+/* Run one <script type="module">; its imports load through
+ * host.load_script. */
+int js_browser_run_module(const char *source, const char *url);
+
 /* Run due setTimeout/setInterval callbacks; call once per UI loop. */
 void js_browser_tick(void);
 

+ 155 - 0
js_mu.c

@@ -85,6 +85,8 @@ struct js_State {
 	int limited;
 	int depth;              /* nested entries from C into JavaScript */
 	void *jsstack;          /* private engine stack (MU_OWN_STACK) */
+	js_ModuleResolve mod_resolve;
+	js_ModuleLoad mod_load;
 };
 
 struct mu_ud {
@@ -622,6 +624,40 @@ static int mu_interrupt(JSRuntime *rt, void *opaque)
 	return J->limited && (int)(u_ticks_ms() - J->deadline) >= 0;
 }
 
+/* An async function or a promise chain that fails with nobody listening
+ * (Vite apps bootstrap from an async IIFE) would otherwise vanish without a
+ * trace.  The error goes to the report hook, like an uncaught exception.
+ * A handler attached later in the same job cannot be detected here, so a
+ * rejection that is handled late is still reported once. */
+static void mu_rejection(JSContext *ctx, JSValueConst promise,
+			 JSValueConst reason, int is_handled, void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	const char *msg, *stack = 0;
+	JSValue st = JS_UNDEFINED;
+	char buf[768];
+
+	(void)promise;
+	if (is_handled || !J->report)
+		return;
+	msg = JS_ToCString(ctx, reason);
+	if (JS_IsObject(reason)) {
+		st = JS_GetPropertyStr(ctx, reason, "stack");
+		if (JS_IsString(st))
+			stack = JS_ToCString(ctx, st);
+	}
+	snprintf(buf, sizeof(buf), "Uncaught (in promise) %s%s%s",
+		 msg ? msg : "error", stack ? "\n" : "", stack ? stack : "");
+	J->report(J, buf);
+	if (stack)
+		JS_FreeCString(ctx, stack);
+	JS_FreeValue(ctx, st);
+	if (msg)
+		JS_FreeCString(ctx, msg);
+	else
+		JS_FreeValue(ctx, JS_GetException(ctx));
+}
+
 js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
 {
 	js_State *J;
@@ -656,6 +692,7 @@ js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
 	}
 	JS_SetContextOpaque(J->ctx, J);
 	JS_SetInterruptHandler(J->rt, mu_interrupt, J);
+	JS_SetHostPromiseRejectionTracker(J->rt, mu_rejection, J);
 	J->registry = JS_NewObject(J->ctx);
 	return J;
 }
@@ -804,6 +841,124 @@ static JSValue mu_compile(js_State *J, const char *filename,
 	return e.result;
 }
 
+/* ---- ES modules ----
+ *
+ * Module specifiers are resolved to absolute URLs by the host, and QuickJS
+ * caches modules by that name, so every URL is fetched and evaluated once
+ * per state, as in a browser.  The loader runs synchronously inside the
+ * engine: the host fetches the source while the script waits. */
+
+static void mu_set_import_meta(JSContext *ctx, JSModuleDef *m,
+			       const char *url)
+{
+	JSValue meta = JS_GetImportMeta(ctx, m);
+
+	if (JS_IsException(meta))
+		return;
+	JS_DefinePropertyValueStr(ctx, meta, "url", JS_NewString(ctx, url),
+				  JS_PROP_C_W_E);
+	JS_FreeValue(ctx, meta);
+}
+
+static char *mu_module_normalize(JSContext *ctx, const char *base,
+				 const char *name, void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	char buf[1024];
+	size_t n;
+	char *out;
+
+	if (!J->mod_resolve || J->mod_resolve(base, name, buf, sizeof(buf)))
+		snprintf(buf, sizeof(buf), "%s", name);
+	n = strlen(buf);
+	out = (char *)js_malloc(ctx, n + 1);
+	if (out)
+		memcpy(out, buf, n + 1);
+	return out;
+}
+
+static JSModuleDef *mu_module_loader(JSContext *ctx, const char *name,
+				     void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	unsigned int len = 0;
+	char *src;
+	JSValue f;
+	JSModuleDef *m;
+
+	src = J->mod_load ? J->mod_load(name, &len) : 0;
+	if (!src) {
+		JS_ThrowReferenceError(ctx, "could not load module '%s'", name);
+		return 0;
+	}
+	f = JS_Eval(ctx, src, len, name,
+		    JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
+	free(src);
+	if (JS_IsException(f))
+		return 0;
+	m = (JSModuleDef *)JS_VALUE_GET_PTR(f);
+	mu_set_import_meta(ctx, m, name);
+	JS_FreeValue(ctx, f);
+	return m;
+}
+
+void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
+		      js_ModuleLoad load)
+{
+	J->mod_resolve = resolve;
+	J->mod_load = load;
+	JS_SetModuleLoaderFunc(J->rt, mu_module_normalize, mu_module_loader, J);
+}
+
+static void mu_do_module(struct mu_entry *e)
+{
+	JSContext *ctx = e->J->ctx;
+	JSValue f;
+
+	f = JS_Eval(ctx, e->source, strlen(e->source),
+		    e->filename ? e->filename : "[module]",
+		    JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
+	if (JS_IsException(f)) {
+		e->result = f;
+		return;
+	}
+	mu_set_import_meta(ctx, (JSModuleDef *)JS_VALUE_GET_PTR(f),
+			   e->filename ? e->filename : "");
+	/* Links the import graph (the loader fetches dependencies), then runs
+	 * it; the result is the evaluation promise. */
+	e->result = JS_EvalFunction(ctx, f);
+}
+
+int js_ploadmodule(js_State *J, const char *filename, const char *source)
+{
+	struct mu_entry e;
+	JSValue p;
+	int st;
+
+	memset(&e, 0, sizeof(e));
+	e.fn = mu_do_module;
+	e.filename = filename;
+	e.source = source;
+	mu_enter(J, &e);
+	p = e.result;
+	if (JS_IsException(p)) {
+		mu_push(J, JS_GetException(J->ctx));
+		return 1;
+	}
+	js_runjobs(J);
+	st = JS_PromiseState(J->ctx, p);
+	if (st == JS_PROMISE_REJECTED) {
+		JSValue r = JS_PromiseResult(J->ctx, p);
+
+		JS_FreeValue(J->ctx, p);
+		mu_push(J, r);
+		return 1;
+	}
+	JS_FreeValue(J->ctx, p);
+	mu_push(J, JS_UNDEFINED);
+	return 0;
+}
+
 int js_ploadstring(js_State *J, const char *filename, const char *source)
 {
 	JSValue f = mu_compile(J, filename, source);

+ 12 - 0
js_mu.h

@@ -44,6 +44,18 @@ void js_setlimit(js_State *J, int limit_ms, int memlimit);
 /* Run queued Promise jobs (then/await continuations). */
 void js_runjobs(js_State *J);
 
+/* ES modules.  resolve() turns a specifier into an absolute URL relative to
+ * the importing module (return 0 on success); load() returns the module
+ * source as a malloc()ed NUL-terminated string (NULL on failure). */
+typedef int (*js_ModuleResolve)(const char *base, const char *name,
+				char *out, unsigned int cap);
+typedef char *(*js_ModuleLoad)(const char *url, unsigned int *len);
+void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
+		      js_ModuleLoad load);
+/* Compile, link and evaluate a module and run the resulting jobs.  Returns
+ * 0 (undefined pushed) or 1 with the error value pushed. */
+int js_ploadmodule(js_State *J, const char *filename, const char *source);
+
 int js_ploadstring(js_State *J, const char *filename, const char *source);
 void js_loadstring(js_State *J, const char *filename, const char *source);
 int js_pcall(js_State *J, int n);

+ 8 - 0
js_prelude.S

@@ -0,0 +1,8 @@
+/* Embeds js_prelude.js (the browser's Web API layer) as a NUL-terminated
+ * string for js_browser.c. */
+	.section .rodata
+	.globl js_prelude_source
+js_prelude_source:
+	.incbin "js_prelude.js"
+	.byte 0
+	.section .note.GNU-stack,"",@progbits

+ 1132 - 0
js_prelude.js

@@ -0,0 +1,1132 @@
+/* Web platform APIs for the NebOS browser, written in JavaScript on top of a
+ * few C primitives (js_browser.c):
+ *   __nb_http(method, url, contentType, body) -> [status, ctype, finalUrl, text]
+ *   __nb_storage(kind[, text])  kind 0 = localStorage, 1 = sessionStorage
+ *   __nb_resolve(base, relative) -> absolute URL
+ *   __nb_nodeproto              prototype shared by every DOM node wrapper
+ * It runs once per page state, before the page's scripts; the primitives are
+ * removed from the global object afterwards.  Embedded by js_prelude.S. */
+(function (g) {
+"use strict";
+var http = g.__nb_http, storage = g.__nb_storage, resolve = g.__nb_resolve;
+var nodeproto = g.__nb_nodeproto;
+delete g.__nb_http; delete g.__nb_storage; delete g.__nb_resolve;
+delete g.__nb_nodeproto;
+var hasOwn = Object.prototype.hasOwnProperty;
+
+function def(name, value) {
+	Object.defineProperty(g, name, { value: value, writable: true,
+		configurable: true, enumerable: false });
+}
+
+/* ---- console, timers, misc globals ---- */
+var con = g.console, rawlog = con.log;
+/* Errors print with their stack (Vue reports caught errors this way). */
+function fmt(a) {
+	if (a instanceof Error)
+		return a.name + ": " + a.message + (a.stack ? "\n" + a.stack : "");
+	if (a !== null && typeof a === "object" && !(typeof a.nodeType === "number")) {
+		try { return JSON.stringify(a); } catch (e) { return String(a); }
+	}
+	return a;
+}
+function logger(prefix) {
+	return function () {
+		var args = Array.prototype.map.call(arguments, fmt);
+		if (prefix) args.unshift(prefix);
+		rawlog.apply(con, args);
+	};
+}
+con.log = logger("");
+con.info = logger("");
+con.debug = logger("");
+con.dir = logger("");
+con.warn = logger("[warn]");
+con.error = logger("[error]");
+con.trace = logger("[trace]");
+["group", "groupCollapsed", "groupEnd", "time", "timeEnd", "timeLog",
+ "table", "count", "countReset", "clear"].forEach(function (k) {
+	if (!con[k]) con[k] = function () {};
+});
+con.assert = function (c) {
+	if (!c) con.log.apply(con, ["Assertion failed:"].concat(
+		Array.prototype.slice.call(arguments, 1)));
+};
+def("self", g); def("top", g); def("parent", g); def("frames", g);
+def("isSecureContext", true);
+def("origin", g.location.origin);
+def("queueMicrotask", function (f) { Promise.resolve().then(f); });
+def("requestIdleCallback", function (f) {
+	return setTimeout(function () {
+		f({ didTimeout: false, timeRemaining: function () { return 10; } });
+	}, 1);
+});
+def("cancelIdleCallback", function (id) { clearTimeout(id); });
+def("structuredClone", function (v) {
+	return v === undefined ? v : JSON.parse(JSON.stringify(v));
+});
+
+class DOMException extends Error {
+	constructor(message, name) {
+		super(message === undefined ? "" : message);
+		this.name = name === undefined ? "Error" : name;
+	}
+}
+def("DOMException", DOMException);
+
+/* ---- base64 ---- */
+var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+def("btoa", function (s) {
+	s = String(s);
+	var out = "", i;
+	for (i = 0; i < s.length; i += 3) {
+		var a = s.charCodeAt(i), b = s.charCodeAt(i + 1),
+		    c = s.charCodeAt(i + 2);
+		if (a > 255 || b > 255 || c > 255)
+			throw new DOMException("Invalid character",
+					       "InvalidCharacterError");
+		var n = (a << 16) | ((b || 0) << 8) | (c || 0);
+		out += B64[n >> 18 & 63] + B64[n >> 12 & 63] +
+			(i + 1 < s.length ? B64[n >> 6 & 63] : "=") +
+			(i + 2 < s.length ? B64[n & 63] : "=");
+	}
+	return out;
+});
+def("atob", function (s) {
+	s = String(s).replace(/[\s=]/g, "");
+	var out = "", bits = 0, acc = 0, i;
+	for (i = 0; i < s.length; i++) {
+		var v = B64.indexOf(s[i]);
+		if (v < 0)
+			throw new DOMException("Invalid character",
+					       "InvalidCharacterError");
+		acc = (acc << 6) | v;
+		bits += 6;
+		if (bits >= 8) {
+			bits -= 8;
+			out += String.fromCharCode((acc >> bits) & 255);
+		}
+	}
+	return out;
+});
+
+/* ---- text encoding ---- */
+function utf8(s) {
+	var out = [], i;
+	s = String(s);
+	for (i = 0; i < s.length; i++) {
+		var c = s.charCodeAt(i);
+		if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) {
+			var d = s.charCodeAt(i + 1);
+			if (d >= 0xdc00 && d < 0xe000) {
+				c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
+				i++;
+			}
+		}
+		if (c < 0x80) out.push(c);
+		else if (c < 0x800) out.push(0xc0 | c >> 6, 0x80 | c & 63);
+		else if (c < 0x10000)
+			out.push(0xe0 | c >> 12, 0x80 | c >> 6 & 63, 0x80 | c & 63);
+		else
+			out.push(0xf0 | c >> 18, 0x80 | c >> 12 & 63,
+				 0x80 | c >> 6 & 63, 0x80 | c & 63);
+	}
+	return new Uint8Array(out);
+}
+function bytesOf(b) {
+	if (b instanceof ArrayBuffer) return new Uint8Array(b);
+	if (ArrayBuffer.isView(b))
+		return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
+	return utf8(b);
+}
+function unutf8(u) {
+	var s = "", i = 0;
+	while (i < u.length) {
+		var c = u[i++];
+		if (c >= 0xf0 && i + 2 < u.length + 0) {
+			c = ((c & 7) << 18) | ((u[i++] & 63) << 12) |
+			    ((u[i++] & 63) << 6) | (u[i++] & 63);
+		} else if (c >= 0xe0) {
+			c = ((c & 15) << 12) | ((u[i++] & 63) << 6) | (u[i++] & 63);
+		} else if (c >= 0xc0) {
+			c = ((c & 31) << 6) | (u[i++] & 63);
+		}
+		s += String.fromCodePoint(c);
+	}
+	return s;
+}
+class TextEncoder {
+	get encoding() { return "utf-8"; }
+	encode(s) { return utf8(s === undefined ? "" : s); }
+}
+class TextDecoder {
+	constructor(label) { this.encoding = "utf-8"; }
+	decode(b) { return b ? unutf8(bytesOf(b)) : ""; }
+}
+def("TextEncoder", TextEncoder);
+def("TextDecoder", TextDecoder);
+
+/* ---- URLSearchParams / URL ---- */
+function qenc(s) {
+	return encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()~]/g,
+		function (c) {
+			return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+		});
+}
+function qdec(s) {
+	s = s.replace(/\+/g, " ");
+	try { return decodeURIComponent(s); } catch (e) { return s; }
+}
+class URLSearchParams {
+	constructor(init) {
+		this._l = [];
+		this._url = null;
+		if (init == null) return;
+		if (init instanceof URLSearchParams) {
+			this._l = init._l.map(function (p) { return [p[0], p[1]]; });
+			return;
+		}
+		if (typeof init === "object" || typeof init === "function") {
+			if (typeof init[Symbol.iterator] === "function") {
+				for (var p of init)
+					this._l.push([String(p[0]), String(p[1])]);
+			} else {
+				for (var k of Object.keys(init))
+					this._l.push([k, String(init[k])]);
+			}
+			return;
+		}
+		this._parse(String(init));
+	}
+	_parse(s) {
+		this._l = [];
+		if (s[0] === "?") s = s.slice(1);
+		for (var part of s.split("&")) {
+			if (!part) continue;
+			var i = part.indexOf("=");
+			this._l.push(i < 0 ? [qdec(part), ""] :
+				[qdec(part.slice(0, i)), qdec(part.slice(i + 1))]);
+		}
+	}
+	_upd() {
+		if (this._url) {
+			var s = this.toString();
+			this._url._search = s ? "?" + s : "";
+		}
+	}
+	append(k, v) { this._l.push([String(k), String(v)]); this._upd(); }
+	delete(k) {
+		k = String(k);
+		this._l = this._l.filter(function (p) { return p[0] !== k; });
+		this._upd();
+	}
+	get(k) {
+		k = String(k);
+		for (var p of this._l) if (p[0] === k) return p[1];
+		return null;
+	}
+	getAll(k) {
+		k = String(k);
+		return this._l.filter(function (p) { return p[0] === k; })
+			.map(function (p) { return p[1]; });
+	}
+	has(k) { return this.get(k) !== null; }
+	set(k, v) {
+		k = String(k); v = String(v);
+		var found = false;
+		this._l = this._l.filter(function (p) {
+			if (p[0] !== k) return true;
+			if (found) return false;
+			found = true;
+			p[1] = v;
+			return true;
+		});
+		if (!found) this._l.push([k, v]);
+		this._upd();
+	}
+	sort() {
+		this._l.sort(function (a, b) {
+			return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
+		});
+		this._upd();
+	}
+	forEach(f, t) { for (var p of this._l.slice()) f.call(t, p[1], p[0], this); }
+	keys() { return this._l.map(function (p) { return p[0]; })[Symbol.iterator](); }
+	values() { return this._l.map(function (p) { return p[1]; })[Symbol.iterator](); }
+	entries() { return this._l.map(function (p) { return [p[0], p[1]]; })[Symbol.iterator](); }
+	[Symbol.iterator]() { return this.entries(); }
+	get size() { return this._l.length; }
+	toString() {
+		return this._l.map(function (p) {
+			return qenc(p[0]) + "=" + qenc(p[1]);
+		}).join("&");
+	}
+}
+def("URLSearchParams", URLSearchParams);
+
+var URL_RE = /^([a-zA-Z][a-zA-Z0-9+.\-]*:)(\/\/([^\/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/;
+class URL {
+	constructor(url, base) {
+		url = String(url).trim();
+		if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:/.test(url)) {
+			if (base === undefined)
+				throw new TypeError("Invalid URL: " + url);
+			base = new URL(String(base)).href;
+			url = resolve(base, url);
+		}
+		this._parse(url);
+	}
+	_parse(u) {
+		var m = URL_RE.exec(u);
+		if (!m) throw new TypeError("Invalid URL: " + u);
+		this._protocol = m[1].toLowerCase();
+		var auth = m[3] || "", at = auth.lastIndexOf("@");
+		this._user = "";
+		this._pass = "";
+		if (at >= 0) {
+			var ui = auth.slice(0, at), c = ui.indexOf(":");
+			auth = auth.slice(at + 1);
+			this._user = c < 0 ? ui : ui.slice(0, c);
+			this._pass = c < 0 ? "" : ui.slice(c + 1);
+		}
+		var pm = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(auth);
+		this._hostname = (pm ? pm[1] : auth).toLowerCase();
+		this._port = (pm && pm[2]) || "";
+		if ((this._protocol === "https:" && this._port === "443") ||
+		    (this._protocol === "http:" && this._port === "80"))
+			this._port = "";
+		this._special = m[2] !== undefined;
+		this._pathname = m[4] || (this._special ? "/" : "");
+		this._search = m[5] && m[5].length > 1 ? m[5] : "";
+		this._hash = m[6] && m[6].length > 1 ? m[6] : "";
+		if (this._sp) this._sp._parse(this._search);
+	}
+	get protocol() { return this._protocol; }
+	set protocol(v) {
+		v = String(v);
+		this._protocol = (v.endsWith(":") ? v : v + ":").toLowerCase();
+	}
+	get username() { return this._user; }
+	set username(v) { this._user = String(v); }
+	get password() { return this._pass; }
+	set password(v) { this._pass = String(v); }
+	get hostname() { return this._hostname; }
+	set hostname(v) { this._hostname = String(v).toLowerCase(); }
+	get port() { return this._port; }
+	set port(v) { this._port = String(v); }
+	get host() { return this._hostname + (this._port ? ":" + this._port : ""); }
+	set host(v) {
+		var m = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(String(v));
+		if (m) { this._hostname = m[1].toLowerCase(); this._port = m[2] || ""; }
+	}
+	get pathname() { return this._pathname; }
+	set pathname(v) {
+		v = String(v);
+		this._pathname = this._special && v[0] !== "/" ? "/" + v : v;
+	}
+	get search() { return this._search; }
+	set search(v) {
+		v = String(v);
+		if (v && v[0] !== "?") v = "?" + v;
+		this._search = v === "?" ? "" : v;
+		if (this._sp) this._sp._parse(this._search);
+	}
+	get hash() { return this._hash; }
+	set hash(v) {
+		v = String(v);
+		if (v && v[0] !== "#") v = "#" + v;
+		this._hash = v === "#" ? "" : v;
+	}
+	get origin() {
+		return this._special && this._protocol !== "file:" ?
+			this._protocol + "//" + this.host : "null";
+	}
+	get href() {
+		var a = this._user ? this._user +
+			(this._pass ? ":" + this._pass : "") + "@" : "";
+		return this._protocol + (this._special ? "//" + a + this.host : "") +
+			this._pathname + this._search + this._hash;
+	}
+	set href(v) { this._parse(String(v)); }
+	get searchParams() {
+		if (!this._sp) {
+			this._sp = new URLSearchParams(this._search);
+			this._sp._url = this;
+		}
+		return this._sp;
+	}
+	toString() { return this.href; }
+	toJSON() { return this.href; }
+	static canParse(u, b) {
+		try { new URL(u, b); return true; } catch (e) { return false; }
+	}
+	static parse(u, b) {
+		try { return new URL(u, b); } catch (e) { return null; }
+	}
+	static createObjectURL() { return "blob:nebos/" + Date.now(); }
+	static revokeObjectURL() {}
+}
+def("URL", URL);
+def("webkitURL", URL);
+
+/* ---- Headers / Blob / FormData / Request / Response ---- */
+class Headers {
+	constructor(init) {
+		this._m = new Map();
+		if (!init) return;
+		if (init instanceof Headers)
+			init.forEach((v, k) => this.append(k, v));
+		else if (typeof init[Symbol.iterator] === "function")
+			for (var p of init) this.append(p[0], p[1]);
+		else
+			for (var k of Object.keys(init)) this.append(k, init[k]);
+	}
+	append(k, v) {
+		k = String(k).toLowerCase();
+		var o = this._m.get(k);
+		this._m.set(k, o !== undefined ? o + ", " + v : String(v));
+	}
+	set(k, v) { this._m.set(String(k).toLowerCase(), String(v)); }
+	get(k) {
+		var v = this._m.get(String(k).toLowerCase());
+		return v === undefined ? null : v;
+	}
+	has(k) { return this._m.has(String(k).toLowerCase()); }
+	delete(k) { this._m.delete(String(k).toLowerCase()); }
+	forEach(f, t) { for (var [k, v] of this._m) f.call(t, v, k, this); }
+	keys() { return this._m.keys(); }
+	values() { return this._m.values(); }
+	entries() { return this._m.entries(); }
+	[Symbol.iterator]() { return this._m.entries(); }
+}
+def("Headers", Headers);
+
+function partText(p) {
+	if (typeof p === "string") return p;
+	if (p instanceof Blob) return p._s;
+	if (p instanceof ArrayBuffer || ArrayBuffer.isView(p))
+		return unutf8(bytesOf(p));
+	return String(p);
+}
+class Blob {
+	constructor(parts, opts) {
+		this._s = (parts || []).map(partText).join("");
+		this.type = (opts && opts.type) || "";
+	}
+	get size() { return utf8(this._s).length; }
+	text() { return Promise.resolve(this._s); }
+	arrayBuffer() { return Promise.resolve(utf8(this._s).buffer); }
+	slice(a, b, t) { return new Blob([this._s.slice(a, b)], { type: t }); }
+}
+class File extends Blob {
+	constructor(parts, name, opts) {
+		super(parts, opts);
+		this.name = String(name);
+		this.lastModified = (opts && opts.lastModified) || Date.now();
+	}
+}
+def("Blob", Blob);
+def("File", File);
+
+class FormData {
+	constructor() { this._l = []; }
+	append(k, v) { this._l.push([String(k), v]); }
+	set(k, v) { this.delete(k); this.append(k, v); }
+	get(k) {
+		for (var p of this._l) if (p[0] === k) return p[1];
+		return null;
+	}
+	getAll(k) {
+		return this._l.filter(function (p) { return p[0] === k; })
+			.map(function (p) { return p[1]; });
+	}
+	has(k) { return this.get(k) !== null; }
+	delete(k) { this._l = this._l.filter(function (p) { return p[0] !== k; }); }
+	forEach(f, t) { for (var p of this._l) f.call(t, p[1], p[0], this); }
+	entries() { return this._l.map(function (p) { return [p[0], p[1]]; })[Symbol.iterator](); }
+	keys() { return this._l.map(function (p) { return p[0]; })[Symbol.iterator](); }
+	values() { return this._l.map(function (p) { return p[1]; })[Symbol.iterator](); }
+	[Symbol.iterator]() { return this.entries(); }
+}
+def("FormData", FormData);
+
+class AbortSignal {
+	constructor() {
+		this.aborted = false;
+		this.reason = undefined;
+		this.onabort = null;
+		this._l = [];
+	}
+	addEventListener(t, f) { if (t === "abort") this._l.push(f); }
+	removeEventListener(t, f) { this._l = this._l.filter(function (x) { return x !== f; }); }
+	throwIfAborted() { if (this.aborted) throw this.reason; }
+	static abort(r) { var c = new AbortController(); c.abort(r); return c.signal; }
+	static timeout(ms) {
+		var c = new AbortController();
+		setTimeout(function () {
+			c.abort(new DOMException("signal timed out", "TimeoutError"));
+		}, ms);
+		return c.signal;
+	}
+}
+class AbortController {
+	constructor() { this.signal = new AbortSignal(); }
+	abort(r) {
+		var s = this.signal, ev;
+		if (s.aborted) return;
+		s.aborted = true;
+		s.reason = r === undefined ?
+			new DOMException("signal is aborted without reason",
+					 "AbortError") : r;
+		ev = { type: "abort", target: s };
+		if (typeof s.onabort === "function") s.onabort(ev);
+		s._l.forEach(function (f) { f(ev); });
+	}
+}
+def("AbortSignal", AbortSignal);
+def("AbortController", AbortController);
+
+class Request {
+	constructor(input, init) {
+		init = init || {};
+		if (input instanceof Request) {
+			this.url = input.url;
+			this.method = input.method;
+			this.headers = new Headers(input.headers);
+			this.body = input.body;
+			this.signal = input.signal;
+		} else {
+			this.url = new URL(String(input), g.location.href).href;
+			this.method = "GET";
+			this.headers = new Headers();
+			this.body = null;
+			this.signal = null;
+		}
+		if (init.method) this.method = String(init.method).toUpperCase();
+		if (init.headers) this.headers = new Headers(init.headers);
+		if (init.body !== undefined) this.body = init.body;
+		if (init.signal) this.signal = init.signal;
+		this.credentials = init.credentials || "same-origin";
+		this.mode = init.mode || "cors";
+	}
+	clone() { return new Request(this); }
+}
+def("Request", Request);
+
+class Response {
+	constructor(body, init) {
+		init = init || {};
+		this._b = body == null ? "" : partText(body);
+		this.status = init.status === undefined ? 200 : init.status;
+		this.statusText = init.statusText || "";
+		this.headers = init.headers instanceof Headers ? init.headers :
+			new Headers(init.headers);
+		this.ok = this.status >= 200 && this.status < 300;
+		this.url = init.url || "";
+		this.redirected = !!init.redirected;
+		this.type = "basic";
+		this.bodyUsed = false;
+		this.body = null;
+	}
+	text() { this.bodyUsed = true; return Promise.resolve(this._b); }
+	json() {
+		this.bodyUsed = true;
+		try { return Promise.resolve(JSON.parse(this._b)); }
+		catch (e) { return Promise.reject(e); }
+	}
+	blob() {
+		this.bodyUsed = true;
+		return Promise.resolve(new Blob([this._b],
+			{ type: this.headers.get("content-type") || "" }));
+	}
+	arrayBuffer() { this.bodyUsed = true; return Promise.resolve(utf8(this._b).buffer); }
+	formData() { return Promise.reject(new TypeError("formData() is not supported")); }
+	clone() {
+		return new Response(this._b, { status: this.status,
+			statusText: this.statusText, url: this.url,
+			headers: new Headers(this.headers) });
+	}
+	static json(data, init) {
+		var h = new Headers(init && init.headers);
+		h.set("content-type", "application/json");
+		return new Response(JSON.stringify(data),
+			Object.assign({}, init, { headers: h }));
+	}
+	static error() { return new Response(null, { status: 0 }); }
+	static redirect(url, status) {
+		return new Response(null, { status: status || 302,
+			headers: { location: String(url) } });
+	}
+}
+def("Response", Response);
+
+var STATUS_TEXT = { 200: "OK", 201: "Created", 204: "No Content",
+	301: "Moved Permanently", 302: "Found", 303: "See Other",
+	304: "Not Modified", 400: "Bad Request", 401: "Unauthorized",
+	403: "Forbidden", 404: "Not Found", 409: "Conflict", 410: "Gone",
+	500: "Internal Server Error", 502: "Bad Gateway",
+	503: "Service Unavailable" };
+
+/* One synchronous request through the browser's fetch helpers. */
+function send(method, url, headers, body) {
+	var ct = headers.get("content-type");
+	if (body instanceof URLSearchParams) {
+		if (!ct) ct = "application/x-www-form-urlencoded;charset=UTF-8";
+		body = body.toString();
+	} else if (body instanceof FormData) {
+		var sp = new URLSearchParams();
+		body.forEach(function (v, k) {
+			sp.append(k, typeof v === "string" ? v : "");
+		});
+		body = sp.toString();
+		ct = "application/x-www-form-urlencoded;charset=UTF-8";
+	} else if (body instanceof Blob) {
+		if (!ct) ct = body.type;
+		body = body._s;
+	} else if (body != null && typeof body !== "string") {
+		body = partText(body);
+	} else if (typeof body === "string" && !ct) {
+		ct = "text/plain;charset=UTF-8";
+	}
+	if (method === "GET" || method === "HEAD") body = null;
+	var r = http(method, url, ct || "", body == null ? "" : body);
+	var h = new Headers();
+	if (r[1]) h.set("content-type", r[1]);
+	return { status: r[0], headers: h, url: r[2] || url, text: r[3] };
+}
+
+def("fetch", function (input, init) {
+	return new Promise(function (res, rej) {
+		var req, out;
+		try {
+			req = new Request(input, init);
+		} catch (e) {
+			rej(e);
+			return;
+		}
+		if (req.signal && req.signal.aborted) {
+			rej(req.signal.reason);
+			return;
+		}
+		try {
+			out = send(req.method, req.url, req.headers, req.body);
+		} catch (e) {
+			rej(new TypeError("Failed to fetch"));
+			return;
+		}
+		res(new Response(out.text, { status: out.status,
+			statusText: STATUS_TEXT[out.status] || "",
+			headers: out.headers, url: out.url,
+			redirected: out.url !== req.url }));
+	});
+});
+
+/* XMLHttpRequest on the same synchronous path; events fire asynchronously
+ * (from a timer) so the caller can finish wiring its handlers. */
+class XMLHttpRequest {
+	constructor() {
+		this.readyState = 0;
+		this.status = 0;
+		this.statusText = "";
+		this.responseText = "";
+		this.response = "";
+		this.responseType = "";
+		this.responseURL = "";
+		this.timeout = 0;
+		this.withCredentials = false;
+		this._h = new Headers();
+		this._rh = new Headers();
+		this._l = {};
+		this.upload = { addEventListener: function () {} };
+	}
+	open(method, url) {
+		this._m = String(method).toUpperCase();
+		this._u = new URL(String(url), g.location.href).href;
+		this.readyState = 1;
+	}
+	setRequestHeader(k, v) { this._h.append(k, v); }
+	getResponseHeader(k) { return this._rh.get(k); }
+	getAllResponseHeaders() {
+		var s = "";
+		this._rh.forEach(function (v, k) { s += k + ": " + v + "\r\n"; });
+		return s;
+	}
+	overrideMimeType() {}
+	addEventListener(t, f) { (this._l[t] = this._l[t] || []).push(f); }
+	removeEventListener(t, f) {
+		if (this._l[t]) this._l[t] = this._l[t].filter(function (x) { return x !== f; });
+	}
+	_fire(t) {
+		var ev = { type: t, target: this, currentTarget: this,
+			   lengthComputable: false, loaded: 0, total: 0 };
+		if (typeof this["on" + t] === "function") this["on" + t](ev);
+		(this._l[t] || []).slice().forEach((f) => f.call(this, ev));
+	}
+	abort() { this._aborted = true; }
+	send(body) {
+		var self = this, out, err = false;
+		try {
+			out = send(this._m, this._u, this._h, body);
+		} catch (e) {
+			err = true;
+		}
+		setTimeout(function () {
+			if (self._aborted) return;
+			if (err) {
+				self.readyState = 4;
+				self._fire("readystatechange");
+				self._fire("error");
+				self._fire("loadend");
+				return;
+			}
+			self.status = out.status;
+			self.statusText = STATUS_TEXT[out.status] || "";
+			self._rh = out.headers;
+			self.responseURL = out.url;
+			self.responseText = out.text;
+			if (self.responseType === "json") {
+				try { self.response = JSON.parse(out.text); }
+				catch (e) { self.response = null; }
+			} else {
+				self.response = out.text;
+			}
+			self.readyState = 4;
+			self._fire("readystatechange");
+			self._fire("load");
+			self._fire("loadend");
+		}, 0);
+	}
+}
+XMLHttpRequest.UNSENT = 0;
+XMLHttpRequest.OPENED = 1;
+XMLHttpRequest.HEADERS_RECEIVED = 2;
+XMLHttpRequest.LOADING = 3;
+XMLHttpRequest.DONE = 4;
+def("XMLHttpRequest", XMLHttpRequest);
+
+/* ---- Web Storage, persisted by the host per origin ---- */
+function makeStorage(kind) {
+	var data = {};
+	try {
+		var t = storage(kind);
+		if (t) data = JSON.parse(t) || {};
+	} catch (e) {
+		data = {};
+	}
+	function save() { storage(kind, JSON.stringify(data)); }
+	var api = {
+		getItem: function (k) {
+			k = String(k);
+			return hasOwn.call(data, k) ? data[k] : null;
+		},
+		setItem: function (k, v) { data[String(k)] = String(v); save(); },
+		removeItem: function (k) { delete data[String(k)]; save(); },
+		clear: function () { data = {}; save(); },
+		key: function (i) {
+			var k = Object.keys(data);
+			return i < k.length ? k[i] : null;
+		}
+	};
+	return new Proxy({}, {
+		get: function (t, k) {
+			if (typeof k === "symbol") return undefined;
+			if (k === "length") return Object.keys(data).length;
+			if (hasOwn.call(api, k)) return api[k];
+			return hasOwn.call(data, k) ? data[k] : undefined;
+		},
+		set: function (t, k, v) {
+			if (typeof k === "symbol") return true;
+			data[k] = String(v);
+			save();
+			return true;
+		},
+		has: function (t, k) {
+			return typeof k === "string" &&
+				(k === "length" || hasOwn.call(api, k) || hasOwn.call(data, k));
+		},
+		deleteProperty: function (t, k) {
+			if (typeof k === "string" && hasOwn.call(data, k)) {
+				delete data[k];
+				save();
+			}
+			return true;
+		},
+		ownKeys: function () { return Object.keys(data); },
+		getOwnPropertyDescriptor: function (t, k) {
+			if (typeof k === "string" && hasOwn.call(data, k))
+				return { value: data[k], writable: true,
+					 enumerable: true, configurable: true };
+			return undefined;
+		}
+	});
+}
+def("localStorage", makeStorage(0));
+def("sessionStorage", makeStorage(1));
+
+/* ---- crypto ---- */
+var K256 = [
+	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
+	0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+	0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
+	0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+	0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
+	0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+	0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
+	0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+	0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
+	0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+	0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
+function sha256(msg) {
+	var h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+		 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
+	var len = msg.length, n = ((len + 9 + 63) >> 6) << 6;
+	var b = new Uint8Array(n), w = new Array(64), i, j;
+	b.set(msg);
+	b[len] = 0x80;
+	b[n - 4] = (len * 8) >>> 24;
+	b[n - 3] = (len * 8) >>> 16 & 255;
+	b[n - 2] = (len * 8) >>> 8 & 255;
+	b[n - 1] = (len * 8) & 255;
+	b[n - 5] = Math.floor(len / 0x20000000) & 255;
+	function rotr(x, r) { return (x >>> r) | (x << (32 - r)); }
+	for (i = 0; i < n; i += 64) {
+		for (j = 0; j < 16; j++)
+			w[j] = (b[i + 4 * j] << 24) | (b[i + 4 * j + 1] << 16) |
+			       (b[i + 4 * j + 2] << 8) | b[i + 4 * j + 3];
+		for (j = 16; j < 64; j++) {
+			var s0 = rotr(w[j - 15], 7) ^ rotr(w[j - 15], 18) ^ (w[j - 15] >>> 3);
+			var s1 = rotr(w[j - 2], 17) ^ rotr(w[j - 2], 19) ^ (w[j - 2] >>> 10);
+			w[j] = (w[j - 16] + s0 + w[j - 7] + s1) | 0;
+		}
+		var a = h[0], bb = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
+		    gg = h[6], hh = h[7];
+		for (j = 0; j < 64; j++) {
+			var S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
+			var ch = (e & f) ^ (~e & gg);
+			var t1 = (hh + S1 + ch + K256[j] + w[j]) | 0;
+			var S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
+			var mj = (a & bb) ^ (a & c) ^ (bb & c);
+			var t2 = (S0 + mj) | 0;
+			hh = gg; gg = f; f = e; e = (d + t1) | 0;
+			d = c; c = bb; bb = a; a = (t1 + t2) | 0;
+		}
+		h[0] = (h[0] + a) | 0; h[1] = (h[1] + bb) | 0;
+		h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0;
+		h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0;
+		h[6] = (h[6] + gg) | 0; h[7] = (h[7] + hh) | 0;
+	}
+	var out = new Uint8Array(32);
+	for (i = 0; i < 8; i++) {
+		out[4 * i] = h[i] >>> 24;
+		out[4 * i + 1] = h[i] >>> 16 & 255;
+		out[4 * i + 2] = h[i] >>> 8 & 255;
+		out[4 * i + 3] = h[i] & 255;
+	}
+	return out;
+}
+/* The entropy is weak (Math.random seeded from the clock, stirred with the
+ * millisecond timer), like the TLS DRBG; fine for PKCE nonces on a hobby
+ * OS, not for long-term keys. */
+var rngState = sha256(utf8(String(Date.now()) + ":" + Math.random() + ":" +
+			   g.performance.now()));
+var rngPos = 0;
+function randomByte() {
+	if (rngPos >= 32) {
+		var seed = new Uint8Array(40);
+		seed.set(rngState);
+		var t = g.performance.now() * 1000 + Math.random() * 4294967296;
+		for (var i = 0; i < 8; i++)
+			seed[32 + i] = Math.floor(t / Math.pow(256, i)) & 255;
+		rngState = sha256(seed);
+		rngPos = 0;
+	}
+	return rngState[rngPos++];
+}
+var subtle = {
+	digest: function (alg, data) {
+		var name = typeof alg === "string" ? alg : alg && alg.name;
+		if (String(name).toUpperCase().replace("-", "") !== "SHA256")
+			return Promise.reject(new DOMException(
+				"Unsupported algorithm " + name, "NotSupportedError"));
+		return Promise.resolve(sha256(bytesOf(data)).buffer);
+	}
+};
+def("crypto", {
+	subtle: subtle,
+	getRandomValues: function (a) {
+		var u = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
+		for (var i = 0; i < u.length; i++) u[i] = randomByte();
+		return a;
+	},
+	randomUUID: function () {
+		var b = new Uint8Array(16), i, s = "";
+		this.getRandomValues(b);
+		b[6] = (b[6] & 0x0f) | 0x40;
+		b[8] = (b[8] & 0x3f) | 0x80;
+		for (i = 0; i < 16; i++) {
+			s += (b[i] + 0x100).toString(16).slice(1);
+			if (i === 3 || i === 5 || i === 7 || i === 9) s += "-";
+		}
+		return s;
+	}
+});
+
+/* ---- observers (no layout notifications yet: inert) ---- */
+class MutationObserver {
+	constructor(cb) { this._cb = cb; }
+	observe() {}
+	disconnect() {}
+	takeRecords() { return []; }
+}
+class ResizeObserver {
+	constructor(cb) { this._cb = cb; }
+	observe() {}
+	unobserve() {}
+	disconnect() {}
+}
+class IntersectionObserver {
+	constructor(cb, opts) { this._cb = cb; this.root = null; this.thresholds = [0]; }
+	observe() {}
+	unobserve() {}
+	disconnect() {}
+	takeRecords() { return []; }
+}
+def("MutationObserver", MutationObserver);
+def("ResizeObserver", ResizeObserver);
+def("IntersectionObserver", IntersectionObserver);
+
+/* ---- DOM classes: instanceof works on the node wrappers ---- */
+function domClass(name, test) {
+	var C = function () { throw new TypeError("Illegal constructor"); };
+	Object.defineProperty(C, "name", { value: name });
+	Object.defineProperty(C, Symbol.hasInstance, {
+		value: function (o) {
+			return o != null && typeof o === "object" &&
+				typeof o.nodeType === "number" && test(o);
+		}
+	});
+	C.prototype = nodeproto;
+	def(name, C);
+	return C;
+}
+function tag(t) { return function (o) { return o.nodeType === 1 && o.tagName === t; }; }
+domClass("EventTarget", function (o) { return true; });
+domClass("Node", function (o) { return true; });
+domClass("Element", function (o) { return o.nodeType === 1; });
+domClass("HTMLElement", function (o) { return o.nodeType === 1; });
+domClass("SVGElement", function (o) { return o.nodeType === 1 && o.namespaceURI === "http://www.w3.org/2000/svg"; });
+domClass("CharacterData", function (o) { return o.nodeType === 3 || o.nodeType === 8; });
+domClass("Text", function (o) { return o.nodeType === 3; });
+domClass("Comment", function (o) { return o.nodeType === 8; });
+domClass("DocumentFragment", function (o) { return o.nodeType === 11; });
+domClass("Document", function (o) { return o.nodeType === 9; });
+domClass("HTMLDocument", function (o) { return o.nodeType === 9; });
+domClass("HTMLInputElement", tag("INPUT"));
+domClass("HTMLTextAreaElement", tag("TEXTAREA"));
+domClass("HTMLSelectElement", tag("SELECT"));
+domClass("HTMLOptionElement", tag("OPTION"));
+domClass("HTMLButtonElement", tag("BUTTON"));
+domClass("HTMLFormElement", tag("FORM"));
+domClass("HTMLAnchorElement", tag("A"));
+domClass("HTMLImageElement", tag("IMG"));
+domClass("HTMLTemplateElement", tag("TEMPLATE"));
+domClass("HTMLIFrameElement", tag("IFRAME"));
+domClass("HTMLLinkElement", tag("LINK"));
+domClass("HTMLScriptElement", tag("SCRIPT"));
+domClass("HTMLStyleElement", tag("STYLE"));
+domClass("HTMLCanvasElement", tag("CANVAS"));
+def("Window", function Window() {});
+def("ShadowRoot", function ShadowRoot() {});
+
+var NodeConst = g.Node;
+[["ELEMENT_NODE", 1], ["ATTRIBUTE_NODE", 2], ["TEXT_NODE", 3],
+ ["CDATA_SECTION_NODE", 4], ["COMMENT_NODE", 8], ["DOCUMENT_NODE", 9],
+ ["DOCUMENT_TYPE_NODE", 10], ["DOCUMENT_FRAGMENT_NODE", 11]]
+	.forEach(function (p) { NodeConst[p[0]] = p[1]; });
+
+/* Methods every node wrapper inherits (the C has-hook answers the rest). */
+var doc = g.document;
+function toNode(n) {
+	return typeof n === "object" && n !== null ? n : doc.createTextNode(String(n));
+}
+Object.assign(nodeproto, {
+	setAttributeNS: function (ns, n, v) {
+		this.setAttribute(String(n).replace(/^[^:]*:/, ""), v);
+	},
+	getAttributeNS: function (ns, n) { return this.getAttribute(n); },
+	removeAttributeNS: function (ns, n) { this.removeAttribute(n); },
+	hasAttributeNS: function (ns, n) { return this.hasAttribute(n); },
+	toggleAttribute: function (n, force) {
+		var on = force === undefined ? !this.hasAttribute(n) : !!force;
+		if (on) this.setAttribute(n, "");
+		else this.removeAttribute(n);
+		return on;
+	},
+	getAttributeNames: function () {
+		var a = this.attributes, out = [], i;
+		for (i = 0; a && i < a.length; i++) out.push(a[i].name);
+		return out;
+	},
+	closest: function (sel) {
+		var e = this;
+		while (e && e.nodeType === 1) {
+			if (e.matches(sel)) return e;
+			e = e.parentNode;
+		}
+		return null;
+	},
+	append: function () {
+		for (var i = 0; i < arguments.length; i++)
+			this.appendChild(toNode(arguments[i]));
+	},
+	prepend: function () {
+		var first = this.firstChild;
+		for (var i = 0; i < arguments.length; i++)
+			this.insertBefore(toNode(arguments[i]), first);
+	},
+	before: function () {
+		var p = this.parentNode;
+		if (!p) return;
+		for (var i = 0; i < arguments.length; i++)
+			p.insertBefore(toNode(arguments[i]), this);
+	},
+	after: function () {
+		var p = this.parentNode, next = this.nextSibling;
+		if (!p) return;
+		for (var i = 0; i < arguments.length; i++)
+			p.insertBefore(toNode(arguments[i]), next);
+	},
+	replaceWith: function () {
+		var p = this.parentNode;
+		if (!p) return;
+		this.before.apply(this, arguments);
+		p.removeChild(this);
+	},
+	replaceChildren: function () {
+		while (this.firstChild) this.removeChild(this.firstChild);
+		this.append.apply(this, arguments);
+	},
+	insertAdjacentElement: function (pos, el) {
+		pos = String(pos).toLowerCase();
+		if (pos === "beforebegin") this.before(el);
+		else if (pos === "afterbegin") this.prepend(el);
+		else if (pos === "beforeend") this.appendChild(el);
+		else if (pos === "afterend") this.after(el);
+		return el;
+	},
+	insertAdjacentText: function (pos, text) {
+		this.insertAdjacentElement(pos, doc.createTextNode(String(text)));
+	},
+	insertAdjacentHTML: function (pos, html) {
+		var tmp = doc.createElement("div"), nodes = [], c;
+		tmp.innerHTML = html;
+		for (c = tmp.firstChild; c; c = c.nextSibling) nodes.push(c);
+		pos = String(pos).toLowerCase();
+		if (pos === "afterbegin") nodes.reverse();
+		for (c of nodes) {
+			tmp.removeChild(c);
+			this.insertAdjacentElement(pos, c);
+		}
+	},
+	getRootNode: function () { return doc; },
+	scrollIntoView: function () {},
+	scrollTo: function () {},
+	scrollBy: function () {},
+	animate: function () {
+		return { finished: Promise.resolve(), cancel: function () {},
+			 play: function () {}, pause: function () {},
+			 onfinish: null };
+	},
+	attachShadow: function () { return this; },
+	compareDocumentPosition: function (other) {
+		if (this === other) return 0;
+		if (this.contains(other)) return 20;
+		if (other.contains && other.contains(this)) return 10;
+		return 4;
+	},
+	isSameNode: function (o) { return this === o; },
+	normalize: function () {}
+});
+
+/* ---- document extras ---- */
+doc.createElementNS = function (ns, name) {
+	var el = doc.createElement(String(name).replace(/^[^:]*:/, ""));
+	if (ns === "http://www.w3.org/2000/svg")
+		el.setAttribute("xmlns", ns);
+	return el;
+};
+doc.createRange = function () {
+	return {
+		createContextualFragment: function (html) {
+			var tmp = doc.createElement("div"),
+			    frag = doc.createDocumentFragment();
+			tmp.innerHTML = html;
+			while (tmp.firstChild) frag.appendChild(tmp.firstChild);
+			return frag;
+		},
+		selectNodeContents: function () {},
+		setStart: function () {}, setEnd: function () {},
+		getBoundingClientRect: function () {
+			return { x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0,
+				 width: 0, height: 0 };
+		}
+	};
+};
+doc.createTreeWalker = undefined;
+doc.hasFocus = function () { return true; };
+doc.getElementsByName = function (n) {
+	return doc.querySelectorAll("[name=\"" + String(n).replace(/"/g, "\\\"") + "\"]");
+};
+doc.hidden = false;
+doc.visibilityState = "visible";
+doc.characterSet = "UTF-8";
+doc.charset = "UTF-8";
+doc.contentType = "text/html";
+doc.referrer = "";
+doc.dir = "";
+doc.fonts = { ready: Promise.resolve(), add: function () {},
+	      load: function () { return Promise.resolve([]); },
+	      check: function () { return true; },
+	      addEventListener: function () {} };
+doc.implementation = {
+	hasFeature: function () { return true; },
+	createHTMLDocument: function () { return doc; }
+};
+Object.defineProperty(doc, "activeElement", {
+	get: function () { return doc.body; }, configurable: true });
+Object.defineProperty(doc, "currentScript", {
+	get: function () { return null; }, configurable: true });
+Object.defineProperty(doc, "defaultView", {
+	get: function () { return g; }, configurable: true });
+
+var nav = g.navigator;
+nav.languages = [nav.language];
+nav.onLine = true;
+nav.cookieEnabled = true;
+nav.maxTouchPoints = 0;
+nav.hardwareConcurrency = 1;
+nav.vendor = "";
+nav.clipboard = {
+	writeText: function () { return Promise.resolve(); },
+	readText: function () { return Promise.resolve(""); }
+};
+nav.sendBeacon = function () { return true; };
+
+g.history.state = null;
+g.screen = { width: g.innerWidth, height: g.innerHeight,
+	     availWidth: g.innerWidth, availHeight: g.innerHeight,
+	     colorDepth: 16, pixelDepth: 16 };
+g.outerWidth = g.innerWidth;
+g.outerHeight = g.innerHeight;
+g.name = "";
+g.closed = false;
+g.open = function () { return null; };
+g.close = function () {};
+g.focus = function () {};
+g.blur = function () {};
+g.print = function () {};
+g.postMessage = function () {};
+g.confirm = function () { return true; };
+g.prompt = function () { return null; };
+g.dispatchEvent = g.dispatchEvent || function () { return true; };
+})(globalThis);

+ 58 - 37
kernel.c

@@ -24,6 +24,7 @@
 #include "rndis.h"
 #include "rtl8821au.h"
 #include "sched.h"
+#include "sys_wm.h"
 #include "thermal.h"
 #include "timer.h"
 #include "tpec.h"
@@ -368,9 +369,10 @@ static int net_restore_boot_config(void)
 	return dns[0] || dns[1] || dns[2] || dns[3];
 }
 
-/* Saved WiFi credentials on the writable /data volume: let the normal
- * supplicant reconnect in the background.  It leaves a wired link that is
- * physically up alone, and a missing /data or wifi helper is harmless. */
+/* Saved WiFi networks on the writable /data volume: let the normal
+ * supplicant scan and join any known network in the background.  It leaves a
+ * wired link that is physically up alone, and a missing /data or wifi helper
+ * is harmless. */
 static void boot_wifi_autoconnect(void)
 {
 	unsigned int sz = 0;
@@ -500,15 +502,6 @@ void kernel_main(void)
 	boot_val("smp cpus", cpu_count);
 	mouse_init();
 	boot_trace("ps2");
-	/* USB HID backend (mouse + keyboard): controller bring-up + first
-	 * scan; devices plugged in later are picked up by the hotplug
-	 * watcher in the WM loop. */
-	asix_register();
-	usbmsc_register();
-	rtl8821au_register();
-	rndis_register();
-	usbhid_init();
-	boot_trace("usb");
 	vga_shadow_init();
 	vga_fb_flush();
 	boot_trace("vga");
@@ -584,6 +577,51 @@ void kernel_main(void)
 	boot_trace("wm off");
 #endif
 
+	/* Publish the storage scan before anything can run a command: disk
+	 * paths wait for vfs_scan_busy (owned by the idle context until the
+	 * bootscan thread's vfs_mount_all() takes it over), /ramfs and /share
+	 * do not.  Then let the WM spawn the first terminal at once; neither
+	 * it nor the WM needs the NIC probe or the disks below. */
+	vfs_scan_owner_pid = 0;
+	vfs_scan_busy = 1;
+#ifndef NOWM
+	wm_server_boot_ready();
+	boot_trace("terminal ready");
+#else
+	boot_trace("terminal off");
+#endif
+
+#ifndef NOWM
+	/* Let the WM put the first terminal on screen before the USB bring-up
+	 * below: kernel_main is the idle context, so halting here hands the
+	 * CPU to the WM and the new terminal.  Bounded, in case no terminal
+	 * ever presents (missing /ramfs/bin/term). */
+	{
+		unsigned int t0 = get_ticks_ms();
+
+		while (!wm_first_window_presented &&
+		       get_ticks_ms() - t0 < 1000)
+			__asm__ volatile ("sti; hlt");
+	}
+	boot_trace("terminal shown");
+#endif
+
+	/* USB HID backend (mouse + keyboard) and the USB device drivers:
+	 * controller bring-up + first scan; devices plugged in later are
+	 * picked up by the hotplug watcher.  Non-preemptible, exactly like
+	 * the bring-up before the WM existed: port resets and the SOF a
+	 * freshly enabled low-speed device needs within 3 ms must not wait
+	 * for a WM frame.  Before the NIC probe: ASIX/RNDIS/RTL8821AU bind
+	 * during this scan, and USB disks before the bootscan thread. */
+	asix_register();
+	usbmsc_register();
+	rtl8821au_register();
+	rndis_register();
+	preempt_disable();
+	usbhid_init();
+	preempt_enable();
+	boot_trace("usb");
+
 	/* Probe the NIC (link negotiation is asynchronous now) before the
 	 * kworker starts, so its netlog flushes have a device to use. */
 	netdev_active();
@@ -602,35 +640,18 @@ void kernel_main(void)
 	}
 	boot_trace("kworker");
 
-	/* Slow storage bring-up happens behind the usable desktop: publish the
-	 * scan (disk paths wait for it) before the thread even runs, so no
-	 * command can see the half-built boot mount table.  Without a thread
-	 * slot, scan inline as before. */
+	/* Slow storage bring-up happens behind the usable desktop, in a
+	 * thread that may sleep through its probe timeouts.  The scan was
+	 * published above; its vfs_mount_all() takes over the ownership.
+	 * Without a thread slot, scan inline as before. */
 	boot_trace("storage begin");
 	storage_inline = 0;
-	{
-		int pid = process_create("bootscan", boot_storage_main);
-
-		if (pid > 0) {
-			vfs_scan_owner_pid = (unsigned int)pid;
-			vfs_scan_busy = 1;
-		} else {
-			vfs_mount_all();
-			boot_trace("storage");
-			storage_inline = 1;
-		}
+	if (process_create("bootscan", boot_storage_main) <= 0) {
+		vfs_mount_all();
+		boot_trace("storage");
+		storage_inline = 1;
 	}
 
-	/* The WM spawns the first terminal once it sees boot_ready.  The
-	 * terminal and every /ramfs command load without waiting for the
-	 * storage scan; a disk path waits for it (vfs_scan_busy). */
-#ifndef NOWM
-	wm_server_boot_ready();
-	boot_trace("terminal ready");
-#else
-	boot_trace("terminal off");
-#endif
-
 	/* With a linked NIC present, try DHCP; on failure the static default
 	 * stays.  A wired NIC without a cable is skipped so the WiFi fallback
 	 * below does not have to wait out the 4 s timeout first.  Deliberately

+ 241 - 3
ngui.c

@@ -21,6 +21,8 @@ const struct ngui_theme ngui_theme_dark = {
 	.icon_file   = NGUI_RGB(204, 210, 226),
 	.icon_disk   = NGUI_RGB(112, 174, 232),
 	.error       = NGUI_RGB(238, 116, 116),
+	.success     = NGUI_RGB(110, 210, 130),
+	.warning     = NGUI_RGB(238, 198, 88),
 };
 
 static unsigned int slen(const char *s)
@@ -494,6 +496,61 @@ void ngui_frame(struct ngui *ui, struct ngui_rect r, unsigned short color)
 	}
 }
 
+/* Brighten (step > 0) or darken (step < 0) an RGB565 color for the
+ * one-pixel bevel.  Green has six bits, red and blue five, so the green
+ * component moves twice as far to keep the shade visually even. */
+static unsigned short shade565(unsigned short c, int step)
+{
+	int r = (int)((c >> 11) & 0x1F) + step;
+	int g = (int)((c >> 5) & 0x3F) + step * 2;
+	int b = (int)(c & 0x1F) + step;
+
+	if (r < 0)
+		r = 0;
+	if (r > 0x1F)
+		r = 0x1F;
+	if (g < 0)
+		g = 0;
+	if (g > 0x3F)
+		g = 0x3F;
+	if (b < 0)
+		b = 0;
+	if (b > 0x1F)
+		b = 0x1F;
+	return (unsigned short)((r << 11) | (g << 5) | b);
+}
+
+/* A one-pixel two-tone edge: `tl` along the top and left, `br` along the
+ * bottom and right.  A raised widget lights its top/left and shades its
+ * bottom/right; an inset one (a text field) swaps the tones. */
+static void bevel_rect(struct ngui *ui, struct ngui_rect r,
+		       unsigned short tl, unsigned short br)
+{
+	if (r.w <= 0 || r.h <= 0)
+		return;
+	ngui_fill_rect(ui, rect_make(r.x, r.y, r.w, 1), tl);
+	ngui_fill_rect(ui, rect_make(r.x, r.y + r.h - 1, r.w, 1), br);
+	if (r.h > 2) {
+		ngui_fill_rect(ui, rect_make(r.x, r.y + 1, 1, r.h - 2), tl);
+		ngui_fill_rect(ui, rect_make(r.x + r.w - 1, r.y + 1, 1,
+					     r.h - 2), br);
+	}
+}
+
+/* Raised button edge: lit on the top/left, shaded on the bottom/right.  A
+ * pressed button inverts the bevel, so it reads as pushed in.  The hovered
+ * button keeps its accent on the lit edge. */
+static void button_bevel(struct ngui *ui, struct ngui_rect r,
+			 unsigned short bg, int hot, int down)
+{
+	if (down)
+		bevel_rect(ui, r, shade565(bg, -4), shade565(bg, 4));
+	else if (hot)
+		bevel_rect(ui, r, ui->theme.accent, shade565(bg, -4));
+	else
+		bevel_rect(ui, r, shade565(bg, 4), shade565(bg, -4));
+}
+
 static int ngui_isqrt(int v)
 {
 	int r = 0, bit = 1 << 30;
@@ -1240,7 +1297,7 @@ int ngui_button(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	else
 		bg = ui->theme.button;
 	ngui_fill_rect(ui, r, bg);
-	ngui_frame(ui, r, hot ? ui->theme.accent : ui->theme.border);
+	button_bevel(ui, r, bg, hot, ui->active == id);
 
 	if (label && label[0]) {
 		tw = (int)ngui_text_width_ui(ui, label);
@@ -1330,6 +1387,180 @@ int ngui_menu_item_utf8(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	return ngui_menu_item_common(ui, id, r, label, shortcut, checked, 1);
 }
 
+void ngui_popover_begin(struct ngui *ui, struct ngui_popover *p)
+{
+	struct ngui_rect all = { 0, 0, ui->w, ui->h };
+
+	ngui_fill_rect(ui, all, ui->theme.bg);
+	p->body = rect_make(12, 12, ui->w - 24, ui->h - 12 - 34);
+	p->footer = rect_make(12, ui->h - 30, ui->w - 24, 18);
+}
+
+void ngui_popover_footer(struct ngui *ui, const struct ngui_popover *p,
+			 const char *text, unsigned short color)
+{
+	if (!p || !text || !text[0])
+		return;
+	ngui_push_clip(ui, p->footer);
+	ngui_text_utf8(ui, p->footer.x, p->footer.y, text, color);
+	ngui_pop_clip(ui);
+}
+
+int ngui_section(struct ngui *ui, struct ngui_rect r, const char *caption,
+		 unsigned int action_id, const char *action)
+{
+	struct ngui_rect br;
+	int fired = 0;
+	int y = r.y + (r.h - 17) / 2;
+
+	if (y < r.y)
+		y = r.y;
+	ngui_text_px(ui, r.x, y, caption, slen(caption), ui->theme.text_dim,
+		     14, 1, 0, 0);
+	ngui_fill_rect(ui, rect_make(r.x, r.y + r.h - 1, r.w, 1),
+		       ui->theme.button);
+	if (action_id && action && action[0]) {
+		int tw = (int)ngui_text_width_ui(ui, action);
+		int bw = tw + 24;
+
+		if (bw < 58)
+			bw = 58;
+		br = rect_make(r.x + r.w - bw, r.y + (r.h - 24) / 2, bw, 24);
+		if (ngui_button(ui, action_id, br, action))
+			fired = 1;
+	}
+	return fired;
+}
+
+/* Shared by the byte and UTF-8 variants: one hover/selection row with an
+ * optional signal icon and right-aligned text. */
+static int ngui_list_row_common(struct ngui *ui, unsigned int id,
+				struct ngui_rect r,
+				const struct ngui_row *row, int utf8)
+{
+	int hot = ui->inside && ngui_rect_contains(&r, ui->mouse_x, ui->mouse_y);
+	int press_hot = ui->pressed &&
+		ngui_rect_contains(&r, ui->press_x, ui->press_y);
+	int release_hot = ui->released &&
+		ngui_rect_contains(&r, ui->release_x, ui->release_y);
+	int fired = 0;
+	int left = r.x + 10, right = r.x + r.w - 10;
+	int title_h, block_h, ty;
+	unsigned short bg = 0, fg, sub_fg, trail_fg;
+
+	if (press_hot)
+		ui->active = id;
+	if (ui->pressed && ui->released && press_hot && release_hot)
+		fired = 1;
+	if (ui->released && ui->active == id) {
+		if (release_hot)
+			fired = 1;
+		ui->active = 0;
+	}
+
+	if (row->selected)
+		bg = ui->theme.selection;
+	else if (hot || ui->active == id)
+		bg = ui->theme.panel_alt;
+	if (bg)
+		ngui_fill_round_rect(ui, r, 6, 6, 6, 6, bg);
+	title_h = ngui_text_line_height(ui, ui->font_px, 0);
+	fg = ui->theme.text;
+	sub_fg = row->selected ? ui->theme.text : ui->theme.text_dim;
+	trail_fg = row->selected ? ui->theme.text : ui->theme.text_dim;
+
+	if (row->selected) {
+		int cy = r.y + r.h / 2;
+
+		ngui_line(ui, left, cy, left + 3, cy + 4, fg);
+		ngui_line(ui, left + 3, cy + 4, left + 11, cy - 5, fg);
+		left += 17;
+	}
+
+	if (row->trailing && row->trailing[0]) {
+		int tw = (int)ngui_text_width_ui(ui, row->trailing);
+
+		right -= tw + 8;
+		if (utf8)
+			ngui_text_utf8(ui, right + 8,
+				       r.y + (r.h - title_h) / 2,
+				       row->trailing, trail_fg);
+		else
+			ngui_text(ui, right + 8,
+				  r.y + (r.h - title_h) / 2,
+				  row->trailing, trail_fg);
+	}
+	if (row->bars >= 0) {
+		struct ngui_rect br;
+
+		right -= 26;
+		br.x = right + 6;
+		br.y = r.y + (r.h - 14) / 2;
+		br.w = 18;
+		br.h = 14;
+		ngui_signal_bars(ui, br, row->bars,
+				 row->selected ? ui->theme.text :
+						 ui->theme.accent);
+	}
+	if (right <= left)
+		return fired;
+
+	block_h = row->subtitle && row->subtitle[0] ? title_h * 2 - 2 :
+						      title_h;
+	ty = r.y + (r.h - block_h) / 2;
+	if (ty < r.y)
+		ty = r.y;
+
+	ngui_push_clip(ui, rect_make(left, r.y, right - left, r.h));
+	if (utf8)
+		ngui_text_utf8(ui, left, ty, row->title, fg);
+	else
+		ngui_text(ui, left, ty, row->title, fg);
+	if (row->subtitle && row->subtitle[0]) {
+		if (utf8)
+			ngui_text_utf8(ui, left, ty + title_h - 2,
+				       row->subtitle, sub_fg);
+		else
+			ngui_text(ui, left, ty + title_h - 2, row->subtitle,
+				  sub_fg);
+	}
+	ngui_pop_clip(ui);
+
+	if (hot)
+		ui->hot = id;
+	return fired;
+}
+
+int ngui_list_row(struct ngui *ui, unsigned int id, struct ngui_rect r,
+		  const struct ngui_row *row)
+{
+	return ngui_list_row_common(ui, id, r, row, 0);
+}
+
+int ngui_list_row_utf8(struct ngui *ui, unsigned int id, struct ngui_rect r,
+		       const struct ngui_row *row)
+{
+	return ngui_list_row_common(ui, id, r, row, 1);
+}
+
+void ngui_signal_bars(struct ngui *ui, struct ngui_rect r, int bars,
+		      unsigned short color)
+{
+	int i;
+	int base = r.y + r.h - 1;
+
+	for (i = 0; i < 4; i++) {
+		int h = 3 + i * 3;
+		struct ngui_rect br;
+
+		br.x = r.x + i * 5;
+		br.y = base - h;
+		br.w = 3;
+		br.h = h;
+		ngui_fill_rect(ui, br, i < bars ? color : ui->theme.button);
+	}
+}
+
 int ngui_icon_button(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		     enum ngui_icon icon){
 	int hot = ui->inside && ngui_rect_contains(&r, ui->mouse_x, ui->mouse_y);
@@ -1356,7 +1587,7 @@ int ngui_icon_button(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	else
 		bg = ui->theme.button;
 	ngui_fill_rect(ui, r, bg);
-	ngui_frame(ui, r, hot ? ui->theme.accent : ui->theme.border);
+	button_bevel(ui, r, bg, hot, ui->active == id);
 	ngui_icon(ui, r, icon, ui->theme.text);
 	if (hot)
 		ui->hot = id;
@@ -1777,7 +2008,14 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	}
 
 	ngui_fill_rect(ui, r, focused ? ui->theme.panel_alt : ui->theme.panel);
-	ngui_frame(ui, r, focused ? ui->theme.accent : ui->theme.border);
+	/* Inset edge: the shadow sits on the top/left, the light on the
+	 * bottom/right.  A focused field keeps the shape in accent blue. */
+	if (focused)
+		bevel_rect(ui, r, ui->theme.accent,
+			   shade565(ui->theme.accent, 4));
+	else
+		bevel_rect(ui, r, shade565(ui->theme.panel, -4),
+			   shade565(ui->theme.panel, 4));
 
 	if (!in->disabled)
 		input_scroll_to_cursor(ui, in, avail);

+ 35 - 0
ngui.h

@@ -61,6 +61,8 @@ struct ngui_theme {
 	unsigned short icon_file;
 	unsigned short icon_disk;
 	unsigned short error;
+	unsigned short success;
+	unsigned short warning;
 };
 
 extern const struct ngui_theme ngui_theme_dark;
@@ -98,6 +100,24 @@ struct ngui_scroll {
 	int drag_dy;
 };
 
+/* A flat menu panel: the surface, a body rectangle for the caller's widgets
+ * and a one-line footer for status text.  There is no title bar or close
+ * button; the app is dismissed by clicking outside it or pressing Esc.  Use
+ * on one chromeless canvas window created with u_win_create_popover(). */
+struct ngui_popover {
+	struct ngui_rect body;
+	struct ngui_rect footer;
+};
+
+/* A two-line list row with optional signal bars and right-aligned text. */
+struct ngui_row {
+	const char *title;
+	const char *subtitle;
+	const char *trailing;
+	int bars;                     /* -1 none, 0..4 signal strength bars */
+	int selected;
+};
+
 struct ngui {
 	unsigned short *px;
 	int w, h;
@@ -246,6 +266,21 @@ int ngui_menu_item_utf8(struct ngui *ui, unsigned int id, struct ngui_rect r,
 			const char *label, const char *shortcut, int checked);
 int ngui_icon_button(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		     enum ngui_icon icon);
+
+/* Menu panel component (see struct ngui_popover). */
+void ngui_popover_begin(struct ngui *ui, struct ngui_popover *p);
+void ngui_popover_footer(struct ngui *ui, const struct ngui_popover *p,
+			 const char *text, unsigned short color);
+/* Section caption with an optional right-aligned action button; returns 1
+ * when the action fired. */
+int  ngui_section(struct ngui *ui, struct ngui_rect r, const char *caption,
+		  unsigned int action_id, const char *action);
+int  ngui_list_row(struct ngui *ui, unsigned int id, struct ngui_rect r,
+		   const struct ngui_row *row);
+int  ngui_list_row_utf8(struct ngui *ui, unsigned int id, struct ngui_rect r,
+			const struct ngui_row *row);
+void ngui_signal_bars(struct ngui *ui, struct ngui_rect r, int bars,
+		      unsigned short color);
 int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		    struct ngui_input *in);
 void ngui_input_set(struct ngui_input *in, const char *s);

+ 7 - 0
sys_net.c

@@ -24,6 +24,7 @@
 #include "process.h"
 #include "tcp.h"
 #include "timer.h"
+#include "wm.h"
 
 /* Accepted server connection (NULL until SYS_TCP_ACCEPT returns one). */
 static struct tcp_conn *srv_conn;
@@ -114,6 +115,12 @@ int sys_net_info(struct sys_netinfo *out)
 	 * the PHY/USB with tick-based delays, so run it with interrupts on and
 	 * the BKL released.  Once probed, this is just a cached lookup. */
 	if (!netdev_probed()) {
+		/* Not for the WM: its first top-bar poll comes before its first
+		 * frame, and a NIC probe (PHY reset, USB control transfers) would
+		 * hold that frame back.  kernel_main probes right after the WM
+		 * starts and the WM polls again every second. */
+		if (wm_server_is_wm())
+			return 0;
 		net_enter();
 		nd = netdev_active();
 		net_exit();

+ 3 - 0
sys_wm.c

@@ -169,6 +169,8 @@ int sys_win_create(const struct win_create *in, struct win_info *out)
 /* One serial line when the first application window (normally the boot
  * terminal) presents a frame: the end point of the boot-time measurement
  * ("[boot] ..." lines are relative to the PIT start, this is uptime). */
+volatile int wm_first_window_presented;
+
 static void boot_first_present(void)
 {
 	static int done;
@@ -176,6 +178,7 @@ static void boot_first_present(void)
 	if (done)
 		return;
 	done = 1;
+	wm_first_window_presented = 1;
 	serial_puts(SERIAL_COM1, "wm: first window frame (");
 	serial_puts(SERIAL_COM1, current_proc()->name);
 	serial_puts(SERIAL_COM1, ") at ");

+ 4 - 0
sys_wm.h

@@ -29,4 +29,8 @@ int sys_win_scroll(struct win_scroll *out);
 int sys_wm_resize(unsigned int index, const struct wm_size *in);
 int sys_win_key_wait(unsigned int timeout_ms);
 
+/* Set once the first application window (the boot terminal) has presented
+ * a frame; kernel_main waits for it before the USB bring-up. */
+extern volatile int wm_first_window_presented;
+
 #endif

+ 204 - 0
terminal.c

@@ -2,6 +2,7 @@
    Commands are spawned as separate processes for preemptive multitasking. */
 
 #include "io.h"
+#include "backlight.h"
 #include "power.h"
 #include "bootcon.h"
 #include "dbg.h"
@@ -67,7 +68,9 @@ static int cmd_idle(struct term *t, const char *args);
 static int cmd_cpufreq(struct term *t, const char *args);
 static int cmd_power(struct term *t, const char *args);
 static int cmd_kexec(struct term *t, const char *args);
+static int cmd_keytest(struct term *t, const char *args);
 static int cmd_kill(struct term *t, const char *args);
+static int cmd_backlight(struct term *t, const char *args);
 static int cmd_poweroff(struct term *t, const char *args);
 static int cmd_ps(struct term *t, const char *args);
 static int cmd_renice(struct term *t, const char *args);
@@ -84,6 +87,8 @@ static const struct kcmd cmds[] = {
 	{ "poweroff",   "poweroff",                      CK_CUSTOM, 0, 0, 0, 0, cmd_poweroff },
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_main, 0, 0, 0 },
+	{ "backlight",  "backlight [0-100|up|down]",     CK_CUSTOM, 0, 0, 0, 0, cmd_backlight },
+	{ "keytest",    "keytest",                       CK_CUSTOM, 0, 0, 0, 0, cmd_keytest },
 	{ "lsusb",      "lsusb",                         CK_SPAWN, 0, program_lsusb_main, 0, 0, 0 },
 	{ "touchpad",   "touchpad [rightclick|tapclick|scroll]", CK_SPAWN_ARG, 0, 0, program_touchpad_main, 0, 0 },
 	{ "netdev",     "netdev [name]",                 CK_SPAWN_ARG, 0, 0, program_netdev_main, 0, 0 },
@@ -404,6 +409,205 @@ static int cmd_power(struct term *t, const char *args)
 	return 0;
 }
 
+static void cmd_put_dec(unsigned int v)
+{
+	char b[12];
+	int i = 0;
+
+	if (!v) {
+		io_putchar('0');
+		return;
+	}
+	while (v) {
+		b[i++] = (char)('0' + v % 10);
+		v /= 10;
+	}
+	while (i)
+		io_putchar(b[--i]);
+}
+
+static void cmd_put_hex(unsigned int v, unsigned int digits)
+{
+	static const char hex[] = "0123456789ABCDEF";
+
+	while (digits) {
+		digits--;
+		io_putchar(hex[(v >> (digits * 4)) & 0xF]);
+	}
+}
+
+static const char *cmd_raw_name(unsigned char raw)
+{
+	switch (raw) {
+	case 0x3B: return "F1";
+	case 0x3C: return "F2";
+	case 0x3D: return "F3";
+	case 0x3E: return "F4";
+	case 0x3F: return "F5";
+	case 0x40: return "F6";
+	case 0x41: return "F7";
+	case 0x42: return "F8";
+	case 0x43: return "F9";
+	case 0x44: return "F10";
+	case 0x57: return "F11";
+	case 0x58: return "F12";
+	}
+	return 0;
+}
+
+static const char *cmd_key_name(int k)
+{
+	switch (k) {
+	case '\n':                 return "Enter";
+	case '\t':                 return "Tab";
+	case '\b':                 return "Backspace";
+	case 0x1B:                 return "Esc";
+	case IO_KEY_LEFT:          return "Left";
+	case IO_KEY_RIGHT:         return "Right";
+	case IO_KEY_UP:            return "Up";
+	case IO_KEY_DOWN:          return "Down";
+	case IO_KEY_PAGE_UP:       return "PageUp";
+	case IO_KEY_PAGE_DOWN:     return "PageDown";
+	case IO_KEY_HOME:          return "Home";
+	case IO_KEY_END:           return "End";
+	case IO_KEY_DELETE:        return "Delete";
+	case IO_KEY_CTRL_LEFT:     return "Ctrl+Left";
+	case IO_KEY_CTRL_RIGHT:    return "Ctrl+Right";
+	case IO_KEY_CTRL_DELETE:   return "Ctrl+Delete";
+	case IO_KEY_CTRL_BACKSPACE: return "Ctrl+Backspace";
+	}
+	return 0;
+}
+
+/* Print every raw scancode the decoder sees, including releases, E0
+ * prefixes and keys that decode to 0 (the brightness/action keys). */
+static int cmd_keytest(struct term *t, const char *args)
+{
+	struct io_keytap e;
+
+	(void)t;
+	(void)args;
+	io_keytap_reset();
+	io_putstr("keytest: press keys (Ctrl+C to stop; E0 = prefix)\n");
+	for (;;) {
+		while (io_keytap_read(&e)) {
+			const char *name;
+
+			io_putstr("raw ");
+			cmd_put_hex(e.raw, 2);
+			io_putstr(e.ext ? " ext" : "    ");
+			if (e.kind == 2)
+				io_putstr(" prefix");
+			else if (e.kind == 1)
+				io_putstr(" break ");
+			else
+				io_putstr(" make  ");
+			io_putstr(" -> 0x");
+			cmd_put_hex((unsigned int)e.key, 4);
+			name = e.kind == 0 ? cmd_key_name(e.key) : 0;
+			if (name) {
+				io_putstr(" (");
+				io_putstr(name);
+				io_putchar(')');
+			} else if (e.kind == 0 && e.key >= 0x20 && e.key <= 0x7E) {
+				io_putstr(" '");
+				io_putchar((char)e.key);
+				io_putstr("'");
+			} else if (e.kind == 0 && !e.ext) {
+				name = cmd_raw_name(e.raw);
+				if (name) {
+					io_putstr(" (");
+					io_putstr(name);
+					io_putchar(')');
+				}
+			}
+			io_putchar('\n');
+		}
+		process_sleep_ms(20);
+	}
+	return 0;
+}
+
+static void backlight_print(int probe)
+{
+	struct backlight_status st;
+
+	if (backlight_status(&st) != 0) {
+		io_putstr("backlight: no Intel CHV/VLV panel PWM\n");
+		return;
+	}
+	io_putstr("backlight: ");
+	cmd_put_dec((unsigned int)st.level);
+	io_putstr("% (pipe ");
+	io_putstr(st.pipe ? "B" : "A");
+	io_putstr(", period ");
+	cmd_put_dec(st.period);
+	io_putstr(", duty ");
+	cmd_put_dec(st.duty);
+	io_putstr(", ");
+	io_putstr(st.enabled ? "enabled" : "disabled");
+	io_putstr(")\n");
+	if (!probe)
+		return;
+	io_putstr("  bar 0x");
+	cmd_put_hex(st.bar, 8);
+	io_putstr("\n  ctl2 A=0x");
+	cmd_put_hex(st.ctl2[0], 8);
+	io_putstr(" B=0x");
+	cmd_put_hex(st.ctl2[1], 8);
+	io_putstr("\n  ctl  A=0x");
+	cmd_put_hex(st.ctl[0], 8);
+	io_putstr(" B=0x");
+	cmd_put_hex(st.ctl[1], 8);
+	io_putchar('\n');
+}
+
+static int cmd_backlight(struct term *t, const char *args)
+{
+	const char *p = args;
+
+	(void)t;
+	while (*p == ' ')
+		p++;
+	if (!*p) {
+		backlight_print(0);
+		return 0;
+	}
+	if (arg_is(p, "probe")) {
+		backlight_print(1);
+		return 0;
+	}
+	if (arg_is(p, "up")) {
+		backlight_step(1);
+		backlight_print(0);
+		return 0;
+	}
+	if (arg_is(p, "down")) {
+		backlight_step(-1);
+		backlight_print(0);
+		return 0;
+	}
+	{
+		unsigned int pct = 0;
+		int digits = 0;
+
+		while (*p >= '0' && *p <= '9') {
+			pct = pct * 10 + (unsigned int)(*p - '0');
+			p++;
+			digits = 1;
+		}
+		while (*p == ' ')
+			p++;
+		if (digits && !*p) {
+			backlight_set_percent((int)pct);
+			backlight_print(0);
+			return 0;
+		}
+	}
+	io_putstr("backlight: usage backlight [0-100|up|down|probe]\n");
+	return 0;
+}
+
 static int cmd_cpufreq(struct term *t, const char *args)
 {
 	(void)t;

+ 91 - 15
tools/mock_chat.py

@@ -5,7 +5,8 @@ Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as
 10.0.2.2:
 
   chat  (default port 18080): /auth/login, /auth/callback, /auth/return,
-        /auth/logout and the /api/* routes the client uses
+        /auth/logout and the /api/* routes the client uses, including
+        /api/avatars/<uid> and /api/attachments/<id> for pictures
   login (default port 18081): /openid/auth, /openid/interaction/<uid>
         (login page with cloudron-config JSON, consent page as a bare
         auto-submit form), POST .../login and .../confirm
@@ -28,19 +29,27 @@ import argparse
 import datetime
 import json
 import secrets
+import struct
 import threading
+import zlib
 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
 from urllib.parse import parse_qs, urlparse
 
 LOCK = threading.Lock()
 STATE = {
     "users": {
-        "u-test": {"id": "u-test", "username": "test", "name": "Test User"},
-        "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example"},
-        "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm"},
-        "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol"},
-        "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User"},
-        "u-consent": {"id": "u-consent", "username": "consent", "name": "Consent User"},
+        "u-test": {"id": "u-test", "username": "test", "name": "Test User",
+                   "picture": ""},
+        "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example",
+                    "picture": "/api/avatars/u-alice"},
+        "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm",
+                  "picture": "/api/avatars/u-bob"},
+        "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol",
+                    "picture": ""},
+        "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User",
+                   "picture": ""},
+        "u-consent": {"id": "u-consent", "username": "consent",
+                      "name": "Consent User", "picture": ""},
     },
     "channels": {},         # id -> {id,name,type,members:set,description}
     "messages": {},         # channel id -> [msg]
@@ -54,6 +63,59 @@ SEQ = [0]
 ARGS = None
 
 
+def png_chunk(tag, data):
+    return (struct.pack(">I", len(data)) + tag + data +
+            struct.pack(">I", zlib.crc32(tag + data) & 0xffffffff))
+
+
+def png_rgb(w, h, pixel):
+    raw = bytearray()
+    for y in range(h):
+        raw.append(0)
+        for x in range(w):
+            raw.extend(pixel(x, y))
+    return (b"\x89PNG\r\n\x1a\n" +
+            png_chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) +
+            png_chunk(b"IDAT", zlib.compress(bytes(raw), 6)) +
+            png_chunk(b"IEND", b""))
+
+
+AVATAR_PNGS = {}
+
+
+def avatar_png(uid):
+    if uid in AVATAR_PNGS:
+        return AVATAR_PNGS[uid]
+    h = sum(ord(c) for c in uid)
+    colors = [(208, 90, 90), (90, 154, 208), (90, 176, 112),
+              (192, 138, 58), (154, 106, 200), (58, 168, 168)]
+    r, g, b = colors[h % len(colors)]
+
+    def pixel(x, y):
+        # A coloured disc with a lighter centre, so the screenshot shows a
+        # real avatar rather than the initial fallback.
+        dx, dy = x - 15.5, y - 15.5
+        if dx * dx + dy * dy > 15.5 * 15.5:
+            return (32, 34, 38)
+        if 8 <= x <= 23 and 12 <= y <= 19:
+            return (245, 245, 245)
+        return (r, g, b)
+
+    AVATAR_PNGS[uid] = png_rgb(32, 32, pixel)
+    return AVATAR_PNGS[uid]
+
+
+def attachment_png():
+    def pixel(x, y):
+        if (x // 8 + y // 8) % 2:
+            return (240, 150, 40)
+        return (40, 90, 160)
+    return png_rgb(96, 64, pixel)
+
+
+ATTACHMENT_PNG = attachment_png()
+
+
 def note(line):
     STATE["log"].append(line)
     if ARGS and ARGS.verbose:
@@ -76,7 +138,9 @@ def add_message(cid, uid, body, client_id=None, reply_to=None, extra=None):
     msgs = STATE["messages"][cid]
     m = {"id": "m%05d" % (SEQ[0] + 1), "clientId": client_id, "channelId": cid,
          "userId": uid, "authorName": STATE["users"][uid]["name"],
-         "authorUsername": STATE["users"][uid]["username"], "body": body,
+         "authorUsername": STATE["users"][uid]["username"],
+         "authorPicture": STATE["users"][uid].get("picture", ""),
+         "body": body,
          "type": None, "parentId": None, "replyToId": reply_to, "replyTo": None,
          "createdAt": now_iso(), "deleted": False, "reactions": [],
          "attachments": [], "threadCount": 0, "readBy": [], "pinned": False}
@@ -109,10 +173,15 @@ def seed(n_general):
                 "NebOS chat timeline, because it keeps going and going with "
                 "plenty of words to test the greedy word wrapper.\nAnd a "
                 "second paragraph.", reply_to=first,
-                extra={"attachments": [{"id": "a1", "filename": "notes.txt",
-                                        "mime": "text/plain", "size": 12}],
-                       "threadCount": 2,
-                       "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
+                extra={
+                    "attachments": [
+                        {"id": "a1", "filename": "notes.txt",
+                         "mime": "text/plain", "size": 12},
+                        {"id": "a2", "filename": "neb.png",
+                         "mime": "image/png", "size": len(ATTACHMENT_PNG),
+                         "url": "/api/attachments/a2"}],
+                    "threadCount": 2,
+                    "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
     add_message("c-secret", "u-alice", "Private channel, only us two.")
     add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
     # test has read general up to the history; the rest is unread
@@ -136,7 +205,8 @@ def last_message(cid):
         return None
     m = msgs[-1]
     return {"id": m["id"], "body": m["body"][:160], "createdAt": m["createdAt"],
-            "userId": m["userId"], "authorName": m["authorName"], "authorPicture": ""}
+            "userId": m["userId"], "authorName": m["authorName"],
+            "authorPicture": m.get("authorPicture", "")}
 
 
 def channel_json(c, uid):
@@ -377,7 +447,7 @@ class ChatHandler(Base):
             if not uid:
                 return self.send(401, {"error": "Unauthorized"})
             if p == "/api/me":
-                return self.send(200, dict(STATE["users"][uid], email="", picture="",
+                return self.send(200, dict(STATE["users"][uid], email="",
                                            active=True))
             if p == "/api/channels":
                 return self.send(200, [channel_json(c, uid) for c in STATE["channels"].values()
@@ -391,9 +461,15 @@ class ChatHandler(Base):
                 return self.send(200, [dm_json(c, uid) for c in STATE["channels"].values()
                                        if c["type"] == "dm" and uid in c["members"]])
             if p == "/api/users":
-                return self.send(200, [dict(x, email="", picture="", active=True)
+                return self.send(200, [dict(x, email="", active=True)
                                        for x in STATE["users"].values()])
             parts = p.strip("/").split("/")
+            if len(parts) == 3 and parts[:2] == ["api", "avatars"]:
+                if parts[2] in STATE["users"]:
+                    return self.send(200, avatar_png(parts[2]), "image/png")
+            if len(parts) == 3 and parts[:2] == ["api", "attachments"]:
+                if parts[2] == "a2":
+                    return self.send(200, ATTACHMENT_PNG, "image/png")
             if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
                 c = STATE["channels"].get(parts[2])
                 if not c or uid not in c["members"]:

+ 4 - 0
tools/qmp_chat_test.py

@@ -285,6 +285,10 @@ def main():
         check("history loaded",
               wait_for(lambda: logged("/api/channels/c-general/messages?limit=50"),
                        30, "history"))
+        check("avatars fetched",
+              wait_for(lambda: logged("GET /api/avatars/"), 20, "avatars"))
+        check("message image fetched",
+              wait_for(lambda: logged("GET /api/attachments/a2"), 20, "image"))
         time.sleep(4.0)
         shot(s, workdir, out, "3-main")
         if not full:

+ 10 - 0
touchpad.c

@@ -19,6 +19,7 @@
  * touchpad_gesture.c so another touchpad driver can reuse it.
  */
 
+#include "cpu.h"
 #include "touchpad.h"
 #include "touchpad_gesture.h"
 #include "i2c.h"
@@ -338,6 +339,15 @@ int touchpad_init(void)
 
 	if (tp_present)
 		return 1;
+	/* The Elan touchpad sits behind the Braswell LPSS I2C blocks (the HP
+	 * Chromebook, Airmont family 6 model 0x4C).  Everywhere else the scan
+	 * below would only map and reset-cycle 32 fixed MMIO windows that
+	 * belong to nobody (2 ms each, ~64 ms of boot) or, worse, to some
+	 * other device, so skip it. */
+	if (cpu_family_model() != 0x64Cu) {
+		tp_err = "not an Airmont (Braswell) platform";
+		return 0;
+	}
 
 	for (r = 0; r < 2; r++) {
 		for (k = 0; k < TP_CTRL_MAX; k++) {

+ 677 - 11
ucmd_chat.c

@@ -3,7 +3,8 @@
  * Login is the native Cloudron OIDC driver in chat_login.c (username,
  * password, optional TOTP) or a pasted session cookie.  The session cookie is
  * kept in a uhttp cookie jar and saved with the server address in a small
- * config file (/share/chat.cfg by default, or the path given as argument).
+ * config file: /data/CHAT.CFG on an installed disk, /share/chat.cfg when
+ * there is no persistent /data mount, or the path given as argument.
  * The password is never stored.
  *
  * Everything else is the Chat REST API over uhttp: the channel and DM
@@ -21,11 +22,13 @@
 #include "uhttp.h"
 #include "ujson.h"
 #include "chat_login.h"
+#include "img.h"
 
 #include <stdlib.h>
 #include <string.h>
 
-#define DEFAULT_CFG    "/share/chat.cfg"
+#define DEFAULT_CFG_DATA  "/data/CHAT.CFG"
+#define DEFAULT_CFG_SHARE "/share/chat.cfg"
 #define RESP_CAP       (512u * 1024u)
 #define JSON_NODES     16384u
 #define JSON_SCAP      (RESP_CAP + 2u * JSON_NODES)
@@ -37,6 +40,20 @@
 #define PAGE_SIZE      50
 #define LIVE_PAGE      50
 
+#define MSG_IMG_MAX    3
+#define CHAT_IMG_W     480
+#define CHAT_IMG_H     320
+#define CHAT_IMG_MAX   16
+#define CHAT_AVATAR_MAX 64
+#define CHAT_AVATAR    32
+#define CHAT_IMG_BUDGET (6u * 1024u * 1024u)
+#define CHAT_IMG_ARENA_MAX (12u * 1024u * 1024u)
+#define CHAT_IMG_FETCH_MAX (4u * 1024u * 1024u)
+#define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16)
+#define CHAT_PIC_QUEUED 0
+#define CHAT_PIC_READY  1
+#define CHAT_PIC_FAILED (-1)
+
 #define POLL_CONV_MS        2000
 #define POLL_CONV_IDLE_MS   5000
 #define POLL_DIR_MS         12000
@@ -76,10 +93,13 @@ struct msg {
 	char id[48];
 	char user_id[48];
 	char author[48];
+	char *author_pic;       /* profile picture URL, or NULL */
 	char created[32];       /* ISO 8601 UTC, sorts as text */
 	char reply[96];         /* "Name: snippet" */
 	char extra[112];        /* attachments / thread / reactions line */
 	char *body;             /* Latin-1, malloc'd */
+	char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
+	unsigned char nimg;
 	unsigned char action;   /* type "me" */
 	int height;
 	int layout_w;
@@ -91,6 +111,7 @@ struct pick {
 	char id[48];
 	char name[64];
 	char sub[64];
+	char pic[256];
 };
 
 static struct ngui ui;
@@ -108,6 +129,7 @@ static enum modal modal = MODAL_NONE;
 static int action, action_arg;
 
 static char cfg_path[CHAT_PATH_MAX];
+static int cfg_is_default;
 static char server[CHAT_SERVER_MAX];
 static char server_host[UHTTP_HOST_MAX];
 static int server_secure;
@@ -342,6 +364,19 @@ static int write_file(const char *path, const char *buf, unsigned int len)
 	return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
 }
 
+/* The persistent data volume wins when it is mounted and writable; the
+ * volatile /share is the fallback (live USB, or a board without /data). */
+static const char *default_cfg_path(void)
+{
+	struct sys_mount m;
+	unsigned int i;
+
+	for (i = 0; u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1; i++)
+		if (strcmp(m.name, "data") == 0 && !m.ro)
+			return DEFAULT_CFG_DATA;
+	return DEFAULT_CFG_SHARE;
+}
+
 static int set_server(const char *s)
 {
 	char norm[CHAT_SERVER_MAX];
@@ -387,6 +422,7 @@ static void maybe_save_cookie(void)
 /* ---- HTTP / JSON plumbing ---- */
 
 static void paint_now(void);
+static int line_h(void);
 
 static void net_drop(void)
 {
@@ -420,6 +456,508 @@ static int parse_resp(void)
 	return root;
 }
 
+/* ---- message images and avatars ---- */
+
+struct chat_pic {
+	char *url;
+	struct img_image img;
+	unsigned int bytes;     /* RGB565 bytes in the message-image budget */
+	unsigned int last_used;
+	int state;              /* CHAT_PIC_* */
+};
+
+static struct chat_pic chat_images[CHAT_IMG_MAX];
+static int nchat_images;
+static unsigned int chat_image_bytes;
+static struct chat_pic chat_avatars[CHAT_AVATAR_MAX];
+static int nchat_avatars;
+static unsigned int chat_pic_clock;
+static unsigned char *chat_fetch_buf;
+static unsigned char *chat_arena;
+static unsigned int chat_arena_size;
+
+static void chat_pic_free(struct chat_pic *p)
+{
+	free(p->url);
+	free(p->img.px);
+	free(p->img.alpha);
+	memset(p, 0, sizeof(*p));
+}
+
+static struct chat_pic *chat_pic_find(struct chat_pic *arr, int n,
+				      const char *url)
+{
+	int i;
+
+	for (i = 0; i < n; i++)
+		if (arr[i].url && strcmp(arr[i].url, url) == 0)
+			return &arr[i];
+	return 0;
+}
+
+/* Pick a cache slot, evicting the least recently used entry when full.
+ * avatars: their images never change the timeline layout. */
+static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max,
+				      const char *url, int avatars)
+{
+	struct chat_pic *p = chat_pic_find(arr, *count, url);
+	unsigned int best = ~0u;
+	int i, victim = -1;
+
+	if (p)
+		return p;
+	if (*count < max) {
+		p = &arr[*count];
+		memset(p, 0, sizeof(*p));
+		p->url = strdup(url);
+		if (!p->url)
+			return 0;
+		(*count)++;
+	} else {
+		for (i = 0; i < *count; i++) {
+			if (arr[i].state == CHAT_PIC_QUEUED)
+				continue;
+			if (arr[i].last_used < best) {
+				best = arr[i].last_used;
+				victim = i;
+			}
+		}
+		if (victim < 0)
+			return 0;
+		p = &arr[victim];
+		if (!avatars) {
+			chat_image_bytes -= p->bytes;
+			msgs_gen++;
+		}
+		chat_pic_free(p);
+		p->url = strdup(url);
+		if (!p->url)
+			return 0;
+	}
+	p->state = CHAT_PIC_QUEUED;
+	p->last_used = ++chat_pic_clock;
+	return p;
+}
+
+static struct chat_pic *chat_image_slot(const char *url)
+{
+	return chat_pic_slot(chat_images, &nchat_images, CHAT_IMG_MAX, url, 0);
+}
+
+static struct chat_pic *chat_avatar_slot(const char *url)
+{
+	return chat_pic_slot(chat_avatars, &nchat_avatars, CHAT_AVATAR_MAX,
+			     url, 1);
+}
+
+static int chat_image_room(unsigned int need)
+{
+	while (chat_image_bytes + need > CHAT_IMG_BUDGET) {
+		unsigned int best = ~0u;
+		int i, victim = -1;
+
+		for (i = 0; i < nchat_images; i++) {
+			if (chat_images[i].state != CHAT_PIC_READY)
+				continue;
+			if (chat_images[i].last_used < best) {
+				best = chat_images[i].last_used;
+				victim = i;
+			}
+		}
+		if (victim < 0)
+			return -1;
+		chat_image_bytes -= chat_images[victim].bytes;
+		chat_pic_free(&chat_images[victim]);
+		msgs_gen++;
+	}
+	return 0;
+}
+
+static unsigned char *chat_pic_arena_get(unsigned int need)
+{
+	if (need <= chat_arena_size)
+		return chat_arena;
+	free(chat_arena);
+	chat_arena = (unsigned char *)malloc(need);
+	chat_arena_size = chat_arena ? need : 0;
+	return chat_arena;
+}
+
+/* Clip the scaled avatar to a circle with a 4x4 supersampled edge.  The RGB
+ * pixels stay untouched; only the alpha plane changes. */
+static void chat_avatar_mask(unsigned char *alpha, unsigned int w,
+			     unsigned int h)
+{
+	unsigned int x, y;
+
+	for (y = 0; y < h; y++) {
+		for (x = 0; x < w; x++) {
+			unsigned int hits = 0;
+			int sx, sy;
+
+			for (sy = 0; sy < 4; sy++) {
+				int py = (int)y * 8 + sy * 2 + 1;
+				int dy = py - (int)h * 4;
+
+				for (sx = 0; sx < 4; sx++) {
+					int px = (int)x * 8 + sx * 2 + 1;
+					int dx = px - (int)w * 4;
+
+					if (dx * dx + dy * dy <=
+					    (int)w * 4 * (int)w * 4)
+						hits++;
+				}
+			}
+			alpha[y * w + x] =
+				(unsigned char)((unsigned int)alpha[y * w + x] *
+						hits / 16u);
+		}
+	}
+}
+
+static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
+{
+	struct img_info info;
+	struct img_options opt;
+	struct img_mem mem;
+	struct img_image decoded;
+	struct img_blit blit;
+	unsigned char *arena, *alpha = 0;
+	unsigned short *px;
+	unsigned int est, scale, dw, dh, sw, sh, i, need;
+	int r;
+
+	if (img_sniff(chat_fetch_buf, len, &info) != 0)
+		return -1;
+	est = img_estimate(&info);
+	if (est == 0xFFFFFFFFu || est > CHAT_IMG_ARENA_MAX)
+		return -1;
+	arena = chat_pic_arena_get(est);
+	if (!arena)
+		return -1;
+	img_mem_init(&mem, arena, est);
+	opt.max_pixels = 4u * 1024u * 1024u;
+	r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded);
+	if (r != 0 || !decoded.w || !decoded.h)
+		return -1;
+
+	if (avatar) {
+		sw = (CHAT_AVATAR << 16) / decoded.w;
+		sh = (CHAT_AVATAR << 16) / decoded.h;
+		scale = sw < sh ? sw : sh;
+		dw = dh = CHAT_AVATAR;
+	} else {
+		scale = 65536;
+		if (decoded.w > CHAT_IMG_W)
+			scale = (CHAT_IMG_W << 16) / decoded.w;
+		if (((decoded.h * scale) >> 16) > CHAT_IMG_H)
+			scale = (CHAT_IMG_H << 16) / decoded.h;
+		dw = (decoded.w * scale) >> 16;
+		dh = (decoded.h * scale) >> 16;
+		if (!dw)
+			dw = 1;
+		if (!dh)
+			dh = 1;
+		need = dw * dh * 2u;
+		if (chat_image_room(need) != 0)
+			return -1;
+	}
+	px = (unsigned short *)malloc(dw * dh * 2u);
+	if (!px)
+		return -1;
+	for (i = 0; i < dw * dh; i++)
+		px[i] = avatar ? 0xFFFF : ui.theme.bg;
+	if (avatar) {
+		/* Keep an alpha plane even for an opaque picture: the circular
+		 * mask below clips it to the avatar circle. */
+		alpha = (unsigned char *)malloc(dw * dh);
+		if (alpha)
+			memset(alpha, 255, dw * dh);
+	}
+	memset(&blit, 0, sizeof(blit));
+	blit.dst = px;
+	blit.dst_w = (int)dw;
+	blit.dst_h = (int)dh;
+	blit.clip_x = 0;
+	blit.clip_y = 0;
+	blit.clip_w = (int)dw;
+	blit.clip_h = (int)dh;
+	blit.x = avatar ? (int)(dw - ((decoded.w * scale) >> 16)) / 2 : 0;
+	blit.y = avatar ? (int)(dh - ((decoded.h * scale) >> 16)) / 2 : 0;
+	blit.scale = scale;
+	blit.bg = avatar ? 0xFFFF : ui.theme.bg;
+	blit.bg2 = blit.bg;
+	blit.dst_a = alpha;
+	blit.flags = alpha ? IMG_BLIT_SAVE_ALPHA :
+		     (decoded.alpha ? IMG_BLIT_OVER_DST : 0);
+	img_draw(&decoded, &blit);
+	if (avatar && alpha)
+		chat_avatar_mask(alpha, dw, dh);
+
+	p->img.format = decoded.format;
+	p->img.w = dw;
+	p->img.h = dh;
+	p->img.px = px;
+	p->img.alpha = alpha;
+	p->img.flags = 0;
+	p->bytes = avatar ? 0 : dw * dh * 2u;
+	if (!avatar)
+		chat_image_bytes += p->bytes;
+	return 0;
+}
+
+static void chat_pic_load(struct chat_pic *p, int avatar)
+{
+	unsigned int len = 0;
+	int st;
+
+	if (!chat_fetch_buf)
+		chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
+	if (!chat_fetch_buf) {
+		p->state = CHAT_PIC_FAILED;
+		return;
+	}
+	http.jar = &jar;
+	http.accept = "image/*,*/*";
+	st = chat_http(&http, 0, p->url, 0, (char *)chat_fetch_buf,
+		       CHAT_IMG_FETCH_MAX, &len);
+	if (st != 200 || len == 0 || chat_pic_store(p, len, avatar) != 0) {
+		p->state = CHAT_PIC_FAILED;
+	} else {
+		p->state = CHAT_PIC_READY;
+		p->last_used = ++chat_pic_clock;
+		if (!avatar) {
+			msgs_gen++;
+			if (at_bottom)
+				tl_scroll.offset = 1 << 28;
+		}
+	}
+	ngui_invalidate(&ui);
+}
+
+static void chat_media_tick(void)
+{
+	int i;
+
+	if (screen != SCR_MAIN || offline)
+		return;
+	for (i = 0; i < nchat_images; i++) {
+		if (chat_images[i].state == CHAT_PIC_QUEUED) {
+			chat_pic_load(&chat_images[i], 0);
+			return;
+		}
+	}
+	for (i = 0; i < nchat_avatars; i++) {
+		if (chat_avatars[i].state == CHAT_PIC_QUEUED) {
+			chat_pic_load(&chat_avatars[i], 1);
+			return;
+		}
+	}
+}
+
+static void chat_media_clear(void)
+{
+	int i;
+
+	for (i = 0; i < nchat_images; i++)
+		chat_pic_free(&chat_images[i]);
+	for (i = 0; i < nchat_avatars; i++)
+		chat_pic_free(&chat_avatars[i]);
+	nchat_images = 0;
+	nchat_avatars = 0;
+	chat_image_bytes = 0;
+	free(chat_fetch_buf);
+	chat_fetch_buf = 0;
+	free(chat_arena);
+	chat_arena = 0;
+	chat_arena_size = 0;
+}
+
+/* Refresh/Retry gives failed pictures another chance. */
+static void chat_media_retry(void)
+{
+	int i;
+
+	for (i = 0; i < nchat_images; i++)
+		if (chat_images[i].state == CHAT_PIC_FAILED)
+			chat_images[i].state = CHAT_PIC_QUEUED;
+	for (i = 0; i < nchat_avatars; i++)
+		if (chat_avatars[i].state == CHAT_PIC_FAILED)
+			chat_avatars[i].state = CHAT_PIC_QUEUED;
+	ngui_invalidate(&ui);
+}
+
+/* Resolve a picture URL; Cloudron's older profile-avatar path is rewritten
+ * to the /api/avatars/ route the current server serves. */
+static int chat_pic_url(const char *raw, char *out, unsigned int cap)
+{
+	static const char old_prefix[] = "/api/v1/profile/avatar/";
+	const char *p;
+	char tmp[CHAT_IMG_URL_MAX];
+	char *q;
+
+	if (!raw || !raw[0])
+		return -1;
+	p = strstr(raw, old_prefix);
+	if (p) {
+		s_copy(tmp, "/api/avatars/", sizeof(tmp));
+		s_cat(tmp, p + sizeof(old_prefix) - 1, sizeof(tmp));
+		q = strchr(tmp, '?');
+		if (q)
+			*q = '\0';
+		raw = tmp;
+	}
+	return uhttp_resolve(server, raw, out, cap);
+}
+
+static int chat_image_name(const char *mime, const char *filename)
+{
+	static const char *const ext[] = {
+		".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga",
+		".ppm", ".pgm", ".pbm", ".ico", ".cur", ".pam"
+	};
+	unsigned int i;
+
+	if (mime && strncmp(mime, "image/", 6) == 0)
+		return 1;
+	if (!filename)
+		return 0;
+	for (i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
+		unsigned int n = (unsigned int)strlen(ext[i]);
+		unsigned int j;
+		const char *s = filename + strlen(filename);
+
+		if ((unsigned int)strlen(filename) < n)
+			continue;
+		s -= n;
+		for (j = 0; j < n; j++) {
+			char a = s[j], b = ext[i][j];
+
+			if (a >= 'A' && a <= 'Z')
+				a = (char)(a - 'A' + 'a');
+			if (a != b)
+				break;
+		}
+		if (j == n)
+			return 1;
+	}
+	return 0;
+}
+
+/* Layout/draw dimensions for one message image.  *state is the cache state
+ * (a missing entry is treated as queued; draw queues it). */
+static void chat_image_measure(const char *url, int tw, int *dw, int *dh,
+			       unsigned int *scale, int *state)
+{
+	struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
+	unsigned int sc = 65536;
+
+	if (p && p->state == CHAT_PIC_READY) {
+		if ((int)p->img.w > tw)
+			sc = ((unsigned int)tw << 16) / p->img.w;
+		if (((p->img.h * sc) >> 16) > CHAT_IMG_H)
+			sc = (CHAT_IMG_H << 16) / p->img.h;
+		*dw = (int)((p->img.w * sc) >> 16);
+		*dh = (int)((p->img.h * sc) >> 16);
+		if (*dw < 1)
+			*dw = 1;
+		if (*dh < 1)
+			*dh = 1;
+		*scale = sc;
+		*state = CHAT_PIC_READY;
+		return;
+	}
+	*dw = tw < 320 ? tw : 320;
+	if (*dw < 40)
+		*dw = 40;
+	*dh = 120;
+	*scale = 65536;
+	*state = p ? p->state : CHAT_PIC_QUEUED;
+}
+
+static struct ngui_rect chat_clip_rect(void)
+{
+	if (ui.nclip > 0)
+		return ui.clip[ui.nclip - 1];
+	return (struct ngui_rect){ 0, 0, ui.w, ui.h };
+}
+
+static void chat_image_draw(const char *url, int x, int y, int tw)
+{
+	struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
+	struct ngui_rect clip = chat_clip_rect();
+	int dw, dh, state;
+	unsigned int scale;
+
+	if (!p)
+		p = chat_image_slot(url);
+	chat_image_measure(url, tw, &dw, &dh, &scale, &state);
+	if (p && p->state == CHAT_PIC_READY) {
+		struct img_blit blit;
+
+		memset(&blit, 0, sizeof(blit));
+		blit.dst = ui.px;
+		blit.dst_w = ui.w;
+		blit.dst_h = ui.h;
+		blit.clip_x = clip.x;
+		blit.clip_y = clip.y;
+		blit.clip_w = clip.w;
+		blit.clip_h = clip.h;
+		blit.x = x;
+		blit.y = y;
+		blit.scale = scale;
+		blit.bg = ui.theme.bg;
+		blit.bg2 = ui.theme.bg;
+		blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
+		img_draw(&p->img, &blit);
+		ngui_frame(&ui, (struct ngui_rect){ x, y, dw, dh },
+			   ui.theme.border);
+	} else {
+		struct ngui_rect box = { x, y, dw, dh };
+
+		ngui_fill_rect(&ui, box, ui.theme.panel_alt);
+		ngui_frame(&ui, box, ui.theme.border);
+		ngui_text_ellipsis(&ui, box, x + 8, y + (dh - line_h()) / 2,
+				   state == CHAT_PIC_FAILED ?
+				   "Image could not be loaded" :
+				   "Loading image...", ui.theme.text_dim);
+	}
+}
+
+static int chat_avatar_draw(const char *url, int x, int y, int size,
+			    unsigned short fallback)
+{
+	struct chat_pic *p;
+
+	if (!url || !url[0])
+		return 0;
+	p = chat_pic_find(chat_avatars, nchat_avatars, url);
+	if (!p)
+		p = chat_avatar_slot(url);
+	if (p && p->state == CHAT_PIC_READY) {
+		struct ngui_rect clip = chat_clip_rect();
+		struct img_blit blit;
+
+		memset(&blit, 0, sizeof(blit));
+		blit.dst = ui.px;
+		blit.dst_w = ui.w;
+		blit.dst_h = ui.h;
+		blit.clip_x = clip.x;
+		blit.clip_y = clip.y;
+		blit.clip_w = clip.w;
+		blit.clip_h = clip.h;
+		blit.x = x;
+		blit.y = y;
+		blit.scale = ((unsigned int)size << 16) / CHAT_AVATAR;
+		blit.bg = fallback;
+		blit.bg2 = fallback;
+		blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
+		img_draw(&p->img, &blit);
+		return 1;
+	}
+	return 0;
+}
+
 static void go_login(const char *why);
 
 /* Common error handling for API calls in the main screen.  Returns 1 when
@@ -546,8 +1084,47 @@ static int load_directory(void)
 
 static void msg_free(struct msg *m)
 {
+	int i;
+
 	free(m->body);
 	m->body = 0;
+	free(m->author_pic);
+	m->author_pic = 0;
+	for (i = 0; i < m->nimg; i++) {
+		free(m->img_url[i]);
+		m->img_url[i] = 0;
+	}
+	m->nimg = 0;
+}
+
+/* Resolve and remember one image URL; duplicates and overflowing messages
+ * are ignored. */
+static int msg_add_image(struct msg *m, const char *raw)
+{
+	char url[CHAT_IMG_URL_MAX];
+	int i;
+
+	if (!raw || !raw[0] || m->nimg >= MSG_IMG_MAX)
+		return 0;
+	if (uhttp_resolve(server, raw, url, sizeof(url)) != 0)
+		return 0;
+	for (i = 0; i < m->nimg; i++)
+		if (strcmp(m->img_url[i], url) == 0)
+			return 0;
+	m->img_url[m->nimg] = strdup(url);
+	if (!m->img_url[m->nimg])
+		return -1;
+	m->nimg++;
+	return 0;
+}
+
+static void msg_set_author_pic(struct msg *m, const char *raw)
+{
+	char url[CHAT_IMG_URL_MAX];
+
+	if (!raw[0] || chat_pic_url(raw, url, sizeof(url)) != 0)
+		return;
+	m->author_pic = strdup(url);
 }
 
 static void clear_messages(void)
@@ -581,16 +1158,21 @@ static void build_extra(struct msg *m, int o)
 	for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
 	     it >= 0; it = ujson_next(&json, it)) {
 		char name[64];
+		const char *mime = ujson_get_str(&json, it, "mime");
+		const char *fn = ujson_get_str(&json, it, "filename");
+		const char *url = ujson_get_str(&json, it, "url");
 
-		to_latin1_line(name, sizeof(name),
-			       ujson_get_str(&json, it, "filename"));
+		if (chat_image_name(mime, fn) && url[0])
+			continue;       /* drawn inline by the timeline */
+		to_latin1_line(name, sizeof(name), fn);
 		if (m->extra[0])
 			s_cat(m->extra, ", ", sizeof(m->extra));
 		else
 			s_cat(m->extra, "[file] ", sizeof(m->extra));
 		s_cat(m->extra, name, sizeof(m->extra));
 	}
-	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT) {
+	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
+	    !ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")[0]) {
 		if (m->extra[0])
 			s_cat(m->extra, "  ", sizeof(m->extra));
 		s_cat(m->extra, "[GIF]", sizeof(m->extra));
@@ -655,6 +1237,7 @@ static int msg_from_json(struct msg *m, int o)
 	if (!nm[0])
 		nm = ujson_get_str(&json, o, "authorUsername");
 	to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
+	msg_set_author_pic(m, ujson_get_str(&json, o, "authorPicture"));
 	s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
 	       sizeof(m->created));
 	m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
@@ -671,8 +1254,39 @@ static int msg_from_json(struct msg *m, int o)
 	while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
 		body[--len] = '\0';
 	m->body = strdup(body);
-	if (!m->body)
+	if (!m->body) {
+		msg_free(m);
 		return -1;
+	}
+	{
+		int it;
+		const char *mime, *fn;
+
+		for (it = ujson_first(&json,
+				      ujson_get(&json, o, "attachments"));
+		     it >= 0; it = ujson_next(&json, it)) {
+			mime = ujson_get_str(&json, it, "mime");
+			fn = ujson_get_str(&json, it, "filename");
+			if (chat_image_name(mime, fn) &&
+			    msg_add_image(m, ujson_get_str(&json, it, "url")) != 0) {
+				msg_free(m);
+				return -1;
+			}
+		}
+	}
+	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
+	    msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "gif"),
+					   "url")) != 0) {
+		msg_free(m);
+		return -1;
+	}
+	if (ujson_type(&json, ujson_get(&json, o, "preview")) == UJSON_OBJECT &&
+	    msg_add_image(m, ujson_get_str(&json,
+					   ujson_get(&json, o, "preview"),
+					   "image")) != 0) {
+		msg_free(m);
+		return -1;
+	}
 	rt = ujson_get(&json, o, "replyTo");
 	if (ujson_type(&json, rt) == UJSON_OBJECT) {
 		char tmp[96];
@@ -1018,6 +1632,14 @@ static void load_picks(int dms)
 		s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
 		if (!p->id[0])
 			continue;
+		p->pic[0] = '\0';
+		{
+			char url[CHAT_IMG_URL_MAX];
+
+			if (chat_pic_url(ujson_get_str(&json, it, "picture"),
+					 url, sizeof(url)) == 0)
+				s_copy(p->pic, url, sizeof(p->pic));
+		}
 		if (dms) {
 			if (strcmp(p->id, me_id) == 0)
 				continue;
@@ -1124,6 +1746,7 @@ static void go_login(const char *why)
 	uhttp_jar_clear(&jar);
 	saved_jar_changes = jar.changes;
 	saved_cookie[0] = '\0';
+	chat_media_clear();
 	screen = SCR_SERVER;
 	modal = MODAL_NONE;
 	clear_messages();
@@ -1311,8 +1934,16 @@ static void load_config(void)
 {
 	static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256];
 	char srv[CHAT_SERVER_MAX];
-	int n = read_file(cfg_path, buf, sizeof(buf));
+	int n, migrated = 0;
 
+	n = read_file(cfg_path, buf, sizeof(buf));
+	/* First start on a persistent volume: carry a session that an older
+	 * build saved in /share into /data once. */
+	if (n <= 0 && cfg_is_default &&
+	    strcmp(cfg_path, DEFAULT_CFG_DATA) == 0) {
+		n = read_file(DEFAULT_CFG_SHARE, buf, sizeof(buf));
+		migrated = n > 0;
+	}
 	ngui_input_set(&cfg_in, cfg_path);
 	if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv),
 					saved_cookie,
@@ -1328,6 +1959,8 @@ static void load_config(void)
 		return;
 	uhttp_jar_import(&jar, server_host, server_secure, saved_cookie);
 	saved_jar_changes = jar.changes;
+	if (migrated)
+		save_config();
 	check_session(1);
 }
 
@@ -1435,6 +2068,7 @@ static void layout_msg(int i, int width)
 {
 	struct msg *m = &msgs[i];
 	int lh = line_h(), h, tw = width - TEXT_X - 12;
+	int k;
 
 	if (tw < 40)
 		tw = 40;
@@ -1446,6 +2080,14 @@ static void layout_msg(int i, int width)
 	if (m->reply[0])
 		h += lh + 2;
 	h += count_lines(m->body, tw) * lh;
+	for (k = 0; k < m->nimg; k++) {
+		int dw, dh, state;
+		unsigned int scale;
+
+		chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale,
+				   &state);
+		h += dh + 6;
+	}
 	if (m->extra[0])
 		h += lh + 2;
 	h += 2;
@@ -1494,7 +2136,7 @@ static unsigned short avatar_color(const char *id)
 }
 
 static void draw_avatar(int x, int y, int size, const char *name,
-			const char *id)
+			const char *id, const char *pic)
 {
 	struct ngui_rect r = { x, y, size, size };
 	char ini[2];
@@ -1502,6 +2144,8 @@ static void draw_avatar(int x, int y, int size, const char *name,
 
 	ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
 			     avatar_color(id));
+	if (chat_avatar_draw(pic, x, y, size, avatar_color(id)))
+		return;
 	ini[0] = name[0] ? name[0] : '?';
 	if (ini[0] >= 'a' && ini[0] <= 'z')
 		ini[0] = (char)(ini[0] - 'a' + 'A');
@@ -1827,7 +2471,8 @@ static void draw_message(struct msg *m, int x, int y, int width)
 		int aw;
 
 		y += PAD_TOP;
-		draw_avatar(x + 10, y, AVATAR, m->author, m->user_id);
+		draw_avatar(x + 10, y, AVATAR, m->author, m->user_id,
+			    m->author_pic);
 		ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
 			     ui.theme.text, ui.font_px, 1, 0, 0);
 		aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
@@ -1859,6 +2504,19 @@ static void draw_message(struct msg *m, int x, int y, int width)
 		pos += adv;
 		y += lh;
 	}
+	{
+		int k;
+
+		for (k = 0; k < m->nimg; k++) {
+			int dw, dh, state;
+			unsigned int scale;
+
+			chat_image_measure(m->img_url[k], tw, &dw, &dh,
+					   &scale, &state);
+			chat_image_draw(m->img_url[k], tx, y, tw);
+			y += dh + 6;
+		}
+	}
 	if (m->extra[0]) {
 		struct ngui_rect er = { tx, y + 2, tw, lh };
 
@@ -2062,7 +2720,8 @@ static void draw_modal(void)
 			ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
 						row.w, 1 }, ui.theme.border);
 			if (modal == MODAL_NEWDM)
-				draw_avatar(row.x + 8, y + 6, 30, p->name, p->id);
+				draw_avatar(row.x + 8, y + 6, 30, p->name, p->id,
+					    p->pic);
 			ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
 						 row.w - 160, lh + 4 },
 					   row.x + 48, y + 4,
@@ -2354,6 +3013,7 @@ static void run_action(void)
 	case ACT_RETRY:
 		backoff_ms = 0;
 		retry_at = 0;
+		chat_media_retry();
 		s_copy(busy, "Refreshing...", sizeof(busy));
 		paint_now();
 		busy[0] = '\0';
@@ -2461,7 +3121,12 @@ void _start(const char *arg)
 	pass_in.secret = 1;
 	totp_in.placeholder = "123456";
 	cookie_in.placeholder = "connect.sid=...";
-	s_copy(cfg_path, arg && arg[0] ? arg : DEFAULT_CFG, sizeof(cfg_path));
+	if (arg && arg[0]) {
+		s_copy(cfg_path, arg, sizeof(cfg_path));
+	} else {
+		s_copy(cfg_path, default_cfg_path(), sizeof(cfg_path));
+		cfg_is_default = 1;
+	}
 	ngui_set_focus(&ui, ID_SERVER);
 	last_input_ms = 0;
 
@@ -2488,6 +3153,7 @@ void _start(const char *arg)
 			run_action();
 		else
 			poll_tick();
+		chat_media_tick();
 		/* The offline retry countdown needs a once-a-second repaint. */
 		if (offline && screen == SCR_MAIN) {
 			static unsigned int last_tick;

+ 76 - 7
ucmd_curl.c

@@ -13,6 +13,7 @@
 
 #include "ucmd_lib.h"
 #include "uhttp.h"
+#include "uhttp_cookie.h"
 
 #define LINE_MAX_C 320
 
@@ -61,7 +62,7 @@ static const struct uhttp_hooks hooks = {
 /* ---- headless fetch helper for the browser ---------------------------- */
 
 #define FETCH_PATH_MAX 32
-#define FETCH_POST_MAX 4096u
+#define FETCH_POST_MAX 16384u
 #define FETCH_MAX   (2u * 1024u * 1024u)
 
 /* Each browser worker gets its own set of /share files; slot -1 keeps the
@@ -140,6 +141,28 @@ static void fetch_fail(unsigned int status, int err, const char *ctype,
 	u_syscall3(SYS_WRITE_FILE, (int)fp.meta, (int)meta, (int)n);
 }
 
+/* One cookie jar for every helper of every browser window, kept in /share
+ * (RAM, cleared at reboot) so a login session survives helper restarts and
+ * the parallel workers.  Re-read before each request and written back when
+ * the response changed it; with several helpers the last writer wins. */
+#define FETCH_JAR_PATH "/share/bcookies"
+static struct uhttp_jar fetch_jar;
+
+static void jar_load(void)
+{
+	int n = u_syscall3(SYS_READ_FILE, (int)FETCH_JAR_PATH,
+			   (int)&fetch_jar, (int)sizeof(fetch_jar));
+
+	if (n != (int)sizeof(fetch_jar))
+		uhttp_jar_init(&fetch_jar);
+}
+
+static void jar_save(void)
+{
+	u_syscall3(SYS_WRITE_FILE, (int)FETCH_JAR_PATH, (int)&fetch_jar,
+		   (int)sizeof(fetch_jar));
+}
+
 struct fetch_times {
 	unsigned int open_ms;
 	unsigned int first_ms;
@@ -172,6 +195,7 @@ static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
 
 /* Fetch one URL through a possibly reused keep-alive connection. */
 static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
+			 const char *method, const char *ctype,
 			 const char *post, unsigned int post_len,
 			 unsigned char *buf, unsigned int *outlen,
 			 unsigned int *outtrunc, int *outerr,
@@ -189,8 +213,11 @@ static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 		times->first_ms = 0;
 		times->total_ms = 0;
 	}
-	uhttp_set_method(h, post_len ? "POST" : 0, post, post_len,
-			 "application/x-www-form-urlencoded");
+	if (!method)
+		method = post_len ? "POST" : 0;
+	if (!ctype || !ctype[0])
+		ctype = "application/x-www-form-urlencoded";
+	uhttp_set_method(h, method, post, post_len, ctype);
 	rv = uhttp_open(h, url, UHTTP_GZIP, 0);
 	if (rv == UHTTP_ERR_BUSY) {
 		int tries;
@@ -279,7 +306,7 @@ static void fetch_once(void)
 
 	uhttp_init(&h);
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
-	helper_fetch(&h, req + i, cap, 0, 0, buf, &body_len, &body_trunc, &err,
+	helper_fetch(&h, req + i, cap, 0, 0, 0, 0, buf, &body_len, &body_trunc, &err,
 		     &times);
 	if (body_len)
 		u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
@@ -330,10 +357,16 @@ static void fetch_serve(const char *arg)
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
 	h.keepalive = 1;
 
+	h.jar = &fetch_jar;
+
 	for (;;) {
 		unsigned int seq = 0, cap = 0, body_len = 0, body_trunc = 0;
-		unsigned int post_len = 0;
+		unsigned int post_len = 0, jar_changes;
 		int is_post = 0;
+		char method[12], ctype[96];
+
+		method[0] = '\0';
+		ctype[0] = '\0';
 		char done[16];
 		unsigned int dn = 0;
 		unsigned int i = 0;
@@ -358,7 +391,38 @@ static void fetch_serve(const char *arg)
 			}
 			while (req[i] == ' ')
 				i++;
-			if (!strncmp(req + i, "POST ", 5)) {
+			method[0] = '\0';
+			ctype[0] = '\0';
+			/* "X <method> <body length> <content type or -> <url>":
+			 * any method, for the browser's fetch()/XHR. */
+			if (!strncmp(req + i, "X ", 2)) {
+				unsigned int k = 0;
+
+				i += 2;
+				while (req[i] && req[i] != ' ' &&
+				       k + 1 < sizeof(method))
+					method[k++] = req[i++];
+				method[k] = '\0';
+				while (req[i] == ' ')
+					i++;
+				while (req[i] >= '0' && req[i] <= '9') {
+					post_len = post_len * 10 +
+						(unsigned int)(req[i] - '0');
+					i++;
+				}
+				while (req[i] == ' ')
+					i++;
+				k = 0;
+				while (req[i] && req[i] != ' ' &&
+				       k + 1 < sizeof(ctype))
+					ctype[k++] = req[i++];
+				ctype[k] = '\0';
+				if (!strcmp(ctype, "-"))
+					ctype[0] = '\0';
+				while (req[i] == ' ')
+					i++;
+				is_post = post_len > 0 || strcmp(method, "GET");
+			} else if (!strncmp(req + i, "POST ", 5)) {
 				is_post = 1;
 				i += 5;
 				while (req[i] >= '0' && req[i] <= '9') {
@@ -403,8 +467,13 @@ static void fetch_serve(const char *arg)
 			post_len = 0;
 		}
 
-		helper_fetch(&h, url, cap, is_post ? (char *)post : 0, post_len,
+		jar_load();
+		jar_changes = fetch_jar.changes;
+		helper_fetch(&h, url, cap, method[0] ? method : 0, ctype,
+			     post_len ? (char *)post : 0, post_len,
 			     buf, &body_len, &body_trunc, &err, &times);
+		if (fetch_jar.changes != jar_changes)
+			jar_save();
 		if (body_len)
 			u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
 				   (int)body_len);

+ 18 - 2
ucmd_lib.h

@@ -269,14 +269,16 @@ static inline int u_wm_sync(void)
 
 /* Generic canvas window (gfx commands own a window instead of replacing a
  * terminal's content). */
-static inline int u_win_create(unsigned int w, unsigned int h, const char *title,
-			       struct win_info *out)
+static inline int u_win_create_flags(unsigned int w, unsigned int h,
+				     const char *title, unsigned int flags,
+				     struct win_info *out)
 {
 	struct win_create in;
 	unsigned int i = 0;
 
 	in.w = w;
 	in.h = h;
+	in.flags = flags;
 	while (title && title[i] && i < sizeof(in.title) - 1) {
 		in.title[i] = title[i];
 		i++;
@@ -285,6 +287,20 @@ static inline int u_win_create(unsigned int w, unsigned int h, const char *title
 	return u_syscall2(SYS_WIN_CREATE, (int)&in, (int)out);
 }
 
+static inline int u_win_create(unsigned int w, unsigned int h, const char *title,
+			       struct win_info *out)
+{
+	return u_win_create_flags(w, h, title, 0, out);
+}
+
+/* A chromeless panel anchored by the WM under the top-bar status icons. */
+static inline int u_win_create_popover(unsigned int w, unsigned int h,
+				       const char *title,
+				       struct win_info *out)
+{
+	return u_win_create_flags(w, h, title, WIN_F_POPOVER, out);
+}
+
 static inline int u_win_present(void)
 {
 	return u_syscall1(SYS_WIN_PRESENT, 0);

+ 488 - 219
ucmd_netmenu.c

@@ -3,9 +3,11 @@
  * Lists the NICs the kernel reports as present (Ethernet, USB Ethernet,
  * RNDIS tethering) and the WiFi networks from a scan.  Selecting a wired or
  * USB device makes it the active netdev and runs DHCP; selecting a WiFi
- * network asks for the WPA2 passphrase when needed, then starts the existing
+ * network joins it with the passphrase saved in /data/WIFI.CFG when one is
+ * known, otherwise it asks for the WPA2 passphrase, then starts the existing
  * `wifi` supplicant with a staged /share/netmenu.wifi request (the SYS_SPAWN
- * argument limit is too small for an SSID plus a long passphrase).  The
+ * argument limit is too small for an SSID plus a long passphrase).  A Saved
+ * view lists the known networks and forgets individual entries.  The
  * supplicant itself runs DHCP once the data port opens.
  *
  * A small ngui canvas window; the WM places it under the network icon and
@@ -13,11 +15,16 @@
 
 #include "ucmd_lib.h"
 #include "ngui.h"
-#include "wifi_cfg.h"
+#include "wifi_store.h"
 
 #define MAX_DEVS 8
 #define MAX_BSS  32
-#define ROW_H    24
+#define DEV_ROW_H        42
+#define WIFI_ROW_H       42
+#define SAVED_ROW_H      30
+#define SAVED_LIST_ROW_H 42
+#define SECTION_H        28
+#define MENU_GAP         10
 #define LOG_MAX  2048
 
 #define ID_REFRESH       1
@@ -27,25 +34,36 @@
 #define ID_PASS_CANCEL   5
 #define ID_CONN_CANCEL   6
 #define ID_PASS          7
+#define ID_SAVED         8
+#define ID_SAVED_BACK    9
 #define ID_DEV_BASE      100
 #define ID_BSS_BASE      200
+#define ID_SAVED_BASE    300
+#define ID_INFO_BASE     400
+#define ID_SAVED_ROW_BASE 500
 
 #define ACT_REFRESH    (1u << 0)
 #define ACT_SCAN       (1u << 1)
 #define ACT_DISCONNECT (1u << 2)
 #define ACT_BACK       (1u << 3)
 #define ACT_CONNECT    (1u << 4)
+#define ACT_SAVED      (1u << 5)
+#define ACT_FORGET     (1u << 6)
 
-enum { VIEW_MAIN, VIEW_PASS, VIEW_CONNECT };
+enum { VIEW_MAIN, VIEW_PASS, VIEW_CONNECT, VIEW_SAVED };
 
 static struct ngui ui;
+static struct ngui_popover pop;
 static struct ngui_input pass_in;
-static struct ngui_scroll wifi_scroll;
+static struct ngui_scroll main_scroll;
+static struct ngui_scroll saved_scroll;
 
 static struct sys_netdev devs[MAX_DEVS];
 static int ndev;
 static struct sys_wifi_bss bss[MAX_BSS];
 static int nbss;
+static struct wifi_cfg saved[WIFI_CFG_MAX];
+static int nsaved;
 static struct sys_wifi_status wst;
 static struct sys_netinfo net;
 static int net_present;
@@ -71,6 +89,7 @@ static unsigned int status_until;
 static unsigned int actions;
 static int action_dev = -1;
 static int action_bss = -1;
+static int action_saved = -1;
 
 static void draw(void);
 static void paint_frame(void);
@@ -135,6 +154,25 @@ static char *put_ip(char *p, const unsigned char ip[4])
 	return p;
 }
 
+static char *put_mac(char *p, const unsigned char mac[6])
+{
+	static const char hex[] = "0123456789abcdef";
+	int i;
+
+	for (i = 0; i < 6; i++) {
+		*p++ = hex[mac[i] >> 4];
+		*p++ = hex[mac[i] & 15];
+		if (i != 5)
+			*p++ = ':';
+	}
+	return p;
+}
+
+static int ip_any(const unsigned char ip[4])
+{
+	return ip[0] || ip[1] || ip[2] || ip[3];
+}
+
 static void ssid_name(const struct sys_wifi_bss *b, char out[33])
 {
 	unsigned int i, n = b->ssid_len;
@@ -155,6 +193,29 @@ static void ssid_name(const struct sys_wifi_bss *b, char out[33])
 	}
 }
 
+static void cfg_ssid_name(const struct wifi_cfg *c, char out[33])
+{
+	unsigned int i, n = c->ssid_len;
+
+	if (n > 32)
+		n = 32;
+	for (i = 0; i < n; i++)
+		out[i] = (char)c->ssid[i];
+	out[n] = '\0';
+}
+
+static void load_saved(void)
+{
+	int n = wifi_store_load(saved, WIFI_CFG_MAX);
+
+	nsaved = n > 0 ? n : 0;
+}
+
+static int bss_saved(const struct sys_wifi_bss *b)
+{
+	return wifi_store_find(saved, nsaved, b->ssid, b->ssid_len);
+}
+
 static const char *security_name(unsigned int s)
 {
 	return s == SYS_WIFI_SEC_OPEN ? "open" :
@@ -336,7 +397,7 @@ static void start_scan(void)
 	scanning = 1;
 	scan_start = u_ticks_ms();
 	nbss = 0;
-	wifi_scroll.offset = 0;
+	main_scroll.offset = 0;
 	ngui_invalidate(&ui);
 }
 
@@ -457,6 +518,7 @@ static void poll_connect(void)
 	if (!u_alive((unsigned int)connect_pid)) {
 		connect_pid = -1;
 		load_status();
+		load_saved();
 		if (wst.state >= SYS_WIFI_ST_LINK) {
 			int have_ip = 0;
 
@@ -529,6 +591,20 @@ static void select_bss(int i)
 		return;
 	}
 	if (bss[i].security == SYS_WIFI_SEC_PSK) {
+		int si = bss_saved(&bss[i]);
+
+		if (si >= 0 && saved[si].pass_len > 0) {
+			char pass[65];
+			unsigned int j;
+
+			for (j = 0; j < saved[si].pass_len; j++)
+				pass[j] = saved[si].pass[j];
+			pass[saved[si].pass_len] = '\0';
+			start_connect(pass);
+			for (j = 0; j < sizeof(pass); j++)
+				((volatile char *)pass)[j] = 0;
+			return;
+		}
 		ngui_input_set(&pass_in, "");
 		pass_in.secret = 1;
 		pass_in.placeholder = "WPA2 passphrase";
@@ -544,11 +620,12 @@ static void select_bss(int i)
 static void handle_actions(void)
 {
 	unsigned int a = actions;
-	int di = action_dev, bi = action_bss;
+	int di = action_dev, bi = action_bss, fi = action_saved;
 
 	actions = 0;
 	action_dev = -1;
 	action_bss = -1;
+	action_saved = -1;
 
 	if (a & ACT_BACK) {
 		if (view == VIEW_CONNECT)
@@ -559,6 +636,28 @@ static void handle_actions(void)
 		}
 		return;
 	}
+	if (a & ACT_SAVED) {
+		load_saved();
+		saved_scroll.offset = 0;
+		view = VIEW_SAVED;
+		set_status("", 0);
+		ngui_invalidate(&ui);
+		return;
+	}
+	if (a & ACT_FORGET) {
+		if (fi >= 0 && fi < nsaved) {
+			if (wifi_store_forget(saved[fi].ssid,
+					      saved[fi].ssid_len) > 0) {
+				load_saved();
+				saved_scroll.offset = 0;
+				set_status("Saved network removed", 0);
+			} else {
+				set_status("Could not remove the saved network", 1);
+			}
+		}
+		ngui_invalidate(&ui);
+		return;
+	}
 	if (a & ACT_CONNECT) {
 		char pass[65];
 		unsigned int i, n;
@@ -614,295 +713,385 @@ static void handle_actions(void)
 	}
 }
 
-static void draw_bars(int x, int y, int bars, unsigned short color)
-{
-	int i;
-
-	for (i = 0; i < 4; i++) {
-		int h = 3 + i * 3;
-		struct ngui_rect r;
-
-		r.x = x + i * 5;
-		r.y = y + 12 - h;
-		r.w = 3;
-		r.h = h;
-		ngui_fill_rect(&ui, r, i < bars ? color : ui.theme.border);
-	}
-}
-
 static void draw_status(void)
 {
 	if (status[0] && status_until &&
 	    (int)(u_ticks_ms() - status_until) < 0)
-		ngui_text_utf8(&ui, 10, ui.h - 22, status,
-			  status_error ? ui.theme.error : ui.theme.accent);
+		ngui_popover_footer(&ui, &pop, status,
+			status_error ? ui.theme.error : ui.theme.success);
 }
 
-static void draw_wifi_list(struct ngui_rect area)
+/* The active connection at the top of the panel: a status dot, the link
+ * state and the device address (plus the SSID and RSSI on Wi-Fi). */
+static void draw_status_card(struct ngui_rect r)
 {
-	char label[40], shortcut[20];
+	struct ngui_rect line_r = { r.x + 34, r.y + 34, r.w - 44, 16 };
+	struct ngui_rect dot = { r.x + 14, r.y + 25, 10, 10 };
+	char line[160], *p;
+	unsigned short dot_color;
+	int i, have_ip = 0;
+
+	for (i = 0; i < 4; i++)
+		if (net.ip[i])
+			have_ip = 1;
+	if (!net_present)
+		dot_color = ui.theme.error;
+	else if (!have_ip ||
+		 (seq(net.name, "wifi") && wst.state < SYS_WIFI_ST_LINK))
+		dot_color = ui.theme.warning;
+	else
+		dot_color = ui.theme.success;
+
+	ngui_fill_round_rect(&ui, r, 8, 8, 8, 8, ui.theme.panel);
+	ngui_frame_round(&ui, r, 8, 8, 8, 8, 1, ui.theme.panel_alt);
+	ngui_fill_round_rect(&ui, dot, 5, 5, 5, 5, dot_color);
+
+	p = line;
+	if (!net_present)
+		p = sput(p, "Offline");
+	else if (seq(net.name, "wifi"))
+		p = sput(p, wst.state >= SYS_WIFI_ST_LINK ?
+			 "Wi-Fi connected" : "Wi-Fi");
+	else if (seq(net.name, "rndis"))
+		p = sput(p, "USB tethering");
+	else
+		p = sput(p, "Wired network");
+	*p = '\0';
+	ngui_text_px(&ui, r.x + 34, r.y + 10, line, slen(line),
+		     ui.theme.text, 14, 1, 0, 0);
+
+	p = line;
+	if (net_present) {
+		p = sput(p, net.name);
+		p = sput(p, " \xC2\xB7 ");
+		if (have_ip)
+			p = put_ip(p, net.ip);
+		else
+			p = sput(p, "no IP");
+		if (seq(net.name, "wifi") && wst.state >= SYS_WIFI_ST_ASSOC) {
+			p = sput(p, " \xC2\xB7 ");
+			for (i = 0; i < wst.ssid_len && i < 32; i++)
+				*p++ = (char)wst.ssid[i];
+			p = sput(p, "  ");
+			p = put_signed(p, wst.rssi);
+			p = sput(p, " dBm");
+		}
+	} else {
+		p = sput(p, "No network device active");
+	}
+	*p = '\0';
+	ngui_text_ellipsis_utf8(&ui, line_r, line_r.x, line_r.y, line,
+				ui.theme.text_dim);
+}
+
+static void draw_wifi_list(struct ngui_rect area, int *y)
+{
+	struct ngui_row row;
+	char ssid[33], sub[72], *p;
 	int i;
 
 	if (!wifi_present) {
-		ngui_text(&ui, area.x + 2, area.y + 4,
-			  "No WiFi card detected", ui.theme.text_dim);
+		ngui_text(&ui, area.x + 12, *y + 12,
+			  "No Wi-Fi card detected", ui.theme.text_dim);
+		*y += WIFI_ROW_H;
 		return;
 	}
 	if (scanning) {
-		ngui_text(&ui, area.x + 2, area.y + 4,
-			  "Scanning...", ui.theme.text_dim);
+		ngui_text(&ui, area.x + 12, *y + 12,
+			  "Scanning for networks...", ui.theme.accent);
+		*y += WIFI_ROW_H;
 		return;
 	}
 	if (nbss == 0) {
-		ngui_text(&ui, area.x + 2, area.y + 4,
-			  wst.state >= SYS_WIFI_ST_ASSOC ?
-			  "Connected - Disconnect to scan for other networks" :
-			  "Press Scan to list WiFi networks",
+		const char *msg = wst.state >= SYS_WIFI_ST_ASSOC ?
+			"Connected - disconnect to scan for other networks" :
+			"Press Scan to list Wi-Fi networks";
+
+		ngui_text(&ui, area.x + 12, *y + 12, msg,
 			  ui.theme.text_dim);
+		*y += WIFI_ROW_H;
 		return;
 	}
 
-	wifi_scroll.content_h = nbss * ROW_H;
-	ngui_scroll_begin(&ui, area, &wifi_scroll);
-	ngui_scroll_wheel(&ui, area, &wifi_scroll);
-	ngui_scroll_keys(&ui, &wifi_scroll);
 	for (i = 0; i < nbss; i++) {
-		struct ngui_rect rr;
 		struct sys_wifi_bss *b = &bss[i];
-		char ssid[33];
-		int sw, bx, clicked;
-		unsigned short signal;
-
-		rr.x = area.x;
-		rr.y = area.y - wifi_scroll.offset + i * ROW_H;
-		rr.w = area.w - 16;
-		rr.h = ROW_H - 2;
-		if (rr.y + rr.h <= area.y || rr.y >= area.y + area.h)
-			continue;
-
-		ssid_name(b, ssid);
-		sput(label, ssid);
-		sput(shortcut, security_name(b->security));
-		clicked = ngui_menu_item_utf8(&ui, ID_BSS_BASE + i, rr, label,
-					 shortcut, bss_is_active(b));
-
-		sw = (int)ngui_text_width_ui(&ui, shortcut);
-		bx = rr.x + rr.w - 8 - sw - 30;
-		if (b->security == SYS_WIFI_SEC_OTHER)
-			signal = ui.theme.error;
-		else
-			signal = rssi_bars(b->rssi) >= 3 ? ui.theme.accent :
-				 ui.theme.text_dim;
-		draw_bars(bx, rr.y + 3, rssi_bars(b->rssi), signal);
-		if (clicked) {
-			action_bss = i;
+		struct ngui_rect r = { area.x, *y, area.w - 18, WIFI_ROW_H };
+
+		if (r.y + r.h > area.y && r.y < area.y + area.h) {
+			ssid_name(b, ssid);
+			p = sub;
+			p = sput(p, security_name(b->security));
+			if (bss_saved(b) >= 0)
+				p = sput(p, " \xC2\xB7 saved");
+			if (bss_is_active(b))
+				p = sput(p, " \xC2\xB7 connected");
+			*p = '\0';
+
+			row.title = ssid;
+			row.subtitle = sub;
+			row.trailing = 0;
+			row.bars = b->security == SYS_WIFI_SEC_OTHER ? -1 :
+				   rssi_bars(b->rssi);
+			row.selected = bss_is_active(b);
+			if (ngui_list_row_utf8(&ui, ID_BSS_BASE + i, r,
+					       &row))
+				action_bss = i;
 		}
+		*y += WIFI_ROW_H;
 	}
-	ngui_scroll_end(&ui, area, &wifi_scroll);
 }
 
 static void draw_main(void)
 {
-	struct ngui_rect body = { 10, 8, ui.w - 20, ui.h - 34 };
-	struct ngui_rect r, rb;
-	char line[128], *p;
-	int i, shown;
+	struct ngui_rect body = pop.body;
+	struct ngui_rect card, area, r;
+	struct ngui_row row;
+	char line[48], *p;
+	int i, y, content_h, shown, more;
 
-	/* Active connection summary. */
-	r = ngui_cut_top(&body, 20);
-	p = line;
-	if (!net_present) {
-		p = sput(p, "No active network device");
-	} else {
-		p = sput(p, "Active: ");
-		p = sput(p, net.name);
-		p = sput(p, " (");
-		p = sput(p, net.chip);
-		p = sput(p, ")");
-		if (seq(net.name, "wifi") && wst.state >= SYS_WIFI_ST_ASSOC) {
-			p = sput(p, "  ");
-			for (i = 0; i < wst.ssid_len && i < 32; i++)
-				*p++ = (char)wst.ssid[i];
-			p = sput(p, " ");
-			p = put_signed(p, wst.rssi);
-			p = sput(p, " dBm");
-		}
-	}
-	*p = '\0';
-	ngui_text_ellipsis_utf8(&ui, r, r.x, r.y, line, ui.theme.text);
+	card = ngui_cut_top(&body, 64);
+	draw_status_card(card);
+	body.y += MENU_GAP;
+	body.h -= MENU_GAP;
 
-	r = ngui_cut_top(&body, 20);
-	p = line;
-	if (net_present) {
-		p = sput(p, "IP ");
-		if (net.ip[0] || net.ip[1] || net.ip[2] || net.ip[3])
-			p = put_ip(p, net.ip);
-		else
-			p = sput(p, "not configured");
-		if (seq(net.name, "wifi"))
-			p = sput(p, wst.state >= SYS_WIFI_ST_LINK ?
-				 "  link up" : "  link down");
-	} else if (wifi_present) {
-		p = sput(p, "WiFi card present - scan to join a network");
-	} else {
-		p = sput(p, "Plug in Ethernet or USB tethering, then Refresh");
-	}
-	*p = '\0';
-	ngui_text_ellipsis_utf8(&ui, r, r.x, r.y, line, ui.theme.text_dim);
-	body.y += 4;
-	body.h -= 4;
-
-	/* Devices. */
-	r = ngui_cut_top(&body, 26);
-	ngui_text(&ui, r.x, r.y + 3, "Network devices", ui.theme.text_dim);
-	rb = r;
-	rb.x = r.x + r.w - 78;
-	rb.w = 78;
-	rb.h = 22;
-	if (ngui_button(&ui, ID_REFRESH, rb, "Refresh"))
+	shown = 0;
+	for (i = 0; i < ndev; i++)
+		if (devs[i].kind != SYS_NETDEV_WIFI)
+			shown++;
+	more = shown > 4 ? shown - 4 : 0;
+	if (shown > 4)
+		shown = 4;
+
+	content_h = SECTION_H + (shown ? shown * DEV_ROW_H : DEV_ROW_H) +
+		    (more ? 20 : 0) + MENU_GAP + SECTION_H;
+	if (!wifi_present || scanning || nbss == 0)
+		content_h += WIFI_ROW_H;
+	else
+		content_h += nbss * WIFI_ROW_H;
+	if (net_present)
+		content_h += MENU_GAP + SECTION_H + 4 * 30;
+	if (nsaved)
+		content_h += SAVED_ROW_H + MENU_GAP;
+
+	main_scroll.content_h = content_h;
+	area = body;
+	ngui_scroll_begin(&ui, area, &main_scroll);
+	ngui_scroll_wheel(&ui, area, &main_scroll);
+	ngui_scroll_keys(&ui, &main_scroll);
+
+	y = area.y - main_scroll.offset;
+	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	if (ngui_section(&ui, r, "Devices", ID_REFRESH, "Refresh"))
 		actions |= ACT_REFRESH;
+	y += SECTION_H;
+
+	{
+		int n = 0;
+
+		for (i = 0; i < ndev && n < shown; i++) {
+			if (devs[i].kind == SYS_NETDEV_WIFI)
+				continue;
+			r = (struct ngui_rect){ area.x, y, area.w - 18,
+						DEV_ROW_H };
+			if (r.y + r.h > area.y && r.y < area.y + area.h) {
+				row.title = devs[i].name;
+				row.subtitle = devs[i].chip;
+				row.trailing = devs[i].active ? "Connected" :
+					       (devs[i].link ? "link" : 0);
+				row.bars = -1;
+				row.selected = devs[i].active;
+				if (ngui_list_row(&ui, ID_DEV_BASE + i, r,
+						  &row))
+					action_dev = i;
+			}
+			y += DEV_ROW_H;
+			n++;
+		}
+	}
+	if (!shown) {
+		const char *msg = wifi_present ?
+			"No wired or USB device" :
+			"No device found - plug one in and Refresh";
 
-	shown = 0;
-	for (i = 0; i < ndev && shown < 6; i++) {
-		if (devs[i].kind == SYS_NETDEV_WIFI)
-			continue;
+		ngui_text(&ui, area.x + 12, y + 12, msg,
+			  ui.theme.text_dim);
+		y += DEV_ROW_H;
+	} else if (more) {
 		p = line;
-		p = sput(p, devs[i].name);
-		p = sput(p, "  ");
-		p = sput(p, devs[i].chip);
+		p = sput(p, "+");
+		p = put_dec(p, (unsigned int)more);
+		p = sput(p, " more devices");
 		*p = '\0';
-		r = ngui_cut_top(&body, ROW_H);
-		if (ngui_menu_item(&ui, ID_DEV_BASE + i, r, line,
-				   devs[i].active ? "active" :
-				   (devs[i].link ? "link" : ""),
-				   devs[i].active))
-			action_dev = i;
-		shown++;
-	}
-	if (!shown) {
-		r = ngui_cut_top(&body, ROW_H);
-		ngui_text(&ui, r.x + 2, r.y + 3,
-			  wifi_present ?
-			  "No wired or USB device - use the WiFi list" :
-			  "None found - Refresh after plugging a device in",
+		ngui_text(&ui, area.x + 12, y + 2, line,
 			  ui.theme.text_dim);
+		y += 20;
 	}
-	body.y += 6;
-	body.h -= 6;
-
-	/* WiFi networks. */
-	r = ngui_cut_top(&body, 26);
-	ngui_text(&ui, r.x, r.y + 3, "WiFi networks", ui.theme.text_dim);
-	rb = r;
-	rb.x = r.x + r.w - 96;
-	rb.w = 96;
-	rb.h = 22;
-	if (wifi_present) {
-		if (wst.state >= SYS_WIFI_ST_ASSOC) {
-			if (ngui_button(&ui, ID_DISCONNECT, rb, "Disconnect"))
-				actions |= ACT_DISCONNECT;
-		} else if (scanning) {
-			ngui_text(&ui, rb.x + 10, rb.y + 3, "Scanning...",
-				  ui.theme.text_dim);
-		} else {
-			if (ngui_button(&ui, ID_SCAN, rb, "Scan"))
-				actions |= ACT_SCAN;
+
+	y += MENU_GAP;
+	r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+	if (wifi_present && wst.state >= SYS_WIFI_ST_ASSOC) {
+		if (ngui_section(&ui, r, "Wi-Fi", ID_DISCONNECT,
+				 "Disconnect"))
+			actions |= ACT_DISCONNECT;
+	} else if (wifi_present && !scanning) {
+		if (ngui_section(&ui, r, "Wi-Fi", ID_SCAN, "Scan"))
+			actions |= ACT_SCAN;
+	} else {
+		ngui_section(&ui, r, "Wi-Fi", 0, 0);
+	}
+	y += SECTION_H;
+
+	draw_wifi_list(area, &y);
+
+	if (net_present) {
+		static const char *labels[4] = {
+			"IP address", "Gateway", "DNS", "MAC address"
+		};
+		char value[40];
+		int di;
+
+		y += MENU_GAP;
+		r = (struct ngui_rect){ area.x, y, area.w - 18, SECTION_H };
+		ngui_section(&ui, r, "Connection", 0, 0);
+		y += SECTION_H;
+		for (di = 0; di < 4; di++) {
+			char *vp = value;
+
+			if (di == 0)
+				vp = ip_any(net.ip) ? put_ip(vp, net.ip) :
+				     sput(vp, "not configured");
+			else if (di == 1)
+				vp = ip_any(net.gw) ? put_ip(vp, net.gw) :
+				     sput(vp, "-");
+			else if (di == 2)
+				vp = ip_any(net.dns) ? put_ip(vp, net.dns) :
+				     sput(vp, "-");
+			else
+				vp = put_mac(vp, net.mac);
+			*vp = '\0';
+
+			r = (struct ngui_rect){ area.x, y, area.w - 18, 30 };
+			if (r.y + r.h > area.y && r.y < area.y + area.h) {
+				row.title = labels[di];
+				row.subtitle = 0;
+				row.trailing = value;
+				row.bars = -1;
+				row.selected = 0;
+				ngui_list_row(&ui, ID_INFO_BASE + di, r, &row);
+			}
+			y += 30;
 		}
 	}
-	draw_wifi_list(body);
+
+	if (nsaved) {
+		char nbuf[12], *np = nbuf;
+
+		y += MENU_GAP;
+		r = (struct ngui_rect){ area.x, y, area.w - 18, SAVED_ROW_H };
+		if (r.y + r.h > area.y && r.y < area.y + area.h) {
+			np = put_dec(np, (unsigned int)nsaved);
+			*np = '\0';
+			row.title = "Saved networks";
+			row.subtitle = 0;
+			row.trailing = nbuf;
+			row.bars = -1;
+			row.selected = 0;
+			if (ngui_list_row(&ui, ID_SAVED, r, &row))
+				actions |= ACT_SAVED;
+		}
+	}
+	ngui_scroll_end(&ui, area, &main_scroll);
 }
 
 static void draw_pass(void)
 {
-	struct ngui_rect body = { 10, 10, ui.w - 20, ui.h - 40 };
+	struct ngui_rect body = pop.body;
 	struct ngui_rect r, b1, b2;
 	char line[80], *p;
 	int ev;
 
 	r = ngui_cut_top(&body, 24);
-	p = sput(line, "Join WiFi network \"");
+	p = sput(line, "Join \"");
 	p = sput(p, sel_ssid);
 	p = sput(p, "\"");
 	*p = '\0';
 	ngui_text_ellipsis_utf8(&ui, r, r.x, r.y, line, ui.theme.text);
 
 	r = ngui_cut_top(&body, 22);
-	ngui_text(&ui, r.x, r.y, "WPA2-PSK passphrase", ui.theme.text_dim);
+	ngui_text_px(&ui, r.x, r.y, "WPA2-PSK passphrase", 19,
+		     ui.theme.text_dim, 14, 1, 0, 0);
 
-	r = ngui_cut_top(&body, 30);
+	r = ngui_cut_top(&body, 34);
 	ev = ngui_text_input(&ui, ID_PASS, r, &pass_in);
 	if (ev & NGUI_INPUT_SUBMIT)
 		actions |= ACT_CONNECT;
 	if (ev & NGUI_INPUT_CANCEL)
 		actions |= ACT_BACK;
-	body.y += 6;
-	body.h -= 6;
+	body.y += MENU_GAP;
+	body.h -= MENU_GAP;
+
+	r = ngui_cut_top(&body, 22);
+	ngui_text(&ui, r.x, r.y,
+		  "8-63 characters, or 64 hex digits for a raw PSK.",
+		  ui.theme.text_dim);
+	body.y += MENU_GAP;
+	body.h -= MENU_GAP;
 
-	r = ngui_cut_top(&body, 30);
+	r = ngui_cut_top(&body, 28);
 	b1 = r;
-	b1.w = 100;
+	b1.w = 110;
 	b2 = r;
-	b2.x = r.x + 110;
-	b2.w = 100;
+	b2.x = r.x + 120;
+	b2.w = 110;
 	if (ngui_button(&ui, ID_PASS_OK, b1, "Connect"))
 		actions |= ACT_CONNECT;
 	if (ngui_button(&ui, ID_PASS_CANCEL, b2, "Cancel"))
 		actions |= ACT_BACK;
-
-	r = ngui_cut_top(&body, 22);
-	ngui_text(&ui, r.x, r.y,
-		  "8-63 characters, or 64 hex digits for a raw PSK.",
-		  ui.theme.text_dim);
-	draw_status();
 }
 
 static void draw_connect(void)
 {
-	struct ngui_rect body = { 10, 10, ui.w - 20, ui.h - 40 };
-	struct ngui_rect r, b;
+	struct ngui_rect body = pop.body;
+	struct ngui_rect log, b, r;
 	char line[96], *p;
 	unsigned int start = 0, lines = 0, i;
-	int y, line_y;
+	int y, line_y = 0;
 
-	r = ngui_cut_top(&body, 24);
-	p = line;
-	if (connect_pid > 0) {
-		p = sput(p, "Connecting to \"");
-		p = sput(p, sel_ssid);
-		p = sput(p, "\"...");
-	} else {
-		p = sput(p, "WiFi connection \"");
-		p = sput(p, sel_ssid);
-		p = sput(p, "\"");
-	}
+	r = ngui_cut_top(&body, 22);
+	p = sput(line, connect_pid > 0 ? "Connecting to \"" :
+		 "Connection to \"");
+	p = sput(p, sel_ssid);
+	p = sput(p, "\"");
 	*p = '\0';
 	ngui_text_ellipsis_utf8(&ui, r, r.x, r.y, line, ui.theme.text);
 
-	r = ngui_cut_top(&body, 22);
-	if (status[0])
-		ngui_text_utf8(&ui, r.x, r.y, status,
-			  status_error ? ui.theme.error : ui.theme.accent);
-	body.y += 4;
-	body.h -= 4;
+	/* The supplicant trail in a recessed card; the connection state is in
+	 * the popover footer. */
+	log = body;
+	log.h -= 38;
+	ngui_fill_round_rect(&ui, log, 6, 6, 6, 6, ui.theme.panel);
+	ngui_push_clip(&ui, (struct ngui_rect){ log.x + 8, log.y + 8,
+						log.w - 16, log.h - 16 });
 
-	/* Last ~12 lines of the helper's terminal output. */
 	for (i = conn_log_len; i > 0; i--) {
 		if (conn_log[i - 1] == '\n' && ++lines > 12) {
 			start = i;
 			break;
 		}
 	}
-	y = body.y;
-	line_y = 0;
-	for (i = start; i < conn_log_len && y + 16 <= body.y + body.h - 34; i++) {
+	y = log.y + 10;
+	for (i = start; i < conn_log_len && y + 17 <= log.y + log.h - 8; i++) {
 		char c = conn_log[i];
 
 		if (c == '\r')
 			continue;
 		if (c == '\n') {
 			line[line_y] = '\0';
-			ngui_text_utf8(&ui, body.x, y, line, ui.theme.text_dim);
-			y += 16;
+			if (line_y)
+				ngui_text_px(&ui, log.x + 10, y, line,
+					     (unsigned int)line_y,
+					     ui.theme.text_dim, 14, 0, 0, 1);
+			y += 17;
 			line_y = 0;
 			continue;
 		}
@@ -911,31 +1100,96 @@ static void draw_connect(void)
 	}
 	if (line_y) {
 		line[line_y] = '\0';
-		ngui_text_utf8(&ui, body.x, y, line, ui.theme.text_dim);
+		ngui_text_px(&ui, log.x + 10, y, line, (unsigned int)line_y,
+			     ui.theme.text_dim, 14, 0, 0, 1);
 	}
+	ngui_pop_clip(&ui);
 
-	/* Cancel at the bottom. */
 	b.x = body.x;
 	b.y = body.y + body.h - 28;
-	b.w = 100;
-	b.h = 24;
+	b.w = 110;
+	b.h = 28;
 	if (ngui_button(&ui, ID_CONN_CANCEL, b,
 			connect_pid > 0 ? "Cancel" : "Back"))
 		actions |= ACT_BACK;
 }
 
+static void draw_saved(void)
+{
+	struct ngui_rect body = pop.body;
+	struct ngui_rect back, row, bt, list, r;
+	struct ngui_row desc;
+	char ssid[33];
+	int i;
+
+	r = ngui_cut_top(&body, 22);
+	ngui_text_px(&ui, r.x, r.y, "Saved Wi-Fi networks", 20,
+		     ui.theme.text, 14, 1, 0, 0);
+
+	if (!nsaved) {
+		ngui_text(&ui, body.x + 2, body.y + 4,
+			  "No saved networks", ui.theme.text_dim);
+	} else {
+		list = body;
+		list.h -= 38;
+		saved_scroll.content_h = nsaved * SAVED_LIST_ROW_H;
+		ngui_scroll_begin(&ui, list, &saved_scroll);
+		ngui_scroll_wheel(&ui, list, &saved_scroll);
+		ngui_scroll_keys(&ui, &saved_scroll);
+		for (i = 0; i < nsaved; i++) {
+			row.x = list.x;
+			row.y = list.y - saved_scroll.offset +
+				i * SAVED_LIST_ROW_H;
+			row.w = list.w - 16;
+			row.h = SAVED_LIST_ROW_H;
+			if (row.y + row.h <= list.y ||
+			    row.y >= list.y + list.h)
+				continue;
+			cfg_ssid_name(&saved[i], ssid);
+			bt = row;
+			bt.x = row.x + row.w - 64;
+			bt.w = 60;
+			bt.h = 28;
+			bt.y = row.y + 7;
+			row.w -= 76;
+
+			desc.title = ssid;
+			desc.subtitle = saved[i].pass_len ? "WPA2-PSK" : "Open";
+			desc.trailing = 0;
+			desc.bars = -1;
+			desc.selected = 0;
+			ngui_list_row_utf8(&ui, ID_SAVED_ROW_BASE + i, row,
+					   &desc);
+
+			if (ngui_button(&ui, ID_SAVED_BASE + i, bt,
+					"Forget")) {
+				action_saved = i;
+				actions |= ACT_FORGET;
+			}
+		}
+		ngui_scroll_end(&ui, list, &saved_scroll);
+	}
+
+	back.x = body.x;
+	back.y = body.y + body.h - 28;
+	back.w = 100;
+	back.h = 28;
+	if (ngui_button(&ui, ID_SAVED_BACK, back, "Back"))
+		actions |= ACT_BACK;
+}
+
 static void draw(void)
 {
-	ngui_fill_rect(&ui, (struct ngui_rect){ 0, 0, ui.w, ui.h },
-		       ui.theme.bg);
+	ngui_popover_begin(&ui, &pop);
 	if (view == VIEW_PASS)
 		draw_pass();
 	else if (view == VIEW_CONNECT)
 		draw_connect();
+	else if (view == VIEW_SAVED)
+		draw_saved();
 	else
 		draw_main();
-	if (view != VIEW_PASS && view != VIEW_CONNECT)
-		draw_status();
+	draw_status();
 }
 
 static void paint_frame(void)
@@ -947,6 +1201,7 @@ static void paint_frame(void)
 	actions = 0;
 	action_dev = -1;
 	action_bss = -1;
+	action_saved = -1;
 }
 
 void _start(const char *arg)
@@ -955,9 +1210,9 @@ void _start(const char *arg)
 	unsigned int last_status = 0;
 
 	(void)arg;
-	if (u_win_create(460, 500, "Network", &wi) != 0 &&
-	    u_win_create(400, 420, "Network", &wi) != 0 &&
-	    u_win_create(340, 360, "Network", &wi) != 0) {
+	if (u_win_create_popover(404, 520, "Network", &wi) != 0 &&
+	    u_win_create_popover(380, 440, "Network", &wi) != 0 &&
+	    u_win_create_popover(340, 360, "Network", &wi) != 0) {
 		u_exit(1);
 	}
 	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
@@ -965,9 +1220,11 @@ void _start(const char *arg)
 	pass_in.secret = 1;
 	pass_in.placeholder = "WPA2 passphrase";
 	view = VIEW_MAIN;
+	main_scroll.offset = 0;
 
 	load_devices();
 	load_status();
+	load_saved();
 	if (wifi_present && wst.state != SYS_WIFI_ST_DOWN &&
 	    wst.state < SYS_WIFI_ST_ASSOC) {
 		start_scan();
@@ -975,6 +1232,7 @@ void _start(const char *arg)
 	}
 
 	for (;;) {
+		static int first_frame = 1;
 		unsigned int now = u_ticks_ms();
 
 		drain_tty();
@@ -994,6 +1252,14 @@ void _start(const char *arg)
 		if (ngui_begin(&ui)) {
 			draw();
 			ngui_end(&ui);
+			if (first_frame) {
+				/* The first present can race the WM's initial
+				 * mapping of the popover canvas; paint a second
+				 * frame once so the panel never shows a black
+				 * tail. */
+				first_frame = 0;
+				ngui_invalidate(&ui);
+			}
 			handle_actions();
 		}
 
@@ -1005,6 +1271,9 @@ void _start(const char *arg)
 				set_status("", 0);
 			} else if (view == VIEW_CONNECT) {
 				cancel_connect();
+			} else if (view == VIEW_SAVED) {
+				view = VIEW_MAIN;
+				set_status("", 0);
 			} else if (ui.focus == 0) {
 				break;
 			}

+ 195 - 160
ucmd_wifi.c

@@ -10,17 +10,21 @@
  *   wifi connectfile <path>      join using an SSID/passphrase/BSSID record
  *                                staged by the network menu (SYS_SPAWN's
  *                                argument buffer is only 64 bytes)
- *   wifi autoconnect            reconnect from /data/WIFI.CFG (boot helper)
- *   wifi forget                 remove the saved credentials
+ *   wifi saved                  list the networks saved in /data/WIFI.CFG
+ *   wifi autoconnect            join any saved network found (boot helper)
+ *   wifi forget [ssid]          remove one saved network, or all without an
+ *                                argument
  *   wifi disconnect
  *
- * The WPA2 handshake (wpa.c) runs here; a small background copy of this
- * command (`wifi __keep <state>`) stays alive after `connect` to answer
- * group-key rekeys, and exits when the connection changes. */
+ * A successful connect adds the SSID/passphrase to a most-recently-used list
+ * (up to WIFI_CFG_MAX networks) in /data/WIFI.CFG.  The WPA2 handshake (wpa.c)
+ * runs here; a small background copy of this command (`wifi __keep <state>`)
+ * stays alive after `connect` to answer group-key rekeys, and exits when the
+ * connection changes. */
 
 #include "ucmd_lib.h"
 #include "tls_rng.h"
-#include "wifi_cfg.h"
+#include "wifi_store.h"
 #include "wpa.h"
 
 #define MAX_BSS 32
@@ -43,34 +47,15 @@ static int name_eq(const char *a, const char *b)
 	return *a == *b;
 }
 
-static int bssid_zero(const unsigned char b[6])
+/* Add the network to /data/WIFI.CFG, replacing an older record for the same
+ * SSID and moving it to the front (most recently used).  The BSSID is
+ * deliberately left zero so a mesh/repeater AP with the same SSID still
+ * works; /data is a plain FAT partition, so the file is 8.3 and the
+ * passphrase is stored in clear. */
+static int remember_wifi(const unsigned char *ssid, unsigned int ssid_len,
+			 const char *pass, unsigned int pass_len)
 {
-	unsigned int i;
-
-	for (i = 0; i < 6; i++)
-		if (b[i])
-			return 0;
-	return 1;
-}
-
-static void wipe_cfg(struct wifi_cfg *cfg)
-{
-	unsigned int i;
-
-	for (i = 0; i < sizeof(*cfg); i++)
-		((volatile unsigned char *)cfg)[i] = 0;
-}
-
-/* Save the network for the next boot.  The BSSID is deliberately left zero
- * so a mesh/repeater AP with the same SSID still works; /data is a plain FAT
- * partition, so WIFI.CFG is 8.3 and the password is stored in clear. */
-static int save_wifi_cred(const unsigned char *ssid, unsigned int ssid_len,
-			  const char *pass, unsigned int pass_len)
-{
-	/* FAT writes may read a final partial sector past the source length;
-	 * keep slack after the record as well. */
-	unsigned char buf[sizeof(struct wifi_cfg) + 512];
-	struct wifi_cfg *cfg = (struct wifi_cfg *)buf;
+	struct wifi_cfg rec;
 	unsigned int i;
 	int r;
 
@@ -78,51 +63,21 @@ static int save_wifi_cred(const unsigned char *ssid, unsigned int ssid_len,
 		ssid_len = 32;
 	if (pass_len > 64)
 		pass_len = 64;
-	for (i = 0; i < sizeof(buf); i++)
-		buf[i] = 0;
-	cfg->magic = WIFI_CFG_MAGIC;
-	cfg->ssid_len = (unsigned char)ssid_len;
-	cfg->pass_len = (unsigned char)pass_len;
+	for (i = 0; i < sizeof(rec); i++)
+		((unsigned char *)&rec)[i] = 0;
+	rec.magic = WIFI_CFG_MAGIC;
+	rec.ssid_len = (unsigned char)ssid_len;
+	rec.pass_len = (unsigned char)pass_len;
 	for (i = 0; i < ssid_len; i++)
-		cfg->ssid[i] = ssid[i];
+		rec.ssid[i] = ssid[i];
 	for (i = 0; i < pass_len; i++)
-		cfg->pass[i] = pass[i];
-	r = u_syscall3(SYS_WRITE_FILE, (int)WIFI_CRED_PATH,
-		       (int)cfg, (int)sizeof(*cfg));
-	for (i = 0; i < sizeof(buf); i++)
-		buf[i] = 0;
+		rec.pass[i] = pass[i];
+	r = wifi_store_remember(&rec);
+	for (i = 0; i < sizeof(rec); i++)
+		((volatile unsigned char *)&rec)[i] = 0;
 	return r;
 }
 
-static int load_wifi_cred(struct wifi_cfg *cfg)
-{
-	/* FAT reads can write a final partial sector past the requested
-	 * length; keep 512 bytes of slack so the stack top is never touched. */
-	unsigned char buf[sizeof(struct wifi_cfg) + 512];
-	unsigned int i;
-	int r;
-
-	wipe_cfg(cfg);
-	r = u_syscall3(SYS_READ_FILE, (int)WIFI_CRED_PATH,
-		       (int)buf, (int)sizeof(*cfg));
-	if (r < (int)sizeof(*cfg) || ((struct wifi_cfg *)buf)->magic !=
-	    WIFI_CFG_MAGIC) {
-		for (i = 0; i < sizeof(buf); i++)
-			buf[i] = 0;
-		return -1;
-	}
-	for (i = 0; i < sizeof(*cfg); i++)
-		((unsigned char *)cfg)[i] = buf[i];
-	for (i = 0; i < sizeof(buf); i++)
-		buf[i] = 0;
-	if (cfg->ssid_len == 0 || cfg->ssid_len > 32 ||
-	    cfg->pass_len > 64) {
-		wipe_cfg(cfg);
-		return -1;
-	}
-	return 0;
-}
-
 static void put_ssid(const unsigned char *s, unsigned int n)
 {
 	unsigned int i;
@@ -441,50 +396,19 @@ static void spawn_keeper(struct wpa_sm *sm, unsigned int conn_id)
 		       "drop at the next group rekey\n");
 }
 
-static int connect_bss(const char *ssid, const char *pass,
-		       const unsigned char *want_bssid)
+/* Join one BSS from a completed scan.  `pass` is empty for an open network.
+ * Returns 0 when the data port is open, 1 on failure. */
+static int join_bss(const struct sys_wifi_bss *b, const char *pass)
 {
 	struct sys_wifi_connect c;
 	struct sys_wifi_status st;
 	static struct wpa_sm sm;
 	unsigned char pmk[32];
-	struct sys_wifi_bss *b = 0;
-	int n, i, r;
-	unsigned int ssid_len;
-	int have_bssid = want_bssid != 0;
-
-	ssid_len = (unsigned int)slen(ssid);
-	if (!ssid_len) {
-		u_puts("usage: wifi connect <ssid> [passphrase]\n");
-		return 1;
-	}
-	if (bring_up() < 0)
-		return 1;
-	wifi(SYS_WIFI_DISCONNECT, 0, 0);
-	u_puts("wifi: scanning for \""); u_puts(ssid); u_puts("\"...\n");
-	n = do_scan();
-	if (n < 0)
-		return 1;
-	for (i = 0; i < n; i++) {
-		unsigned int j;
+	unsigned int ssid_len = b->ssid_len;
+	int i, r;
 
-		if (bss[i].ssid_len != ssid_len)
-			continue;
-		if (have_bssid) {
-			for (j = 0; j < 6 && bss[i].bssid[j] == want_bssid[j]; j++)
-				;
-			if (j != 6)
-				continue;
-		}
-		for (j = 0; j < ssid_len && bss[i].ssid[j] == (unsigned char)ssid[j]; j++)
-			;
-		if (j == ssid_len) {
-			b = &bss[i];       /* sorted: first match is strongest */
-			break;
-		}
-	}
-	if (!b) {
-		u_puts("wifi: network not found\n");
+	if (ssid_len == 0 || ssid_len > 32) {
+		u_puts("wifi: malformed SSID in scan result\n");
 		return 1;
 	}
 	if (b->security == SYS_WIFI_SEC_OTHER) {
@@ -500,9 +424,9 @@ static int connect_bss(const char *ssid, const char *pass,
 	for (i = 0; i < 6; i++)
 		c.bssid[i] = b->bssid[i];
 	c.channel = b->channel;
-	c.ssid_len = ssid_len;
+	c.ssid_len = (unsigned char)ssid_len;
 	for (i = 0; i < (int)ssid_len; i++)
-		c.ssid[i] = (unsigned char)ssid[i];
+		c.ssid[i] = b->ssid[i];
 	c.beacon_int = b->beacon_int;
 	c.dtim = b->dtim;
 	if (b->security == SYS_WIFI_SEC_PSK) {
@@ -549,6 +473,51 @@ static int connect_bss(const char *ssid, const char *pass,
 	return r == 0 ? 0 : 1;
 }
 
+static int connect_bss(const char *ssid, const char *pass,
+		       const unsigned char *want_bssid)
+{
+	struct sys_wifi_bss *b = 0;
+	int n, i;
+	unsigned int ssid_len;
+	int have_bssid = want_bssid != 0;
+
+	ssid_len = (unsigned int)slen(ssid);
+	if (!ssid_len) {
+		u_puts("usage: wifi connect <ssid> [passphrase]\n");
+		return 1;
+	}
+	if (bring_up() < 0)
+		return 1;
+	wifi(SYS_WIFI_DISCONNECT, 0, 0);
+	u_puts("wifi: scanning for \""); u_puts(ssid); u_puts("\"...\n");
+	n = do_scan();
+	if (n < 0)
+		return 1;
+	for (i = 0; i < n; i++) {
+		unsigned int j;
+
+		if (bss[i].ssid_len != ssid_len)
+			continue;
+		if (have_bssid) {
+			for (j = 0; j < 6 && bss[i].bssid[j] == want_bssid[j]; j++)
+				;
+			if (j != 6)
+				continue;
+		}
+		for (j = 0; j < ssid_len && bss[i].ssid[j] == (unsigned char)ssid[j]; j++)
+			;
+		if (j == ssid_len) {
+			b = &bss[i];       /* sorted: first match is strongest */
+			break;
+		}
+	}
+	if (!b) {
+		u_puts("wifi: network not found\n");
+		return 1;
+	}
+	return join_bss(b, pass);
+}
+
 static int cmd_connect(const char *args)
 {
 	char ssid[33], pass[80], bssid_s[13];
@@ -569,9 +538,9 @@ static int cmd_connect(const char *args)
 	}
 	r = connect_bss(ssid, pass, have_bssid ? want_bssid : 0);
 	if (r == 0) {
-		if (save_wifi_cred((const unsigned char *)ssid,
-				   (unsigned int)slen(ssid), pass,
-				   (unsigned int)slen(pass)) == 0)
+		if (remember_wifi((const unsigned char *)ssid,
+				  (unsigned int)slen(ssid), pass,
+				  (unsigned int)slen(pass)) == 0)
 			u_puts("wifi: saved for auto-connect\n");
 		else
 			u_puts("wifi: note: could not save credentials to /data\n");
@@ -611,8 +580,8 @@ static int cmd_connect_file(const char *args)
 	pass[cfg.pass_len] = '\0';
 	r = connect_bss(ssid, pass, cfg.bssid);
 	if (r == 0) {
-		if (save_wifi_cred(cfg.ssid, cfg.ssid_len, cfg.pass,
-				   cfg.pass_len) == 0)
+		if (remember_wifi(cfg.ssid, cfg.ssid_len, cfg.pass,
+				  cfg.pass_len) == 0)
 			u_puts("wifi: saved for auto-connect\n");
 		else
 			u_puts("wifi: note: credentials not saved (no writable /data)\n");
@@ -624,66 +593,130 @@ static int cmd_connect_file(const char *args)
 	return r;
 }
 
-/* Boot-time helper: reconnect to the network saved in /data/WIFI.CFG.  A
- * wired link that is physically up wins; an existing WiFi link is left
- * alone. */
+/* Boot-time helper: scan once, then join the strongest network present whose
+ * SSID is in /data/WIFI.CFG.  If none succeeds, scan again after three
+ * seconds.  A wired link that is physically up wins; an existing WiFi link
+ * is left alone. */
 static int cmd_autoconnect(void)
 {
-	struct wifi_cfg cfg;
+	struct wifi_cfg nets[WIFI_CFG_MAX];
 	struct sys_wifi_status ws;
 	struct sys_netinfo ni;
-	char ssid[33], pass[65];
-	unsigned int i;
-	int attempt, r = 1;
+	char pass[65];
+	int count, n, i, round, r = 1;
 
-	if (load_wifi_cred(&cfg) != 0)
+	count = wifi_store_load(nets, WIFI_CFG_MAX);
+	if (count <= 0)
 		return 0;
 	/* A wired link that is physically up wins: do not even probe the WiFi
 	 * card in that case.  Only fall back to WiFi when no cable is
 	 * connected. */
 	if (u_net_info(&ni) == 1 && ni.present && ni.link &&
-	    !name_eq(ni.name, "wifi")) {
-		wipe_cfg(&cfg);
-		return 0;
-	}
-	if (u_wifi(SYS_WIFI_STATUS, (int)&ws, 0) != 0 || !ws.present) {
-		wipe_cfg(&cfg);
-		return 0;
-	}
-	if (ws.state >= SYS_WIFI_ST_LINK) {
-		wipe_cfg(&cfg);
-		return 0;
-	}
-	for (i = 0; i < cfg.ssid_len; i++)
-		ssid[i] = (char)cfg.ssid[i];
-	ssid[cfg.ssid_len] = '\0';
-	for (i = 0; i < cfg.pass_len; i++)
-		pass[i] = cfg.pass[i];
-	pass[cfg.pass_len] = '\0';
-	for (attempt = 0; attempt < 2; attempt++) {
-		r = connect_bss(ssid, pass,
-				bssid_zero(cfg.bssid) ? 0 : cfg.bssid);
-		if (r == 0)
-			break;
-		if (attempt == 0)
+	    !name_eq(ni.name, "wifi"))
+		goto out;
+	if (u_wifi(SYS_WIFI_STATUS, (int)&ws, 0) != 0 || !ws.present)
+		goto out;
+	if (ws.state >= SYS_WIFI_ST_LINK)
+		goto out;
+	if (bring_up() < 0)
+		goto out;
+	for (round = 0; round < 2 && r; round++) {
+		unsigned char tried[WIFI_CFG_MAX];
+		unsigned int j;
+
+		if (round)
 			u_sleep_ms(3000);
+		for (j = 0; j < WIFI_CFG_MAX; j++)
+			tried[j] = 0;
+		wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		n = do_scan();
+		if (n < 0)
+			continue;
+		for (i = 0; i < n && r; i++) {
+			struct sys_wifi_bss *b = &bss[i];
+			int ci;
+
+			if (b->security == SYS_WIFI_SEC_OTHER)
+				continue;
+			ci = wifi_store_find(nets, count, b->ssid,
+					     b->ssid_len);
+			if (ci < 0 || tried[ci])
+				continue;
+			if (b->security == SYS_WIFI_SEC_PSK &&
+			    nets[ci].pass_len == 0)
+				continue;
+			tried[ci] = 1;
+			for (j = 0; j < nets[ci].pass_len; j++)
+				pass[j] = nets[ci].pass[j];
+			pass[nets[ci].pass_len] = '\0';
+			u_puts("wifi: auto-connect \"");
+			put_ssid(b->ssid, b->ssid_len);
+			u_puts("\"\n");
+			r = join_bss(b, pass);
+			for (j = 0; j < sizeof(pass); j++)
+				((volatile char *)pass)[j] = 0;
+			if (r != 0)
+				wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		}
 	}
-	for (i = 0; i < sizeof(cfg); i++)
-		((unsigned char *)&cfg)[i] = 0;
-	for (i = 0; i < sizeof(pass); i++)
+out:
+	for (i = 0; i < (int)sizeof(nets); i++)
+		((volatile unsigned char *)nets)[i] = 0;
+	for (i = 0; i < (int)sizeof(pass); i++)
 		((volatile char *)pass)[i] = 0;
 	return r;
 }
 
-static int cmd_forget(void)
+static int cmd_saved(void)
 {
-	if (u_syscall1(SYS_UNLINK, (int)WIFI_CRED_PATH) == 0)
-		u_puts("wifi: saved credentials removed\n");
-	else
-		u_puts("wifi: no saved credentials\n");
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	int n, i;
+	unsigned int j;
+
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	if (n <= 0) {
+		u_puts("wifi: no saved networks\n");
+		return 0;
+	}
+	u_puts("saved networks (");
+	u_putdec((unsigned int)n);
+	u_puts("):\n");
+	for (i = 0; i < n; i++) {
+		u_puts("  \"");
+		put_ssid(list[i].ssid, list[i].ssid_len);
+		u_puts("\"  ");
+		u_puts(list[i].pass_len ? "WPA2-PSK" : "open");
+		u_puts("\n");
+	}
+	for (j = 0; j < sizeof(list); j++)
+		((volatile unsigned char *)list)[j] = 0;
 	return 0;
 }
 
+static int cmd_forget(const char *args)
+{
+	char ssid[33];
+	int r;
+
+	args = word(args, ssid, sizeof(ssid));
+	if (!ssid[0]) {
+		if (u_syscall1(SYS_UNLINK, (int)WIFI_CRED_PATH) == 0)
+			u_puts("wifi: saved networks removed\n");
+		else
+			u_puts("wifi: no saved networks\n");
+		return 0;
+	}
+	r = wifi_store_forget((const unsigned char *)ssid,
+			      (unsigned int)slen(ssid));
+	if (r > 0)
+		u_puts("wifi: saved network removed\n");
+	else if (r == 0)
+		u_puts("wifi: network is not saved\n");
+	else
+		u_puts("wifi: could not update /data/WIFI.CFG\n");
+	return r < 0 ? 1 : 0;
+}
+
 /* Background: answer group-key rekeys until the connection changes. */
 static int keeper(const char *args)
 {
@@ -763,15 +796,17 @@ void _start(const char *arg)
 		r = cmd_connect(a + 8);
 	else if (starts(a, "connectfile "))
 		r = cmd_connect_file(a + 12);
+	else if (starts(a, "saved"))
+		r = cmd_saved();
 	else if (starts(a, "autoconnect"))
 		r = cmd_autoconnect();
 	else if (starts(a, "forget"))
-		r = cmd_forget();
+		r = cmd_forget(a + 6);
 	else if (starts(a, "disconnect")) {
 		wifi(SYS_WIFI_DISCONNECT, 0, 0);
 		u_puts("wifi: disconnected\n");
 	} else {
-		u_puts("usage: wifi [up|scan|connect <ssid> [pass] [bssid]|connectfile <path>|autoconnect|forget|disconnect]\n");
+		u_puts("usage: wifi [up|scan|connect <ssid> [pass] [bssid]|connectfile <path>|saved|autoconnect|forget [ssid]|disconnect]\n");
 		r = 1;
 	}
 	u_exit(r);

+ 282 - 39
ucmd_wm.c

@@ -65,6 +65,19 @@ static int bar_pwr_tip_want;       /* tooltip computed for this frame */
 static int bar_pwr_tip_on;         /* tooltip pixels currently on screen */
 static int bar_pwr_tip_on_x, bar_pwr_tip_on_y;
 static unsigned int bar_pwr_tip_on_w, bar_pwr_tip_on_h;
+/* Brightness OSD: a centered bubble shown after the kernel's backlight
+ * seq changes, then hidden after OSD_MS. */
+#define OSD_MS    3000
+#define OSD_W     210
+#define OSD_H     60
+static int osd_show;               /* should be visible this frame */
+static int osd_visible;            /* pixels are on screen */
+static int osd_level;
+static unsigned int osd_until;
+static unsigned int osd_seen_seq;
+static int osd_seen_valid;
+static int osd_x, osd_y;
+static unsigned int osd_w, osd_h;
 static char bar_msg[24];
 static unsigned int bar_msg_until;
 static int bar_msg_dirty;
@@ -89,7 +102,6 @@ static int bar_net_kind;
 static int bar_net_bars;
 static unsigned int bar_net_color = 0xFF5050u;
 static int netmenu_pid;
-static int netmenu_placed;
 
 static void bar_notice(const char *msg)
 {
@@ -561,6 +573,29 @@ static void draw_bar(void)
 	}
 }
 
+/* A popover is a flat, chromeless panel: the canvas fills the window. */
+static void draw_popover_clip(unsigned int idx, int cx, int cy,
+			      unsigned int cw, unsigned int ch)
+{
+	struct uwin *u = &wins[idx];
+	struct wm_window_info *w = &u->info;
+	unsigned int cwid = w->content_w, chei = w->content_h;
+
+	if (u->mapped && u->map.kind == WM_KIND_GFX) {
+		struct uwm_canvas c;
+
+		c.px = (const unsigned short *)u->map.va;
+		c.w = u->map.w;
+		c.h = u->map.h;
+		if (c.w == cwid && c.h == chei) {
+			usurf_canvas(&screen, &c, w->x, w->y,
+				     cx, cy, cw, ch);
+			return;
+		}
+	}
+	fill_clip(w->x, w->y, cwid, chei, 0x181C28u, cx, cy, cw, ch);
+}
+
 static void draw_window_clip(unsigned int idx, int cx, int cy,
 			     unsigned int cw, unsigned int ch)
 {
@@ -574,6 +609,11 @@ static void draw_window_clip(unsigned int idx, int cx, int cy,
 	unsigned int content_w = w->content_w;
 	unsigned int content_h = w->content_h;
 
+	if (w->popover) {
+		draw_popover_clip(idx, cx, cy, cw, ch);
+		return;
+	}
+
 	/* Border, title bar, close button. */
 	fill_clip(x, y, pw, ph, COL_BORDER, cx, cy, cw, ch);
 	fill_clip(x + 1, y + 1, pw - 2, WM_TITLE_H,
@@ -620,17 +660,23 @@ static void draw_window_clip(unsigned int idx, int cx, int cy,
 	}
 }
 
-/* Front-to-back window order: the focused window is on top, the others
- * follow in descending slot order.  Painting and hit-testing share it. */
+/* Front-to-back window order: popovers float above everything, then the
+ * focused window, then the others in descending slot order.  Painting and
+ * hit-testing share it. */
 static unsigned int build_order(int *order)
 {
 	unsigned int i, n = 0;
 
 	for (i = 0; i < WM_MAX_WINDOWS; i++)
-		if (wins[i].info.used && wins[i].info.focused)
+		if (wins[i].info.used && wins[i].info.popover)
+			order[n++] = (int)i;
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && wins[i].info.focused &&
+		    !wins[i].info.popover)
 			order[n++] = (int)i;
 	for (i = WM_MAX_WINDOWS; i-- > 0;)
-		if (wins[i].info.used && !wins[i].info.focused)
+		if (wins[i].info.used && !wins[i].info.focused &&
+		    !wins[i].info.popover)
 			order[n++] = (int)i;
 	return n;
 }
@@ -699,6 +745,7 @@ static void draw_rect_naive(int x, int y, unsigned int w, unsigned int h)
 	usurf_fill(&screen, x, y, w, h, COL_BG);
 	for (i = 0; i < WM_MAX_WINDOWS; i++)
 		if (wins[i].info.used && !wins[i].info.focused &&
+		    !wins[i].info.popover &&
 		    x < wins[i].info.x + (int)wins[i].info.w &&
 		    x + (int)w > wins[i].info.x &&
 		    y < wins[i].info.y + (int)wins[i].info.h &&
@@ -706,6 +753,14 @@ static void draw_rect_naive(int x, int y, unsigned int w, unsigned int h)
 			draw_window_clip(i, x, y, w, h);
 	for (i = 0; i < WM_MAX_WINDOWS; i++)
 		if (wins[i].info.used && wins[i].info.focused &&
+		    !wins[i].info.popover &&
+		    x < wins[i].info.x + (int)wins[i].info.w &&
+		    x + (int)w > wins[i].info.x &&
+		    y < wins[i].info.y + (int)wins[i].info.h &&
+		    y + (int)h > wins[i].info.y)
+			draw_window_clip(i, x, y, w, h);
+	for (i = 0; i < WM_MAX_WINDOWS; i++)
+		if (wins[i].info.used && wins[i].info.popover &&
 		    x < wins[i].info.x + (int)wins[i].info.w &&
 		    x + (int)w > wins[i].info.x &&
 		    y < wins[i].info.y + (int)wins[i].info.h &&
@@ -794,6 +849,18 @@ static int window_at(int mx, int my)
 	for (i = 0; i < n; i++) {
 		struct wm_window_info *w = &wins[order[i]].info;
 
+		if (!w->popover)
+			continue;
+		if (mx >= w->x && my >= w->y &&
+		    mx < w->x + (int)w->w &&
+		    my < w->y + (int)w->h)
+			return order[i];
+	}
+	for (i = 0; i < n; i++) {
+		struct wm_window_info *w = &wins[order[i]].info;
+
+		if (w->popover)
+			continue;
 		if (mx >= w->x && my >= w->y &&
 		    mx < w->x + (int)w->w &&
 		    my < w->y + (int)w->h)
@@ -865,6 +932,98 @@ static void bar_tooltip_overlay(struct wm_present_info *p)
 		 bar_pwr_tip_on_w, bar_pwr_tip_on_h);
 }
 
+/* Center the brightness bubble in the work area, clamped on small screens. */
+static void osd_geom(void)
+{
+	int x, y;
+
+	osd_w = OSD_W;
+	osd_h = OSD_H;
+	x = ((int)fbw - (int)osd_w) / 2;
+	y = WM_BAR_H + ((int)fbh - WM_BAR_H - (int)osd_h) * 3 / 5;
+	if (x < 0)
+		x = 0;
+	if (x + (int)osd_w > (int)fbw)
+		x = (int)fbw - (int)osd_w;
+	if (y < WM_BAR_H)
+		y = WM_BAR_H;
+	if (y + (int)osd_h > (int)fbh)
+		y = (int)fbh - (int)osd_h;
+	osd_x = x;
+	osd_y = y;
+}
+
+/* A small sun: a filled circle plus four rays, all from 1-pixel fills. */
+static void osd_sun(int cx, int cy)
+{
+	static const unsigned char half[11] = { 2, 4, 5, 6, 6, 6, 6, 6, 5, 4, 2 };
+	int i;
+
+	for (i = -5; i <= 5; i++)
+		usurf_fill(&screen, cx - half[i + 5], cy + i,
+			   half[i + 5] * 2 + 1, 1, 0xFFD250u);
+	usurf_fill(&screen, cx - 1, cy - 9, 2, 3, 0xFFD250u);
+	usurf_fill(&screen, cx - 1, cy + 7, 2, 3, 0xFFD250u);
+	usurf_fill(&screen, cx - 9, cy - 1, 3, 2, 0xFFD250u);
+	usurf_fill(&screen, cx + 7, cy - 1, 3, 2, 0xFFD250u);
+}
+
+static void osd_draw(void)
+{
+	char pct[8];
+	unsigned int n = 0;
+	unsigned int bar_x, bar_y, bar_w;
+	int x, y, tw;
+
+	osd_geom();
+	x = osd_x;
+	y = osd_y;
+	usurf_fill(&screen, x, y, osd_w, osd_h, 0x26263Au);
+	usurf_fill(&screen, x, y, osd_w, 1, 0x70709Au);
+	usurf_fill(&screen, x, y + (int)osd_h - 1, osd_w, 1, 0x70709Au);
+	usurf_fill(&screen, x, y + 1, 1, osd_h - 2, 0x70709Au);
+	usurf_fill(&screen, x + (int)osd_w - 1, y + 1, 1, osd_h - 2,
+		   0x70709Au);
+	osd_sun(x + 22, y + (int)osd_h / 2);
+
+	if (osd_level >= 100) {
+		pct[n++] = '1';
+		pct[n++] = '0';
+		pct[n++] = '0';
+	} else {
+		if (osd_level >= 10)
+			pct[n++] = (char)('0' + osd_level / 10);
+		pct[n++] = (char)('0' + osd_level % 10);
+	}
+	pct[n++] = '%';
+	pct[n] = '\0';
+
+	usurf_text(&screen, x + 42, y + 9, "Brightness", 0xE8E8F6u,
+		   x, y, osd_w, osd_h);
+	tw = (int)usurf_text_width(&screen, pct);
+	usurf_text(&screen, x + (int)osd_w - 14 - tw, y + 9, pct,
+		   0xFFD250u, x, y, osd_w, osd_h);
+
+	bar_x = (unsigned int)(x + 42);
+	bar_y = (unsigned int)(y + 35);
+	bar_w = osd_w - 42 - 14;
+	usurf_fill(&screen, (int)bar_x, (int)bar_y, bar_w, 10, 0x44445Au);
+	usurf_fill(&screen, (int)bar_x, (int)bar_y,
+		   (bar_w * (unsigned int)osd_level + 50) / 100, 10,
+		   0xFFD250u);
+}
+
+/* Put the power tooltip and the brightness OSD back on top after a render
+ * pass that may have overwritten them. */
+static void wm_overlays(struct wm_present_info *p)
+{
+	bar_tooltip_overlay(p);
+	if (osd_show) {
+		osd_draw();
+		add_rect(p, osd_x, osd_y, osd_w, osd_h);
+	}
+}
+
 /* A focused window is topmost, so the shadow contains exactly its pixels in
  * the old rectangle.  Move that block and repaint only the old part the new
  * rectangle does not cover.  When either rectangle is partly off-screen the
@@ -904,7 +1063,7 @@ static void move_window_pixels(struct uwin *u, int ox, int oy, int nx, int ny)
 	for (k = 0; k < np; k++)
 		add_rect(&present, pieces[k].x, pieces[k].y,
 			 pieces[k].w, pieces[k].h);
-	bar_tooltip_overlay(&present);
+	wm_overlays(&present);
 	u_wm_present(&present);
 }
 
@@ -928,7 +1087,7 @@ static void redraw_geom(struct uwin *u, int ox, int oy,
 		for (i = 0; i < present.count; i++)
 			draw_rect(present.rect[i].x, present.rect[i].y,
 				  present.rect[i].w, present.rect[i].h);
-		bar_tooltip_overlay(&present);
+		wm_overlays(&present);
 		u_wm_present(&present);
 	}
 }
@@ -1026,6 +1185,32 @@ static void do_update(struct wm_status *st)
 	int kexec_changed = (st->kexec_busy != bar_kexec_busy) ||
 		(st->kexec_busy && st->kexec_progress != bar_kexec_progress);
 	unsigned int msg_now = u_ticks_ms();
+	int osd_hide = 0, osd_repaint = 0;
+
+	/* The kernel bumps backlight_seq on every brightness key/command.
+	 * Pop the OSD on a change and keep it up for OSD_MS after the last
+	 * one.  The first poll only records the current sequence, so a WM
+	 * restart does not flash a stale bubble. */
+	if (st->backlight_present) {
+		if (!osd_seen_valid) {
+			osd_seen_valid = 1;
+			osd_seen_seq = st->backlight_seq;
+		} else if (st->backlight_seq != osd_seen_seq) {
+			osd_seen_seq = st->backlight_seq;
+			osd_level = (int)st->backlight_level;
+			osd_until = msg_now + OSD_MS;
+			osd_show = 1;
+		}
+	} else if (osd_show) {
+		osd_show = 0;
+		osd_hide = 1;
+	}
+	if (osd_show && (int)(msg_now - osd_until) >= 0) {
+		osd_show = 0;
+		osd_hide = 1;
+	}
+	if (osd_hide && osd_visible)
+		osd_repaint = 1;
 
 	/* Spawn the first terminal once the kernel says the storage scan is
 	 * done, so a shell command can never race the mount table. */
@@ -1113,43 +1298,35 @@ static void do_update(struct wm_status *st)
 			}
 		}
 	}
-	/* Anchor the network menu under its bar icon once it has created its
-	 * window.  The WM owns the geometry syscall, so the app itself does
-	 * not need a special placement ABI. */
-	if (netmenu_pid > 0) {
-		int found = 0;
+	/* Popovers are WM-anchored overlays, right-aligned to the network
+	 * status icon and just below the bar.  The WM owns the geometry, so
+	 * the app does not need a placement ABI. */
+	{
+		int netmenu_found = 0;
 
 		for (i = 0; i < WM_MAX_WINDOWS; i++) {
 			struct wm_window_info ni;
+			int nx, ny;
 
-			if (!wins[i].info.used ||
-			    wins[i].info.pid != (unsigned int)netmenu_pid)
+			if (!wins[i].info.used || !wins[i].info.popover)
 				continue;
-			found = 1;
-			if (!netmenu_placed) {
-				int nx = (bar_net_x >= 0 ?
-					  bar_net_x + (int)bar_net_w :
-					  (int)fbw) - (int)wins[i].info.w;
-				int ny = WM_BAR_H + 2;
-
-				if (nx < 4)
-					nx = 4;
-				if (nx + (int)wins[i].info.w > (int)fbw - 4)
-					nx = (int)fbw - 4 -
-					     (int)wins[i].info.w;
+			if (netmenu_pid > 0 &&
+			    wins[i].info.pid == (unsigned int)netmenu_pid)
+				netmenu_found = 1;
+			nx = (bar_net_x >= 0 ? bar_net_x + (int)bar_net_w :
+			      (int)fbw - 4) - (int)wins[i].info.w;
+			ny = WM_BAR_H + 4;
+			if (nx != wins[i].info.x || ny != wins[i].info.y) {
 				if (u_wm_set_geom(i, nx, ny) == 0 &&
 				    u_wm_info(i, &ni) == 1) {
 					wins[i].info = ni;
 					full_redraw = 1;
 				}
-				netmenu_placed = 1;
 			}
-			break;
 		}
-		if (!found && !u_alive((unsigned int)netmenu_pid)) {
+		if (!netmenu_found && netmenu_pid > 0 &&
+		    !u_alive((unsigned int)netmenu_pid))
 			netmenu_pid = 0;
-			netmenu_placed = 0;
-		}
 	}
 	/* The RTC is slow (CMOS polling) and the temperature/battery state only
 	 * changes once a second; query them at 1 Hz instead of every 10 ms. */
@@ -1226,6 +1403,9 @@ static void do_update(struct wm_status *st)
 			draw_rect(0, 0, fbw, fbh);
 			draw_bar();
 			bar_tooltip_commit();
+			if (osd_show)
+				osd_draw();
+			osd_visible = osd_show;
 			present.count = 0;
 			add_rect(&present, 0, 0, fbw, fbh);
 			present.immediate = 0;
@@ -1243,6 +1423,12 @@ static void do_update(struct wm_status *st)
 	/* Partial cell/canvas updates and the bar clock. */
 	present.count = 0;
 	present.immediate = 0;
+	if (osd_repaint) {
+		add_rect(&present, osd_x, osd_y, osd_w, osd_h);
+		need = 1;
+	}
+	if (osd_show)
+		need = 1;
 	if (bar_dirty) {
 		need = 1;
 		add_rect(&present, 0, 0, fbw, WM_BAR_H);
@@ -1257,8 +1443,9 @@ static void do_update(struct wm_status *st)
 			continue;
 		if (!w->dmg_w || !w->dmg_h)
 			continue;
-		rx = w->x + 1 + (int)w->dmg_x;
-		ry = w->y + 1 + WM_TITLE_H + (int)w->dmg_y;
+		rx = w->x + (w->popover ? 0 : 1) + (int)w->dmg_x;
+		ry = w->y + (w->popover ? 0 : 1 + WM_TITLE_H) +
+		     (int)w->dmg_y;
 		rw = w->dmg_w;
 		rh = w->dmg_h;
 		add_rect(&present, rx, ry, rw, rh);
@@ -1295,6 +1482,11 @@ static void do_update(struct wm_status *st)
 	} else {
 		bar_pwr_tip_on = 0;
 	}
+	if (osd_show) {
+		osd_draw();
+		add_rect(&present, osd_x, osd_y, osd_w, osd_h);
+	}
+	osd_visible = osd_show;
 
 	for (i = 0; i < WM_MAX_WINDOWS; i++) {
 		struct uwin *u = &wins[i];
@@ -1330,7 +1522,7 @@ static void spawn_app_checked(const char *path)
 	}
 }
 
-/* The network icon opens one menu at a time; a second click focuses it. */
+/* The network icon opens one menu at a time; a second click closes it. */
 static void open_netmenu(void)
 {
 	unsigned int i;
@@ -1339,10 +1531,17 @@ static void open_netmenu(void)
 		for (i = 0; i < WM_MAX_WINDOWS; i++)
 			if (wins[i].info.used &&
 			    wins[i].info.pid == (unsigned int)netmenu_pid) {
-				u_wm_focus(i);
-				full_redraw = 1;
+				if (u_wm_close(i) == 0) {
+					netmenu_pid = 0;
+					full_redraw = 1;
+				} else {
+					u_wm_focus(i);
+					full_redraw = 1;
+				}
 				return;
 			}
+		/* The process is alive but has not created its window yet. */
+		return;
 	}
 	if (!free_window_slot()) {
 		bar_notice("window limit");
@@ -1350,7 +1549,6 @@ static void open_netmenu(void)
 		return;
 	}
 	netmenu_pid = u_spawn("/ramfs/bin/netmenu", "", 0, "/");
-	netmenu_placed = 0;
 	if (netmenu_pid < 0) {
 		netmenu_pid = 0;
 		bar_notice("spawn failed");
@@ -1360,6 +1558,45 @@ static void open_netmenu(void)
 	}
 }
 
+/* Index of a popover containing the point, or -1. */
+static int popover_under(unsigned int mx, unsigned int my)
+{
+	unsigned int i;
+
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		struct wm_window_info *w = &wins[i].info;
+
+		if (w->used && w->popover &&
+		    mx >= (unsigned int)w->x && my >= (unsigned int)w->y &&
+		    mx < (unsigned int)(w->x + (int)w->w) &&
+		    my < (unsigned int)(w->y + (int)w->h))
+			return (int)i;
+	}
+	return -1;
+}
+
+/* A press anywhere outside an open popover dismisses it; the click then
+ * continues normally so the target under the pointer still reacts. */
+static void dismiss_popover_outside(unsigned int mx, unsigned int my)
+{
+	unsigned int i;
+
+	if (popover_under(mx, my) >= 0)
+		return;
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		if (!wins[i].info.used || !wins[i].info.popover)
+			continue;
+		if (wins[i].info.pid == (unsigned int)netmenu_pid)
+			netmenu_pid = 0;
+		if (u_wm_close(i) == 0) {
+			wins[i].info.used = 0;
+			wins[i].mapped = 0;
+			full_redraw = 1;
+		}
+		break;
+	}
+}
+
 static void handle_mouse(struct wm_status *st)
 {
 	unsigned int buttons = st->mouse.buttons;
@@ -1371,6 +1608,8 @@ static void handle_mouse(struct wm_status *st)
 		int prev_title_id = last_title_id;
 		unsigned int now = u_ticks_ms();
 
+		if (!bar_net_hit(mx, my))
+			dismiss_popover_outside(mx, my);
 		last_title_id = -1;
 		if (bar_net_hit(mx, my)) {
 			open_netmenu();
@@ -1430,7 +1669,11 @@ static void handle_mouse(struct wm_status *st)
 				int ry = u->info.y + 1;
 
 				u_wm_focus((unsigned int)idx);
-				if (pmx >= rx &&
+				if (u->info.popover) {
+					/* A popover has no title bar, close
+					 * button or resize grip; the app owns
+					 * its content. */
+				} else if (pmx >= rx &&
 				    pmx < u->info.x + (int)u->info.w &&
 				    pmy >= ry && pmy < ry + WM_TITLE_H) {
 					u_wm_close((unsigned int)idx);
@@ -1546,7 +1789,7 @@ static void handle_mouse(struct wm_status *st)
 								  present.rect[i].y,
 								  present.rect[i].w,
 								  present.rect[i].h);
-							bar_tooltip_overlay(&present);
+							wm_overlays(&present);
 							u_wm_present(&present);
 						}
 					}

+ 48 - 7
uhttp.c

@@ -113,13 +113,26 @@ int uhttp_parse_url(const char *s, struct uhttp_url *u)
 
 	i = 0;
 	if (*p == '/') {
-		while (p[i]) {
-			if (p[i] == '#')
-				break;
-			if (i + 1 >= UHTTP_PATH_MAX)
+		static const char hex[] = "0123456789ABCDEF";
+		unsigned int j = 0;
+
+		/* Percent-encode what cannot go on a request line (spaces,
+		 * controls, quotes, non-ASCII), like a browser does; scripts
+		 * build URLs such as "...&scope=openid email profile". */
+		while (p[j] && p[j] != '#') {
+			unsigned char c = (unsigned char)p[j++];
+			int esc = c <= ' ' || c >= 0x7F || c == '"' ||
+				  c == '<' || c == '>';
+
+			if (i + (esc ? 3u : 1u) >= UHTTP_PATH_MAX)
 				return UHTTP_ERR_URL;
-			u->path[i] = p[i];
-			i++;
+			if (esc) {
+				u->path[i++] = '%';
+				u->path[i++] = hex[c >> 4];
+				u->path[i++] = hex[c & 15];
+			} else {
+				u->path[i++] = (char)c;
+			}
 		}
 	}
 	u->path[i] = '\0';
@@ -160,9 +173,37 @@ static void url_build(const struct uhttp_url *u, char *out, unsigned int cap)
 	out[n] = '\0';
 }
 
+static int path_normalize_part(char *path);
+
 /* Normalize an absolute URL path in place: collapse "//", "." and "..".
- * 0 ok, -1 too long. */
+ * Only the path: a query or fragment is kept verbatim (it may carry a URL,
+ * e.g. ?redirect_uri=https://host/cb).  0 ok, -1 too long. */
 static int path_normalize(char *path)
+{
+	char rest[UHTTP_PATH_MAX];
+	unsigned int q = 0, i, n;
+	int rv;
+
+	while (path[q] && path[q] != '?' && path[q] != '#')
+		q++;
+	if (!path[q])
+		return path_normalize_part(path);
+	for (i = 0; path[q + i]; i++)
+		rest[i] = path[q + i];
+	rest[i] = '\0';
+	path[q] = '\0';
+	rv = path_normalize_part(path);
+	n = 0;
+	while (path[n])
+		n++;
+	if (rv != 0 || n + i + 1 > UHTTP_PATH_MAX)
+		return -1;
+	for (q = 0; q <= i; q++)
+		path[n + q] = rest[q];
+	return 0;
+}
+
+static int path_normalize_part(char *path)
 {
 	char tmp[UHTTP_PATH_MAX];
 	unsigned int i, o = 1, len = 0, start, seglen, j;

+ 8 - 3
usb.c

@@ -797,10 +797,15 @@ int usb_scan(usb_probe_fn probe)
 
 	if (scan_busy)
 		return -2;
-	if (usb_hcd_init() != 0)
-		return -1;
-
+	/* Claim the bus before the first controller bring-up: the boot scan
+	 * runs while the WM and the first terminal are already up, and their
+	 * USB calls must see the scan (usb_scan_foreign) rather than half-
+	 * initialized controllers. */
 	scan_begin();
+	if (usb_hcd_init() != 0) {
+		scan_busy = 0;
+		return -1;
+	}
 	generation++;
 	current_probe = probe;
 	print_devices = (probe == 0);

+ 6 - 2
usbhid.c

@@ -332,14 +332,18 @@ static void hid_scan(void)
 
 void usbhid_init(void)
 {
-	if (usb_hcd_init() != 0) {
+	/* usb_scan() brings the controllers up itself, under the scan claim;
+	 * hcd_ok stays 0 until it returns, so usbhid_poll() keeps out. */
+	int r = usb_scan(hid_probe);
+
+	if (r == -1) {
 		serial_puts(SERIAL_COM1, "usbhid: no USB host controller\n");
 		hcd_ok = 0;
 		return;
 	}
 	hcd_ok = 1;
 
-	if (usb_scan(hid_probe) != 0) {
+	if (r != 0) {
 		/* A scan is already running (unlikely at boot): finish from
 		   the watcher. */
 		need_rescan = 1;

+ 24 - 7
wifi_cfg.h

@@ -1,16 +1,26 @@
-/* Staged WiFi connect request, written by the network menu and read by
- * `wifi connectfile <path>`.
+/* WiFi credential records: the staged connect request written by the network
+ * menu and read by `wifi connectfile <path>`, plus the saved-network list in
+ * /data/WIFI.CFG (see wifi_store.c).
  *
  * The normal `wifi connect <ssid> <pass>` command arguments are limited by
  * SYS_SPAWN's VFS_PATH_MAX buffer (64 bytes), which is too small for a long
- * SSID plus a 63-character WPA2 passphrase.  The menu therefore writes this
- * fixed-size record to a /share file and spawns a helper with a short path. */
+ * SSID plus a 63-character WPA2 passphrase.  The menu therefore writes the
+ * single fixed-size record to a /share file and spawns a helper with a short
+ * path.
+ *
+ * /data/WIFI.CFG is a header (`struct wifi_cfg_list`) followed by `count`
+ * `struct wifi_cfg` records, most recently connected first.  A file that
+ * starts directly with WIFI_CFG_MAGIC is the old one-record format and is
+ * accepted as a one-entry list. */
 #ifndef WIFI_CFG_H
 #define WIFI_CFG_H
 
-#define WIFI_CFG_MAGIC 0x4E425746u   /* "NBWF" */
-#define WIFI_CFG_STAGED "/share/netmenu.wifi"
-#define WIFI_CRED_PATH  "/data/WIFI.CFG"
+#define WIFI_CFG_MAGIC      0x4E425746u   /* "NBWF": one network record */
+#define WIFI_CFG_LIST_MAGIC 0x4E42574Cu   /* "NBWL": saved-network list */
+#define WIFI_CFG_LIST_VER   1u
+#define WIFI_CFG_MAX        16            /* saved networks in /data/WIFI.CFG */
+#define WIFI_CFG_STAGED     "/share/netmenu.wifi"
+#define WIFI_CRED_PATH      "/data/WIFI.CFG"
 
 struct wifi_cfg {
 	unsigned int magic;
@@ -21,4 +31,11 @@ struct wifi_cfg {
 	char pass[65];                   /* NUL terminated, pass_len used */
 };
 
+struct wifi_cfg_list {
+	unsigned int magic;
+	unsigned int version;
+	unsigned int count;
+	struct wifi_cfg net[WIFI_CFG_MAX];
+};
+
 #endif

+ 157 - 0
wifi_store.c

@@ -0,0 +1,157 @@
+/* Saved WiFi networks: a small fixed-capacity list in one 8.3 FAT file.
+ * Everything is read/written whole; the network menu and the boot helper
+ * both go through this module. */
+
+#include "ucmd_lib.h"
+#include "wifi_store.h"
+
+#define CFG_SLACK 512   /* FAT may write a final partial sector */
+
+static void wipe(void *p, unsigned int n)
+{
+	volatile unsigned char *b = (volatile unsigned char *)p;
+
+	while (n--)
+		*b++ = 0;
+}
+
+static int cfg_valid(const struct wifi_cfg *c)
+{
+	return c->magic == WIFI_CFG_MAGIC && c->ssid_len >= 1 &&
+	       c->ssid_len <= 32 && c->pass_len <= 64;
+}
+
+int wifi_store_find(const struct wifi_cfg *list, int count,
+		    const unsigned char *ssid, unsigned int ssid_len)
+{
+	int i;
+
+	if (!list || !ssid || ssid_len == 0 || ssid_len > 32)
+		return -1;
+	for (i = 0; i < count; i++) {
+		unsigned int j;
+
+		if (list[i].ssid_len != ssid_len)
+			continue;
+		for (j = 0; j < ssid_len; j++)
+			if (list[i].ssid[j] != ssid[j])
+				break;
+		if (j == ssid_len)
+			return i;
+	}
+	return -1;
+}
+
+int wifi_store_load(struct wifi_cfg *out, int max)
+{
+	union {
+		struct wifi_cfg_list list;
+		struct wifi_cfg one;
+		unsigned char raw[sizeof(struct wifi_cfg_list) + CFG_SLACK];
+	} buf;
+	int r, n = 0, i;
+
+	if (!out || max <= 0)
+		return 0;
+	r = u_syscall3(SYS_READ_FILE, (int)WIFI_CRED_PATH, (int)buf.raw,
+		       (int)sizeof(buf.raw));
+	if (r >= 4 && buf.list.magic == WIFI_CFG_LIST_MAGIC) {
+		int count;
+
+		if (r < 12 || buf.list.version != WIFI_CFG_LIST_VER)
+			goto done;
+		count = (int)buf.list.count;
+		if (count > WIFI_CFG_MAX)
+			count = WIFI_CFG_MAX;
+		if ((unsigned int)r < 12u +
+		    (unsigned int)count * sizeof(struct wifi_cfg))
+			count = (r - 12) / (int)sizeof(struct wifi_cfg);
+		for (i = 0; i < count && n < max; i++) {
+			const struct wifi_cfg *c = &buf.list.net[i];
+
+			if (!cfg_valid(c))
+				continue;
+			if (wifi_store_find(out, n, c->ssid, c->ssid_len) >= 0)
+				continue;
+			out[n++] = *c;
+		}
+	} else if (r >= (int)sizeof(struct wifi_cfg) && cfg_valid(&buf.one)) {
+		out[0] = buf.one;
+		n = 1;
+	}
+done:
+	wipe(buf.raw, sizeof(buf.raw));
+	return n;
+}
+
+int wifi_store_save(const struct wifi_cfg *list, int count)
+{
+	union {
+		struct wifi_cfg_list list;
+		unsigned char raw[sizeof(struct wifi_cfg_list) + CFG_SLACK];
+	} buf;
+	unsigned int len;
+	int i, r;
+
+	if (!list || count <= 0) {
+		u_syscall1(SYS_UNLINK, (int)WIFI_CRED_PATH);
+		return 0;
+	}
+	if (count > WIFI_CFG_MAX)
+		count = WIFI_CFG_MAX;
+	wipe(buf.raw, sizeof(buf.raw));
+	buf.list.magic = WIFI_CFG_LIST_MAGIC;
+	buf.list.version = WIFI_CFG_LIST_VER;
+	buf.list.count = (unsigned int)count;
+	for (i = 0; i < count; i++)
+		buf.list.net[i] = list[i];
+	len = 12u + (unsigned int)count * sizeof(struct wifi_cfg);
+	r = u_syscall3(SYS_WRITE_FILE, (int)WIFI_CRED_PATH, (int)buf.raw,
+		       (int)len);
+	wipe(buf.raw, sizeof(buf.raw));
+	return r == 0 ? 0 : -1;
+}
+
+int wifi_store_remember(const struct wifi_cfg *rec)
+{
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	int n, i, idx, r;
+
+	if (!rec || !cfg_valid(rec))
+		return -1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	idx = wifi_store_find(list, n, rec->ssid, rec->ssid_len);
+	if (idx >= 0) {
+		for (i = idx; i + 1 < n; i++)
+			list[i] = list[i + 1];
+		n--;
+	}
+	if (n >= WIFI_CFG_MAX)
+		n = WIFI_CFG_MAX - 1;      /* drop the least recently used */
+	for (i = n; i > 0; i--)
+		list[i] = list[i - 1];
+	list[0] = *rec;
+	list[0].magic = WIFI_CFG_MAGIC;
+	r = wifi_store_save(list, n + 1);
+	wipe(list, sizeof(list));
+	return r;
+}
+
+int wifi_store_forget(const unsigned char *ssid, unsigned int ssid_len)
+{
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	int n, i, idx, r;
+
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	idx = wifi_store_find(list, n, ssid, ssid_len);
+	if (idx < 0) {
+		wipe(list, sizeof(list));
+		return 0;
+	}
+	for (i = idx; i + 1 < n; i++)
+		list[i] = list[i + 1];
+	n--;
+	r = wifi_store_save(list, n) == 0 ? 1 : -1;
+	wipe(list, sizeof(list));
+	return r;
+}

+ 28 - 0
wifi_store.h

@@ -0,0 +1,28 @@
+/* Saved WiFi networks in /data/WIFI.CFG, shared by the `wifi` command and the
+ * network menu.  The file is a wifi_cfg_list header + record array; the old
+ * one-record format is still read.  See wifi_cfg.h for the layout. */
+#ifndef WIFI_STORE_H
+#define WIFI_STORE_H
+
+#include "wifi_cfg.h"
+
+/* Read the saved list into `out` (most recently used first), dropping
+ * malformed and duplicate records.  Returns 0..max, or 0 when the file is
+ * absent, empty or unreadable. */
+int wifi_store_load(struct wifi_cfg *out, int max);
+
+/* Rewrite the list.  An empty list removes the file.  -> 0 / -1 */
+int wifi_store_save(const struct wifi_cfg *list, int count);
+
+/* Move `rec` to the front (replacing a record with the same SSID, dropping
+ * the least recently used entry when the list is full) and write it. */
+int wifi_store_remember(const struct wifi_cfg *rec);
+
+/* Index of the record whose SSID matches, or -1. */
+int wifi_store_find(const struct wifi_cfg *list, int count,
+		    const unsigned char *ssid, unsigned int ssid_len);
+
+/* Remove one network: 1 removed, 0 not found, -1 write error. */
+int wifi_store_forget(const unsigned char *ssid, unsigned int ssid_len);
+
+#endif

+ 205 - 0
wifi_store_test.c

@@ -0,0 +1,205 @@
+/* Host test for the saved-WiFi list (wifi_store.c).  The syscall layer is
+ * replaced by a small in-memory FAT file, so the real load/save/remember/
+ * forget paths run unchanged. */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "syscall.h"
+
+/* Skip the real ucmd_lib.h (its wrappers are inline `int 0x80` calls) and
+ * provide the two syscalls the store uses. */
+#define UCMD_LIB_H
+
+static unsigned char flash[8192];
+static unsigned int flash_len;
+static int flash_present;
+
+static int fake_syscall1(int num, int a1)
+{
+	(void)a1;
+	if (num == SYS_UNLINK) {
+		flash_present = 0;
+		flash_len = 0;
+		return 0;
+	}
+	return -1;
+}
+
+static int fake_syscall3(int num, int a1, int a2, int a3)
+{
+	(void)a1;
+	if (num == SYS_READ_FILE) {
+		unsigned int n;
+
+		if (!flash_present)
+			return -1;
+		n = flash_len < (unsigned int)a3 ? flash_len : (unsigned int)a3;
+		memcpy((void *)a2, flash, n);
+		return (int)n;
+	}
+	if (num == SYS_WRITE_FILE) {
+		if ((unsigned int)a3 > sizeof(flash))
+			return -1;
+		memcpy(flash, (const void *)a2, (unsigned int)a3);
+		flash_len = (unsigned int)a3;
+		flash_present = 1;
+		return 0;
+	}
+	return -1;
+}
+
+#define u_syscall1 fake_syscall1
+#define u_syscall3 fake_syscall3
+#include "wifi_store.c"
+
+static int failures;
+
+static void check(int ok, const char *what)
+{
+	if (!ok) {
+		printf("FAIL: %s\n", what);
+		failures++;
+	}
+}
+
+static struct wifi_cfg rec(const char *ssid, const char *pass, int extra)
+{
+	struct wifi_cfg c;
+	unsigned int i;
+
+	memset(&c, 0, sizeof(c));
+	c.magic = WIFI_CFG_MAGIC;
+	c.ssid_len = (unsigned char)strlen(ssid);
+	c.pass_len = (unsigned char)strlen(pass);
+	for (i = 0; i < c.ssid_len; i++)
+		c.ssid[i] = (unsigned char)ssid[i];
+	for (i = 0; i < c.pass_len; i++)
+		c.pass[i] = pass[i];
+	c.pass[63] = (char)('a' + extra % 26);
+	return c;
+}
+
+static int is(const struct wifi_cfg *c, const char *ssid, const char *pass)
+{
+	return c->ssid_len == strlen(ssid) &&
+	       memcmp(c->ssid, ssid, c->ssid_len) == 0 &&
+	       c->pass_len == strlen(pass) &&
+	       memcmp(c->pass, pass, c->pass_len) == 0;
+}
+
+static void reset(void)
+{
+	memset(flash, 0, sizeof(flash));
+	flash_len = 0;
+	flash_present = 0;
+}
+
+int main(void)
+{
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	struct wifi_cfg r;
+	struct wifi_cfg_list *l;
+	int i, n;
+
+	/* An empty list removes the file. */
+	reset();
+	check(wifi_store_save(NULL, 0) == 0, "save empty");
+	check(!flash_present, "empty file removed");
+
+	/* Newest first. */
+	check(wifi_store_remember(&(struct wifi_cfg){0}) < 0,
+	      "reject invalid record");
+	r = rec("alpha", "pass-one", 0);
+	check(wifi_store_remember(&r) == 0, "remember alpha");
+	r = rec("bravo", "pass-two", 1);
+	check(wifi_store_remember(&r) == 0, "remember bravo");
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 2, "two records");
+	check(is(&list[0], "bravo", "pass-two"), "bravo first");
+	check(is(&list[1], "alpha", "pass-one"), "alpha second");
+
+	/* Reconnecting updates the passphrase and moves the record to front. */
+	r = rec("alpha", "new-pass", 2);
+	check(wifi_store_remember(&r) == 0, "update alpha");
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 2, "still two records");
+	check(is(&list[0], "alpha", "new-pass"), "alpha updated and first");
+	check(is(&list[1], "bravo", "pass-two"), "bravo second");
+	check(wifi_store_find(list, n, (const unsigned char *)"alpha", 5) == 0,
+	      "find alpha");
+	check(wifi_store_find(list, n, (const unsigned char *)"zulu", 4) == -1,
+	      "find missing");
+
+	/* Full list drops the least recently used entry. */
+	reset();
+	for (i = 0; i < WIFI_CFG_MAX + 1; i++) {
+		char ssid[16];
+
+		snprintf(ssid, sizeof(ssid), "net%d", i);
+		r = rec(ssid, "password", i);
+		check(wifi_store_remember(&r) == 0, "remember full-list entry");
+	}
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == WIFI_CFG_MAX, "list capped");
+	check(is(&list[0], "net16", "password"), "newest kept");
+	check(is(&list[WIFI_CFG_MAX - 1], "net1", "password"),
+	      "oldest dropped");
+
+	/* Forget one record; forgetting a missing SSID reports not found. */
+	check(wifi_store_forget((const unsigned char *)"net16", 5) == 1,
+	      "forget present");
+	check(wifi_store_forget((const unsigned char *)"net16", 5) == 0,
+	      "forget missing");
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == WIFI_CFG_MAX - 1, "forget shrinks the list");
+	check(is(&list[0], "net15", "password"), "next record promoted");
+
+	/* The old one-record file is still read. */
+	reset();
+	r = rec("legacy", "oldpass", 0);
+	memcpy(flash, &r, sizeof(r));
+	flash_len = sizeof(r);
+	flash_present = 1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 1 && is(&list[0], "legacy", "oldpass"),
+	      "legacy record accepted");
+
+	/* A truncated header and duplicate SSIDs are handled. */
+	reset();
+	memcpy(flash, &(unsigned int){ WIFI_CFG_LIST_MAGIC }, 4);
+	flash_len = 8;
+	flash_present = 1;
+	check(wifi_store_load(list, WIFI_CFG_MAX) == 0, "truncated header");
+
+	reset();
+	l = (struct wifi_cfg_list *)flash;
+	l->magic = WIFI_CFG_LIST_MAGIC;
+	l->version = WIFI_CFG_LIST_VER;
+	l->count = 2;
+	l->net[0] = rec("dup", "pass", 0);
+	l->net[1] = rec("dup", "pass", 0);
+	flash_len = 12 + 2 * sizeof(struct wifi_cfg);
+	flash_present = 1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 1 && is(&list[0], "dup", "pass"), "duplicate dropped");
+
+	/* A header that promises more records than the file holds is clamped
+	 * to the bytes actually present. */
+	reset();
+	l = (struct wifi_cfg_list *)flash;
+	l->magic = WIFI_CFG_LIST_MAGIC;
+	l->version = WIFI_CFG_LIST_VER;
+	l->count = 5;
+	l->net[0] = rec("first", "pass", 0);
+	l->net[1] = rec("second", "pass", 0);
+	flash_len = 12 + 2 * sizeof(struct wifi_cfg);
+	flash_present = 1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 2 && is(&list[0], "first", "pass") &&
+	      is(&list[1], "second", "pass"), "short list clamped");
+
+	if (!failures)
+		printf("wifi_store_test: all checks passed\n");
+	return failures ? 1 : 0;
+}

+ 89 - 25
wm.c

@@ -2,6 +2,7 @@
  * mapping/presentation and input routing.  There is no in-kernel WM. */
 
 #include "wm.h"
+#include "backlight.h"
 #include "bootcon.h"
 #include "io.h"
 #include "kexec.h"
@@ -63,6 +64,18 @@ static void wm_clamp_window(struct window *w, int nx, int ny);
 static void wm_server_unmap_index(unsigned int idx);
 static int wm_window_at(int px, int py);
 
+/* Content origin: a normal window has a 1 px border and title bar, a popover
+ * is a flat chromeless panel whose canvas fills the window. */
+static int win_content_x(const struct window *w)
+{
+	return w->x + (w->popover ? 0 : 1);
+}
+
+static int win_content_y(const struct window *w)
+{
+	return w->y + (w->popover ? 0 : 1 + WM_TITLE_H);
+}
+
 void wm_request_redraw(void)
 {
 	wm_full_redraw = 1;
@@ -182,6 +195,9 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 	unsigned short *back;
 	unsigned int i, j, pages, cw, ch, base;
 	unsigned int flags;
+	int popover = (in && (in->flags & WIN_F_POPOVER)) ? 1 : 0;
+	unsigned int pad = popover ? 0 : 1;
+	unsigned int top = popover ? 0 : WM_TITLE_H + 1;
 
 	if (!in || !out)
 		return -1;
@@ -194,7 +210,8 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 		return -1;
 	if (cw * ch * 2 > WM_CONTENT_SLOT || cw * ch * 2 > USER_WIN_RANGE)
 		return -1;
-	if (cw + 2 > vga_fb_width() || ch + WM_TITLE_H + 2 > vga_fb_height())
+	if (cw + pad * 2 > vga_fb_width() ||
+	    ch + top + pad > vga_fb_height())
 		return -1;
 	for (i = 0; i < MAX_WINDOWS; i++)
 		if (!windows[i].used)
@@ -235,6 +252,7 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 	irq_restore(flags);
 
 	w->used = 1;
+	w->popover = popover;
 	w->canvas_window = 1;
 	w->pid = current_proc()->pid;
 	w->owner_cr3 = base;
@@ -248,15 +266,20 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 	w->scroll_x = w->scroll_y = 0;
 	w->canvas_dmg_x = w->canvas_dmg_y = 0;
 	w->canvas_dmg_w = w->canvas_dmg_h = 0;
-	w->pw = cw + 2;
-	w->ph = ch + WM_TITLE_H + 2;
-	w->x = 24 + (int)i * 32;
-	w->y = WM_BAR_H + 12 + (int)i * 28;
-	if (w->x + (int)w->pw > (int)vga_fb_width())
-		w->x = ((int)vga_fb_width() > (int)w->pw) ?
-		       (int)vga_fb_width() - (int)w->pw : 0;
-	if (w->y + (int)w->ph > (int)vga_fb_height())
-		w->y = WM_BAR_H + 4;
+	w->pw = cw + pad * 2;
+	w->ph = ch + top + pad;
+	if (popover) {
+		w->x = (int)vga_fb_width() - (int)w->pw - 8;
+		w->y = WM_BAR_H + 2;
+	} else {
+		w->x = 24 + (int)i * 32;
+		w->y = WM_BAR_H + 12 + (int)i * 28;
+		if (w->x + (int)w->pw > (int)vga_fb_width())
+			w->x = ((int)vga_fb_width() > (int)w->pw) ?
+			       (int)vga_fb_width() - (int)w->pw : 0;
+		if (w->y + (int)w->ph > (int)vga_fb_height())
+			w->y = WM_BAR_H + 4;
+	}
 	wm_clamp_window(w, w->x, w->y);
 	w->focused = 0;
 	w->content_gen = 1;
@@ -443,8 +466,8 @@ int wm_server_win_pointer(struct win_pointer *out)
 	w = &windows[idx];
 	mx = mouse_get_x();
 	my = mouse_get_y();
-	cx = (int)mx - (int)w->x - 1;
-	cy = (int)my - (int)w->y - 1 - WM_TITLE_H;
+	cx = (int)mx - win_content_x(w);
+	cy = (int)my - win_content_y(w);
 	out->x = cx;
 	out->y = cy;
 	out->buttons = mouse_buttons_state();
@@ -490,18 +513,20 @@ int wm_server_resize(unsigned int index, unsigned int cw, unsigned int ch)
 	struct window *w;
 	struct gfx_canvas nf;
 	unsigned short *nb;
-	unsigned int i, pages;
+	unsigned int i, pages, pad, top;
 
 	if (!wm_server_is_wm() || index >= MAX_WINDOWS || !windows[index].used)
 		return -1;
 	w = &windows[index];
 	if (!w->canvas_window || !process_is_alive(w->pid))
 		return -1;
+	pad = w->popover ? 0 : 1;
+	top = w->popover ? 0 : WM_TITLE_H + 1;
 	if (cw < 160 || ch < 80 || cw > WM_WIN_MAX_W || ch > WM_WIN_MAX_H)
 		return -1;
 	if (cw * ch * 2 > WM_CONTENT_SLOT || cw * ch * 2 > USER_WIN_RANGE)
 		return -1;
-	if (cw + 2 > vga_fb_width() || ch + WM_TITLE_H + 2 > vga_fb_height())
+	if (cw + pad * 2 > vga_fb_width() || ch + top + pad > vga_fb_height())
 		return -1;
 	if (gfx_alloc(&nf, cw, ch) != 0)
 		return -1;
@@ -528,8 +553,8 @@ int wm_server_resize(unsigned int index, unsigned int cw, unsigned int ch)
 	w->pending_back = nb;
 	w->pending_pages = pages;
 	w->resize_pending = 1;
-	w->pw = cw + 2;
-	w->ph = ch + WM_TITLE_H + 2;
+	w->pw = cw + pad * 2;
+	w->ph = ch + top + pad;
 	w->content_gen++;
 	/* The owner is probably parked in SYS_WIN_KEY_WAIT; wake it so it
 	 * acknowledges the resize (and reflows its content) immediately. */
@@ -659,6 +684,7 @@ int wm_server_info(unsigned int index, struct wm_window_info *out)
 	out->used = 1;
 	out->focused = w->focused ? 1 : 0;
 	out->pid = w->pid;
+	out->popover = w->popover ? 1 : 0;
 	out->x = (int)w->x;
 	out->y = (int)w->y;
 	out->w = w->pw;
@@ -853,13 +879,14 @@ static void wm_route_pointer(unsigned int mx, unsigned int my,
 
 		if (idx >= 0) {
 			struct window *w = &windows[idx];
-			int cx = (int)mx - w->x - 1;
-			int cy = (int)my - w->y - 1 - WM_TITLE_H;
+			int cx = (int)mx - win_content_x(w);
+			int cy = (int)my - win_content_y(w);
 
 			if (w->canvas_window && cx >= 0 && cy >= 0 &&
 			    cx < (int)w->canvas.w && cy < (int)w->canvas.h &&
-			    !((int)mx >= w->x + (int)w->pw - 16 &&
-			      (int)my >= w->y + (int)w->ph - 16)) {
+			    (w->popover ||
+			     !((int)mx >= w->x + (int)w->pw - 16 &&
+			       (int)my >= w->y + (int)w->ph - 16))) {
 				wm_queue_ptr_event(w, WIN_EV_POINTER_DOWN,
 						   cx, cy, buttons);
 				wm_ptr_capture = idx;
@@ -870,8 +897,8 @@ static void wm_route_pointer(unsigned int mx, unsigned int my,
 		struct window *w = &windows[wm_ptr_capture];
 
 		if (w->used && w->canvas_window) {
-			int cx = (int)mx - (int)w->x - 1;
-			int cy = (int)my - (int)w->y - 1 - WM_TITLE_H;
+			int cx = (int)mx - win_content_x(w);
+			int cy = (int)my - win_content_y(w);
 
 			wm_queue_ptr_event(w, WIN_EV_POINTER_UP,
 					   cx, cy, buttons);
@@ -896,8 +923,8 @@ static void wm_route_scroll(unsigned int mx, unsigned int my)
 	w = &windows[idx];
 	if (!w->canvas_window)
 		return;
-	cx = (int)mx - w->x - 1;
-	cy = (int)my - w->y - 1 - WM_TITLE_H;
+	cx = (int)mx - win_content_x(w);
+	cy = (int)my - win_content_y(w);
 	if (cx < 0 || cy < 0 || cx >= (int)w->canvas.w ||
 	    cy >= (int)w->canvas.h)
 		return;
@@ -930,6 +957,13 @@ int wm_server_poll(struct wm_status *out)
 	out->kexec_busy = kexec_busy ? 1 : 0;
 	out->kexec_progress = kexec_progress;
 	out->kexec_total = kexec_total;
+	{
+		int level = backlight_percent();
+
+		out->backlight_present = level >= 0 ? 1 : 0;
+		out->backlight_level = level > 0 ? (unsigned int)level : 0;
+		out->backlight_seq = backlight_seq();
+	}
 	wm_full_redraw = 0;
 	return 0;
 }
@@ -1192,10 +1226,16 @@ static void wm_close_window(unsigned int idx)
 	wm_request_redraw();
 }
 
-/* Topmost window containing (px,py), or -1. */
+/* Topmost window containing (px,py), or -1.  A popover overrides the normal
+ * focus/slot order: it is an overlay panel and always receives the click. */
 static int wm_window_at(int px, int py)
 {
 	unsigned int i;
+	for (i = 0; i < MAX_WINDOWS; i++)
+		if (windows[i].used && windows[i].popover &&
+		    wm_point_in_rect(px, py, windows[i].x, windows[i].y,
+				     windows[i].pw, windows[i].ph))
+			return (int)i;
 	for (i = 0; i < MAX_WINDOWS; i++)
 		if (windows[i].used && windows[i].focused &&
 		    wm_point_in_rect(px, py, windows[i].x, windows[i].y,
@@ -1223,6 +1263,30 @@ static void wm_clamp_window(struct window *w, int nx, int ny)
 	int miny = WM_BAR_H;
 	int maxy = fbh - WM_TITLE_H;
 
+	if (w->popover) {
+		/* A popover is an overlay panel: keep all of it on screen,
+		 * below the bar. */
+		minx = 4;
+		maxx = fbw - (int)w->pw - 4;
+		miny = WM_BAR_H + 2;
+		maxy = fbh - (int)w->ph - 4;
+		if (minx > maxx)
+			minx = maxx = 0;
+		if (miny > maxy)
+			miny = maxy = WM_BAR_H + 2;
+		if (nx < minx)
+			nx = minx;
+		else if (nx > maxx)
+			nx = maxx;
+		if (ny < miny)
+			ny = miny;
+		else if (ny > maxy)
+			ny = maxy;
+		w->x = nx;
+		w->y = ny;
+		return;
+	}
+
 	if (minx > maxx)
 		minx = maxx = 0;
 	if (miny > maxy)

+ 1 - 0
wm.h

@@ -16,6 +16,7 @@
 
 struct window {
 	int used;
+	int popover;             /* WIN_F_POPOVER: no chrome, anchored by the WM */
 	int x, y;                /* title bar top-left; may be negative */
 	unsigned int pw, ph;     /* pixel size */
 	char title[16];

+ 12 - 0
wm_abi.h

@@ -67,6 +67,11 @@
 #define WM_KIND_NONE 0
 #define WM_KIND_GFX  1
 
+/* Canvas-window flags (struct win_create.flags).  A popover is chromeless,
+ * always on top and anchored by the WM under the top-bar network icon; its
+ * canvas fills the whole window rectangle. */
+#define WIN_F_POPOVER   0x1u
+
 struct wm_screen_info {
 	unsigned int width;
 	unsigned int height;
@@ -89,12 +94,18 @@ struct wm_status {
 	unsigned int kexec_busy;
 	unsigned int kexec_progress;
 	unsigned int kexec_total;
+	/* Panel backlight, for the WM's brightness OSD.  seq changes on every
+	 * key/command adjustment; level is 0 when no PWM was found. */
+	unsigned int backlight_present;
+	unsigned int backlight_level;
+	unsigned int backlight_seq;
 };
 
 struct wm_window_info {
 	unsigned int used;
 	unsigned int focused;
 	unsigned int pid;
+	unsigned int popover;      /* WIN_F_POPOVER: no title bar, drawn on top */
 	int x, y;
 	unsigned int w, h;         /* outer window rectangle */
 	unsigned int content_w, content_h;
@@ -142,6 +153,7 @@ struct wm_size {
 /* Generic canvas-window client API (gfx commands own their own window). */
 struct win_create {
 	unsigned int w, h;
+	unsigned int flags;        /* WIN_F_* */
 	char title[16];
 };
 

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů