Răsfoiți Sursa

settings: real windowed app with WM preferences

Replace the old control-center popover with a titled Settings window: a
section sidebar and a scrollable page for Network, Power, Date & Time,
Appearance (desktop colour and wallpaper picker), Windows and About.

The top-bar netmenu is now a compact quick-settings popover whose six
pills open the matching section through SYS_WM_OPEN_SETTINGS.  A running
Settings window is reused, and the WM hands it the requested pane via
/share/settings.req.

Add SYS_WM_PREFS so the Settings app can apply and persist window shadows,
edge snapping, drag resistance and the desktop colour.  Preferences live in
/data/SETTINGS.CFG (or /share/settings.cfg) and are replayed by the WM after
boot_ready; the WM and sys_wm objects build -Os to stay under 0x90000.
Johannes Zellner 23 ore în urmă
părinte
comite
99417e8e77

+ 140 - 88
AGENTS.md

@@ -155,8 +155,8 @@ make clean
   `install/kernel.bin` and `bin/browser.app`), because the ~1 MB WiFi
   firmware and the ~500 KB gzip browser do not fit a 1.44 MB floppy; a
   floppy boot runs the browser from `BROWSER` on `root.img`.  `bin/init` and
-  `bin/service` are in **both** packs; the current lite gzip pack is ~714 KB
-  and the floppy image still has ~350 KB of internal padding.  The kernel
+  `bin/service` are in **both** packs; the current lite gzip pack is ~744 KB
+  and the floppy image still has ~312 KB of internal padding.  The kernel
   itself no longer carries the pack; the boot path loads it into RAM and
   `ramfs_init` takes a private copy (`bin/<name>` mounted at `/ramfs`).
 - The WiFi firmware `firmware/iwlwifi-7265D-29.ucode` (Chromebook) and
@@ -557,7 +557,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   distance falloff, so its corners fade in a curve.  Shadows are painted
   after the windows, back to front, so a front
   window's shadow falls on the windows behind it and is clipped by every
-  window in front; popovers stay flat.  Geometry damage expands by the
+  window in front; popovers stay flat.  The shadow can be turned off in the
+  Settings app; the WM then uses a zero spread (`shadow_px`), so the damage
+  paths still work without a ring.  Geometry damage expands by the
   spread, and a focused drag copies the window block but repaints the old
   and new ring strips with `draw_rect()` because the ring's background is
   stationary and must not be block-copied.  A resize
@@ -590,7 +592,12 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   keeping the grab point at the same fraction of the title bar.  While
   dragging, screen edges and the facing edges of windows that overlap on the
   other axis resist the window: it stays flush until the pointer overshoots
-  by `WM_RESIST` (24 px) (`resist_geom()` in `ucmd_wm.c`).  A press in the
+  by `WM_RESIST` (24 px) (`resist_geom()` in `ucmd_wm.c`).  The Settings
+  *Windows* page can turn edge snapping (`wm_prefs.snap`) and that resistance
+  (`wm_prefs.resist`) off independently; double-click maximize stays
+  available.  The WM exchanges the prefs with the kernel through
+  `SYS_WM_PREFS` (128), reads the current copy from `wm_status` on every
+  `SYS_WM_POLL`, and replays the saved file at boot.  A press in the
   resize band (1 px inside, 4 px outside, with 12 px corner squares) along
   any edge or corner starts a resize: the grabbed edges follow the pointer
   while the opposite edges stay
@@ -602,12 +609,13 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   moved `WM_RESIZE_MIN_STEP` (8 px), and the release forces the final
   geometry; the kernel carries the previous front canvas over so the content
   does not blink black while the client reflows (see the canvas API bullet).
-  The desktop background is `COL_BG` until a wallpaper is installed.  The
-  image viewer pre-renders the current image to a screen-aspect RGB565
-  buffer (at most 1440x810, cropped to cover) and writes one
+  The desktop background is `wm_prefs.bg_rgb` (default `#202030`), unless a
+  wallpaper image is installed.  The image viewer and the Settings app's
+  *Appearance* page pre-render an image to a screen-aspect RGB565
+  buffer (at most 1440x810, cropped to cover) and write one
   `struct wm_wallpaper_hdr` (magic `NBWAL1`, width, height) plus the pixels to
   `/data/WALLPAPR.BIN` when the data volume is mounted, else the RAM-only
-  `/share/wallpaper`.  It then calls `SYS_WM_WALLPAPER` (123, op 1), which
+  `/share/wallpaper`.  They then call `SYS_WM_WALLPAPER` (123, op 1), which
   bumps `wm_status.wallpaper_seq`; the WM's loop sees the new sequence,
   reloads the file (`/data` first, then `/share`), rebuilds its x/y
   nearest-neighbour maps and repaints.  The WM has no image decoder: it
@@ -617,9 +625,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   at the row and is indexed with absolute screen x, so a partial damage rect
   paints exactly the same pixels as a full redraw; adding x0 to both shifted
   the wallpaper inside the rect and left the previous window pixels behind
-  while dragging.  A missing or invalid file falls back to `COL_BG`.  The
-  file survives a reboot on an installed board because it lives on the
-  `NEBOSDATA` volume.
+  while dragging.  A missing or invalid file falls back to the configured
+  colour.  The file survives a reboot on an installed board because it lives
+  on the `NEBOSDATA` volume; Settings can remove it, which unlinks both
+  copies and signals the WM.
   The NebOS banner in the top-left corner is the start button.  Clicking it
   opens the WM's Windows-like start menu, a flat overlay panel drawn by the
   WM (not a window, so it does not consume a `WM_MAX_WINDOWS` slot).  It is
@@ -649,10 +658,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   pill; a dot under an icon marks a running app.  Clicking a running app
   focuses its window (matched by canvas title: `term`, `Files`, `Browser`,
   ...), otherwise it goes through the same launcher path as the start menu;
-  Settings focuses the control panel.  While the pointer is over an icon,
-  the panel or its label, the WM takes `SYS_WM_MOUSE_CAPTURE` so clicks and
-  wheel events cannot leak to the window underneath; the capture is released
-  on leave (or after the button is released).  The dock joins
+  Settings opens or focuses the Settings window.  While the pointer is over
+  an icon, the panel or its label, the WM takes `SYS_WM_MOUSE_CAPTURE` so
+  clicks and wheel events cannot leak to the window underneath; the capture
+  is released on leave (or after the button is released).  The dock joins
   `wm_overlays()`, and window damage intersecting it repaints it.  A
   focused-window drag that starts with the shadow partly covered by the dock
   (or the brightness OSD) takes the full-repaint path instead of the block
@@ -668,8 +677,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   share the same `BAR_BTN_Y`/`BAR_BTN_H` geometry and rounded style, so their
   pills stop one pixel above the rainbow separator; both turn selection-blue
   while their panel is open.  A click anywhere in the cluster opens the
-  control panel (whose Date & Time section has the editor; the start menu's
-  Clock entry opens the analog clock).
+  control-center popover (the start menu's Clock entry opens the analog
+  clock).
   The rightmost bar item is the AC/battery status icon: the Adwaita
   `ac-adapter` symbol while the adapter is online and the `battery` outline
   with our own level fill inside on battery.  To its left is the network
@@ -680,14 +689,15 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   when a WiFi card is present but not associated).  The WM polls
   `SYS_NET_INFO` (and
   `SYS_WIFI_STATUS` only while WiFi is active) at 1 Hz.  The whole right
-  status cluster toggles one `/ramfs/bin/netmenu` control popover, anchored
-  flush against the bottom of the top bar and the right screen edge
-  (`u_wm_set_geom`).  It opens
-  collapsed: the battery/clock summary and
-  the Quick settings pills are visible, while the network, power-mode and
-  date/time settings are hidden until their pill is clicked.  A pill toggles
-  its section in place; the panel resizes itself to the content height (up to
-  the screen) and scrolls when a section is taller.  A popover is a chromeless
+  status cluster toggles one `/ramfs/bin/netmenu` quick-settings popover,
+  anchored flush against the bottom of the top bar and the right screen edge
+  (`u_wm_set_geom`).  It shows the battery/clock summary, a brightness slider
+  when a panel PWM exists, and six pills: Network, Power, Date & Time,
+  Appearance, Windows and About.  A pill is a launcher, not an inline editor:
+  it calls `SYS_WM_OPEN_SETTINGS` (129), the WM opens or focuses
+  `/ramfs/bin/settings` at that section and writes the request to
+  `/share/settings.req`, and the popover closes.  A running Settings window
+  consumes that file and switches panes.  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.
@@ -697,7 +707,25 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   window starts its content one title bar below the origin; a popover uses
   the origin directly).  An outside press dismisses the
   popover and then continues with the normal click handling; a second click
-  on the status cluster toggles it.
+  on the status cluster toggles it.  The titled Settings window itself is a
+  normal canvas window: a left sidebar with the six sections and a scrollable
+  right pane.  Network keeps the NIC selection, DHCP, Wi-Fi scan/join/saved
+  list and connection details; Power has the three P-state modes, brightness
+  and AC/battery state; Date & Time edits the RTC and runs SNTP; Appearance
+  selects a desktop colour and can browse the VFS mounts for a wallpaper
+  image (decoded with the image library and written in the same pre-scaled
+  RGB565 format the viewer uses); Windows toggles shadows, edge snapping and
+  drag resistance; About shows version, display, uptime, memory and CPU
+  temperature.  The WM is the only process that may focus another window, so
+  start menu, dock and popover launchers all go through `SYS_WM_OPEN_SETTINGS`
+  and the WM's `open_settings()`: it reuses the window titled `Settings`,
+  writes the section request, or spawns the app and keeps its pid.  Window
+  preferences are the `struct wm_prefs` in `wm_abi.h`: the kernel keeps the
+  authoritative copy, `SYS_WM_PREFS` (128) gets/sets it, the WM reads it from
+  `wm_status` at every poll and replays the saved file at boot after
+  `boot_ready` (with the same retry window as the wallpaper) from
+  `/data/SETTINGS.CFG`, else `/share/settings.cfg`.  The Settings app saves
+  the same `struct wm_prefs_file` after every change.
   The start menu entries spawn the same pack binaries (`Chat` ->
   `/ramfs/bin/chat`, `Tasks` -> `/ramfs/bin/process`, `Services` ->
   `/ramfs/bin/service --gui`, `Disks` -> `/ramfs/bin/disks`, ...).  When the full date/time would cross
@@ -730,8 +758,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   (121) takes/releases the pointer for a WM drag or resize (see the Mouse
   cursors bullet).
   `SYS_WIN_RESIZE_SELF` (115) lets a canvas window grow or shrink itself and
-  `SYS_SCREEN_INFO` (116) returns the framebuffer dimensions; the panel uses
-  them to collapse to the pills or grow over an expanded section.  The kernel
+  `SYS_SCREEN_INFO` (116) returns the framebuffer dimensions; apps size their
+  popovers and panels from them.  The kernel
   refuses a self-resize while the WM owns a frame, and the caller retries.  The WM
   composites the front canvas; presented frames carry monotonic seq
   counters, so the WM can never lose one.  `SYS_WM_RESIZE` carries the
@@ -876,11 +904,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   sees the right century.  `SYS_RTC_GET`/`SYS_RTC_SET` (104/105)
   expose the full `struct sys_datetime`; `SYS_RTC_HMS`/`SYS_RTC_DATETIME`
   (56/69) stay the small read-only views.  The WM top-bar date/time is a
-  click target that opens the control panel's inline Date & Time editor; the
-  start menu's Date & Time entry spawns `/ramfs/bin/settime`, whose "Sync
-  NTP" button fetches UTC through `SYS_NTP_SYNC` and writes it with
-  `SYS_RTC_SET`; the `date` command prints the classic `date` line and a
-  small `+FORMAT` subset.
+  click target for the quick-settings popover; the Settings app's Date &
+  Time page has the editor (the start menu's Date & Time entry still
+  spawns `/ramfs/bin/settime`, whose "Sync NTP" button fetches UTC through
+  `SYS_NTP_SYNC` and writes it with `SYS_RTC_SET`; the `date` command prints
+  the classic `date` line and a small `+FORMAT` subset).
 - **Fonts**: `ufont.c/h`, `ufont_ttf.c`, `ufont_draw.c`, `ufont_file.c`,
   `ufont_woff.c` — a
   fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for
@@ -1103,20 +1131,24 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   failure.  Every receive/send goes through `netdev_rx_frame()`/
   `netdev_tx_frame()`, which keep the 32-bit frame byte counters behind
   `SYS_NET_INFO.rx_bytes/tx_bytes` (the `process` monitor's network graph).
-  The top-bar status cluster opens `ucmd_netmenu.c`, the control
-  panel.  It lists every present driver through `SYS_NET_DEVLIST` (111),
-  selects one
-  through `SYS_NET_SELECT` (112) and runs DHCP; the same popover lists scanned
+  The top-bar status cluster opens `ucmd_netmenu.c`, the quick-settings
+  popover.  Its Network pill asks the WM to open or focus
+  `ucmd_settings.c` at the Network page.  That page lists every present
+  driver through `SYS_NET_DEVLIST` (111), selects one
+  through `SYS_NET_SELECT` (112) and runs DHCP; the same page 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 battery/AC and clock summary, a brightness
-  slider (when a panel PWM exists), and a Quick settings grid of
-  `ngui_tile`s for Network, the P-state power mode (`SYS_CPUFREQ`) and
-  Date & Time.  Clicking a tile expands that section in place: the network
-  devices/Wi-Fi/connection area (built with `ngui_section` and
-  `ngui_list_row`), three power-mode rows, or an inline date/time editor
-  (fields, Set, Now, Sync NTP — no separate `settime` window).  It opens as a
-  `WIN_F_POPOVER` canvas window, not as a titled window.
+  The settings window is a normal titled canvas window with a left sidebar and
+  a scrollable right pane.  The popover itself is only a launcher: a
+  battery/AC and clock summary, a brightness slider (when a panel PWM exists),
+  and a 2-column `ngui_tile` grid for Network, Power, Date & Time, Appearance,
+  Windows and About.  Clicking a tile calls `SYS_WM_OPEN_SETTINGS`, closes the
+  popover, and the WM opens or focuses the Settings window at that section.
+  The Settings pages are the network devices/Wi-Fi/connection area (built with
+  `ngui_section` and `ngui_list_row`), three power-mode rows plus brightness
+  and AC/battery state, an inline date/time editor (fields, Set, Now, Sync
+  NTP), an appearance page with desktop colours and an image file picker, the
+  WM shadow/snapping/resistance toggles, and an About page.
   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
@@ -1211,9 +1243,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `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 control panel's staged SSID/pass/BSSID
-  record, `wifi saved` to list the saved networks, `wifi autoconnect` for the
-  boot helper and `wifi forget [ssid]`),
+  `wifi connectfile <path>` for the Settings Network page's staged
+  SSID/pass/BSSID 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
@@ -1310,8 +1342,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `2357:011f`)**: `rtl8821au.c/h` ports the Linux rtw88 8821A/USB bring-up
   (`rtw88xxa_power_on()`, `__rtw_download_firmware_legacy()`,
   `rtw_parse_tbl_phy_cond()`, `rtw88xxa_set_channel()`) behind the same
-  entry points as `iwl_mvm.c`, so `wifi.c`, `wifi`, the netmenu and
-  autoconnect work unchanged.  The USB device probe (registered before
+  entry points as `iwl_mvm.c`, so `wifi.c`, `wifi`, the Settings network page
+  and autoconnect work unchanged.  The USB device probe (registered before
   RNDIS; `USB_MAX_DEVICE_PROBES` is 6) matches the Linux `rtw88_8821au` ID
   list, takes the bulk-IN and up to four bulk-OUT endpoints and sets the
   configuration; nothing is powered on until the first `wifi` command.
@@ -1342,7 +1374,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   USB errors, a disconnected port or a re-enumeration set `fatal`, and
   `wifi.c` reloads on the next use.  Tested by QEMU `usb-host` passthrough
   on xHCI (C-cut chip, firmware 42.4): 2.4 + 5 GHz scan, WPA2-PSK connect
-  and DHCP through the control panel.
+  and DHCP through the Settings Network page.
 - **Mouse cursors**: the set is GNOME's Adwaita theme (adwaita-cursors 51,
   LGPL-3 or CC-BY-SA-3.0).  `assets/cursors/adwaita/` holds its Xcursor
   files trimmed to the 24 px images (`tools/xcursor_trim.py`; the X11 alias
@@ -1567,7 +1599,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   and on Nehalem the C3/C6 and package residency; the Airmont line adds the
   FSB, nominal MHz, turbo pstate/VID, VID range and the live `PERF_CTL`.
   `cpufreq [auto|min|max|off|<pstate>]` overrides the governor on both;
-  `SYS_CPUFREQ` exposes the same mode set/get to the control panel.
+  `SYS_CPUFREQ` exposes the same mode set/get to the Settings Power page.
 - **CPU temperature**: `thermal.c/h` — Intel DTS through `IA32_THERM_STATUS`
   (MSR `0x19C`).  Each CPU samples itself once a second from its scheduler
   tick (`struct cpu.temp_c`), and `SYS_CPU_TEMP` (`sys_info.c`) exposes the
@@ -2566,7 +2598,7 @@ filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `process`, `spin`,
 `clock`, `colors`, `settime`, `date`, `files`, `disks`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
-`netreset`, `websrv`, `curl`, `wifi`, `netmenu`, `solitaire` and `hello` are files in `/ramfs/bin`
+`netreset`, `websrv`, `curl`, `wifi`, `netmenu`, `settings`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
 commands spawned as processes, or builtins (`cd`, `path`, `help`, `clear`).
 
@@ -3157,12 +3189,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    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), the 15 full-colour app icons and `install/kernel.bin` is
-   ~2.16 MB gzip (~2 MB under the cap), inflating to ~4.8 MB, which adds
-   about half a second to the boot; the floppy lite pack is ~714 KB gzip
+   ~2.21 MB gzip (~2 MB under the cap), inflating to ~4.7 MB, which adds
+   about half a second to the boot; the floppy lite pack is ~744 KB gzip
    and deliberately omits the firmware, the cursor bundle,
    `install/kernel.bin` and the browser (`BROWSER` on `root.img` is the
    floppy copy).  `libdeflate-gzip -12` is still preferred.  Over
-   115200 serial a raw `cmds-dev` pack (4.8 MB) now takes about four
+   115200 serial a raw `cmds-dev` pack (4.7 MB) now takes about four
    minutes; use `net-cmds` (~45 s in QEMU).
 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
@@ -3227,7 +3259,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 21. The TCP backlog's early-request buffers cost 8 KB of kernel BSS
     (8 slots x 1 KB), and the FAT listing cache another 5 KB.  The command
-    pack is out of the kernel now; after the WiFi/netmenu/install code and the
+    pack is out of the kernel now; after the WiFi/install code and the
     per-connection TCP queues moved to the frame allocator, `_end` is
     ~0x8ef20 before (with the 6200/6300 DVM layer, the RTL8821AU driver, the
     8×16 boot-console font, the IOAPIC/AMD-thermal additions and the safe
@@ -3235,7 +3267,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     ~0x8bf20 once the frame bitmap moved out of BSS; with the ioremap
     window, the EHCI handoff fix, the boot-scan log ring, the init bootstrap,
     parent-pid tree kill, the tty control syscalls and `TTY_MAX` 16 it is
-    ~0x8f260, ~3.4 KB below the `0x90000` wall, and the
+    ~0x8e260, ~7.5 KB below the `0x90000` wall.  The WM and `sys_wm.o`
+    build with `-Os` because their extra settings code otherwise pushed the
+    `.data` end across a page boundary and moved the 4 KB-aligned BSS by a
+    whole page; the
     remaining limit
     is kernel code/buffers only.
 
@@ -3610,34 +3645,48 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     window yet and uses a byte-oriented AES-CCM per frame, so high RX
     throughput is CPU-bound.  The driver was written against the Linux iwlwifi
     sources without hardware in the loop; expect bring-up debugging on the
-    Chromebook.  The kernel budget is tight: WiFi added ~28 KB with both
-    firmware layers, `_end` is ~0x85ca0 with the RTL8821AU driver (~41 KB
-    below the `0x90000` wall).
-
-36. Control panel limits (`ucmd_netmenu.c`): building the device list probes
-    every driver, so opening the menu on a machine with an unconfigured USB
+    Chromebook.  The kernel budget stays tight (see item 21 for the current
+    `_end`); the settings syscalls are small and `wm.o`/`sys_wm.o` build
+    with `-Os`.
+
+36. Settings and control-center limits (`ucmd_settings.c`, `ucmd_netmenu.c`):
+    the Settings window is the only editor; the top-bar popover holds a
+    summary, brightness and six launcher pills.  The WM opens or focuses one
+    window titled `Settings`, and section requests are a small
+    `/share/settings.req` file the app polls (250 ms) and consumes; spawning
+    `settings` manually from a terminal can still create a second window, so
+    two instances can race the same request file and the fixed
+    `/share/netmenu.wifi` record.  Building the device list probes every
+    driver, so opening the Network page 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 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 panel opens at a compact height (the summary plus the Quick settings
-    pills) and calls `SYS_WIN_RESIZE_SELF` to grow over an expanded section;
-    it is clamped to the screen and the section scrolls when it is taller.
-    The brightness card and the Power mode pill are hidden when the machine
-    has no panel PWM / P-state control.  The inline Date & Time editor writes
-    the RTC and can block for a 5 s NTP sync.  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 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.
+    that was not the boot-time winner.  The page shows at most four non-WiFi
+    device rows plus a "+N more devices" line, and WiFi scanning is refused
+    while associated (use Disconnect first).  Brightness and the P-state rows
+    are hidden when the machine has no panel PWM / frequency control.  The
+    Date & Time page writes the RTC and its Sync NTP can block the app for a
+    5 s NTP timeout.  Closing Settings does not cancel an already started
+    `wifi` helper.  The staged `/share/netmenu.wifi` record contains the WPA2
+    passphrase until the `wifi` helper reads and unlinks it.  The `wifi`
+    helper is asynchronous: closing the window does not cancel a connection
+    attempt.  Saved credentials live in plaintext `/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 Settings 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.
+    The Appearance page's file picker stops at 96 entries per directory,
+    starts at `/data` (else `/share`, else the VFS root), lists the mount
+    table for `/`, and decodes a chosen image in the app (4 MB file, 24 MB
+    decode arena); the window blocks while that decode runs.  The desktop
+    colour is only visible while no wallpaper image is installed, and
+    removing the image unlinks both `/data/WALLPAPR.BIN` and
+    `/share/wallpaper`.  Window preferences are saved in
+    `/data/SETTINGS.CFG` (8.3) when the data volume is mounted, otherwise
+    only the RAM copy `/share/settings.cfg` survives until reboot; the WM
+    retries the file for ten seconds after `boot_ready`, matching the
+    wallpaper retry window.  The prefs structure is not versioned beyond
+    `WM_PREFS_VERSION`, so an old `/data` file is ignored rather than
+    migrated.
 
 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
@@ -3691,14 +3740,17 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `_end` (see item 21).
 
 40. Wallpaper limits: one screen-aspect image pre-scaled to at most
-    1440x810 (cropped to cover, no crop/position choice), no slideshow and
-    no Clear action in the viewer.  The WM reads the whole file when
+    1440x810 (cropped to cover, no crop/position choice), no slideshow.  The
+    image viewer and the Settings Appearance page can set or remove it; the
+    Settings picker lists at most 96 entries per directory and decodes a file
+    up to 4 MB.  The WM reads the whole file when
     `SYS_WM_WALLPAPER` bumps the sequence, so installing/switching a
     wallpaper blocks the WM for the FAT read; the storage is
     `/data/WALLPAPR.BIN` on installed boards and the RAM-only
     `/share/wallpaper` otherwise.  The WM keeps a 2.4 MB static copy plus a
     256 KB RGB565->BGRA table (16/24 bpp convert per pixel), all inside the
-    4 MB user image window, and has no image decoder of its own.
+    4 MB user image window, and has no image decoder of its own.  A desktop
+    colour (`wm_prefs.bg_rgb`) is available only while no image is installed.
 
 41. Init/service limits: the service table is static (`service_defs.c`), with
     no enable/disable persistence, dependencies, targets, one-shot services,

+ 15 - 4
Makefile

@@ -124,9 +124,13 @@ kobj = $(if $(filter vesa_stage,$(1)),$(B)/boot/$(1).o,$(if $(filter \
        font_8x16 inflate,$(1)),$(B)/common/$(1).o,$(B)/kernel/$(1).o))
 KERNEL_OBJS = $(foreach n,$(KERNEL_LINK_ORDER),$(call kobj,$(n)))
 
+# Size-sensitive kernel objects build -Os.  wm/sys_wm carry the settings
+# ABI; at -O2 their extra .text/.data pushed the .data end across a page
+# boundary and moved the 4 KB-aligned BSS by a whole page.
 KERNEL_OS = terminal disk fat nvidia nv50 uhci ohci ehci xhci asix rndis \
 	iwl_trans iwl_mvm iwl_dvm wifi_fw rtl8821au wifi ccmp usb lsusb lspci \
-	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs
+	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs \
+	wm sys_wm
 $(addprefix $(B)/kernel/,$(addsuffix .o,$(KERNEL_OS))): OPT = -Os
 $(B)/kernel/e1000e.o: OPT = -Oz
 # The ACPI table/S5 parser and the poweroff path are cold boot/shutdown code
@@ -399,7 +403,7 @@ UCMDS = cpuinfo ls cat save rm mkdir rmdir \
         netconsole netregs netloop netreset net100 netmac curl \
         files view sensors powerinfo mines solitaire \
         settime date gallery websrv browser chat \
-        wifi netmenu disks membench init service
+        wifi netmenu settings disks membench init service
 
 app = $(U)/apps/$(1)/ucmd_$(1)
 UCMD_ELFS = $(foreach a,$(UCMDS),$(call app,$(a)).elf)
@@ -481,8 +485,15 @@ $(call app,curl).elf: $(call app,curl).o $(UHTTP_OBJS) $(IMG_DECODE_OBJS) $(INFL
 $(call app,wifi).elf: $(call app,wifi).o $(WIFI_STORE) $(WPA_OBJS) $(UL)/tls/tls_rng.o $(UL)/tls/tls_sha256.o $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
-# Control panel: NIC list, WiFi scan, saved networks, power and date/time.
-$(call app,netmenu).elf: $(call app,netmenu).o $(WIFI_STORE) $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
+# Control panel: battery/clock summary, brightness and the Settings pills.
+$(call app,netmenu).elf: $(call app,netmenu).o $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
+	$(ULINK)
+
+# Settings: sidebar sections, network/WiFi management, clock, power,
+# appearance (wallpaper picker) and window-manager preferences.
+$(call app,settings).o: OPT = -Os
+$(call app,settings).o: XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
+$(call app,settings).elf: $(call app,settings).o $(WIFI_STORE) $(IMG_DECODE_OBJS) $(UL)/img/img_file.o $(INFLATE) $(NGUI_APP) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
 # Storage manager: devices, partitions, mount policies, format/install.

+ 1 - 1
docs/cpu.html

@@ -399,7 +399,7 @@
 		<ul>
 			<li><strong>Nehalem/Westmere P-states.</strong> <code>power_init</code> enables SpeedStep, raises the package C-state limit to C6 when unlocked, reads min/max ratios from <code>PLATFORM_INFO</code> and starts at the maximum non-turbo ratio. The target ratio goes in bits 15:8 of <code>IA32_PERF_CTL</code> with the low byte zero.</li>
 			<li><strong>Airmont/Braswell P-states.</strong> Family 6 model <code>0x4C</code> reads the Atom ratio/VID MSRs (<code>0x66A..0x66D</code>), <code>MSR_FSB_FREQ</code> and the FSB table. The N3060 reports pstates 6..20, BCLK 80 MHz (1600 MHz nominal), turbo pstate 31 (2480 MHz) and VID 0x2D..0x3C. <code>power_init</code> enters at max non-turbo and the governor drops to pstate 6 (480 MHz); <code>IA32_PERF_CTL</code> carries the pstate in 15:8 and the Linux-interpolated VID in 7:0. Turbo is detected but not requested. The probe deliberately avoids package/power-SKU MSRs; an unsupported <code>rdmsr</code> before the IDT triple-faults.</li>
-			<li><strong>Governor.</strong> A 100 ms window picks min/max/linear target pstates; short busy streaks jump to max immediately. Each CPU writes its own <code>IA32_PERF_CTL</code>; <code>cpufreq [auto|min|max|off|&lt;pstate&gt;]</code> overrides it, and <code>SYS_CPUFREQ</code> exposes the same auto/min/max/off mode to the control panel's Power mode tile.</li>
+			<li><strong>Governor.</strong> A 100 ms window picks min/max/linear target pstates; short busy streaks jump to max immediately. Each CPU writes its own <code>IA32_PERF_CTL</code>; <code>cpufreq [auto|min|max|off|&lt;pstate&gt;]</code> overrides it, and <code>SYS_CPUFREQ</code> exposes the same auto/min/max/off mode to the Settings Power page.</li>
 			<li><strong>Telemetry.</strong> <code>power</code> prints effective MHz from APERF/MPERF, the current/requested pstate and, on Airmont, the FSB, nominal MHz, turbo pstate/VID, VID range and live <code>PERF_CTL</code>; <code>sensors</code> prints the CPU temperature, board sensors and both EC types; <code>powerinfo</code> prints the AC adapter and battery state, and the WM top bar shows the temperature plus a far-right AC plug or level-filled battery icon on ThinkPads and Chromebooks.</li>
 			<li><strong>Thermal.</strong> On Intel, each CPU samples its DTS once a second from its scheduler tick; the hottest core is exposed to ring 3. TjMax comes from <code>IA32_TEMPERATURE_TARGET</code> on Nehalem/Westmere, the coretemp 90 °C table on Airmont, and the Bonnell table on older Atoms. On AMD family 15h models below <code>0x60</code> (Bulldozer/Piledriver/Steamroller), <span class="file">thermal.c</span> reads the package Tctl from <code>D18F3xA4</code> at PCI <code>0:18.3</code> (k10temp's <code>(raw × 125) m°C</code>, with the 49 °C range offset when bits 17:16 are both set) and publishes it to every CPU from the kworker under the BKL; PCI config space is deliberately not touched from the per-CPU timer interrupt.</li>
 			<li><strong>Limits.</strong> Package C-states/S0ix remain firmware-managed; Airmont reports no C3/C6 residency and does not request the turbo pstate. The explicit <code>idle c6</code> override is the Nehalem <code>0x20</code> hint; use <code>idle auto</code> for the Airmont C6N (<code>0x58</code>) path.</li>

+ 2 - 2
docs/drivers.html

@@ -681,8 +681,8 @@
 			the full <code>struct sys_datetime</code>; the older
 			<code>SYS_RTC_HMS</code>/<code>SYS_RTC_DATETIME</code> calls remain
 			the small read-only views. The WM’s top-bar date/time opens the
-			control panel, whose Date &amp; Time tile reveals an inline
-			editor; its <em>Sync NTP</em> button fetches UTC through
+			quick-settings popover; its Date &amp; Time pill opens the
+			Settings page, whose <em>Sync NTP</em> button fetches UTC through
 			<code>SYS_NTP_SYNC</code> (106), backed
 			by the SNTP client in <span class="file">ntp.c</span>, and writes
 			it with <code>SYS_RTC_SET</code>. The <code>date</code> command

+ 55 - 32
docs/graphics.html

@@ -164,19 +164,28 @@
 			shows the hand cursor. Every normal window also casts a 10 px
 			soft drop shadow: <code>usurf_window_shadow()</code> darkens
 			the ring outside the window edge with a rounded distance
-			falloff, so the corners fade in a curve.
+			falloff, so the corners fade in a curve. The shadow, the edge
+			snapping and the drag resistance can be changed in
+			<code>bin/settings</code> (<em>Windows</em>): the WM keeps a
+			<code>struct wm_prefs</code> in <code>wm_status</code>, applied
+			through <code>SYS_WM_PREFS</code> and persisted in
+			<code>/data/SETTINGS.CFG</code> (or the RAM copy
+			<code>/share/settings.cfg</code>).
 			Shadows are painted after the windows, back to front, so a
 			front window's shadow falls on the windows behind it and is
 			clipped by every window in front; popovers stay flat. Geometry
 			damage grows by the shadow spread, while a title-bar drag
 			repaints only the old and new ring strips around the copied
-			window block. The desktop starts as a flat colour;
-			<code>view</code>'s
-			<em>Background</em> button stores a pre-scaled RGB565 file
-			(<code>/data/WALLPAPR.BIN</code> on an installed board, else
-			<code>/share/wallpaper</code>) and signals the WM through
-			<code>SYS_WM_WALLPAPER</code>, which reloads and stretches it
-			under the windows. The WM has no image decoder of its own.
+			window block. The desktop is a configurable flat colour
+			(<code>wm_prefs.bg_rgb</code>, default <code>#202030</code>);
+			<code>view</code>'s <em>Background</em> button or the
+			Settings app's <em>Appearance</em> page stores a pre-scaled
+			RGB565 file (<code>/data/WALLPAPR.BIN</code> on an installed
+			board, else <code>/share/wallpaper</code>) and signals the WM
+			through <code>SYS_WM_WALLPAPER</code>, which reloads and
+			stretches it under the windows. The image wins over the colour
+			while it is installed; removing it in Settings exposes the
+			colour again. The WM has no image decoder of its own.
 			Click-to-focus, drag-by-title-bar and close are routed through the
 			same pointer path. To the left of the rightmost AC/battery status
 			icon, a network status icon shows the Adwaita
@@ -193,19 +202,21 @@
 			bar buttons use the same height and rounded style, stopping just
 			above the rainbow separator, and turn selection-blue while their
 			panel is open. It opens the anchored <code>bin/netmenu</code>
-			control panel (a second click closes it).
-			It opens collapsed: the battery/clock summary and Quick settings
-			pills are visible, while the network, power-mode and date/time
-			settings stay hidden until their pill is clicked.  Present NICs
-			can then be selected (DHCP runs), and scanned WiFi networks can be
-			joined, asking for the WPA2 passphrase first when the AP requires
-			one.
+			quick-settings popover (a second click closes it).
+			The popover holds the battery/clock summary, a brightness slider
+			and six pills: Network, Power, Date &amp; Time, Appearance,
+			Windows and About. Clicking a pill never expands the popover;
+			it calls <code>SYS_WM_OPEN_SETTINGS(section)</code>, the WM
+			opens or focuses the real <code>bin/settings</code> window and
+			writes the requested section to <code>/share/settings.req</code>,
+			and the popover closes. A running Settings window consumes that
+			request and switches panes without restarting.
 		</p>
 		<p>
 			The NebOS banner in the top-left is the start button. Clicking it
 			opens a Windows-like start menu drawn by the WM as a flat overlay,
 			not a window, so it floats above every canvas without consuming a
-			window slot. The panel uses the control panel's theme: a flat
+			window slot. The panel uses the quick-settings popover's theme: a flat
 			<code>theme.bg</code> surface with no rim, a dim
 			<code>Applications</code> caption as its first row, rounded hover
 			rows and a rounded Power tile. Every self-contained GUI
@@ -245,8 +256,7 @@
 			<code>Browser</code>, ...), since the canvas ABI carries no
 			executable id.  Clicking a running app focuses its window;
 			otherwise the click goes through the same launcher path as the
-			start menu.  Settings focuses the control panel rather than
-			toggling it.  While the pointer is over an icon, the panel or its
+			start menu.  Settings opens or focuses the Settings window.  While the pointer is over an icon, the panel or its
 			label, the WM takes <code>SYS_WM_MOUSE_CAPTURE</code>, so a click
 			or wheel event cannot leak to the window underneath; it releases
 			the capture on leave (or after the button is released).  The dock
@@ -277,16 +287,15 @@
 			popover and the click then continues normally; a second click on
 			the status cluster toggles it. The panel itself is drawn with the
 			ngui components: a battery/AC and clock summary, a brightness
-			slider when the panel PWM is present, and Quick settings tiles for
-			Network, the CPU power mode (<code>SYS_CPUFREQ</code>) and Date
-			&amp; Time.  Clicking a tile expands that section in place — the
-			network devices/Wi-Fi/connection lists, the three power modes, or
-			an inline date/time editor with Set, Now and Sync NTP (no separate
-			window).  <code>SYS_WIN_RESIZE_SELF</code> grows or shrinks the
-			popover to the section, clamped to <code>SYS_SCREEN_INFO</code>'s
-			framebuffer; the section scrolls with the wheel, touchpad or page
-			keys when it is taller than the screen, and its overlay scrollbar
-			slides in while the pointer is over the panel.
+			slider when the panel PWM is present, and a 2-column grid of
+			quick-settings tiles for Network, Power, Date &amp; Time,
+			Appearance, Windows and About.  A tile is a launcher, not an
+			inline editor: it asks the WM for that Settings section (see
+			above), so network selection, Wi-Fi join, the clock editor,
+			wallpaper selection and the WM preference toggles all live in
+			the titled <code>bin/settings</code> window.  The popover has no
+			resizing path left; its content is static and the window height
+			is computed once from the presence of the brightness slider.
 		</p>
 		<p>
 			The WM is the ring-3 process loaded from
@@ -436,6 +445,10 @@
 			the work area at full height, and the top edge maximizes it. The
 			restore geometry is saved only when a window leaves the normal state,
 			so snapping and then maximizing still restores the original size.
+			The Settings <em>Windows</em> page can turn edge snapping off
+			(<code>wm_prefs.snap</code>); double-click maximize stays
+			available.  Edge resistance (<code>wm_prefs.resist</code>) is a
+			separate toggle.
 			Dragging a maximized or snapped window restores it first, with the
 			grab point kept at the same fraction of the title bar, and a manual
 			resize clears the state. While a window is dragged, the screen edges
@@ -475,7 +488,8 @@
 			Adwaita symbolic icons (see <a href="#icons">UI icons</a>), a theme palette, layout cut helpers and scrolling
 			panes. It is linked into <code>files</code>, <code>mines</code>,
 			<code>solitaire</code>, <code>process</code>, <code>chat</code>,
-			the control panel and the real <code>gallery.elf</code>.
+			<code>settings</code>, <code>netmenu</code> and the real
+			<code>gallery.elf</code>.
 		</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>
@@ -552,9 +566,17 @@
 				<h3>view</h3>
 				<p>Image viewer with fit, 1:1, zoom, pan, EXIF orientation and animated GIF playback. Its <em>Background</em> button (or the <code>b</code> key) installs the image as the desktop wallpaper, persisted in <code>/data/WALLPAPR.BIN</code> when the data volume is mounted.</p>
 			</div>
+			<div class="card">
+				<h3>settings</h3>
+				<p>The real Settings window: a titled canvas window with a left section sidebar and a scrollable right pane. Network (NIC selection, DHCP, Wi-Fi scan/join/saved networks and details), Power (P-state modes, brightness, AC/battery), Date &amp; Time (RTC editor and SNTP), Appearance (desktop colour and an image picker for the wallpaper), Windows (soft shadows, edge snapping and drag resistance through <code>SYS_WM_PREFS</code>) and About (version, display, uptime, memory, CPU temperature). It is reused by the WM; a pill click focuses it and hands over the requested section.</p>
+			</div>
+			<div class="card">
+				<h3>netmenu</h3>
+				<p>The top-bar quick-settings popover: battery/AC and clock summary, a brightness slider and six launcher pills that open the matching Settings section.</p>
+			</div>
 			<div class="card">
 				<h3>clock / colors / settime</h3>
-				<p>Small canvas demos: an analog clock, a colour test window, and the standalone Date &amp; Time editor (<code>settime</code>). The control panel's Date &amp; Time tile reveals its own inline editor, which reads and writes the CMOS RTC and can fetch UTC from an SNTP server.</p>
+				<p>Small canvas demos: an analog clock, a colour test window, and the standalone Date &amp; Time editor (<code>settime</code>). The Settings app's Date &amp; Time page has the same editor, which reads and writes the CMOS RTC and can fetch UTC from an SNTP server.</p>
 			</div>
 			<div class="card">
 				<h3>browser</h3>
@@ -680,7 +702,7 @@
 		<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. <code>SYS_BACKLIGHT</code> gives ring 3 the same get/set/step, which drives the control panel's brightness slider. 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>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. <code>SYS_BACKLIGHT</code> gives ring 3 the same get/set/step, which drives the quick-settings popover's brightness slider and the Settings Power page. 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>
@@ -697,7 +719,8 @@
 			<li><code>kernel/wm.c</code>, <code>kernel/wm.h</code>, <code>include/wm_abi.h</code> — kernel window server and shared ABI</li>
 			<li><code>kernel/init.c</code>, <code>kernel/init.h</code> — starts PID 1; init is the only WM creator</li>
 			<li><code>user/apps/wm/ucmd_wm.c</code>, <code>user/lib/uwm/uwm_lib.c</code> — ring-3 WM</li>
-			<li><code>user/apps/netmenu/ucmd_netmenu.c</code> — top-bar control panel (network/WiFi, brightness, power mode, Date &amp; Time)</li>
+			<li><code>user/apps/netmenu/ucmd_netmenu.c</code> — top-bar quick-settings popover (summary, brightness and the Settings section pills)</li>
+			<li><code>user/apps/settings/ucmd_settings.c</code> — titled Settings window: Network, Power, Date &amp; Time, Appearance (wallpaper picker), Windows preferences and About</li>
 			<li><code>user/apps/settime/ucmd_settime.c</code>, <code>kernel/rtc.c</code>, <code>kernel/ntp.c</code> — Date &amp; Time editor, RTC access and SNTP sync</li>
 			<li><code>kernel/gfx.c</code>, <code>kernel/gfx.h</code> — RGB565 window canvases</li>
 			<li><code>kernel/sys_wm.c</code>, <code>kernel/sys_wm.h</code> — WM/window ABI</li>

+ 2 - 2
docs/index.html

@@ -212,12 +212,12 @@
 			</a>
 			<a class="card" href="graphics.html">
 				<h3>Graphics &amp; UI</h3>
-				<p>VBE framebuffer, shadow buffer, damage rectangles, compositor, canvas ABI, ngui, the Adwaita UI icons and mouse cursors, the fixed-point TrueType text engine and image codecs.</p>
+				<p>VBE framebuffer, shadow buffer, damage rectangles, compositor, canvas ABI, ngui, the Settings window, the Adwaita UI icons and mouse cursors, the fixed-point TrueType text engine and image codecs.</p>
 				<span class="card-tag">graphics.html</span>
 			</a>
 			<a class="card" href="network.html">
 				<h3>Networking</h3>
-				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3/1.2, USB tethering, WiFi, the top-bar control panel, netconsole and netkexec.</p>
+				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3/1.2, USB tethering, WiFi, the Settings app's network pages, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 			</a>
 			<a class="card" href="drivers.html#wifi">

+ 23 - 20
docs/network.html

@@ -146,18 +146,20 @@
 		<p>
 			The right top-bar status area (network, battery, clock and
 			temperature) is one button that opens
-			<span class="file">ucmd_netmenu.c</span>, the control panel.  The
-			network settings stay collapsed until its Network pill is clicked;
-			the section then asks the kernel for every present driver through
-			<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 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
-			strongest entry (the active BSSID wins when connected), and hidden
-			SSIDs are omitted because the menu cannot join them.
+			<span class="file">ucmd_netmenu.c</span>, the quick-settings
+			popover.  Its Network pill asks the WM to open (or focus)
+			<span class="file">ucmd_settings.c</span> at the Network
+			section.  That page asks the kernel for every present driver
+			through <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 page 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 strongest entry (the active BSSID wins when
+			connected), and hidden SSIDs are omitted because the page cannot
+			join them.
 		</p>
 		<p>
 			<span class="file">rndis.c</span> is the USB tethering path, not a
@@ -188,19 +190,20 @@
 			Data frames are converted between Ethernet and non-QoS 802.11 +
 			LLC/SNAP; EAPOL (ethertype <code>0x888e</code>) never reaches
 			<code>net_pump()</code> and is queued for the supplicant instead.
-			The top-bar control panel starts the same supplicant through
-			<code>wifi connectfile &lt;path&gt;</code>: it stages the SSID,
-			passphrase and BSSID in a small <code>/share/netmenu.wifi</code>
-			record because a <code>SYS_SPAWN</code> argument is limited to
+			The Settings window's Network page starts the same supplicant
+			through <code>wifi connectfile &lt;path&gt;</code>: it stages the
+			SSID, passphrase and BSSID in a small
+			<code>/share/netmenu.wifi</code> record because a
+			<code>SYS_SPAWN</code> argument is limited to
 			<code>VFS_PATH_MAX</code> (64) bytes. The helper removes the file
 			after reading it.
 		</p>
 		<p>
-			A successful <code>wifi connect</code> (from the CLI or the menu) adds
+			A successful <code>wifi connect</code> (from the CLI or Settings) 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 control panel marks every scanned SSID that is in the
+			partition. The Settings page 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
@@ -508,7 +511,7 @@
 					<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>/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>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>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 Settings <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>
@@ -524,7 +527,7 @@
 			<li><code>kernel/e1000e.c</code>, <code>kernel/r8168.c</code>, <code>kernel/ne2000.c</code>, <code>kernel/asix.c</code>, <code>kernel/rndis.c</code></li>
 			<li><code>kernel/wifi.c</code>, <code>kernel/wifi_fw.c</code>, <code>kernel/iwl_mvm.c</code>, <code>kernel/iwl_dvm.c</code>, <code>kernel/iwl_trans.c</code>, <code>kernel/rtl8821au.c</code> — Intel 7265D/3165 and 6200/6300 WiFi, Realtek RTL8821AU USB WiFi</li>
 			<li><code>user/lib/wifi/wpa.c</code>, <code>user/lib/tls/wpa_crypto.c</code>, <code>user/apps/wifi/ucmd_wifi.c</code> — WPA2-PSK supplicant and the <code>wifi</code> command (<code>make test-wpa</code>)</li>
-			<li><code>user/apps/netmenu/ucmd_netmenu.c</code>, <code>include/wifi_cfg.h</code>, <code>user/lib/wifi/wifi_store.c/h</code> — top-bar control panel, staged WiFi connect request and the saved-network list</li>
+			<li><code>user/apps/netmenu/ucmd_netmenu.c</code>, <code>user/apps/settings/ucmd_settings.c</code>, <code>include/wifi_cfg.h</code>, <code>user/lib/wifi/wifi_store.c/h</code> — top-bar quick popover, Settings window (NIC/WiFi pages), staged WiFi connect request and the saved-network list</li>
 			<li><code>kernel/net.c</code>, <code>kernel/net.h</code> — ARP cache/ICMP/UDP/IP</li>
 			<li><code>kernel/netcore.c</code>, <code>kernel/netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>kernel/dhcp.c</code>, <code>kernel/dns.c</code>, <code>kernel/ntp.c</code></li>

+ 9 - 6
docs/userland.html

@@ -325,12 +325,13 @@
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
 					<tr><td>WiFi</td><td>110</td><td><code>SYS_WIFI(op, a2, a3)</code>: up, status, scan/results, connect/disconnect, EAPOL RX/TX, set key, authorize, set/get PTK for the rekey helper (<span class="file">wifi.c</span>)</td></tr>
 					<tr><td>NIC menu</td><td>111–112</td><td><code>SYS_NET_DEVLIST</code> (present drivers with kind/active/link) and <code>SYS_NET_SELECT</code> (make a named netdev active)</td></tr>
-					<tr><td>Hardware settings</td><td>113–114</td><td><code>SYS_BACKLIGHT(op, value)</code> get/set/step the panel PWM, <code>SYS_CPUFREQ(mode)</code> get/set the P-state mode (control panel sliders/tiles)</td></tr>
-					<tr><td>Popover layout</td><td>115–116</td><td><code>SYS_WIN_RESIZE_SELF(w, h)</code> resizes the caller's canvas, <code>SYS_SCREEN_INFO(out)</code> returns the framebuffer dimensions (the control panel collapses/grows)</td></tr>
+					<tr><td>Hardware settings</td><td>113–114</td><td><code>SYS_BACKLIGHT(op, value)</code> get/set/step the panel PWM, <code>SYS_CPUFREQ(mode)</code> get/set the P-state mode (Settings sliders/tiles)</td></tr>
+					<tr><td>Popover layout</td><td>115–116</td><td><code>SYS_WIN_RESIZE_SELF(w, h)</code> resizes the caller's canvas, <code>SYS_SCREEN_INFO(out)</code> returns the framebuffer dimensions (apps size their windows from it)</td></tr>
 					<tr><td>Boot log</td><td>122</td><td><code>SYS_BOOTLOG(STAT|READ, ...)</code> returns the ring counters or one 1 KB chunk of the <code>bootscan</code> thread's captured COM1 output (the <code>bootscan</code> window)</td></tr>
 					<tr><td>Storage</td><td>119–120</td><td><code>SYS_BLK_READ(index, lba, buf)</code> reads one raw sector, <code>SYS_MOUNT_CTL(op, ...)</code> sets/gets a mount policy (name, read-only, no automount); used by <code>disks</code></td></tr>
 					<tr><td>Mouse cursor</td><td>117–118, 121</td><td><code>SYS_WIN_SET_CURSOR(shape)</code> sets the caller's content cursor, <code>SYS_WM_SET_CURSOR(shape | -1)</code> is the WM's override for its chrome, and <code>SYS_WM_MOUSE_CAPTURE(on)</code> takes/releases the pointer while the WM drags or resizes a window (shapes in <span class="file">cursor_abi.h</span>)</td></tr>
 					<tr><td>Wallpaper</td><td>123</td><td><code>SYS_WM_WALLPAPER(1)</code> bumps <code>wm_status.wallpaper_seq</code> after a client writes the RGB565 wallpaper file; the WM reloads it and repaints the desktop</td></tr>
+					<tr><td>Settings</td><td>128–129</td><td><code>SYS_WM_PREFS(GET|SET, struct wm_prefs *)</code> exchanges the live WM preferences (shadows, edge snapping, drag resistance and desktop colour); <code>SYS_WM_OPEN_SETTINGS(section)</code> asks the WM to open or focus <code>bin/settings</code> at a section</td></tr>
 				</tbody>
 			</table>
 		</div>
@@ -426,7 +427,7 @@
 			</div>
 			<div class="card">
 				<h3>Network</h3>
-				<p><code>netinfo</code> <code>netip</code> <code>netdns</code> <code>host</code> <code>dhcp</code> <code>ping</code> <code>pong</code> <code>netsend</code> <code>netrecv</code> <code>netlog</code> <code>netconsole</code> <code>netregs</code> <code>netloop</code> <code>netreset</code> <code>net100</code> <code>netmac</code> <code>curl</code> <code>websrv</code> <code>wifi</code> <code>netmenu</code></p>
+				<p><code>netinfo</code> <code>netip</code> <code>netdns</code> <code>host</code> <code>dhcp</code> <code>ping</code> <code>pong</code> <code>netsend</code> <code>netrecv</code> <code>netlog</code> <code>netconsole</code> <code>netregs</code> <code>netloop</code> <code>netreset</code> <code>net100</code> <code>netmac</code> <code>curl</code> <code>websrv</code> <code>wifi</code> <code>netmenu</code> <code>settings</code></p>
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
@@ -463,8 +464,9 @@
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback. Its <em>Background</em> button (or <code>b</code>) cover-scales the image to a screen-aspect RGB565 wallpaper, writes <code>/data/WALLPAPR.BIN</code> when the data volume is mounted (otherwise the RAM-only <code>/share/wallpaper</code>), and signals the WM; the status bar reports the result.</li>
 			<li><strong>edit</strong> — text editor that draws its own text with the 8x16 font.</li>
 			<li><strong>clock</strong> / <strong>colors</strong> — small window canvas demos.</li>
-			<li><strong>settime</strong> — the standalone Date &amp; Time editor (the control panel has an inline editor on its Date &amp; Time tile). It reads and writes the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code>; the <em>Sync NTP</em> button asks the kernel's SNTP client (<code>SYS_NTP_SYNC</code>, 106) for UTC and writes the result to the RTC. The two-digit RTC year is expanded over 1970–2069 so dead-battery defaults such as 1980/1990 can be corrected.</li>
-			<li><strong>netmenu</strong> — the top-bar control panel, opened by clicking anywhere in the right top-bar status area (temperature, date/time, network and AC/battery items). It is a chromeless <code>WIN_F_POPOVER</code> canvas window, anchored flush under the bar at the right screen edge, dismissed by a click outside or <code>Esc</code>, and has no title bar, shadow or rounded outer corners. It opens collapsed: the battery/AC and clock summary, a brightness slider when the panel PWM is present, and Quick settings pills for Network, the P-state power mode (<code>SYS_CPUFREQ</code>) and Date &amp; Time. Clicking a pill expands that section in place and grows the window with <code>SYS_WIN_RESIZE_SELF</code>; the network section has the connection status card and NIC/WiFi lists, the power section has the three modes, and the date section has an inline editor (Set/Now/Sync NTP) instead of opening <code>settime</code>. It lists the present NICs from <code>SYS_NET_DEVLIST</code> (Ethernet, USB Ethernet, RNDIS tethering), selects one with <code>SYS_NET_SELECT</code> and runs DHCP. Its WiFi section scans through <code>SYS_WIFI_SCAN</code>/<code>RESULTS</code>, asks for a WPA2 passphrase when the network is not saved and starts the <code>wifi</code> helper through a <code>/share/netmenu.wifi</code> request, because the 64-byte <code>SYS_SPAWN</code> argument cannot hold a long SSID plus passphrase. Networks in <code>/data/WIFI.CFG</code> are marked <em>saved</em> and join with the stored passphrase; a <em>Saved</em> view lists them with a <em>Forget</em> button each. A Connection section shows IP, gateway, DNS and MAC. On success the helper moves the SSID/passphrase to the front of the saved list; the next boot's <code>wifi autoconnect</code> helper joins any saved network found. Duplicate BSSIDs for one SSID are collapsed to the strongest entry (or the active one), and hidden networks are omitted.</li>
+			<li><strong>settime</strong> — the standalone Date &amp; Time editor (the Settings app has the same editor on its Date &amp; Time page). It reads and writes the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code>; the <em>Sync NTP</em> button asks the kernel's SNTP client (<code>SYS_NTP_SYNC</code>, 106) for UTC and writes the result to the RTC. The two-digit RTC year is expanded over 1970–2069 so dead-battery defaults such as 1980/1990 can be corrected.</li>
+			<li><strong>netmenu</strong> — the top-bar quick-settings popover, opened by clicking anywhere in the right top-bar status area (temperature, date/time, network and AC/battery items). It is a chromeless <code>WIN_F_POPOVER</code> canvas window, anchored flush under the bar at the right screen edge and dismissed by a click outside or <code>Esc</code>. It shows the battery/AC and clock summary, a brightness slider when the panel PWM is present, and six pills: Network, Power, Date &amp; Time, Appearance, Windows and About. A pill is a launcher: it calls <code>SYS_WM_OPEN_SETTINGS(section)</code>, the WM opens or focuses <code>bin/settings</code> at that section, and the popover closes. All editors and lists now live in the Settings window.</li>
+			<li><strong>settings</strong> — the real Settings window (start menu <em>Settings</em>, dock <em>Settings</em>, or <code>settings [section]</code>): a titled canvas window with a left section sidebar and a scrollable right pane. <em>Network</em> lists the present NICs from <code>SYS_NET_DEVLIST</code> (Ethernet, USB Ethernet, RNDIS tethering), selects one with <code>SYS_NET_SELECT</code> and runs DHCP, scans Wi-Fi through <code>SYS_WIFI_SCAN</code>/<code>RESULTS</code>, asks for a WPA2 passphrase (staged in <code>/share/netmenu.wifi</code> because the <code>SYS_SPAWN</code> argument is too short for an SSID plus passphrase), joins saved networks from <code>/data/WIFI.CFG</code>, can forget entries, and shows IP/gateway/DNS/MAC. <em>Power</em> offers the three <code>SYS_CPUFREQ</code> modes, a brightness slider when available and the AC/battery state. <em>Date &amp; Time</em> edits the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SET</code> and syncs UTC with <code>SYS_NTP_SYNC</code>. <em>Appearance</em> selects the desktop colour and a wallpaper image through an in-app file picker that browses the VFS mounts and decodes the chosen image with the image library into the same pre-scaled <code>WALLPAPR.BIN</code>/<code>/share/wallpaper</code> format the viewer uses. <em>Windows</em> toggles soft window shadows, edge snapping and drag resistance; the changes go through <code>SYS_WM_PREFS</code>, apply immediately, and are persisted in <code>/data/SETTINGS.CFG</code> (or <code>/share/settings.cfg</code>). <em>About</em> shows the OS version, display size, uptime, memory and CPU temperature. A second launch is not a second window: the WM focuses the existing one and writes the requested section to <code>/share/settings.req</code>, which the app polls and consumes.</li>
 			<li><strong>wm</strong> / <strong>term</strong> — the ring-3 window manager and terminal launcher used by the desktop.</li>
 		</ul>
 		<p>
@@ -562,7 +564,8 @@
 			<li><code>user/apps/disks/ucmd_disks.c</code> — storage manager</li>
 			<li><code>user/apps/process/ucmd_process.c</code> — graphical task manager and its history graphs</li>
 			<li><code>user/apps/bootscan/ucmd_bootscan.c</code> — live boot-scan log window (<code>SYS_BOOTLOG</code>, <code>kernel/bootcon.c</code>)</li>
-			<li><code>user/apps/netmenu/ucmd_netmenu.c</code>, <code>include/wifi_cfg.h</code>, <code>user/lib/wifi/wifi_store.c/h</code> — top-bar control panel, staged WiFi connect record and saved-network list</li>
+			<li><code>user/apps/netmenu/ucmd_netmenu.c</code> — top-bar quick-settings popover</li>
+			<li><code>user/apps/settings/ucmd_settings.c</code>, <code>user/apps/wifi/ucmd_wifi.c</code>, <code>include/wifi_cfg.h</code>, <code>user/lib/wifi/wifi_store.c/h</code> — Settings window, WiFi supplicant, staged WiFi connect record and saved-network list</li>
 		</ul>
 	</section>
 </main>

+ 7 - 0
include/syscall.h

@@ -290,6 +290,13 @@ struct sys_spawn {
 #define SYS_TTY_CLOSE     126 /* (id) -> 0/-1; owner only */
 #define SYS_IS_INIT       127 /* () -> 1 when the caller is the kernel's init */
 
+/* Window-manager preferences (SYS_WM_PREFS: op 0 = struct wm_prefs *out,
+ * op 1 = const struct wm_prefs *in) and the Settings launcher request. */
+#define SYS_WM_PREFS       128
+#define SYS_WM_PREFS_GET   0
+#define SYS_WM_PREFS_SET   1
+#define SYS_WM_OPEN_SETTINGS 129 /* (int WM_SETTINGS_* section) -> 0/-1 */
+
 struct sys_netinfo {
 	unsigned int present;
 	unsigned char mac[6];

+ 46 - 0
include/wm_abi.h

@@ -40,6 +40,45 @@
 #define WM_KIND_NONE 0
 #define WM_KIND_GFX  1
 
+/* Settings sections.  The control-center popover's pills ask the WM to open
+ * one of these in the Settings app, and the app's sidebar uses the same
+ * order. */
+#define WM_SETTINGS_NETWORK    0
+#define WM_SETTINGS_POWER      1
+#define WM_SETTINGS_DATETIME   2
+#define WM_SETTINGS_APPEARANCE 3
+#define WM_SETTINGS_WINDOWS    4
+#define WM_SETTINGS_ABOUT      5
+#define WM_SETTINGS_COUNT      6
+
+/* Persistent window-manager preferences.  The Settings app writes this
+ * structure to a small file on /data (or /share before the data volume is
+ * mounted) and pushes it through SYS_WM_PREFS, so a running WM applies the
+ * change immediately and a restarted WM can restore it. */
+#define WM_DEFAULT_BG_RGB 0x202030u
+
+struct wm_prefs {
+	unsigned int shadow;       /* 1 = soft window shadows */
+	unsigned int snap;         /* 1 = snap to screen edges on drop */
+	unsigned int resist;       /* 1 = edge resistance while dragging */
+	unsigned int bg_rgb;       /* desktop colour without a wallpaper */
+	unsigned int reserved[4];
+};
+
+#define WM_PREFS_MAGIC   "NBSET1\0\0"
+#define WM_PREFS_VERSION 1u
+#define WM_PREFS_DATA    "/data/SETTINGS.CFG"
+#define WM_PREFS_SHARE   "/share/settings.cfg"
+/* The WM writes the requested section here before focusing an already
+ * running Settings window; the app polls it and switches panes. */
+#define WM_SETTINGS_REQUEST "/share/settings.req"
+
+struct wm_prefs_file {
+	char magic[8];
+	unsigned int version;
+	struct wm_prefs prefs;
+};
+
 /* 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. */
@@ -75,6 +114,13 @@ struct wm_status {
 	/* Bumped when a client installs a new wallpaper (SYS_WM_WALLPAPER);
 	 * the WM reloads its copy when this changes. */
 	unsigned int wallpaper_seq;
+	/* Current preferences and a change counter (SYS_WM_PREFS). */
+	unsigned int prefs_seq;
+	struct wm_prefs prefs;
+	/* A client asked the WM to open Settings at a section
+	 * (SYS_WM_OPEN_SETTINGS); the sequence makes every request visible. */
+	unsigned int settings_req_seq;
+	unsigned int settings_req_section;
 };
 
 /* Wallpaper file: one header followed by tightly packed RGB565 pixels,

+ 29 - 0
kernel/sys_wm.c

@@ -3,6 +3,7 @@
  * a buggy WM returns -1 instead of faulting in ring 0. */
 
 #include "sys_wm.h"
+#include "syscall.h"
 #include "paging.h"
 #include "process.h"
 #include "wm.h"
@@ -317,3 +318,31 @@ int sys_wm_wallpaper(int op)
 	wm_server_wallpaper_changed();
 	return 0;
 }
+
+int sys_wm_prefs(int op, void *arg)
+{
+	struct wm_prefs p;
+
+	if (op == SYS_WM_PREFS_GET) {
+		if (!user_ok(arg, sizeof(p), 1))
+			return -1;
+		if (wm_server_prefs_get(&p) != 0)
+			return -1;
+		copy_to_user(arg, &p, sizeof(p));
+		return 0;
+	}
+	if (op == SYS_WM_PREFS_SET) {
+		if (!user_ok(arg, sizeof(p), 0))
+			return -1;
+		copy_from_user(&p, arg, sizeof(p));
+		return wm_server_prefs_set(&p);
+	}
+	return -1;
+}
+
+int sys_wm_open_settings(int section)
+{
+	if (section < 0 || section >= WM_SETTINGS_COUNT)
+		return -1;
+	return wm_server_open_settings((unsigned int)section);
+}

+ 2 - 0
kernel/sys_wm.h

@@ -33,6 +33,8 @@ int sys_win_set_cursor(int shape);
 int sys_wm_set_cursor(int shape);
 int sys_wm_mouse_capture(int on);
 int sys_wm_wallpaper(int op);
+int sys_wm_prefs(int op, void *arg);
+int sys_wm_open_settings(int section);
 
 /* Set once the first application window (the boot terminal) has presented
  * a frame; kernel_main waits for it before the USB bring-up. */

+ 4 - 0
kernel/syscall.c

@@ -364,6 +364,10 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_wm_mouse_capture((int)a1);
 	case SYS_WM_WALLPAPER:
 		return sys_wm_wallpaper((int)a1);
+	case SYS_WM_PREFS:
+		return sys_wm_prefs((int)a1, (void *)a2);
+	case SYS_WM_OPEN_SETTINGS:
+		return sys_wm_open_settings((int)a1);
 	case SYS_SCREEN_INFO: {
 		struct sys_screen *out = (struct sys_screen *)a1;
 

+ 55 - 0
kernel/wm.c

@@ -52,6 +52,15 @@ static int wm_frame_active;
 static int wm_first_frame;
 static int wm_boot_ready;
 static unsigned int wm_wallpaper_seq;
+/* Settings live here so they survive a WM restart; the Settings app and the
+ * WM exchange them through SYS_WM_PREFS.  Defaults match the old hardcoded
+ * ring-3 WM behaviour. */
+static struct wm_prefs wm_prefs = {
+	1, 1, 1, WM_DEFAULT_BG_RGB, { 0, 0, 0, 0 }
+};
+static unsigned int wm_prefs_seq;
+static unsigned int wm_settings_req_seq;
+static unsigned int wm_settings_req_section;
 static unsigned int wm_last_seen;
 
 static inline unsigned int irq_save_disable(void)
@@ -1172,6 +1181,10 @@ int wm_server_poll(struct wm_status *out)
 		out->backlight_seq = backlight_seq();
 	}
 	out->wallpaper_seq = wm_wallpaper_seq;
+	out->prefs_seq = wm_prefs_seq;
+	out->prefs = wm_prefs;
+	out->settings_req_seq = wm_settings_req_seq;
+	out->settings_req_section = wm_settings_req_section;
 	wm_full_redraw = 0;
 	return 0;
 }
@@ -1188,6 +1201,48 @@ void wm_server_wallpaper_changed(void)
 	wm_wallpaper_seq++;
 }
 
+static void wm_prefs_sanitize(struct wm_prefs *p)
+{
+	unsigned int i;
+
+	p->shadow = p->shadow ? 1u : 0u;
+	p->snap = p->snap ? 1u : 0u;
+	p->resist = p->resist ? 1u : 0u;
+	p->bg_rgb &= 0x00FFFFFFu;
+	for (i = 0; i < sizeof(p->reserved) / sizeof(p->reserved[0]); i++)
+		p->reserved[i] = 0;
+}
+
+int wm_server_prefs_get(struct wm_prefs *out)
+{
+	if (!out)
+		return -1;
+	*out = wm_prefs;
+	return 0;
+}
+
+int wm_server_prefs_set(const struct wm_prefs *in)
+{
+	struct wm_prefs p;
+
+	if (!in)
+		return -1;
+	p = *in;
+	wm_prefs_sanitize(&p);
+	wm_prefs = p;
+	wm_prefs_seq++;
+	return 0;
+}
+
+int wm_server_open_settings(unsigned int section)
+{
+	if (section >= WM_SETTINGS_COUNT)
+		return -1;
+	wm_settings_req_section = section;
+	wm_settings_req_seq++;
+	return 0;
+}
+
 int wm_server_begin(void)
 {
 	if (!wm_server_is_wm() || wm_frame_active)

+ 3 - 0
kernel/wm.h

@@ -94,6 +94,9 @@ int  wm_server_win_set_cursor(int shape);
 int  wm_server_set_cursor(int shape);
 int  wm_server_set_pointer_capture(int on);
 void wm_server_wallpaper_changed(void);
+int  wm_server_prefs_get(struct wm_prefs *out);
+int  wm_server_prefs_set(const struct wm_prefs *in);
+int  wm_server_open_settings(unsigned int section);
 void wm_server_boot_ready(void);
 struct window *wm_focused_window(void);
 int  wm_is_focused(const struct window *w);

Fișier diff suprimat deoarece este prea mare
+ 52 - 1077
user/apps/netmenu/ucmd_netmenu.c


+ 2929 - 0
user/apps/settings/ucmd_settings.c

@@ -0,0 +1,2929 @@
+/* settings: the real Settings window.
+ *
+ * A normal titled canvas window with a section sidebar on the left and the
+ * selected page on the right:
+ *
+ *   Network     NIC selection, DHCP, Wi-Fi scan/join/saved networks and the
+ *               current connection details
+ *   Power       P-state mode, panel brightness and AC/battery state
+ *   Date & Time CMOS clock editor and SNTP sync
+ *   Appearance  desktop colour and a wallpaper image picker
+ *   Windows     window shadows, edge snapping and drag resistance
+ *   About       version, screen, memory and temperature
+ *
+ * The top-bar control-center popover's pills call SYS_WM_OPEN_SETTINGS, but
+ * a running Settings window is reused: the WM focuses it and writes the
+ * requested section to WM_SETTINGS_REQUEST, which this app polls.  Window
+ * preferences are pushed through SYS_WM_PREFS and persisted in
+ * /data/SETTINGS.CFG (or /share/settings.cfg before the data volume is
+ * mounted), so the ring-3 WM applies them immediately and after a restart. */
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+#include "img.h"
+#include "img_file.h"
+#include "wifi_store.h"
+#include "version.h"
+
+#define MAX_DEVS 8
+#define MAX_BSS  32
+
+#define SIDEBAR_W      190
+#define SIDEBAR_MIN_W  154
+#define NAV_ROW_H      44
+#define NAV_GAP        4
+#define HEADER_H       54
+#define FOOTER_H       28
+#define SECTION_H      28
+#define GAP            10
+#define CARD_H         64
+#define DEV_ROW_H      42
+#define BSS_ROW_H      42
+#define INFO_ROW_H     30
+#define SAVED_ROW_H    42
+#define STATUS_MS      6000
+
+#define PICK_MAX       96
+#define PICK_ROW_H     38
+#define PICK_PATH_MAX  256
+#define WALL_FILE_CAP  (4u * 1024u * 1024u)
+#define WALL_HEAP_CAP  (24u * 1024u * 1024u)
+
+#define ID_NAV_BASE     10
+#define ID_NET_REFRESH  100
+#define ID_NET_SCAN     101
+#define ID_NET_DISCONNECT 102
+#define ID_NET_SAVED    103
+#define ID_NET_SAVED_BACK 104
+#define ID_NET_PASS_INPUT 105
+#define ID_NET_PASS_OK  106
+#define ID_NET_PASS_CANCEL 107
+#define ID_NET_CONN_CANCEL 108
+#define ID_DEV_BASE     120
+#define ID_BSS_BASE     140
+#define ID_INFO_BASE    180
+#define ID_SAVED_ROW_BASE 200
+#define ID_SAVED_FORGET_BASE 230
+#define ID_POWER_MODE_BASE 300
+#define ID_BRIGHTNESS   310
+#define ID_DATE_FIELD   400
+#define ID_TIME_FIELD   401
+#define ID_NTP_FIELD    402
+#define ID_DATE_SET     403
+#define ID_DATE_NOW     404
+#define ID_DATE_NTP     405
+#define ID_BG_BASE      500
+#define ID_WALL_CHOOSE  540
+#define ID_WALL_REMOVE  541
+#define ID_PICK_UP      550
+#define ID_PICK_CANCEL  551
+#define ID_PICK_ROW_BASE 600
+#define ID_WIN_SHADOW   750
+#define ID_WIN_SNAP     751
+#define ID_WIN_RESIST   752
+
+enum {
+	SEC_NETWORK,
+	SEC_POWER,
+	SEC_DATETIME,
+	SEC_APPEARANCE,
+	SEC_WINDOWS,
+	SEC_ABOUT,
+	SEC_COUNT
+};
+
+enum {
+	NET_MAIN,
+	NET_PASS,
+	NET_CONNECT,
+	NET_SAVED
+};
+
+enum {
+	A_NONE = 0,
+	A_NAV,
+	A_REFRESH,
+	A_SCAN,
+	A_DISCONNECT,
+	A_DEV,
+	A_BSS,
+	A_SAVED,
+	A_SAVED_BACK,
+	A_FORGET,
+	A_PASS_OK,
+	A_PASS_CANCEL,
+	A_CONN_CANCEL,
+	A_POWER,
+	A_DATE_SET,
+	A_DATE_NOW,
+	A_DATE_NTP,
+	A_BG,
+	A_WALL_CHOOSE,
+	A_WALL_REMOVE,
+	A_PICK_UP,
+	A_PICK_CANCEL,
+	A_PICK_ROW,
+	A_WIN_SHADOW,
+	A_WIN_SNAP,
+	A_WIN_RESIST
+};
+
+struct section_info {
+	const char *label;
+	const char *subtitle;
+	const char *arg;
+};
+
+static const struct section_info sections[SEC_COUNT] = {
+	{ "Network",     "Devices and Wi-Fi",      "network" },
+	{ "Power",       "Mode and brightness",    "power" },
+	{ "Date & Time", "Clock and time sync",    "time" },
+	{ "Appearance",  "Desktop background",     "appearance" },
+	{ "Windows",     "Shadows and snapping",   "windows" },
+	{ "About",       "System information",     "about" }
+};
+
+struct bg_choice {
+	const char *name;
+	unsigned int rgb;
+};
+
+static const struct bg_choice bg_choices[] = {
+	{ "Midnight",  0x202030u },
+	{ "Deep blue", 0x152238u },
+	{ "Forest",    0x18281Cu },
+	{ "Plum",      0x2A1A2Eu },
+	{ "Cocoa",     0x2C2118u },
+	{ "Graphite",  0x222428u },
+	{ "Slate",     0x23303Au },
+	{ "Wine",      0x301A22u }
+};
+#define NBG ((int)(sizeof(bg_choices) / sizeof(bg_choices[0])))
+
+static struct ngui ui;
+static int cur_section = SEC_NETWORK;
+static int quit;
+static int pending_action;
+static int pending_arg;
+static struct ngui_scroll content_scroll;
+static struct ngui_slider brightness_slider;
+static char status[160];
+static int status_error;
+static unsigned int status_until;
+static unsigned int last_status_ms;
+static unsigned int last_request_ms;
+
+static struct wm_prefs prefs;
+
+/* Network state. */
+static struct sys_netdev devs[MAX_DEVS];
+static int ndev;
+static int devs_loaded;
+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;
+static int wifi_checked;
+static int wifi_present;
+static int net_view = NET_MAIN;
+static int sel_bss = -1;
+static char sel_ssid[33];
+static int scanning;
+static unsigned int scan_start;
+static int connect_pid = -1;
+static int connect_tty;
+static unsigned int connect_start;
+static char conn_log[2048];
+static unsigned int conn_log_len;
+static struct ngui_input pass_in;
+
+/* Power state. */
+static int brightness = -1;
+static int cpufreq_mode = -1;
+static struct sys_powerinfo powerinfo;
+static int power_ok;
+
+/* Clock state. */
+static struct sys_datetime now;
+static int now_ok;
+static int date_loaded;
+static struct ngui_input date_in;
+static struct ngui_input time_in;
+static struct ngui_input ntp_in;
+
+/* Appearance state. */
+static int wallpaper_present;
+static char wallpaper_source[32];
+static int picker_mode;
+static char pick_path[PICK_PATH_MAX];
+static char pick_names[PICK_MAX][64];
+static unsigned int pick_sizes[PICK_MAX];
+static unsigned char pick_dirs[PICK_MAX];
+static int pick_count;
+static struct ngui_scroll picker_scroll;
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void settings_draw_frame(void);
+static void draw_picker(struct ngui_rect area, int *yy);
+static void set_wallpaper_file(const char *path);
+
+static int s_eq(const char *a, const char *b)
+{
+	while (*a && *a == *b) {
+		a++;
+		b++;
+	}
+	return *a == *b;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static char *s_put(char *p, const char *s)
+{
+	while (s && *s)
+		*p++ = *s++;
+	return p;
+}
+
+static char *s_put_dec(char *p, unsigned int v)
+{
+	char b[10];
+	unsigned int n = 0;
+
+	do {
+		b[n++] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v);
+	while (n)
+		*p++ = b[--n];
+	return p;
+}
+
+static char *s_put_2(char *p, unsigned int v)
+{
+	*p++ = (char)('0' + (v / 10) % 10);
+	*p++ = (char)('0' + v % 10);
+	return p;
+}
+
+static void set_status(const char *msg, int err)
+{
+	unsigned int i;
+
+	for (i = 0; msg && msg[i] && i + 1 < sizeof(status); i++)
+		status[i] = msg[i];
+	status[i] = '\0';
+	status_error = err;
+	status_until = msg && msg[0] ? u_ticks_ms() + STATUS_MS : 0;
+	ngui_invalidate(&ui);
+}
+
+static void request_action(int action, int arg)
+{
+	if (!pending_action) {
+		pending_action = action;
+		pending_arg = arg;
+	}
+}
+
+/* Paint the current state before a blocking action (DHCP, a WiFi scan or an
+ * NTP request), so the message and the pressed control are visible. */
+static void paint_current(void)
+{
+	if (ngui_begin(&ui)) {
+		settings_draw_frame();
+		ngui_end(&ui);
+	}
+}
+
+static int section_from_name(const char *name)
+{
+	int i;
+
+	if (!name || !name[0])
+		return SEC_NETWORK;
+	for (i = 0; i < SEC_COUNT; i++)
+		if (s_eq(name, sections[i].arg))
+			return i;
+	return SEC_NETWORK;
+}
+
+/* ------------------------------------------------------------------ */
+/* Window-manager preferences                                          */
+
+static void prefs_defaults(void)
+{
+	memset(&prefs, 0, sizeof(prefs));
+	prefs.shadow = 1;
+	prefs.snap = 1;
+	prefs.resist = 1;
+	prefs.bg_rgb = WM_DEFAULT_BG_RGB;
+}
+
+static int prefs_file_magic_ok(const struct wm_prefs_file *f)
+{
+	unsigned int i;
+
+	for (i = 0; i < sizeof(f->magic); i++)
+		if (f->magic[i] != WM_PREFS_MAGIC[i])
+			return 0;
+	return 1;
+}
+
+static int prefs_file_load(void)
+{
+	/* A FAT read may write a final partial sector past the requested
+	 * length, so keep a sector of slack around the header. */
+	unsigned char buf[sizeof(struct wm_prefs_file) + 512];
+	struct wm_prefs_file *f = (struct wm_prefs_file *)buf;
+	const char *paths[2] = { WM_PREFS_DATA, WM_PREFS_SHARE };
+	int i;
+
+	for (i = 0; i < 2; i++) {
+		int n = u_syscall3(SYS_READ_FILE, (int)paths[i], (int)buf,
+				   (int)sizeof(*f));
+
+		if (n < (int)sizeof(*f) || !prefs_file_magic_ok(f) ||
+		    f->version != WM_PREFS_VERSION)
+			continue;
+		prefs = f->prefs;
+		prefs.shadow = prefs.shadow ? 1u : 0u;
+		prefs.snap = prefs.snap ? 1u : 0u;
+		prefs.resist = prefs.resist ? 1u : 0u;
+		prefs.bg_rgb &= 0x00FFFFFFu;
+		memset(prefs.reserved, 0, sizeof(prefs.reserved));
+		return 0;
+	}
+	return -1;
+}
+
+static int prefs_file_save(void)
+{
+	struct wm_prefs_file f;
+	struct sys_stat st;
+	const char *path = WM_PREFS_SHARE;
+
+	memset(&f, 0, sizeof(f));
+	memcpy(f.magic, WM_PREFS_MAGIC, sizeof(f.magic));
+	f.version = WM_PREFS_VERSION;
+	f.prefs = prefs;
+	if (u_stat("/data", &st) == 0 && st.is_dir)
+		path = WM_PREFS_DATA;
+	return u_syscall3(SYS_WRITE_FILE, (int)path, (int)&f, (int)sizeof(f));
+}
+
+static void commit_prefs(const char *ok_msg)
+{
+	if (u_wm_set_prefs(&prefs) != 0) {
+		set_status("The window manager refused the settings", 1);
+		return;
+	}
+	if (prefs_file_save() < 0)
+		set_status("Applied, but the settings file could not be saved", 1);
+	else if (ok_msg && ok_msg[0])
+		set_status(ok_msg, 0);
+	else
+		set_status("Settings saved", 0);
+}
+
+/* ------------------------------------------------------------------ */
+/* Small drawing helpers                                               */
+
+static unsigned short rgb565(unsigned int rgb)
+{
+	return (unsigned short)((((rgb >> 16) & 0xFF) >> 3) << 11 |
+				(((rgb >> 8) & 0xFF) >> 2) << 5 |
+				((rgb & 0xFF) >> 3));
+}
+
+static void format_size(char *b, unsigned int bytes)
+{
+	char *p = b;
+
+	if (bytes >= 1024u * 1024u) {
+		p = s_put_dec(p, bytes / (1024u * 1024u));
+		p = s_put(p, " MB");
+	} else if (bytes >= 1024u) {
+		p = s_put_dec(p, (bytes + 1023u) / 1024u);
+		p = s_put(p, " KB");
+	} else {
+		p = s_put_dec(p, bytes);
+		p = s_put(p, " B");
+	}
+	*p = '\0';
+}
+
+/* One clickable settings row: an optional colour swatch, a title, a dim
+ * subtitle and a right-aligned value.  Mirrors the ngui list-row press /
+ * release semantics so clicks agree with the rest of the toolkit. */
+static int settings_row(unsigned int id, struct ngui_rect r,
+			const char *title, const char *subtitle,
+			const char *trailing, int selected, int swatch_rgb)
+{
+	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 = 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 (selected)
+		bg = ui.theme.selection;
+	else if (hot || ui.active == id)
+		bg = ui.theme.panel_alt;
+	if (bg)
+		ngui_fill_round_rect(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+				     NGUI_RADIUS, NGUI_RADIUS, bg);
+
+	if (swatch_rgb >= 0) {
+		struct ngui_rect sw = { left, r.y + (r.h - 16) / 2, 16, 16 };
+
+		ngui_fill_round_rect(&ui, sw, 4, 4, 4, 4,
+				     rgb565((unsigned int)swatch_rgb));
+		ngui_frame_round(&ui, sw, 4, 4, 4, 4, 1, ui.theme.border);
+		left += 26;
+	}
+
+	fg = ui.theme.text;
+	sub_fg = selected ? ui.theme.text : ui.theme.text_dim;
+	trail_fg = selected ? ui.theme.text : ui.theme.text_dim;
+	if (trailing && trailing[0]) {
+		int tw = (int)ngui_text_width_ui(&ui, trailing);
+
+		right -= tw + 8;
+		ngui_text_utf8(&ui, right + 8, r.y + (r.h - 16) / 2,
+			       trailing, trail_fg);
+	}
+	if (right <= left)
+		return fired;
+
+	title_h = ngui_text_line_height(&ui, ui.font_px, 0);
+	block_h = subtitle && 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, (struct ngui_rect){ left, r.y,
+					       right - left, r.h });
+	ngui_text_utf8(&ui, left, ty, title, fg);
+	if (subtitle && subtitle[0])
+		ngui_text_utf8(&ui, left, ty + title_h - 2, subtitle, sub_fg);
+	ngui_pop_clip(&ui);
+	if (hot) {
+		ui.hot = id;
+		ngui_set_cursor(&ui, CURSOR_POINTER);
+	}
+	return fired;
+}
+
+static int info_row(struct ngui_rect area, int *y, const char *label,
+		    const char *value)
+{
+	struct ngui_rect r = { area.x, *y, area.w, INFO_ROW_H };
+	int th = ngui_text_line_height(&ui, ui.font_px, 0);
+
+	ngui_text_utf8(&ui, r.x + 10, r.y + (r.h - th) / 2, label,
+		       ui.theme.text_dim);
+	ngui_text_utf8(&ui, r.x + r.w / 2, r.y + (r.h - th) / 2, value,
+		       ui.theme.text);
+	*y += INFO_ROW_H;
+	return 0;
+}
+
+/* ------------------------------------------------------------------ */
+/* Network                                                             */
+
+static void drain_tty(void)
+{
+	char buf[256];
+	int n;
+
+	if (connect_tty <= 0)
+		return;
+	while ((n = u_tty_read(connect_tty, buf, sizeof(buf))) > 0) {
+		int i;
+
+		for (i = 0; i < n; i++) {
+			if (conn_log_len + 1 >= sizeof(conn_log)) {
+				unsigned int half = sizeof(conn_log) / 2;
+				unsigned int j;
+
+				for (j = 0; j < half; j++)
+					conn_log[j] = conn_log[conn_log_len -
+								 half + j];
+				conn_log_len = half;
+			}
+			conn_log[conn_log_len++] = buf[i];
+		}
+		conn_log[conn_log_len] = '\0';
+		ngui_invalidate(&ui);
+	}
+}
+
+static void load_saved(void)
+{
+	int n = wifi_store_load(saved, WIFI_CFG_MAX);
+
+	if (n > WIFI_CFG_MAX)
+		n = 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" :
+	       s == SYS_WIFI_SEC_PSK ? "WPA2" : "unsupported";
+}
+
+static int rssi_bars(int rssi)
+{
+	if (rssi >= -55)
+		return 4;
+	if (rssi >= -65)
+		return 3;
+	if (rssi >= -75)
+		return 2;
+	return 1;
+}
+
+static int bss_is_active(const struct sys_wifi_bss *b)
+{
+	unsigned int i;
+
+	if (wst.state < SYS_WIFI_ST_ASSOC)
+		return 0;
+	for (i = 0; i < 6; i++)
+		if (wst.bssid[i] != b->bssid[i])
+			return 0;
+	return 1;
+}
+
+static void load_status(void)
+{
+	int i;
+
+	net_present = (u_net_info(&net) == 1 && net.present);
+	if (!wifi_checked || wifi_present) {
+		if (u_wifi(SYS_WIFI_STATUS, (int)&wst, 0) == 0) {
+			wifi_checked = 1;
+			wifi_present = wst.present != 0;
+		} else {
+			wifi_checked = 1;
+			wifi_present = 0;
+		}
+	}
+	for (i = 0; i < ndev; i++) {
+		devs[i].active = (net_present && s_eq(net.name, devs[i].name)) ?
+				 1u : 0u;
+		if (devs[i].active)
+			devs[i].link = net.link;
+	}
+	power_ok = (u_power_info(&powerinfo, 0) == 0);
+	now_ok = (u_rtc_get(&now) == 0);
+	brightness = u_backlight_get();
+	cpufreq_mode = u_cpufreq_get();
+}
+
+static void load_devices(void)
+{
+	int n = u_net_devlist(devs, MAX_DEVS);
+
+	if (n > MAX_DEVS)
+		n = MAX_DEVS;
+	ndev = n > 0 ? n : 0;
+	devs_loaded = 1;
+	load_status();
+}
+
+static void sort_bss(void)
+{
+	int i, j;
+
+	for (i = 1; i < nbss; i++)
+		for (j = i; j > 0 && bss[j].rssi > bss[j - 1].rssi; j--) {
+			struct sys_wifi_bss t = bss[j];
+
+			bss[j] = bss[j - 1];
+			bss[j - 1] = t;
+		}
+}
+
+static int same_ssid(const struct sys_wifi_bss *a,
+		     const struct sys_wifi_bss *b)
+{
+	unsigned int i;
+
+	if (a->ssid_len == 0 || a->ssid_len != b->ssid_len)
+		return 0;
+	for (i = 0; i < a->ssid_len; i++)
+		if (a->ssid[i] != b->ssid[i])
+			return 0;
+	return 1;
+}
+
+static void filter_bss(void)
+{
+	int i, j, out = 0;
+
+	for (i = 0; i < nbss; i++) {
+		int dup = -1;
+
+		if (bss[i].ssid_len == 0)
+			continue;
+		for (j = 0; j < out; j++)
+			if (bss[i].security == bss[j].security &&
+			    same_ssid(&bss[i], &bss[j])) {
+				dup = j;
+				break;
+			}
+		if (dup < 0) {
+			bss[out++] = bss[i];
+		} else if (bss_is_active(&bss[i]) &&
+			   !bss_is_active(&bss[dup])) {
+			bss[dup] = bss[i];
+		}
+	}
+	nbss = out;
+}
+
+static void ssid_name(const struct sys_wifi_bss *b, char out[33])
+{
+	unsigned int i, n = b->ssid_len;
+
+	if (n > 32)
+		n = 32;
+	for (i = 0; i < n; i++)
+		out[i] = (char)b->ssid[i];
+	out[n] = '\0';
+	if (!n) {
+		s_copy(out, "(hidden)", 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 start_scan(void)
+{
+	int r;
+
+	if (scanning || !wifi_present)
+		return;
+	set_status("Scanning for WiFi networks...", 0);
+	paint_current();
+	r = u_wifi(SYS_WIFI_SCAN, 0, 0);
+	if (r < 0) {
+		char m[64], *p;
+
+		u_wifi(SYS_WIFI_STATUS, (int)&wst, 0);
+		p = s_put(m, "WiFi: ");
+		p = s_put(p, wst.detail[0] ? wst.detail : "scan failed");
+		*p = '\0';
+		set_status(m, 1);
+		return;
+	}
+	scanning = 1;
+	scan_start = u_ticks_ms();
+	nbss = 0;
+	content_scroll.offset = 0;
+	ngui_invalidate(&ui);
+}
+
+static void poll_scan(void)
+{
+	int n;
+
+	if (!scanning)
+		return;
+	n = u_wifi(SYS_WIFI_RESULTS, (int)bss, MAX_BSS);
+	if (n == -2) {
+		if (u_ticks_ms() - scan_start > 15000) {
+			scanning = 0;
+			set_status("WiFi scan timed out", 1);
+		}
+		return;
+	}
+	scanning = 0;
+	if (n < 0) {
+		set_status("WiFi scan failed", 1);
+		return;
+	}
+	if (n > MAX_BSS)
+		n = MAX_BSS;
+	nbss = n;
+	sort_bss();
+	filter_bss();
+	if (nbss == 0)
+		set_status("No WiFi networks found", 1);
+	else
+		set_status("WiFi scan complete", 0);
+	ngui_invalidate(&ui);
+}
+
+static int write_wifi_cfg(const struct sys_wifi_bss *b, const char *pass)
+{
+	struct wifi_cfg cfg;
+	unsigned int i, n = s_len(pass);
+	int r;
+
+	memset(&cfg, 0, sizeof(cfg));
+	cfg.magic = WIFI_CFG_MAGIC;
+	cfg.ssid_len = b->ssid_len;
+	cfg.pass_len = (unsigned char)(n > 64 ? 64 : n);
+	for (i = 0; i < 6; i++)
+		cfg.bssid[i] = b->bssid[i];
+	for (i = 0; i < b->ssid_len && i < 32; i++)
+		cfg.ssid[i] = b->ssid[i];
+	for (i = 0; i < cfg.pass_len; i++)
+		cfg.pass[i] = pass[i];
+	r = u_syscall3(SYS_WRITE_FILE, (int)WIFI_CFG_STAGED,
+		       (int)&cfg, (int)sizeof(cfg));
+	memset(&cfg, 0, sizeof(cfg));
+	return r;
+}
+
+static void start_connect(const char *pass)
+{
+	struct sys_wifi_bss *b;
+	char msg[96], *p;
+	int pid;
+
+	if (sel_bss < 0 || sel_bss >= nbss)
+		return;
+	if (connect_pid > 0 && u_alive((unsigned int)connect_pid)) {
+		set_status("A WiFi connection is already in progress", 1);
+		return;
+	}
+	b = &bss[sel_bss];
+	ssid_name(b, sel_ssid);
+	if (write_wifi_cfg(b, pass) != 0) {
+		set_status("Cannot stage the WiFi request in /share", 1);
+		return;
+	}
+	if (connect_tty <= 0) {
+		connect_tty = u_tty_create();
+		if (connect_tty < 0)
+			connect_tty = 0;
+	}
+	conn_log_len = 0;
+	conn_log[0] = '\0';
+	connect_start = u_ticks_ms();
+
+	pid = u_spawn_detached("/ramfs/bin/wifi",
+			       "connectfile /share/netmenu.wifi",
+			       connect_tty, "/");
+	if (pid < 0) {
+		u_syscall1(SYS_UNLINK, (int)"/share/netmenu.wifi");
+		set_status("Cannot start the WiFi helper", 1);
+		return;
+	}
+	connect_pid = pid;
+	net_view = NET_CONNECT;
+	p = s_put(msg, "Connecting to \"");
+	p = s_put(p, sel_ssid);
+	p = s_put(p, "\"...");
+	*p = '\0';
+	set_status(msg, 0);
+}
+
+static void cancel_connect(void)
+{
+	if (connect_pid > 0 && u_alive((unsigned int)connect_pid))
+		u_kill((unsigned int)connect_pid);
+	connect_pid = -1;
+	u_wifi(SYS_WIFI_DISCONNECT, 0, 0);
+	net_view = NET_MAIN;
+	set_status("WiFi connection cancelled", 0);
+	load_status();
+}
+
+static void poll_connect(void)
+{
+	int i;
+
+	if (connect_pid <= 0)
+		return;
+
+	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;
+
+			for (i = 0; i < 4; i++)
+				if (net.ip[i])
+					have_ip = 1;
+			net_view = NET_MAIN;
+			if (net_present && s_eq(net.name, "wifi")) {
+				if (have_ip)
+					set_status("WiFi connected and DHCP is up", 0);
+				else
+					set_status("WiFi connected, but DHCP got no lease",
+						   1);
+			} else {
+				set_status("WiFi associated, but the netdev is busy",
+					   1);
+			}
+		} else {
+			set_status("WiFi connection failed", 1);
+		}
+		ngui_invalidate(&ui);
+		return;
+	}
+	if (u_ticks_ms() - connect_start > 45000) {
+		u_kill((unsigned int)connect_pid);
+		connect_pid = -1;
+		u_wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		set_status("WiFi connection timed out", 1);
+	}
+}
+
+static void select_device(int i)
+{
+	char msg[64], *p;
+
+	if (i < 0 || i >= ndev)
+		return;
+	p = s_put(msg, "Selecting ");
+	p = s_put(p, devs[i].name);
+	*p = '\0';
+	set_status(msg, 0);
+	paint_current();
+	if (u_net_select(devs[i].name) != 0) {
+		set_status("Cannot select that netdev (busy or unavailable)", 1);
+		return;
+	}
+	set_status("Running DHCP...", 0);
+	if (u_dhcp_run(6000) == 0)
+		set_status("Device selected; DHCP lease acquired", 0);
+	else
+		set_status("Device selected, but DHCP got no lease", 1);
+	load_devices();
+	ngui_invalidate(&ui);
+}
+
+static void select_bss(int i)
+{
+	if (i < 0 || i >= nbss)
+		return;
+	if (bss[i].ssid_len == 0) {
+		set_status("Hidden network: use `wifi connect` from a terminal",
+			   1);
+		return;
+	}
+	sel_bss = i;
+	ssid_name(&bss[i], sel_ssid);
+	if (bss[i].security == SYS_WIFI_SEC_OTHER) {
+		set_status("Unsupported security (only open and WPA2-PSK)", 1);
+		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";
+		net_view = NET_PASS;
+		set_status("", 0);
+		ngui_set_focus(&ui, ID_NET_PASS_INPUT);
+		ngui_invalidate(&ui);
+		return;
+	}
+	start_connect("");
+}
+
+static void draw_status_card(struct ngui_rect r)
+{
+	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 ||
+		 (s_eq(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, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
+	ngui_frame_round(&ui, r, NGUI_RADIUS, NGUI_RADIUS,
+			 NGUI_RADIUS, NGUI_RADIUS, 1, ui.theme.panel_alt);
+	ngui_fill_round_rect(&ui, dot, 5, 5, 5, 5, dot_color);
+
+	p = line;
+	if (!net_present)
+		p = s_put(p, "Offline");
+	else if (s_eq(net.name, "wifi"))
+		p = s_put(p, wst.state >= SYS_WIFI_ST_LINK ?
+			  "Wi-Fi connected" : "Wi-Fi");
+	else if (s_eq(net.name, "rndis"))
+		p = s_put(p, "USB tethering");
+	else
+		p = s_put(p, "Wired network");
+	*p = '\0';
+	ngui_text_px(&ui, r.x + 34, r.y + 10, line, s_len(line),
+		     ui.theme.text, 14, 1, 0, 0);
+
+	p = line;
+	if (net_present) {
+		p = s_put(p, net.name);
+		p = s_put(p, " \xC2\xB7 ");
+		if (have_ip) {
+			p = s_put_dec(p, net.ip[0]); *p++ = '.';
+			p = s_put_dec(p, net.ip[1]); *p++ = '.';
+			p = s_put_dec(p, net.ip[2]); *p++ = '.';
+			p = s_put_dec(p, net.ip[3]);
+		} else {
+			p = s_put(p, "no IP");
+		}
+		if (s_eq(net.name, "wifi") && wst.state >= SYS_WIFI_ST_ASSOC) {
+			p = s_put(p, " \xC2\xB7 ");
+			for (i = 0; i < wst.ssid_len && i < 32; i++)
+				*p++ = (char)wst.ssid[i];
+			p = s_put(p, "  ");
+			if (wst.rssi < 0) {
+				*p++ = '-';
+				p = s_put_dec(p, (unsigned int)(-wst.rssi));
+			} else {
+				p = s_put_dec(p, (unsigned int)wst.rssi);
+			}
+			p = s_put(p, " dBm");
+		}
+	} else {
+		p = s_put(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_net_main(struct ngui_rect area, int *yy)
+{
+	struct ngui_row row;
+	struct ngui_rect r;
+	char ssid[33], sub[80], *p, value[48];
+	int i, shown = 0, more, n, y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Connection", 0, 0);
+	y += SECTION_H;
+	r = (struct ngui_rect){ area.x, y, area.w, CARD_H };
+	draw_status_card(r);
+	y += CARD_H + GAP;
+
+	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;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	if (ngui_section(&ui, r, "Devices", ID_NET_REFRESH, "Refresh"))
+		request_action(A_REFRESH, 0);
+	y += SECTION_H;
+	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, 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))
+				request_action(A_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";
+
+		ngui_text_utf8(&ui, area.x + 12, y + 12, msg,
+			       ui.theme.text_dim);
+		y += DEV_ROW_H;
+	} else if (more) {
+		char line[32], *lp = line;
+
+		lp = s_put(lp, "+");
+		lp = s_put_dec(lp, (unsigned int)more);
+		lp = s_put(lp, " more devices");
+		*lp = '\0';
+		ngui_text_utf8(&ui, area.x + 12, y + 2, line,
+			       ui.theme.text_dim);
+		y += 20;
+	}
+
+	y += GAP;
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	if (wifi_present && wst.state >= SYS_WIFI_ST_ASSOC) {
+		if (ngui_section(&ui, r, "Wi-Fi", ID_NET_DISCONNECT,
+				 "Disconnect"))
+			request_action(A_DISCONNECT, 0);
+	} else if (wifi_present && !scanning) {
+		if (ngui_section(&ui, r, "Wi-Fi", ID_NET_SCAN, "Scan"))
+			request_action(A_SCAN, 0);
+	} else {
+		ngui_section(&ui, r, "Wi-Fi", 0, 0);
+	}
+	y += SECTION_H;
+
+	if (!wifi_present) {
+		ngui_text_utf8(&ui, area.x + 12, y + 12,
+			       "No Wi-Fi card detected", ui.theme.text_dim);
+		y += BSS_ROW_H;
+	} else if (scanning) {
+		ngui_text_utf8(&ui, area.x + 12, y + 12,
+			       "Scanning for networks...", ui.theme.accent);
+		y += BSS_ROW_H;
+	} else if (nbss == 0) {
+		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_utf8(&ui, area.x + 12, y + 12, msg,
+			       ui.theme.text_dim);
+		y += BSS_ROW_H;
+	} else {
+		for (i = 0; i < nbss; i++) {
+			struct sys_wifi_bss *b = &bss[i];
+			struct ngui_rect br = { area.x, y, area.w, BSS_ROW_H };
+
+			if (br.y + br.h > area.y && br.y < area.y + area.h) {
+				ssid_name(b, ssid);
+				p = sub;
+				p = s_put(p, security_name(b->security));
+				if (bss_saved(b) >= 0)
+					p = s_put(p, " \xC2\xB7 saved");
+				if (bss_is_active(b))
+					p = s_put(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,
+						       br, &row))
+					request_action(A_BSS, i);
+			}
+			y += BSS_ROW_H;
+		}
+	}
+
+	if (net_present) {
+		static const char *labels[4] = {
+			"IP address", "Gateway", "DNS", "MAC address"
+		};
+		int di;
+
+		y += GAP;
+		r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+		ngui_section(&ui, r, "Details", 0, 0);
+		y += SECTION_H;
+		for (di = 0; di < 4; di++) {
+			char *vp = value;
+
+			if (di == 0) {
+				if (net.ip[0] || net.ip[1] || net.ip[2] ||
+				    net.ip[3]) {
+					vp = s_put_dec(vp, net.ip[0]); *vp++ = '.';
+					vp = s_put_dec(vp, net.ip[1]); *vp++ = '.';
+					vp = s_put_dec(vp, net.ip[2]); *vp++ = '.';
+					vp = s_put_dec(vp, net.ip[3]);
+				} else {
+					vp = s_put(vp, "not configured");
+				}
+			} else if (di == 1) {
+				if (net.gw[0] || net.gw[1] || net.gw[2] ||
+				    net.gw[3]) {
+					vp = s_put_dec(vp, net.gw[0]); *vp++ = '.';
+					vp = s_put_dec(vp, net.gw[1]); *vp++ = '.';
+					vp = s_put_dec(vp, net.gw[2]); *vp++ = '.';
+					vp = s_put_dec(vp, net.gw[3]);
+				} else {
+					vp = s_put(vp, "-");
+				}
+			} else if (di == 2) {
+				if (net.dns[0] || net.dns[1] || net.dns[2] ||
+				    net.dns[3]) {
+					vp = s_put_dec(vp, net.dns[0]); *vp++ = '.';
+					vp = s_put_dec(vp, net.dns[1]); *vp++ = '.';
+					vp = s_put_dec(vp, net.dns[2]); *vp++ = '.';
+					vp = s_put_dec(vp, net.dns[3]);
+				} else {
+					vp = s_put(vp, "-");
+				}
+			} else {
+				static const char hex[] = "0123456789abcdef";
+				int k;
+
+				for (k = 0; k < 6; k++) {
+					*vp++ = hex[net.mac[k] >> 4];
+					*vp++ = hex[net.mac[k] & 15];
+					if (k != 5)
+						*vp++ = ':';
+				}
+			}
+			*vp = '\0';
+			r = (struct ngui_rect){ area.x, y, area.w, INFO_ROW_H };
+			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 += INFO_ROW_H;
+		}
+	}
+
+	if (nsaved) {
+		char nbuf[12], *np = nbuf;
+
+		y += GAP;
+		r = (struct ngui_rect){ area.x, y, area.w, SAVED_ROW_H };
+		if (r.y + r.h > area.y && r.y < area.y + area.h) {
+			np = s_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_NET_SAVED, r, &row))
+				request_action(A_SAVED, 0);
+		}
+		y += SAVED_ROW_H;
+	}
+	*yy = y;
+}
+
+static void draw_net_pass(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r;
+	char line[96], *p;
+	int ev, y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, 24 };
+	p = s_put(line, "Join \"");
+	p = s_put(p, sel_ssid);
+	p = s_put(p, "\"");
+	*p = '\0';
+	ngui_text_ellipsis_utf8(&ui, r, r.x, r.y, line, ui.theme.text);
+	y += 28;
+
+	r = (struct ngui_rect){ area.x, y, area.w, 20 };
+	ngui_text_px(&ui, r.x, r.y, "WPA2-PSK passphrase", 19,
+		     ui.theme.text_dim, 14, 1, 0, 0);
+	y += 20;
+	r = (struct ngui_rect){ area.x, y, area.w, 34 };
+	ev = ngui_text_input(&ui, ID_NET_PASS_INPUT, r, &pass_in);
+	if (ev & NGUI_INPUT_SUBMIT)
+		request_action(A_PASS_OK, 0);
+	if (ev & NGUI_INPUT_CANCEL)
+		request_action(A_PASS_CANCEL, 0);
+	y += 34 + GAP;
+
+	ngui_text_utf8(&ui, area.x, y,
+		       "8-63 characters, or 64 hex digits for a raw PSK.",
+		       ui.theme.text_dim);
+	y += 24 + GAP;
+
+	r = (struct ngui_rect){ area.x, y, 110, 28 };
+	if (ngui_button(&ui, ID_NET_PASS_OK, r, "Connect"))
+		request_action(A_PASS_OK, 0);
+	r.x += 120;
+	if (ngui_button(&ui, ID_NET_PASS_CANCEL, r, "Cancel"))
+		request_action(A_PASS_CANCEL, 0);
+	y += 28;
+	*yy = y;
+}
+
+static void draw_net_connect(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect log, b, r;
+	char line[96], *p;
+	unsigned int start = 0, lines = 0, i;
+	int y = *yy, line_y = 0;
+
+	r = (struct ngui_rect){ area.x, y, area.w, 22 };
+	p = s_put(line, connect_pid > 0 ? "Connecting to \"" :
+		  "Connection to \"");
+	p = s_put(p, sel_ssid);
+	p = s_put(p, "\"");
+	*p = '\0';
+	ngui_text_ellipsis_utf8(&ui, r, r.x, r.y, line, ui.theme.text);
+	y += 28;
+
+	log = (struct ngui_rect){ area.x, y, area.w, 240 };
+	ngui_fill_round_rect(&ui, log, NGUI_RADIUS, NGUI_RADIUS,
+			     NGUI_RADIUS, NGUI_RADIUS, ui.theme.panel);
+	ngui_push_clip(&ui, (struct ngui_rect){ log.x + 8, log.y + 8,
+						log.w - 16, log.h - 16 });
+	for (i = conn_log_len; i > 0; i--) {
+		if (conn_log[i - 1] == '\n' && ++lines > 12) {
+			start = i;
+			break;
+		}
+	}
+	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';
+			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;
+		}
+		if ((unsigned int)line_y + 1 < sizeof(line))
+			line[line_y++] = c;
+	}
+	if (line_y) {
+		line[line_y] = '\0';
+		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);
+	y = log.y + log.h + GAP;
+
+	b = (struct ngui_rect){ area.x, y, 110, 28 };
+	if (ngui_button(&ui, ID_NET_CONN_CANCEL, b,
+			connect_pid > 0 ? "Cancel" : "Back"))
+		request_action(A_CONN_CANCEL, 0);
+	y += 28;
+	*yy = y;
+}
+
+static void draw_net_saved(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r, bt;
+	struct ngui_row desc;
+	char ssid[33];
+	int i, y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, 22 };
+	ngui_text_px(&ui, r.x, r.y, "Saved Wi-Fi networks", 20,
+		     ui.theme.text, 14, 1, 0, 0);
+	y += 28;
+
+	if (!nsaved) {
+		ngui_text_utf8(&ui, area.x, y, "No saved networks",
+			       ui.theme.text_dim);
+		y += 24;
+	} else {
+		for (i = 0; i < nsaved; i++) {
+			r = (struct ngui_rect){ area.x, y, area.w,
+						SAVED_ROW_H };
+
+			if (r.y + r.h > area.y && r.y < area.y + area.h) {
+				cfg_ssid_name(&saved[i], ssid);
+				bt = r;
+				bt.x = r.x + r.w - 74;
+				bt.w = 64;
+				bt.h = 28;
+				bt.y = r.y + 7;
+				r.w -= 84;
+
+				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,
+						   r, &desc);
+				if (ngui_button(&ui, ID_SAVED_FORGET_BASE + i,
+						bt, "Forget"))
+					request_action(A_FORGET, i);
+			}
+			y += SAVED_ROW_H;
+		}
+	}
+	r = (struct ngui_rect){ area.x, y, 100, 28 };
+	if (ngui_button(&ui, ID_NET_SAVED_BACK, r, "Back"))
+		request_action(A_SAVED_BACK, 0);
+	y += 28;
+	*yy = y;
+}
+
+static void draw_network(struct ngui_rect area, int *yy)
+{
+	if (net_view == NET_PASS)
+		draw_net_pass(area, yy);
+	else if (net_view == NET_CONNECT)
+		draw_net_connect(area, yy);
+	else if (net_view == NET_SAVED)
+		draw_net_saved(area, yy);
+	else
+		draw_net_main(area, yy);
+}
+
+/* ------------------------------------------------------------------ */
+/* Power                                                               */
+
+static const char *power_mode_name(int mode)
+{
+	switch (mode) {
+	case SYS_CPUFREQ_MAX:
+		return "Performance";
+	case SYS_CPUFREQ_MIN:
+		return "Power saver";
+	case SYS_CPUFREQ_OFF:
+		return "Off";
+	case SYS_CPUFREQ_FIXED:
+		return "Fixed";
+	case SYS_CPUFREQ_AUTO:
+		return "Balanced";
+	default:
+		return "Unavailable";
+	}
+}
+
+static void set_power_mode(int mode)
+{
+	int got = u_cpufreq_set(mode);
+	char msg[48], *p;
+
+	if (got < 0) {
+		set_status("Power mode is not available", 1);
+		return;
+	}
+	cpufreq_mode = got;
+	p = s_put(msg, "Power mode: ");
+	p = s_put(p, power_mode_name(got));
+	*p = '\0';
+	set_status(msg, 0);
+	ngui_invalidate(&ui);
+}
+
+static void draw_power(struct ngui_rect area, int *yy)
+{
+	static const char *labels[3] = {
+		"Balanced", "Performance", "Power saver"
+	};
+	static const char *subs[3] = {
+		"Automatic race-to-idle", "Maximum non-turbo P-state",
+		"Minimum P-state"
+	};
+	static const int modes[3] = {
+		SYS_CPUFREQ_AUTO, SYS_CPUFREQ_MAX, SYS_CPUFREQ_MIN
+	};
+	struct ngui_rect r;
+	struct ngui_row row;
+	int i, y = *yy;
+	int batt = -1, charging = 0, discharging = 0, ac = -1;
+	char value[48], *p;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Power mode", 0, 0);
+	y += SECTION_H;
+	for (i = 0; i < 3; i++) {
+		r = (struct ngui_rect){ area.x, y, area.w, 42 };
+		if (r.y + r.h > area.y && r.y < area.y + area.h) {
+			row.title = labels[i];
+			row.subtitle = subs[i];
+			row.trailing = 0;
+			row.bars = -1;
+			row.selected = cpufreq_mode == modes[i];
+			if (ngui_list_row(&ui, ID_POWER_MODE_BASE + i, r,
+					  &row))
+				request_action(A_POWER, modes[i]);
+		}
+		y += 42;
+	}
+	y += GAP;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Changes the P-state governor immediately.",
+		       ui.theme.text_dim);
+	y += 22;
+
+	if (brightness >= 0) {
+		struct ngui_rect slider;
+		int v = brightness;
+		char b[8], *bp = b;
+
+		y += GAP;
+		r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+		ngui_section(&ui, r, "Brightness", 0, 0);
+		y += SECTION_H;
+		bp = s_put_dec(bp, (unsigned int)brightness);
+		*bp++ = '%';
+		*bp = '\0';
+		ngui_text_utf8(&ui, area.x + 10, y, b, ui.theme.text);
+		y += 20;
+		slider = (struct ngui_rect){ area.x + 10, y,
+					     area.w - 20, 16 };
+		if (ngui_slider(&ui, ID_BRIGHTNESS, &brightness_slider,
+				slider, &v, 5, 100)) {
+			int got = u_backlight_set(v);
+
+			brightness = got >= 0 ? got : v;
+		}
+		y += 24;
+	}
+
+	if (power_ok) {
+		ac = powerinfo.ac_online;
+		for (i = 0; i < SYS_POWER_BATT_MAX; i++) {
+			struct sys_battery *b = &powerinfo.battery[i];
+
+			if (!b->present)
+				continue;
+			if (b->percent_valid)
+				batt = (int)b->percent;
+			charging = (int)b->charging;
+			discharging = (int)b->discharging;
+			break;
+		}
+	}
+
+	y += GAP;
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Power source", 0, 0);
+	y += SECTION_H;
+	if (!power_ok) {
+		ngui_text_utf8(&ui, area.x + 10, y + 8,
+			       "No battery or AC information on this machine.",
+			       ui.theme.text_dim);
+		y += 32;
+	} else {
+		p = value;
+		if (ac > 0)
+			p = s_put(p, "AC online");
+		else if (ac == 0)
+			p = s_put(p, "Battery");
+		else
+			p = s_put(p, "Unknown");
+		*p = '\0';
+		info_row(area, &y, "Source", value);
+		p = value;
+		if (batt >= 0) {
+			p = s_put_dec(p, (unsigned int)batt);
+			*p++ = '%';
+			if (charging)
+				p = s_put(p, " charging");
+			else if (discharging)
+				p = s_put(p, " discharging");
+		} else {
+			p = s_put(p, "not present");
+		}
+		*p = '\0';
+		info_row(area, &y, "Battery", value);
+	}
+	*yy = y;
+}
+
+/* ------------------------------------------------------------------ */
+/* Date & time                                                         */
+
+static unsigned int days_in_month(unsigned int y, unsigned int m)
+{
+	static const unsigned char dm[12] = {
+		31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+	};
+
+	if (m < 1 || m > 12)
+		return 0;
+	if (m == 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0))
+		return 29;
+	return dm[m - 1];
+}
+
+static int parse_num(const char *s, unsigned int n, unsigned int *out)
+{
+	unsigned int v = 0, i;
+
+	if (!n)
+		return -1;
+	for (i = 0; i < n; i++) {
+		if (s[i] < '0' || s[i] > '9')
+			return -1;
+		v = v * 10 + (unsigned int)(s[i] - '0');
+	}
+	*out = v;
+	return 0;
+}
+
+static int parse_date(const char *s, unsigned int *y, unsigned int *mo,
+		      unsigned int *d)
+{
+	if (s_len(s) != 10)
+		return -1;
+	if ((s[4] != '-' && s[4] != '/') ||
+	    (s[7] != '-' && s[7] != '/'))
+		return -1;
+	if (parse_num(s, 4, y) != 0 ||
+	    parse_num(s + 5, 2, mo) != 0 ||
+	    parse_num(s + 8, 2, d) != 0)
+		return -1;
+	return 0;
+}
+
+static int parse_time(const char *s, unsigned int *h, unsigned int *mi,
+		      unsigned int *sec)
+{
+	unsigned int len = s_len(s);
+
+	if (len == 5) {
+		*sec = 0;
+	} else if (len == 8) {
+		if (s[5] != ':' || parse_num(s + 6, 2, sec) != 0)
+			return -1;
+	} else {
+		return -1;
+	}
+	if (s[2] != ':' ||
+	    parse_num(s, 2, h) != 0 ||
+	    parse_num(s + 3, 2, mi) != 0)
+		return -1;
+	return 0;
+}
+
+static void format_date(char *b, const struct sys_datetime *dt)
+{
+	char *p = s_put_dec(b, dt->year);
+
+	*p++ = '-';
+	p = s_put_2(p, dt->month);
+	*p++ = '-';
+	p = s_put_2(p, dt->day);
+	*p = '\0';
+}
+
+static void format_time_sec(char *b, const struct sys_datetime *dt)
+{
+	char *p = s_put_2(b, dt->hour);
+
+	*p++ = ':';
+	p = s_put_2(p, dt->minute);
+	*p++ = ':';
+	p = s_put_2(p, dt->second);
+	*p = '\0';
+}
+
+static void load_datetime_fields(int force)
+{
+	char b[24];
+
+	if (date_loaded && !force)
+		return;
+	if (force || !now_ok) {
+		if (u_rtc_get(&now) != 0) {
+			now_ok = 0;
+			return;
+		}
+		now_ok = 1;
+	}
+	format_date(b, &now);
+	ngui_input_set(&date_in, b);
+	format_time_sec(b, &now);
+	ngui_input_set(&time_in, b);
+	if (!ntp_in.len)
+		ngui_input_set(&ntp_in, "pool.ntp.org");
+	date_loaded = 1;
+}
+
+static void apply_datetime(void)
+{
+	struct sys_datetime dt;
+	unsigned int y, mo, d, h, mi, s;
+
+	if (parse_date(date_in.text, &y, &mo, &d) != 0) {
+		set_status("Date must be YYYY-MM-DD", 1);
+		return;
+	}
+	if (parse_time(time_in.text, &h, &mi, &s) != 0) {
+		set_status("Time must be HH:MM:SS", 1);
+		return;
+	}
+	if (y < 1970 || y > 2069) {
+		set_status("Year must be 1970-2069", 1);
+		return;
+	}
+	if (mo < 1 || mo > 12) {
+		set_status("Month must be 1-12", 1);
+		return;
+	}
+	if (d < 1 || d > days_in_month(y, mo)) {
+		set_status("Day is not valid for that month", 1);
+		return;
+	}
+	if (h > 23 || mi > 59 || s > 59) {
+		set_status("Time is out of range", 1);
+		return;
+	}
+
+	dt.year = y;
+	dt.month = mo;
+	dt.day = d;
+	dt.hour = h;
+	dt.minute = mi;
+	dt.second = s;
+	dt.wday = 0;
+	if (u_rtc_set(&dt) != 0) {
+		set_status("RTC write failed", 1);
+		return;
+	}
+	load_status();
+	load_datetime_fields(1);
+	set_status("Date and time updated", 0);
+}
+
+static const char *ntp_error(int r)
+{
+	switch (r) {
+	case SYS_NTP_ENONIC:
+		return "NTP: no network adapter";
+	case SYS_NTP_ENAME:
+		return "NTP: cannot resolve the server";
+	case SYS_NTP_EARP:
+		return "NTP: server is unreachable (ARP)";
+	case SYS_NTP_ETX:
+		return "NTP: transmit failed";
+	case SYS_NTP_ETIMEOUT:
+		return "NTP: server did not respond";
+	case SYS_NTP_EREPLY:
+		return "NTP: invalid server reply";
+	case SYS_NTP_EBUSY:
+		return "NTP: network is busy";
+	default:
+		return "NTP: sync failed";
+	}
+}
+
+static void sync_ntp(void)
+{
+	struct sys_datetime dt;
+	const char *server = ntp_in.text[0] ? ntp_in.text : "pool.ntp.org";
+	int r;
+
+	set_status("Syncing NTP...", 0);
+	paint_current();
+	r = u_ntp_sync(server, 5000, &dt);
+	if (r != 0) {
+		set_status(ntp_error(r), 1);
+		return;
+	}
+	if (u_rtc_set(&dt) != 0) {
+		set_status("RTC write failed", 1);
+		return;
+	}
+	load_status();
+	load_datetime_fields(1);
+	set_status("Date and time synced", 0);
+}
+
+static void date_field(struct ngui_rect area, int *yy, const char *label,
+		       unsigned int id, struct ngui_input *in,
+		       unsigned int next_id)
+{
+	struct ngui_rect r;
+	int ev;
+
+	r = (struct ngui_rect){ area.x + 10, *yy, area.w - 20, 18 };
+	ngui_text_utf8(&ui, r.x, r.y, label, ui.theme.text_dim);
+	*yy += 18;
+	r = (struct ngui_rect){ area.x + 10, *yy, area.w - 20, 32 };
+	ev = ngui_text_input(&ui, id, r, in);
+	if (ev & NGUI_INPUT_SUBMIT)
+		request_action(id == ID_NTP_FIELD ? A_DATE_NTP : A_DATE_SET, 0);
+	if (ev & NGUI_INPUT_NEXT)
+		ngui_set_focus(&ui, next_id);
+	if (ev & NGUI_INPUT_CANCEL)
+		ngui_set_focus(&ui, 0);
+	*yy += 32 + 8;
+}
+
+static void draw_datetime(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r;
+	char current[64], *p;
+	int y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Date & Time", 0, 0);
+	y += SECTION_H;
+
+	p = current;
+	p = s_put(p, "Current: ");
+	if (now_ok) {
+		format_date(p, &now);
+		p += s_len(p);
+		*p++ = ' ';
+		format_time_sec(p, &now);
+	} else {
+		s_put(p, "unavailable");
+	}
+	ngui_text_utf8(&ui, area.x + 10, y, current, ui.theme.text_dim);
+	y += 24;
+
+	date_field(area, &y, "Date (YYYY-MM-DD)", ID_DATE_FIELD, &date_in,
+		   ID_TIME_FIELD);
+	date_field(area, &y, "Time (HH:MM:SS)", ID_TIME_FIELD, &time_in,
+		   ID_NTP_FIELD);
+	date_field(area, &y, "NTP server (UTC)", ID_NTP_FIELD, &ntp_in,
+		   ID_DATE_FIELD);
+
+	r = (struct ngui_rect){ area.x + 10, y, 80, 28 };
+	if (ngui_button(&ui, ID_DATE_SET, r, "Set"))
+		request_action(A_DATE_SET, 0);
+	r.x += 88;
+	if (ngui_button(&ui, ID_DATE_NOW, r, "Now"))
+		request_action(A_DATE_NOW, 0);
+	r.x += 88;
+	r.w = 110;
+	if (ngui_button(&ui, ID_DATE_NTP, r, "Sync NTP"))
+		request_action(A_DATE_NTP, 0);
+	y += 28 + GAP;
+
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Sync NTP fetches UTC and writes the RTC.",
+		       ui.theme.text_dim);
+	y += 22;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Year range: 1970-2069. Enter applies.",
+		       ui.theme.text_dim);
+	y += 22;
+	*yy = y;
+}
+
+/* ------------------------------------------------------------------ */
+/* Appearance and the wallpaper picker                                 */
+
+static int path_is_file(const char *path)
+{
+	struct sys_stat st;
+
+	return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0;
+}
+
+static void wallpaper_refresh(void)
+{
+	if (path_is_file(WM_WALLPAPER_DATA)) {
+		wallpaper_present = 1;
+		s_copy(wallpaper_source, "/data/WALLPAPR.BIN",
+		       sizeof(wallpaper_source));
+	} else if (path_is_file(WM_WALLPAPER_SHARE)) {
+		wallpaper_present = 1;
+		s_copy(wallpaper_source, "/share/wallpaper",
+		       sizeof(wallpaper_source));
+	} else {
+		wallpaper_present = 0;
+		wallpaper_source[0] = '\0';
+	}
+}
+
+static int lower_char(int c)
+{
+	return c >= 'A' && c <= 'Z' ? c + 'a' - 'A' : c;
+}
+
+static int ext_is_image(const char *name)
+{
+	static const char *const exts[] = {
+		".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga", ".ppm",
+		".pgm", ".pbm", ".ico", ".cur", ".pam"
+	};
+	unsigned int i;
+	int n = (int)s_len(name), e;
+
+	for (e = n - 1; e >= 0 && name[e] != '.'; e--)
+		;
+	if (e < 0)
+		return 0;
+	for (i = 0; i < sizeof(exts) / sizeof(exts[0]); i++) {
+		const char *x = exts[i];
+		int k = 0;
+
+		while (x[k] && e + k < n &&
+		       lower_char((unsigned char)name[e + k]) == x[k])
+			k++;
+		if (!x[k] && e + k == n)
+			return 1;
+	}
+	return 0;
+}
+
+static void trim_name(char *s)
+{
+	int n = (int)s_len(s);
+
+	while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t'))
+		s[--n] = '\0';
+}
+
+static void path_join(char *out, unsigned int cap, const char *base,
+		      const char *name)
+{
+	unsigned int n = s_len(base);
+	int slash = n > 0 && base[n - 1] == '/';
+
+	if (n >= cap - 1) {
+		out[0] = '\0';
+		return;
+	}
+	s_copy(out, base, cap);
+	if (!slash && s_len(out) + 1 < cap) {
+		out[s_len(out)] = '/';
+		out[s_len(out) + 1] = '\0';
+	}
+	if (s_len(out) + s_len(name) + 1 < cap)
+		s_copy(out + s_len(out), name, cap - s_len(out));
+}
+
+static void load_picker_dir(const char *path)
+{
+	struct sys_dirent d;
+	int i = 0, n;
+
+	s_copy(pick_path, path && path[0] ? path : "/", sizeof(pick_path));
+	if (s_len(pick_path) > 1 && pick_path[s_len(pick_path) - 1] == '/')
+		pick_path[s_len(pick_path) - 1] = '\0';
+	pick_count = 0;
+	picker_scroll.offset = 0;
+	if (s_eq(pick_path, "/")) {
+		/* The VFS root is the mount table, not a directory with
+		 * entries; mirror the files app and list the mounts. */
+		struct sys_mount m;
+
+		while (pick_count < PICK_MAX &&
+		       u_syscall2(SYS_LIST_MOUNTS, i++, (int)&m) == 1) {
+			trim_name(m.name);
+			if (!m.name[0])
+				continue;
+			s_copy(pick_names[pick_count], m.name, 64);
+			pick_sizes[pick_count] = 0;
+			pick_dirs[pick_count] = 1;
+			pick_count++;
+		}
+	} else {
+		while (pick_count < PICK_MAX &&
+		       (n = u_syscall3(SYS_LIST_DIR, (int)pick_path, i++,
+				       (int)&d)) == 1) {
+			char disp[64];
+
+			if (d.raw_83) {
+				u_fat_name(d.name, disp, sizeof(disp));
+			} else {
+				trim_name(d.name);
+				s_copy(disp, d.name, sizeof(disp));
+			}
+			if (!disp[0] || s_eq(disp, ".") || s_eq(disp, ".."))
+				continue;
+			if (!d.is_dir && !ext_is_image(disp))
+				continue;
+			s_copy(pick_names[pick_count], disp, 64);
+			pick_sizes[pick_count] = d.size;
+			pick_dirs[pick_count] = d.is_dir ? 1 : 0;
+			pick_count++;
+		}
+	}
+	/* Directories first, then case-insensitive name order. */
+	for (i = 1; i < pick_count; i++) {
+		int j = i;
+
+		while (j > 0) {
+			int swap;
+			int a = j - 1, b = j;
+			unsigned int k;
+
+			if (pick_dirs[a] != pick_dirs[b]) {
+				swap = pick_dirs[b] > pick_dirs[a];
+			} else {
+				swap = 0;
+				for (k = 0; pick_names[a][k] &&
+					    pick_names[b][k]; k++) {
+					int ca = lower_char((unsigned char)
+							    pick_names[a][k]);
+					int cb = lower_char((unsigned char)
+							    pick_names[b][k]);
+
+					if (ca != cb) {
+						swap = cb < ca;
+						break;
+					}
+				}
+				if (!swap && !pick_names[a][k] &&
+				    pick_names[b][k])
+					swap = 1;
+			}
+			if (!swap)
+				break;
+			{
+				char tn[64];
+				unsigned int ts = pick_sizes[a];
+				unsigned char td = pick_dirs[a];
+
+				s_copy(tn, pick_names[a], sizeof(tn));
+				s_copy(pick_names[a], pick_names[b], 64);
+				pick_sizes[a] = pick_sizes[b];
+				pick_dirs[a] = pick_dirs[b];
+				s_copy(pick_names[b], tn, 64);
+				pick_sizes[b] = ts;
+				pick_dirs[b] = td;
+			}
+			j--;
+		}
+	}
+}
+
+static void pick_parent(char *out, unsigned int cap)
+{
+	char tmp[PICK_PATH_MAX];
+	unsigned int n;
+
+	s_copy(tmp, pick_path, sizeof(tmp));
+	n = s_len(tmp);
+	if (n && tmp[n - 1] == '/')
+		tmp[--n] = '\0';
+	while (n > 0 && tmp[n - 1] != '/')
+		n--;
+	if (n == 0)
+		s_copy(out, "/", cap);
+	else {
+		tmp[n - 1] = '\0';
+		s_copy(out, n == 1 ? "/" : tmp, cap);
+	}
+}
+
+static void picker_activate(int idx)
+{
+	char full[PICK_PATH_MAX + 72];
+
+	if (idx < 0 || idx >= pick_count)
+		return;
+	path_join(full, sizeof(full), pick_path, pick_names[idx]);
+	if (pick_dirs[idx]) {
+		load_picker_dir(full);
+		ngui_invalidate(&ui);
+		return;
+	}
+	set_status("Loading wallpaper...", 0);
+	paint_current();
+	set_wallpaper_file(full);
+	picker_mode = 0;
+	wallpaper_refresh();
+	ngui_invalidate(&ui);
+}
+
+static void set_wallpaper_file(const char *path)
+{
+	struct sys_stat st;
+	struct img_info info;
+	struct img_options opt;
+	struct img_mem mem;
+	struct img_image img;
+	struct img_blit b;
+	struct wm_wallpaper_hdr *h;
+	unsigned char *file = 0, *arena = 0, *out = 0;
+	unsigned int cap, est, sw, sh, tw, th, pixbytes, total, i;
+	unsigned long long sx, sy, scale, dw, dh;
+	int n, r;
+
+	if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0) {
+		set_status("Cannot read that image", 1);
+		return;
+	}
+	if (st.size >= WALL_FILE_CAP) {
+		set_status("Image is larger than 4 MB", 1);
+		return;
+	}
+	cap = st.size + 512;      /* a FAT read may round up to a sector */
+	file = (unsigned char *)malloc(cap);
+	if (!file) {
+		set_status("Not enough memory for the image", 1);
+		return;
+	}
+	n = img_read_file(path, file, cap);
+	if (n < 0) {
+		set_status(img_error_string(n), 1);
+		goto out;
+	}
+	r = img_sniff(file, (unsigned int)n, &info);
+	if (r != 0) {
+		set_status(img_error_string(r), 1);
+		goto out;
+	}
+	est = img_estimate(&info);
+	if (est == 0xFFFFFFFFu || est > WALL_HEAP_CAP) {
+		set_status("Image needs too much memory", 1);
+		goto out;
+	}
+	arena = (unsigned char *)malloc(est);
+	if (!arena) {
+		set_status("Not enough memory for the image", 1);
+		goto out;
+	}
+	img_mem_init(&mem, arena, est);
+	memset(&opt, 0, sizeof(opt));
+	r = img_decode(file, (unsigned int)n, &opt, &mem, &img);
+	if (r != 0) {
+		set_status(img_error_string(r), 1);
+		goto out;
+	}
+	if (u_screen_size(&sw, &sh) != 0 || !sw || !sh) {
+		set_status("Cannot read the screen size", 1);
+		goto out;
+	}
+	tw = sw;
+	th = sh;
+	if (tw > WM_WALLPAPER_MAX_W) {
+		th = (unsigned int)((unsigned long long)th *
+				    WM_WALLPAPER_MAX_W / tw);
+		tw = WM_WALLPAPER_MAX_W;
+	}
+	if (th > WM_WALLPAPER_MAX_H) {
+		tw = (unsigned int)((unsigned long long)tw *
+				    WM_WALLPAPER_MAX_H / th);
+		th = WM_WALLPAPER_MAX_H;
+	}
+	if (!tw)
+		tw = 1;
+	if (!th)
+		th = 1;
+	pixbytes = tw * th * 2u;
+	total = sizeof(*h) + pixbytes;
+	out = (unsigned char *)malloc(total);
+	if (!out) {
+		set_status("Not enough memory for the wallpaper", 1);
+		goto out;
+	}
+	memset(out, 0, total);
+	h = (struct wm_wallpaper_hdr *)out;
+	for (i = 0; i < sizeof(h->magic); i++)
+		h->magic[i] = WM_WALLPAPER_MAGIC[i];
+	h->width = tw;
+	h->height = th;
+
+	sx = (((unsigned long long)tw << 16) + img.w - 1) / img.w;
+	sy = (((unsigned long long)th << 16) + img.h - 1) / img.h;
+	scale = sx > sy ? sx : sy;
+	if (!scale)
+		scale = 1;
+	dw = ((unsigned long long)img.w * scale) >> 16;
+	dh = ((unsigned long long)img.h * scale) >> 16;
+	memset(&b, 0, sizeof(b));
+	b.dst = (unsigned short *)(out + sizeof(*h));
+	b.dst_w = (int)tw;
+	b.dst_h = (int)th;
+	b.clip_w = (int)tw;
+	b.clip_h = (int)th;
+	b.x = ((int)tw - (int)dw) / 2;
+	b.y = ((int)th - (int)dh) / 2;
+	b.scale = (unsigned int)scale;
+	img_draw(&img, &b);
+
+	r = u_syscall3(SYS_WRITE_FILE, (int)WM_WALLPAPER_DATA, (int)out,
+		       (int)total);
+	if (r < 0) {
+		struct sys_stat dst;
+
+		/* Only fall back to the RAM copy when there is no data
+		 * volume at all.  Writing the share copy while an older
+		 * /data image exists would make the WM load the stale one. */
+		if (u_stat("/data", &dst) == 0 && dst.is_dir) {
+			set_status("Cannot save the wallpaper to /data", 1);
+			goto out;
+		}
+		r = u_syscall3(SYS_WRITE_FILE, (int)WM_WALLPAPER_SHARE,
+			       (int)out, (int)total);
+	}
+	if (r < 0) {
+		set_status("Cannot save the wallpaper", 1);
+		goto out;
+	}
+	u_syscall1(SYS_WM_WALLPAPER, 1);
+	wallpaper_present = 1;
+	set_status("Wallpaper set", 0);
+out:
+	free(out);
+	free(arena);
+	free(file);
+}
+
+static void draw_appearance(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r;
+	char line[96], *p;
+	int i, y = *yy;
+
+	if (picker_mode) {
+		draw_picker(area, yy);
+		return;
+	}
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Desktop colour", 0, 0);
+	y += SECTION_H;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Used when no wallpaper image is installed.",
+		       ui.theme.text_dim);
+	y += 24;
+	for (i = 0; i < NBG; i++) {
+		char sub[16], *sp = sub;
+
+		sp = s_put(sp, "#");
+		{
+			static const char hex[] = "0123456789abcdef";
+			unsigned int rgb = bg_choices[i].rgb;
+			int k;
+
+			for (k = 5; k >= 0; k--)
+				*sp++ = hex[(rgb >> (k * 4)) & 15];
+		}
+		*sp = '\0';
+		r = (struct ngui_rect){ area.x, y, area.w, 36 };
+		if (settings_row(ID_BG_BASE + i, r, bg_choices[i].name, sub,
+				 prefs.bg_rgb == bg_choices[i].rgb ?
+				 "Selected" : "",
+				 prefs.bg_rgb == bg_choices[i].rgb ? 1 : 0,
+				 (int)bg_choices[i].rgb))
+			request_action(A_BG, i);
+		y += 38;
+	}
+
+	y += GAP;
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Wallpaper", 0, 0);
+	y += SECTION_H;
+	if (wallpaper_present) {
+		p = s_put(line, "Image: ");
+		p = s_put(p, wallpaper_source);
+		*p = '\0';
+		ngui_text_utf8(&ui, area.x + 10, y, line, ui.theme.text_dim);
+		y += 24;
+		ngui_text_utf8(&ui, area.x + 10, y,
+			       "The image covers the desktop colour.",
+			       ui.theme.text_dim);
+		y += 24;
+	} else {
+		ngui_text_utf8(&ui, area.x + 10, y,
+			       "No wallpaper image is installed.",
+			       ui.theme.text_dim);
+		y += 24;
+	}
+	r = (struct ngui_rect){ area.x + 10, y, 150, 28 };
+	if (ngui_button(&ui, ID_WALL_CHOOSE, r,
+			wallpaper_present ? "Change image..." :
+					    "Choose image..."))
+		request_action(A_WALL_CHOOSE, 0);
+	if (wallpaper_present) {
+		r.x += 160;
+		r.w = 110;
+		if (ngui_button(&ui, ID_WALL_REMOVE, r, "Remove"))
+			request_action(A_WALL_REMOVE, 0);
+	}
+	y += 28 + GAP;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Images are scaled to cover the screen and stored on the",
+		       ui.theme.text_dim);
+	y += 20;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "data volume (or /share without one).",
+		       ui.theme.text_dim);
+	y += 22;
+	*yy = y;
+}
+
+static void draw_picker(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r;
+	struct ngui_row row;
+	char size[24];
+	int i, y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, 22 };
+	ngui_text_px(&ui, r.x, r.y, "Choose a wallpaper image", 24,
+		     ui.theme.text, 14, 1, 0, 0);
+	y += 26;
+	ngui_text_ellipsis_utf8(&ui, (struct ngui_rect){ area.x, y,
+							area.w, 18 },
+				area.x, y, pick_path, ui.theme.text_dim);
+	y += 24;
+
+	r = (struct ngui_rect){ area.x, y, 70, 26 };
+	if (ngui_button(&ui, ID_PICK_UP, r, "Up"))
+		request_action(A_PICK_UP, 0);
+	r.x += 80;
+	r.w = 90;
+	if (ngui_button(&ui, ID_PICK_CANCEL, r, "Cancel"))
+		request_action(A_PICK_CANCEL, 0);
+	y += 26 + GAP;
+
+	picker_scroll.content_h = pick_count * PICK_ROW_H;
+	picker_scroll.view_h = area.y + area.h - y;
+	{
+		struct ngui_rect list_r = { area.x, y, area.w,
+					    area.y + area.h - y };
+
+		ngui_scroll_begin(&ui, list_r, &picker_scroll);
+		ngui_scroll_wheel(&ui, list_r, &picker_scroll);
+		ngui_scroll_keys(&ui, &picker_scroll);
+		y -= picker_scroll.offset;
+		if (!pick_count) {
+			ngui_text_utf8(&ui, area.x + 10, y,
+				       "No folders or image files here",
+				       ui.theme.text_dim);
+			y += PICK_ROW_H;
+		}
+		for (i = 0; i < pick_count; i++) {
+			r = (struct ngui_rect){ area.x,
+						y + i * PICK_ROW_H, area.w,
+						PICK_ROW_H };
+			if (r.y + r.h <= area.y || r.y >= area.y + area.h)
+				continue;
+			if (pick_dirs[i]) {
+				s_copy(size, "Folder", sizeof(size));
+			} else {
+				format_size(size, pick_sizes[i]);
+			}
+			row.title = pick_names[i];
+			row.subtitle = size;
+			row.trailing = 0;
+			row.bars = -1;
+			row.selected = 0;
+			if (ngui_list_row_utf8(&ui, ID_PICK_ROW_BASE + i,
+					       r, &row))
+				request_action(A_PICK_ROW, i);
+		}
+		ngui_scroll_end(&ui, list_r, &picker_scroll);
+	}
+	*yy = area.y + area.h;
+}
+
+/* ------------------------------------------------------------------ */
+/* Windows and About                                                   */
+
+static void draw_windows(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r;
+	int y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Window manager", 0, 0);
+	y += SECTION_H;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Changes apply immediately and are saved for the next "
+		       "boot.", ui.theme.text_dim);
+	y += 26;
+
+	r = (struct ngui_rect){ area.x, y, area.w, 44 };
+	if (settings_row(ID_WIN_SHADOW, r, "Window shadows",
+			 "Soft drop shadow around normal windows",
+			 prefs.shadow ? "On" : "Off", prefs.shadow ? 1 : 0, -1))
+		request_action(A_WIN_SHADOW, 0);
+	y += 46;
+	r = (struct ngui_rect){ area.x, y, area.w, 44 };
+	if (settings_row(ID_WIN_SNAP, r, "Snap windows",
+			 "Drag a title bar to a screen edge to snap it",
+			 prefs.snap ? "On" : "Off", prefs.snap ? 1 : 0, -1))
+		request_action(A_WIN_SNAP, 0);
+	y += 46;
+	r = (struct ngui_rect){ area.x, y, area.w, 44 };
+	if (settings_row(ID_WIN_RESIST, r, "Edge resistance",
+			 "Hold a window briefly at screen and window edges",
+			 prefs.resist ? "On" : "Off", prefs.resist ? 1 : 0,
+			 -1))
+		request_action(A_WIN_RESIST, 0);
+	y += 46 + GAP;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Double-clicking a title bar still maximizes or "
+		       "restores a window.", ui.theme.text_dim);
+	y += 22;
+	*yy = y;
+}
+
+static void draw_about(struct ngui_rect area, int *yy)
+{
+	struct ngui_rect r;
+	struct sys_meminfo mi;
+	struct sys_cputemp ct;
+	char value[64], *p;
+	unsigned int sw = 0, sh = 0, secs, h, m, s;
+	int y = *yy;
+
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "System", 0, 0);
+	y += SECTION_H;
+
+	p = value;
+	p = s_put(p, OS_NAME);
+	p = s_put(p, " ");
+	p = s_put(p, OS_VERSION);
+	*p = '\0';
+	info_row(area, &y, "Operating system", value);
+
+	u_screen_size(&sw, &sh);
+	p = value;
+	p = s_put_dec(p, sw);
+	p = s_put(p, " x ");
+	p = s_put_dec(p, sh);
+	*p = '\0';
+	info_row(area, &y, "Display", value);
+
+	secs = u_ticks_ms() / 1000;
+	h = secs / 3600;
+	m = (secs / 60) % 60;
+	s = secs % 60;
+	p = value;
+	p = s_put_dec(p, h);
+	p = s_put(p, "h ");
+	p = s_put_dec(p, m);
+	p = s_put(p, "m ");
+	p = s_put_dec(p, s);
+	p = s_put(p, "s");
+	*p = '\0';
+	info_row(area, &y, "Uptime", value);
+
+	if (u_syscall1(SYS_MEMINFO, (int)&mi) == 0) {
+		p = value;
+		p = s_put_dec(p, mi.total_kb / 1024u);
+		p = s_put(p, " MB");
+		*p = '\0';
+		info_row(area, &y, "Memory", value);
+		p = value;
+		p = s_put_dec(p, (mi.free_pages * mi.page_size) /
+			      (1024u * 1024u));
+		p = s_put(p, " MB");
+		*p = '\0';
+		info_row(area, &y, "Free", value);
+	}
+
+	if (u_cpu_temp(&ct) == 0 && ct.temp_c >= 0) {
+		p = value;
+		p = s_put_dec(p, (unsigned int)ct.temp_c);
+		p = s_put(p, " C");
+		*p = '\0';
+		info_row(area, &y, "CPU temperature", value);
+	}
+
+	y += GAP;
+	r = (struct ngui_rect){ area.x, y, area.w, SECTION_H };
+	ngui_section(&ui, r, "Settings", 0, 0);
+	y += SECTION_H;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Window preferences: /data/SETTINGS.CFG",
+		       ui.theme.text_dim);
+	y += 22;
+	ngui_text_utf8(&ui, area.x + 10, y,
+		       "Without a data volume the RAM copy is "
+		       "/share/settings.cfg.", ui.theme.text_dim);
+	y += 22;
+	*yy = y;
+}
+
+/* ------------------------------------------------------------------ */
+/* Frame                                                               */
+
+static int sidebar_width(void)
+{
+	return ui.w < 620 ? SIDEBAR_MIN_W : SIDEBAR_W;
+}
+
+static void settings_draw_frame(void)
+{
+	struct ngui_rect all = { 0, 0, ui.w, ui.h };
+	struct ngui_rect body = all, side, header, content, footer;
+	int side_w = sidebar_width();
+	int i, y;
+
+	ngui_fill_rect(&ui, all, ui.theme.bg);
+	side = ngui_cut_left(&body, side_w);
+	ngui_fill_rect(&ui, side, ui.theme.panel);
+
+	ngui_text_px(&ui, side.x + 14, side.y + 14, "Settings",
+		     s_len("Settings"), ui.theme.text, 20, 1, 0, 0);
+	ngui_text(&ui, side.x + 14, side.y + 40, OS_NAME " " OS_VERSION,
+		  ui.theme.text_dim);
+
+	y = side.y + 70;
+	for (i = 0; i < SEC_COUNT; i++) {
+		struct ngui_rect r = { side.x + 8, y, side.w - 16, NAV_ROW_H };
+
+		if (settings_row(ID_NAV_BASE + i, r, sections[i].label,
+				 sections[i].subtitle, 0,
+				 cur_section == i ? 1 : 0, -1))
+			request_action(A_NAV, i);
+		y += NAV_ROW_H + NAV_GAP;
+	}
+
+	header = ngui_cut_top(&body, HEADER_H);
+	ngui_text_px(&ui, header.x + 16, header.y + 8, sections[cur_section].label,
+		     s_len(sections[cur_section].label), ui.theme.text, 20, 1,
+		     0, 0);
+	ngui_text_utf8(&ui, header.x + 16, header.y + 32,
+		       sections[cur_section].subtitle, ui.theme.text_dim);
+	ngui_fill_rect(&ui, (struct ngui_rect){ header.x + 16,
+						header.y + HEADER_H - 1,
+						header.w - 32, 1 },
+		       ui.theme.panel_alt);
+
+	footer = ngui_cut_bottom(&body, FOOTER_H);
+	ngui_fill_rect(&ui, footer, ui.theme.panel);
+	ngui_fill_rect(&ui, (struct ngui_rect){ footer.x, footer.y,
+						footer.w, 1 },
+		       ui.theme.panel_alt);
+	if (status[0] && status_until &&
+	    (int)(u_ticks_ms() - status_until) < 0) {
+		ngui_text_ellipsis_utf8(&ui,
+			(struct ngui_rect){ footer.x + 12, footer.y + 6,
+					    footer.w - 24, 18 },
+			footer.x + 12, footer.y + 6, status,
+			status_error ? ui.theme.error : ui.theme.success);
+	} else {
+		ngui_text_utf8(&ui, footer.x + 12, footer.y + 6,
+			       "Changes are saved automatically.",
+			       ui.theme.text_dim);
+	}
+
+	content = body;
+	content.x += 16;
+	content.w -= 24;
+	content.y += 6;
+	content.h -= 8;
+	{
+		int picker_only = (cur_section == SEC_APPEARANCE &&
+				   picker_mode != 0);
+
+		if (picker_only) {
+			/* The picker has its own scroll pane; do not let the
+			 * outer pane eat the wheel or PgUp/PgDn keys. */
+			content_scroll.offset = 0;
+			ngui_push_clip(&ui, content);
+			y = content.y;
+		} else {
+			ngui_scroll_begin(&ui, content, &content_scroll);
+			ngui_scroll_wheel(&ui, content, &content_scroll);
+			ngui_scroll_keys(&ui, &content_scroll);
+			y = content.y - content_scroll.offset;
+		}
+		switch (cur_section) {
+		case SEC_NETWORK:
+			draw_network(content, &y);
+			break;
+		case SEC_POWER:
+			draw_power(content, &y);
+			break;
+		case SEC_DATETIME:
+			draw_datetime(content, &y);
+			break;
+		case SEC_APPEARANCE:
+			draw_appearance(content, &y);
+			break;
+		case SEC_WINDOWS:
+			draw_windows(content, &y);
+			break;
+		case SEC_ABOUT:
+			draw_about(content, &y);
+			break;
+		default:
+			break;
+		}
+		if (picker_only) {
+			ngui_pop_clip(&ui);
+		} else {
+			content_scroll.content_h =
+				y + content_scroll.offset - content.y + GAP;
+			ngui_scroll_end(&ui, content, &content_scroll);
+		}
+	}
+}
+
+/* ------------------------------------------------------------------ */
+/* Actions                                                             */
+
+static void set_section(int s)
+{
+	if (s < 0 || s >= SEC_COUNT)
+		return;
+	if (s == cur_section)
+		return;
+	cur_section = s;
+	content_scroll.offset = 0;
+	picker_mode = 0;
+	if (s == SEC_NETWORK && !devs_loaded) {
+		set_status("Loading network devices...", 0);
+		paint_current();
+		load_devices();
+		set_status("", 0);
+		if (wifi_present && wst.state < SYS_WIFI_ST_ASSOC)
+			start_scan();
+	}
+	if (s == SEC_DATETIME)
+		load_datetime_fields(0);
+	if (s == SEC_APPEARANCE)
+		wallpaper_refresh();
+	ngui_set_focus(&ui, 0);
+	ngui_invalidate(&ui);
+}
+
+static void handle_action(void)
+{
+	int a = pending_action, arg = pending_arg;
+
+	pending_action = A_NONE;
+	pending_arg = 0;
+	switch (a) {
+	case A_NAV:
+		set_section(arg);
+		break;
+	case A_REFRESH:
+		set_status("Refreshing network devices...", 0);
+		load_devices();
+		set_status("Device list refreshed", 0);
+		ngui_invalidate(&ui);
+		break;
+	case A_SCAN:
+		start_scan();
+		break;
+	case A_DISCONNECT:
+		u_wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		load_status();
+		set_status("WiFi disconnected", 0);
+		ngui_invalidate(&ui);
+		break;
+	case A_DEV:
+		select_device(arg);
+		break;
+	case A_BSS:
+		select_bss(arg);
+		break;
+	case A_SAVED:
+		load_saved();
+		content_scroll.offset = 0;
+		net_view = NET_SAVED;
+		ngui_invalidate(&ui);
+		break;
+	case A_SAVED_BACK:
+		net_view = NET_MAIN;
+		content_scroll.offset = 0;
+		ngui_invalidate(&ui);
+		break;
+	case A_FORGET:
+		if (arg >= 0 && arg < nsaved) {
+			if (wifi_store_forget(saved[arg].ssid,
+					      saved[arg].ssid_len) > 0) {
+				load_saved();
+				set_status("Saved network removed", 0);
+			} else {
+				set_status("Could not remove the saved network", 1);
+			}
+		}
+		ngui_invalidate(&ui);
+		break;
+	case A_PASS_OK: {
+		char pass[65];
+		unsigned int i, n;
+
+		ngui_input_value(&pass_in, pass, sizeof(pass));
+		n = s_len(pass);
+		if (n == 0) {
+			set_status("Enter the WPA2 passphrase", 1);
+		} else if (n < 8 || n > 63) {
+			int hex = n == 64;
+
+			if (hex) {
+				unsigned int j;
+
+				for (j = 0; j < n; j++) {
+					char c = pass[j];
+
+					if (!((c >= '0' && c <= '9') ||
+					      (c >= 'a' && c <= 'f') ||
+					      (c >= 'A' && c <= 'F'))) {
+						hex = 0;
+						break;
+					}
+				}
+			}
+			if (hex)
+				start_connect(pass);
+			else
+				set_status("Use 8-63 characters or 64 hex digits",
+					   1);
+		} else {
+			start_connect(pass);
+		}
+		for (i = 0; i < sizeof(pass); i++)
+			((volatile char *)pass)[i] = 0;
+		break;
+	}
+	case A_PASS_CANCEL:
+	case A_CONN_CANCEL:
+		if (net_view == NET_CONNECT)
+			cancel_connect();
+		else {
+			net_view = NET_MAIN;
+			set_status("", 0);
+			ngui_invalidate(&ui);
+		}
+		break;
+	case A_POWER:
+		set_power_mode(arg);
+		break;
+	case A_DATE_SET:
+		apply_datetime();
+		break;
+	case A_DATE_NOW:
+		load_datetime_fields(1);
+		set_status("Date and time reloaded", 0);
+		break;
+	case A_DATE_NTP:
+		sync_ntp();
+		break;
+	case A_BG:
+		if (arg >= 0 && arg < NBG) {
+			prefs.bg_rgb = bg_choices[arg].rgb;
+			commit_prefs("Background colour saved");
+		}
+		break;
+	case A_WALL_CHOOSE: {
+		struct sys_stat st;
+
+		picker_mode = 1;
+		content_scroll.offset = 0;
+		if (u_stat("/data", &st) == 0 && st.is_dir)
+			load_picker_dir("/data");
+		else if (u_stat("/share", &st) == 0 && st.is_dir)
+			load_picker_dir("/share");
+		else
+			load_picker_dir("/");
+		ngui_invalidate(&ui);
+		break;
+	}
+	case A_WALL_REMOVE:
+		u_syscall1(SYS_UNLINK, (int)WM_WALLPAPER_DATA);
+		u_syscall1(SYS_UNLINK, (int)WM_WALLPAPER_SHARE);
+		u_syscall1(SYS_WM_WALLPAPER, 1);
+		wallpaper_refresh();
+		if (wallpaper_present)
+			set_status("The wallpaper on the data volume could not be removed",
+				   1);
+		else
+			set_status("Wallpaper removed; the desktop colour is visible",
+				   0);
+		ngui_invalidate(&ui);
+		break;
+	case A_PICK_UP: {
+		char parent[PICK_PATH_MAX];
+
+		pick_parent(parent, sizeof(parent));
+		load_picker_dir(parent);
+		ngui_invalidate(&ui);
+		break;
+	}
+	case A_PICK_CANCEL:
+		picker_mode = 0;
+		ngui_invalidate(&ui);
+		break;
+	case A_PICK_ROW:
+		picker_activate(arg);
+		break;
+	case A_WIN_SHADOW:
+		prefs.shadow = prefs.shadow ? 0 : 1;
+		commit_prefs(prefs.shadow ? "Window shadows enabled" :
+					    "Window shadows disabled");
+		break;
+	case A_WIN_SNAP:
+		prefs.snap = prefs.snap ? 0 : 1;
+		commit_prefs(prefs.snap ? "Edge snapping enabled" :
+					  "Edge snapping disabled");
+		break;
+	case A_WIN_RESIST:
+		prefs.resist = prefs.resist ? 0 : 1;
+		commit_prefs(prefs.resist ? "Edge resistance enabled" :
+					    "Edge resistance disabled");
+		break;
+	default:
+		break;
+	}
+}
+
+static void check_section_request(void)
+{
+	char buf[24];
+	unsigned int now_ms = u_ticks_ms();
+	int n, i;
+
+	if (now_ms - last_request_ms < 250)
+		return;
+	last_request_ms = now_ms;
+	n = u_read_file(WM_SETTINGS_REQUEST, buf, sizeof(buf) - 1);
+	if (n <= 0)
+		return;
+	buf[n] = '\0';
+	while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r' ||
+			 buf[n - 1] == ' '))
+		buf[--n] = '\0';
+	/* Consume the request: the WM writes a fresh file for every pill
+	 * click, and a stale one must not pull the user back after they
+	 * picked another section by hand. */
+	u_syscall1(SYS_UNLINK, (int)WM_SETTINGS_REQUEST);
+	if (!buf[0])
+		return;
+	for (i = 0; i < SEC_COUNT; i++) {
+		if (s_eq(buf, sections[i].arg)) {
+			if (i != cur_section)
+				set_section(i);
+			break;
+		}
+	}
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+	unsigned int sw = 0, sh = 0;
+	int w, h;
+
+	u_screen_size(&sw, &sh);
+	if (!sw || !sh) {
+		sw = 1024;
+		sh = 768;
+	}
+	w = (int)sw - 40;
+	h = (int)sh - 80;
+	if (w > 900)
+		w = 900;
+	if (h > 620)
+		h = 620;
+	if (w < 460)
+		w = 460;
+	if (h < 360)
+		h = 360;
+
+	prefs_defaults();
+	if (u_wm_get_prefs(&prefs) != 0)
+		prefs_defaults();
+	/* The WM may not have reached the data volume yet (the first boot
+	 * or a quick launch); prefer the persisted file when it is valid. */
+	if (prefs_file_load() == 0)
+		u_wm_set_prefs(&prefs);
+
+	cur_section = section_from_name(arg);
+	if (u_win_create((unsigned int)w, (unsigned int)h, "Settings", &wi) != 0) {
+		u_puts("settings: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
+	pass_in.secret = 1;
+	pass_in.placeholder = "WPA2 passphrase";
+	ntp_in.placeholder = "pool.ntp.org";
+	if (cur_section == SEC_NETWORK) {
+		set_status("Loading network devices...", 0);
+		paint_current();
+	}
+	load_status();
+	load_saved();
+	wallpaper_refresh();
+	if (cur_section == SEC_NETWORK) {
+		load_devices();
+		set_status("", 0);
+		if (wifi_present && wst.state < SYS_WIFI_ST_ASSOC)
+			start_scan();
+	}
+	if (cur_section == SEC_DATETIME)
+		load_datetime_fields(0);
+
+	last_status_ms = u_ticks_ms();
+
+	for (;;) {
+		static int first_frame = 1;
+		unsigned int now_ms = u_ticks_ms();
+
+		drain_tty();
+		poll_scan();
+		poll_connect();
+		check_section_request();
+		if (now_ms - last_status_ms >= 1000) {
+			last_status_ms = now_ms;
+			load_status();
+			if (cur_section == SEC_DATETIME)
+				load_datetime_fields(0);
+			ngui_invalidate(&ui);
+		}
+		if (status_until && (int)(now_ms - status_until) >= 0) {
+			status[0] = '\0';
+			status_until = 0;
+			ngui_invalidate(&ui);
+		}
+
+		if (ngui_begin(&ui)) {
+			settings_draw_frame();
+			ngui_end(&ui);
+			if (first_frame) {
+				first_frame = 0;
+				ngui_invalidate(&ui);
+			}
+		}
+		if (pending_action)
+			handle_action();
+
+		if (ngui_key_peek(&ui) == NGUI_KEY_ESC) {
+			ngui_key(&ui);
+			if (picker_mode) {
+				picker_mode = 0;
+				ngui_invalidate(&ui);
+			} else if (net_view != NET_MAIN) {
+				net_view = NET_MAIN;
+				set_status("", 0);
+				ngui_invalidate(&ui);
+			} else if (ui.focus == 0) {
+				quit = 1;
+			}
+		}
+		if (quit)
+			break;
+		u_sleep_ms(20);
+	}
+	ngui_font_detach(&ui);
+	u_win_close();
+	u_exit(0);
+}

+ 194 - 17
user/apps/wm/ucmd_wm.c

@@ -85,6 +85,24 @@ static unsigned short wall_ymap[WALL_MAP_MAX];
 /* RGB565 -> 0xFFRRGGBB, built when the wallpaper loads so the 32 bpp
  * desktop path is a table lookup instead of per-pixel shifts. */
 static unsigned int wall_rgb32[65536];
+/* Settings pushed by the Settings app through SYS_WM_PREFS.  The kernel
+ * keeps them across a WM restart; the app loads the file at boot and pushes
+ * it here. */
+static struct wm_prefs prefs = { 1, 1, 1, WM_DEFAULT_BG_RGB, { 0, 0, 0, 0 } };
+static unsigned int prefs_seq_seen;
+static int prefs_seen_valid;
+static int shadow_px = WM_SHADOW_SPREAD;
+static unsigned int desktop_rgb = WM_DEFAULT_BG_RGB;
+/* Settings app launcher: SYS_WM_OPEN_SETTINGS bumps a request counter in
+ * wm_status.  One window is reused, and a section request for a running app
+ * goes through /share/settings.req so it switches panes. */
+static int settings_pid;
+static unsigned int settings_req_seen;
+static int settings_req_seen_valid;
+static int prefs_boot_seen;
+static int prefs_retries;
+static unsigned int prefs_retry_ms;
+static int prefs_loaded;
 static int drag_id = -1;
 static int drag_dx, drag_dy;
 static int drag_mx, drag_my;       /* press position, for restore-on-drag */
@@ -208,7 +226,7 @@ struct sm_app {
 };
 
 /* Every self-contained GUI application in the pack.  Terminal and Settings
- * are WM actions (a new terminal canvas and the control panel); edit gets a
+ * are WM actions (a new terminal canvas and the Settings window); edit gets a
  * scratch file so it can start without a file argument. */
 static const struct sm_app sm_apps[] = {
 	{ "Terminal",    "",                    "",                     0x3C8CD2u, 'T', SM_ACT_TERM,     APP_ICON_TERMINAL, "term" },
@@ -224,7 +242,7 @@ static const struct sm_app sm_apps[] = {
 	{ "Disks",       "/ramfs/bin/disks",    "",                     0x5A8CC8u, 'D', SM_ACT_SPAWN,    APP_ICON_DISKS,    "Disks" },
 	{ "Tasks",       "/ramfs/bin/process",  "",                     0xE0B040u, 'P', SM_ACT_SPAWN,    APP_ICON_TASKS,    "Processes" },
 	{ "Services",    "/ramfs/bin/service",  "--gui",                0x9A6AC8u, 'V', SM_ACT_SPAWN,    APP_ICON_SERVICES, "Services" },
-	{ "Settings",    "",                    "",                     0x7A7A9Au, 'S', SM_ACT_SETTINGS, APP_ICON_SETTINGS, "Control Center" },
+	{ "Settings",    "",                    "",                     0x7A7A9Au, 'S', SM_ACT_SETTINGS, APP_ICON_SETTINGS, "Settings" },
 	{ "Date & Time", "/ramfs/bin/settime",  "",                     0x5AA0A0u, 'D', SM_ACT_SPAWN,    APP_ICON_DATETIME, "Date & Time" },
 };
 #define SM_NAPP ((int)(sizeof(sm_apps) / sizeof(sm_apps[0])))
@@ -996,6 +1014,8 @@ static void draw_shadows(const struct orect *dmg)
 	int order[WM_MAX_WINDOWS];
 	unsigned int n = build_order(order), i, j, ncur;
 
+	if (shadow_px <= 0)
+		return;
 	for (i = n; i-- > 0;) {
 		struct uwin *u = &wins[order[i]];
 		struct orect own, fr;
@@ -1003,10 +1023,10 @@ static void draw_shadows(const struct orect *dmg)
 
 		if (!u->info.used || u->info.popover)
 			continue;
-		x0 = u->info.x - WM_SHADOW_SPREAD;
-		y0 = u->info.y - WM_SHADOW_SPREAD;
-		x1 = u->info.x + (int)u->info.w + WM_SHADOW_SPREAD;
-		y1 = u->info.y + (int)u->info.h + WM_SHADOW_SPREAD;
+		x0 = u->info.x - shadow_px;
+		y0 = u->info.y - shadow_px;
+		x1 = u->info.x + (int)u->info.w + shadow_px;
+		y1 = u->info.y + (int)u->info.h + shadow_px;
 		if (x0 < dmg->x) x0 = dmg->x;
 		if (y0 < dmg->y) y0 = dmg->y;
 		if (x1 > dmg->x + (int)dmg->w) x1 = dmg->x + (int)dmg->w;
@@ -1040,7 +1060,7 @@ static void draw_shadows(const struct orect *dmg)
 		for (j = 0; j < ncur; j++)
 			usurf_window_shadow(&screen, u->info.x, u->info.y,
 					    (int)u->info.w, (int)u->info.h,
-					    WM_SHADOW_SPREAD,
+					    shadow_px,
 					    cur[j].x, cur[j].y,
 					    cur[j].w, cur[j].h);
 	}
@@ -1121,6 +1141,46 @@ static void wall_load(void)
 	}
 }
 
+static void apply_prefs(void)
+{
+	shadow_px = prefs.shadow ? WM_SHADOW_SPREAD : 0;
+	desktop_rgb = prefs.bg_rgb & 0x00FFFFFFu;
+}
+
+static int prefs_file_magic_ok(const struct wm_prefs_file *f)
+{
+	unsigned int i;
+
+	for (i = 0; i < sizeof(f->magic); i++)
+		if (f->magic[i] != WM_PREFS_MAGIC[i])
+			return 0;
+	return 1;
+}
+
+/* Read one preference file and push it through the kernel, which also
+ * updates this WM on the next poll.  Returns 0 when a file was accepted. */
+static int prefs_read_file(const char *path)
+{
+	/* Leave a sector of slack: the FAT driver may write the final partial
+	 * sector past the requested length. */
+	unsigned char buf[sizeof(struct wm_prefs_file) + 512];
+	struct wm_prefs_file *f = (struct wm_prefs_file *)buf;
+	int n;
+
+	n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)sizeof(*f));
+	if (n < (int)sizeof(*f) || !prefs_file_magic_ok(f) ||
+	    f->version != WM_PREFS_VERSION)
+		return -1;
+	return u_wm_set_prefs(&f->prefs);
+}
+
+static int prefs_load(void)
+{
+	if (prefs_read_file(WM_PREFS_DATA) == 0)
+		return 0;
+	return prefs_read_file(WM_PREFS_SHARE);
+}
+
 /* Paint the desktop part of one damage rectangle. */
 static void wall_draw(int x, int y, unsigned int w, unsigned int h)
 {
@@ -1130,7 +1190,7 @@ static void wall_draw(int x, int y, unsigned int w, unsigned int h)
 	unsigned int yy, xx;
 
 	if (!wall_ready) {
-		usurf_fill(&screen, x, y, w, h, COL_BG);
+		usurf_fill(&screen, x, y, w, h, desktop_rgb);
 		return;
 	}
 	if (x0 < 0) x0 = 0;
@@ -1474,10 +1534,10 @@ static void add_rect(struct wm_present_info *p, int x, int y,
 static void window_shadow_rect(struct orect *r, int x, int y,
 			       unsigned int w, unsigned int h)
 {
-	r->x = x - WM_SHADOW_SPREAD;
-	r->y = y - WM_SHADOW_SPREAD;
-	r->w = w + 2 * WM_SHADOW_SPREAD;
-	r->h = h + 2 * WM_SHADOW_SPREAD;
+	r->x = x - shadow_px;
+	r->y = y - shadow_px;
+	r->w = w + 2 * (unsigned int)shadow_px;
+	r->h = h + 2 * (unsigned int)shadow_px;
 	if (r->y < WM_BAR_H) {
 		unsigned int cut = (unsigned int)(WM_BAR_H - r->y);
 
@@ -2558,6 +2618,83 @@ static void spawn_app_arg_checked(const char *path, const char *arg)
 	}
 }
 
+static const char *settings_section_name(unsigned int section)
+{
+	switch (section) {
+	case WM_SETTINGS_NETWORK:    return "network";
+	case WM_SETTINGS_POWER:      return "power";
+	case WM_SETTINGS_DATETIME:   return "time";
+	case WM_SETTINGS_APPEARANCE: return "appearance";
+	case WM_SETTINGS_WINDOWS:    return "windows";
+	case WM_SETTINGS_ABOUT:      return "about";
+	default:                     return "network";
+	}
+}
+
+/* The running Settings window polls this file; a focus request for another
+ * section therefore switches the pane without a restart. */
+static void settings_write_request(unsigned int section)
+{
+	const char *name = settings_section_name(section);
+	char buf[20];
+	unsigned int n = 0;
+
+	while (name[n] && n + 2 < sizeof(buf)) {
+		buf[n] = name[n];
+		n++;
+	}
+	buf[n++] = '\n';
+	buf[n] = '\0';
+	u_syscall3(SYS_WRITE_FILE, (int)WM_SETTINGS_REQUEST, (int)buf, (int)n);
+}
+
+static int window_title_is(const struct wm_window_info *w, const char *title)
+{
+	unsigned int i = 0;
+
+	while (w->title[i] && title[i] && w->title[i] == title[i])
+		i++;
+	return w->title[i] == title[i];
+}
+
+/* Open the Settings app at one section.  The WM is the only process that
+ * may focus another window, so every launcher (popover pills, start menu
+ * and dock) goes through SYS_WM_OPEN_SETTINGS and lands here. */
+static void open_settings(unsigned int section)
+{
+	unsigned int i;
+
+	if (section >= WM_SETTINGS_COUNT)
+		section = WM_SETTINGS_NETWORK;
+	settings_write_request(section);
+	for (i = 0; i < WM_MAX_WINDOWS; i++) {
+		if (!wins[i].info.used || !window_title_is(&wins[i].info,
+							   "Settings"))
+			continue;
+		if (u_wm_focus(i) == 0) {
+			full_redraw = 1;
+			return;
+		}
+	}
+	if (settings_pid > 0 && u_alive((unsigned int)settings_pid))
+		return;                 /* window is still being created */
+	settings_pid = 0;
+	if (!free_window_slot()) {
+		bar_notice("window limit");
+		full_redraw = 1;
+		return;
+	}
+	settings_pid = u_spawn("/ramfs/bin/settings",
+			       settings_section_name(section), 0, "/");
+	if (settings_pid < 0) {
+		settings_pid = 0;
+		bar_notice("cannot start settings");
+		full_redraw = 1;
+	} else {
+		full_redraw = 1;
+	}
+}
+
 /* Any status target opens one control panel; a second click closes it. */
 static void open_control_panel(void)
 {
@@ -2617,7 +2754,7 @@ static void sm_launch(int idx)
 			full_redraw = 1;
 		}
 	} else if (a->action == SM_ACT_SETTINGS) {
-		open_control_panel();
+		open_settings(WM_SETTINGS_NETWORK);
 	} else {
 		spawn_app_arg_checked(a->path, a->arg);
 	}
@@ -3038,7 +3175,7 @@ static void dock_activate(int idx)
 		return;
 	}
 	if (a->action == SM_ACT_SETTINGS) {
-		open_control_panel();
+		open_settings(WM_SETTINGS_NETWORK);
 		return;
 	}
 	sm_launch(dock_apps[idx]);
@@ -3372,7 +3509,8 @@ static void handle_mouse(struct wm_status *st)
 				nx = (int)mx - drag_dx;
 				ny = (int)my - drag_dy;
 
-				resist_geom(u, drag_id, &nx, &ny);
+				if (prefs.resist)
+					resist_geom(u, drag_id, &nx, &ny);
 				clamp_geom(u, &nx, &ny);
 				if (nx != ox || ny != oy) {
 					struct wm_present_info present;
@@ -3431,8 +3569,11 @@ static void handle_mouse(struct wm_status *st)
 			resize_window_drag(&wins[resize_id],
 					   (unsigned int)resize_id, mx, my, 1);
 		/* Dropping a window with the pointer on the left/right screen
-		 * edge snaps it to that half; on the top edge it maximizes. */
-		if (drag_id >= 0 && drag_moved && wins[drag_id].info.used &&
+		 * edge snaps it to that half; on the top edge it maximizes.
+		 * The Settings app can turn edge snapping off, leaving the
+		 * double-click maximize gesture alone. */
+		if (prefs.snap && drag_id >= 0 && drag_moved &&
+		    wins[drag_id].info.used &&
 		    wins[drag_id].state == WIN_NORMAL) {
 			struct uwin *u = &wins[drag_id];
 			int st = WIN_NORMAL;
@@ -3525,6 +3666,25 @@ void _start(const char *arg)
 
 		if (u_wm_poll(&st) != 0)
 			u_exit(1);
+		if (!prefs_seen_valid || st.prefs_seq != prefs_seq_seen) {
+			unsigned int old_shadow = (unsigned int)shadow_px;
+			unsigned int old_bg = desktop_rgb;
+
+			prefs = st.prefs;
+			prefs_seq_seen = st.prefs_seq;
+			prefs_seen_valid = 1;
+			apply_prefs();
+			if (old_shadow != (unsigned int)shadow_px ||
+			    old_bg != desktop_rgb)
+				full_redraw = 1;
+		}
+		if (!settings_req_seen_valid) {
+			settings_req_seen = st.settings_req_seq;
+			settings_req_seen_valid = 1;
+		} else if (st.settings_req_seq != settings_req_seen) {
+			settings_req_seen = st.settings_req_seq;
+			open_settings(st.settings_req_section);
+		}
 		/* A poweroff that could not cut the power returns instead of
 		 * halting; tell the user rather than leaving a dead menu. */
 		if (poweroff_pid > 0 &&
@@ -3554,6 +3714,23 @@ void _start(const char *arg)
 			if (wall_ready)
 				full_redraw = 1;
 		}
+		/* Preferences live on /data like the wallpaper, so the same
+		 * boot-order retry applies.  A missing file keeps the kernel's
+		 * defaults (and any values a previous WM set). */
+		if (st.boot_ready && !prefs_boot_seen) {
+			prefs_boot_seen = 1;
+			prefs_retries = 0;
+			prefs_retry_ms = u_ticks_ms() + 1000;
+			if (prefs_load() == 0)
+				prefs_loaded = 1;
+		} else if (prefs_boot_seen && !prefs_loaded &&
+			   prefs_retries < 10 &&
+			   (int)(u_ticks_ms() - prefs_retry_ms) >= 0) {
+			prefs_retries++;
+			prefs_retry_ms += 1000;
+			if (prefs_load() == 0)
+				prefs_loaded = 1;
+		}
 		if (st.full_redraw)
 			full_redraw = 1;
 		usurf_pixels = 0;

+ 17 - 0
user/ucmd_lib.h

@@ -384,6 +384,23 @@ static inline int u_wm_mouse_capture(int on)
 	return u_syscall1(SYS_WM_MOUSE_CAPTURE, on);
 }
 
+/* Window-manager preferences (struct wm_prefs in wm_abi.h) and the request
+ * that focuses/starts the Settings app at a section. */
+static inline int u_wm_get_prefs(struct wm_prefs *out)
+{
+	return u_syscall2(SYS_WM_PREFS, SYS_WM_PREFS_GET, (int)out);
+}
+
+static inline int u_wm_set_prefs(const struct wm_prefs *in)
+{
+	return u_syscall2(SYS_WM_PREFS, SYS_WM_PREFS_SET, (int)in);
+}
+
+static inline int u_open_settings(int section)
+{
+	return u_syscall1(SYS_WM_OPEN_SETTINGS, section);
+}
+
 static inline int u_screen_size(unsigned int *w, unsigned int *h)
 {
 	struct sys_screen s;

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff