1
0

6 Коммиты 8373a22461 ... 75e0dc9ead

Автор SHA1 Сообщение Дата
  Johannes Zellner 75e0dc9ead acpi: real S5 poweroff on BIOS and UEFI 3 дней назад
  Johannes Zellner 56aba2f2e6 browser: en-US Intl, form constraint validation, stripped prelude 3 дней назад
  Johannes Zellner 29b7a1c185 wm: fix wallpaper blits in partial damage rects 3 дней назад
  Johannes Zellner dac20d37c3 wm: persisted desktop wallpaper from the image viewer 3 дней назад
  Johannes Zellner f268094347 usb: arm EHCI bulk-IN qTDs with the exact transfer length 3 дней назад
  Johannes Zellner 4a08a46b4b browser: downloads from a context menu with a toolbar panel 3 дней назад

+ 1 - 0
.gitignore

@@ -12,6 +12,7 @@ netmonitor
 mkpack
 mkrootfs
 mkrtwtbl
+jsstrip
 tls_test
 img_test
 img_test_asan

+ 133 - 16
AGENTS.md

@@ -16,7 +16,7 @@ Targets i586 (first-gen Pentium); runs under QEMU or on real hardware.
 | `user/` | `ucmd_lib.h` (the ring-3 syscall wrappers) and `ucmd.ld` |
 | `user/apps/<name>/` | One ring-3 program per directory: entry file `ucmd_<name>.c` plus private modules (`browser/` holds `browser.c`, `browser_html.c`, `js_*.c`, `svg_raster.c`; `chat/` holds `chat_login.c`; `gallery/` holds the real `gallery.c` behind the `ucmd_gallery.c` launcher; `hello/` has its own `hello.ld`) |
 | `user/lib/<lib>/` | Ring-3 libraries: `libc`, `ngui`, `ufont`, `img`, `tls` (crypto incl. `wpa_crypto.c`), `uhttp`, `ujson`, `uwm` (`uwm_lib.c`), `wifi` (`wifi_store.c`, `wpa.c`); host tests live next to their library |
-| `tools/` | Host tools (`mkpack.c`, `mkrootfs.c`, `mkrtwtbl.c`, `mkcursors.c`, `mkicons.c`, `mkwoff.py`, `kexec_send.c`, `netkexec_send.c`, `netmonitor.c`, `flash.sh`, `xcursor_trim.py`), the QMP test scripts and `cursor_test.c` |
+| `tools/` | Host tools (`mkpack.c`, `mkrootfs.c`, `mkrtwtbl.c`, `mkcursors.c`, `mkicons.c`, `jsstrip.c`, `mkwoff.py`, `kexec_send.c`, `netkexec_send.c`, `netmonitor.c`, `flash.sh`, `xcursor_trim.py`), the QMP test scripts and `cursor_test.c` |
 | `assets/` | Imported assets: `assets/cursors/adwaita/` (the Adwaita 24 px Xcursor files) and `assets/icons/adwaita/` (the Adwaita symbolic SVGs used as UI icons), both LGPL-3 / CC-BY-SA-3.0, with README and licences |
 | `host/` | Linux SDL3 browser harness |
 
@@ -128,7 +128,9 @@ make clean
 ```
 
 - Build flags (in `Makefile`): `-m32 -march=i586 -ffreestanding -fno-pie -nostdlib
-  -fno-stack-protector -mno-sse -mno-sse2 -mno-mmx -O2`.
+  -fno-stack-protector -mno-sse -mno-sse2 -mno-mmx -O2`.  The ring-3 WM and
+  viewer are per-object `-Os` with function sections, like the other size-
+  sensitive GUIs, because the 2 MB gzip rootfs pack is close to its cap.
 - `make browser-host` is a development-only harness, not part of the images: it
   builds `browser.c`, ngui, the image/TLS stack and QuickJS as a 32-bit Linux
   program against the same `SYS_*` ABI (`host/syscall.c`, an SDL3 window,
@@ -353,7 +355,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   and the shadow flush) or the BKL is held; voluntary blocks/yields go through
   the `int 0x81` gate.
 - **SMP / ACPI**: `acpi.c/h` (RSDP → RSDT/XSDT → MADT; CPU/LAPIC and IOAPIC
-  base lists; 4 MB table page mapping; malformed tables are ignored),
+  base lists; 4 MB table page mapping; the FADT PM1 control blocks, flags and
+  the DSDT (or SSDT) `\_S5` sleep types; malformed tables are ignored),
   `ioapic.c/h` (masks the normal IOAPIC redirection entries after ACPI init so
   the 8259/LINT0 path is deterministic; ExtINT entries are preserved),
   `lapic.c/h`
@@ -373,6 +376,21 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   into `struct process.fpu` and FRSTORs the incoming one (FNINIT for a
   process that never ran); the kernel uses no x87, and its SSE helpers
   touch only XMM registers, which ring 3 (`-mno-sse`) never uses.
+  `acpi_poweroff()` enables ACPI through the FADT SMI command (or the
+  conventional `0xB2`/`0xF1` pair) when `SCI_EN` is clear, then sets
+  `SLP_TYP` and `SLP_EN` in PM1a/PM1b with a read-modify-write that keeps
+  `SCI_EN` set (the type first, `SLP_EN` in a second write).  The values
+  come from the FADT and the decoded `\_S5` package.  Intel-style
+  southbridges also clear `SMI_EN.SLP_SMI_EN` (bit 4 at PMBASE+0x30) so
+  the sleep write is not turned into an SMI.  NVIDIA nForce/MCP boards (the
+  ION) run S5 through the firmware SMM instead: the same path writes the
+  sleep state into the BIOS NVS (ASSB=5, AOTB/OSTP for Linux, AAXB=0) and
+  arms PS1S/PS1E in the SMI block, matching the DSDT's `_PTS(5)`.  So
+  `poweroff` performs a real ACPI S5 shutdown on BIOS and UEFI boots alike
+  (both hand the kernel the same ACPI tables); the Bochs/QEMU ports are
+  only the emulator fallback.  If no path works the command returns instead
+  of halting: the WM shows `poweroff failed` and the FADT/S5/`SCI_EN` state
+  is in the netlog.
 - **Memory**: `phys.h` — `MM_MAX_PHYS` (1 GB, the lowmem/identity-map
   ceiling, also used by the UEFI loader for the pack buffer), `MM_KMAP_VA`
   (`0x4FC00000`) and `MM_HIGH_LIMIT` (4 GB).  Lowmem ends where ring-3 space
@@ -514,6 +532,24 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   window behind it.  While dragged or resized the WM owns the pointer
   (`SYS_WM_MOUSE_CAPTURE`), so canvas clients see no held button and cannot
   start a scrollbar drag.  The kernel hit-test uses the same order.
+  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
+  `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
+  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
+  stretches the stored buffer into every desktop damage rectangle under the
+  bar and windows, with a static 2.4 MB buffer plus a 256 KB RGB565-to-BGRA
+  table for 32 bpp (and direct stores for 16/24 bpp).  A row pointer starts
+  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.
   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
@@ -616,8 +652,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `SYS_GFX_BEGIN/PRESENT/END` terminal-takeover service and the kernel
   text-canvas renderer are removed.  Pointer input: `SYS_WIN_POINTER` reports
   the content-relative position, buttons and focus, and `SYS_WIN_EVENT` queues
-  press/release edges with a capture window, so a click that starts in a
-  window still gets its release after the pointer leaves.  The userland
+  left and right press/release edges with a capture window (its `button` field
+  says which button changed), so a click that starts in a window still gets
+  its release after the pointer leaves.  `ngui` exposes `right_pressed`/
+  `right_released` beside the left `pressed`/`released` edges, which widgets
+  do not consume; the browser uses them for its page context menu.  The userland
   `ngui.c/h` immediate-mode toolkit builds on those: clipped RGB565
   primitives, buttons, text input, the Adwaita symbolic icons and scrolling panes
   (`ngui_scroll`: an overlay scrollbar that is hidden while the pointer is
@@ -909,6 +948,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   works.  Files are 8.3 only until FAT LFN write support exists.  A reinstall
   replaces P1..P3 and keeps P4; `net-install` never touches it.  The data
   volume is not available on the live USB unless that stick was installed.
+  The image viewer stores the desktop wallpaper in `WALLPAPR.BIN` here (the
+  WM's `wall_load()` looks for it at boot and after a change).
 - **SATA/AHCI**: `ahci.c/h` — polled AHCI driver (first controller only, PCI
   class `01:06:01`, no IRQs, no NCQ): port bring-up with COMRESET, IDENTIFY
   (shared `ata_identify_parse()` with `ata.c`) and READ/WRITE DMA EXT through
@@ -1245,8 +1286,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   ngui) uses the same ids for the bar's network and battery icons.
   `tools/mkicons.c` rasterizes
   each SVG with the browser's `svg_raster.c` into a 16x16 8-bit coverage
-  mask and writes one `NBICO1` bundle (16-byte header + masks, 24 icons,
-  ~6.2 KB, ~1.3 KB gzip) packed as `icons/adwaita16.icn` in **both** packs.
+  mask and writes one `NBICO1` bundle (16-byte header + masks, 25 icons,
+  ~6.3 KB, ~1.4 KB gzip) packed as `icons/adwaita16.icn` in **both** packs.
   Its XML reader handles only what symbolic icons use (`<svg viewBox>`,
   `<g>`, `<path>`, `<rect>`, `<circle>`, `<ellipse>`,
   fill/fill-rule/opacity) and
@@ -1788,6 +1829,29 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   Up/Down preview a row in the bar, Delete forgets the highlighted row,
   Esc closes the list (and drops the completion), a click opens a row.
   The in-session back/forward stack (`history[]`, 16 entries) is separate.
+  **Downloads**: right-clicking the page opens an in-window context menu
+  (`ngui.right_pressed`): over an `<img>` or a CSS `background-image` it
+  offers *Save image*, over a link *Save link*, and anywhere *Save page*
+  (not for `about:` URLs).  `dl_queue()` puts one job in a 24-entry static
+  list; a dedicated fifth `curl __serve` helper outside `fetch_workers`
+  fetches it, so a navigation that cancels the page's image workers does not
+  cancel the download.  The request line is `<seq> <cap> DL <url>`; the
+  helper skips gzip, reads the body in 16 KB slices and writes
+  `/share/bf...prog` (`seq`, bytes received, Content-Length or 0) at most
+  every 100 ms.  When `/data` is mounted the browser copies the body to
+  `/data/DOWNLOAD`, else `/share/DOWNLOAD`, with a FAT-safe 8.3 name from
+  the URL basename (MIME-type extension when there is none, `~N` collision
+  suffixes), then drops the helper files.  The body cap is the helper's
+  4 MB.  The toolbar's download button opens a panel with the newest twelve
+  jobs: live percentage/progress bar for the active one, size for a finished
+  file, error text for a failure, and a *Clear* action for completed
+  entries.  The icon carries a progress bar while a job runs and an accent
+  dot for unseen completions.  The list is `/share/bdownloads` plus
+  `/data/BDOWN.DAT` (8.3, plaintext `NBDL1\n` then
+  `state\nsize\nname\npath\n`), so history survives a reload/reboot; the
+  panel reads `/share` first, else `/data`.  One download runs at a time
+  (the extra helper keeps the page pool intact) and it continues while the
+  page scrolls, a new page loads or the window loses focus.
   Images are prefetched up to four at a time and only when their measured
   position is within the viewport plus 160 px; deferred images are loaded as
   the page scrolls.  Network work runs in up to `FETCH_WORKERS` (four)
@@ -1940,8 +2004,26 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   run (the microtask checkpoint, `mu_do_jobs`) and reported only if no
   handler was attached by then (`Promise.reject(e).then(f).catch(g)` used
   to print "Uncaught").  `js_prelude.js` (embedded by `js_prelude.S`, run once per
-  state before the page's scripts) implements the Web APIs in JavaScript on
+  state before the page's scripts; the build embeds
+  `build/user/apps/browser/js_prelude.min.js`, which the host tool
+  `tools/jsstrip.c` makes by dropping comments, indentation and the blanks
+  that do not separate two tokens -- ~4 KB of gzip in the rootfs pack, with
+  names and line breaks kept) implements the Web APIs in JavaScript on
   three C primitives (`__nb_http`, `__nb_storage`, `__nb_resolve`):
+  an en-US-only `Intl` (QuickJS has none; the Cloudron dashboard's date
+  helpers threw `'Intl' is not defined`): `DateTimeFormat` (fields,
+  `dateStyle`/`timeStyle`, `formatToParts`, always UTC, which is also
+  `resolvedOptions().timeZone`), `NumberFormat` (decimal/percent/currency/
+  unit, compact, significant digits, sign display), `RelativeTimeFormat`,
+  `DurationFormat`, `DisplayNames` (a small language/region table),
+  `Collator`, `PluralRules`, `ListFormat` and a stub `Locale`; it also
+  replaces `Date.prototype.toLocale*String`, `Number.prototype.
+  toLocaleString` and `String.prototype.localeCompare` (ICU-like: case- and
+  accent-blind first, whitespace < punctuation < digits < letters);
+  constraint validation (`checkValidity`/`reportValidity`/`validity`/
+  `setCustomValidity` on controls and forms: required, min/maxlength,
+  pattern, email/url syntax, number min/max; `reportValidity` shows no
+  bubble; the dashboard's domain dialog calls it on every input),
   `fetch`/`Request`/`Response`/`Headers`, `XMLHttpRequest`, `URL`/
   `URLSearchParams`, `TextEncoder`/`TextDecoder`, `btoa`/`atob`, `Blob`/
   `File`/`FormData` (urlencoded only), `AbortController`,
@@ -2199,7 +2281,12 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   animated GIF frames are supported as well; arithmetic JPEG/CMYK are not.
   The viewer, `ucmd_view.c`, owns a canvas window and reads its file through
   `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size,
-  animates GIFs, and gives a clear error for unsupported variants.  The chat
+  animates GIFs, and gives a clear error for unsupported variants.  Its
+  toolbar's *Background* button (or `b`) calls `view_set_wallpaper()`: it
+  reads `SYS_SCREEN_INFO`, cover-scales the image into a screen-aspect
+  RGB565 buffer capped at 1440x810, writes `/data/WALLPAPR.BIN` or
+  `/share/wallpaper` and signals the WM.  The status bar shows
+  "Wallpaper set" (or the failure) for four seconds.  The chat
   client decodes fetched message images and avatars into a 480x320 / 32x32
   cache (passing those bounds to `img_options.max_w/h`) and draws them with
   `img_draw()`.  Host
@@ -2270,7 +2357,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 ## Shell commands
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
-`mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
+`mkdir <path>`, `rmdir <path>`, `hello`, `acpidump` (writes the mapped
+DSDT to `/share/DSDT.BIN`), `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `disks` (the ngui storage manager), `meminfo`, `top`, `process` (the ngui task manager), `bootscan` (the live boot storage-scan window), `sched`, `format [-y] <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk; `-y` skips the prompt), `install [-y] <target> [source|self]` (clone the live image, or write the running image; auto-detects the source, preferring `usb0`; `auto` targets the only non-USB NebOS disk),
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `membench` (ring-3 speed check: TSC, ALU, heap/BSS memcpy, syscall rates), `backlight [0-100|up|down]` (also `probe`), `keytest` (raw scancode tap), `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
 
@@ -2510,7 +2598,12 @@ briefly reporting disconnected.
   Disabling clears ASE and acknowledges `STS_IAA`; leaving the IAA doorbell
   status set stalls the next enable.  Bulk `in`/`out` use one qTD per call
   (up to five 4 KB buffer pages), which is enough for the ASIX AX88772 RX/TX
-  path.  The HCD vtable's optional `bulk_reset` disarms the endpoint's qTD,
+  path.  A bulk-IN qTD is armed with exactly the length of the call that
+  starts it and is not pre-armed for a later, possibly shorter chunk: a
+  device that ends a transfer on a max-packet boundary without a zero-length
+  packet (a USB stick's 512-byte READ(10) data stage) would otherwise leave a
+  larger qTD ACTIVE forever.  The HCD vtable's optional `bulk_reset` disarms
+  the endpoint's qTD,
   clears its data toggle and drops the bulk state, so a timed-out bulk-IN
   transfer cannot leave the endpoint permanently armed; xHCI stops the
   endpoint before dropping its ring.  After an async-transfer gap of 100 ms
@@ -2875,9 +2968,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    with `--gc-sections`; the current full pack with the UI fonts, both
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
-   bytes) and `install/kernel.bin` is ~1.98 MiB gzip (~20 KB under the
-   cap), inflating to ~4.1 MB, which adds about
-   half a second to the boot; the floppy lite pack is ~638 KiB gzip and
+   bytes) and `install/kernel.bin` is ~2.00 MiB gzip (~4 KB under the
+   cap), inflating to ~4.13 MB, which adds about
+   half a second to the boot; the floppy lite pack is ~641 KiB gzip and
    deliberately omits the firmware, `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.1 MiB) now takes about four
@@ -2979,6 +3072,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     small RX ring and stall TLS handshakes into a 10 s timeout; use e1000
     (the shared receive-window budget in `tcp.c` limits, but does not
     rule out, such overruns).
+    `Intl` is a small en-US subset: the locale argument is ignored (a
+    `de` formatter prints English), every date is formatted in UTC
+    whatever `timeZone` says, `DisplayNames` knows ~45 languages and ~18
+    regions (others fall back to the code), and number rounding goes
+    through binary `toFixed` (ICU rounds the decimal value, so a few
+    halfway cases differ).
     `DOMParser` and `document.implementation.createHTMLDocument` return an
     inert detached document (its nodes live in the page arena; markup goes
     through the innerHTML fragment parser, split at `<head>`/`<body>`),
@@ -3103,6 +3202,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     normal browser's.  `@layer` ranks nested layers flat by first
     appearance (a parent layer's own rules lose to its sublayers, the spec
     says the reverse).
+    Downloads are capped at the helper's 4 MB, run one at a time, cannot be
+    cancelled or retried from the panel, use 8.3 names on both `/data` and
+    `/share`, skip `data:`/`mailto:`/`javascript:` targets, and the panel
+    shows only the newest twelve of 24 entries.  The history file is
+    last-writer-wins between browser windows.
     TLS is phase A (no certificate verification); `https` is shown as
     unverified.  The disk app
     is loaded from FAT at spawn time, so a cold floppy start takes a few
@@ -3122,8 +3226,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     OVMF delivers the ISA IRQs through the 8259 path; the kernel nevertheless
     masks the IOAPIC's normal redirection entries after ACPI init, so
     firmware-left vectors cannot collide with the PIC or LAPIC timer.
-    UEFI runtime services are not used, so
-    `reboot`/`poweroff` still use the legacy ports.  The image is 17 MB: the
+    UEFI runtime services are not used: `reboot` still pulses the keyboard
+    controller and `poweroff` uses ACPI S5 (the FADT PM1a/PM1b control blocks
+    and the DSDT `\_S5` sleep type, enabling ACPI through the SMI command
+    when `SCI_EN` is clear) on both BIOS and UEFI boots, with the
+    Bochs/QEMU ports as an emulator fallback.  The image is 17 MB: the
     9 MB kernel + rootfs disk and the 8 MB ESP.  Maxwell GPUs such as the
     GTX 960 use the firmware VBE/GOP framebuffer only; there is no native
     NVIDIA driver, and `nv50_probe()` is gated to the ION/nv50 chipsets.
@@ -3379,3 +3486,13 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     The cursor shape follows the WM poll, so it can lag the pointer by
     one WM loop.  The 4 KB save buffer and the cursor code (~8 KB in all) are included in
     `_end` ~0x8df80, ~8 KB below the `0x90000` wall.
+
+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
+    `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.

+ 25 - 3
Makefile

@@ -129,6 +129,10 @@ KERNEL_OS = terminal disk fat nvidia nv50 uhci ohci ehci xhci asix rndis \
 	peek ne2000 r8168 blkdev fatdetect fatformat format install usbmsc dbg vfs
 $(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
+# and the kernel is close to the low-memory wall; squeeze them hard.
+$(B)/kernel/acpi.o: OPT = -Oz
+$(B)/kernel/poweroff.o: OPT = -Oz
 
 # The AP trampoline is linked at 0x6000 and embedded as a binary blob; ld
 # names its symbols after the input path, so run it inside the build dir
@@ -412,6 +416,11 @@ $(call app,edit).o $(call app,wm).o $(call app,files).o $(call app,mines).o \
 $(call app,settime).o $(call app,solitaire).o $(U)/apps/gallery/gallery.o \
 $(U)/apps/hello/hello.o: XFLAGS =
 $(call app,settime).o $(call app,solitaire).o: OPT = -Os
+# Both link with --gc-sections; the section-per-function build lets the pack
+# drop their unreachable helpers (the rootfs cap is tight).
+$(call app,wm).o: XFLAGS = $(SECTION_CFLAGS)
+$(call app,view).o: XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
+$(call app,wm).o $(call app,view).o: OPT = -Os
 
 # membench times memcpy/memset over a libc heap buffer.
 $(call app,membench).elf: $(call app,membench).o $(UCMD_LD) $(LIBC_A)
@@ -582,9 +591,9 @@ $(HOST_BUILD)/host/%.o: host/%.c
 	@mkdir -p $(dir $@)
 	$(HOST_CC) $(HOST_CFLAGS) $(DEPFLAGS) -c -o $@ $<
 
-$(HOST_BUILD)/js_prelude.o: user/apps/browser/js_prelude.S user/apps/browser/js_prelude.js
+$(HOST_BUILD)/js_prelude.o: user/apps/browser/js_prelude.S $(BR)/js_prelude.min.js
 	@mkdir -p $(dir $@)
-	$(HOST_CC) -m32 -Wa,-Iuser/apps/browser -c -o $@ $<
+	$(HOST_CC) -m32 -Wa,-I$(BR) -c -o $@ $<
 
 $(HOST_BUILD)/user/apps/browser/browser.o: HOST_EXTRA = -D_start=browser_start
 $(HOST_BUILD)/user/apps/curl/ucmd_curl.o: HOST_EXTRA = -D_start=curl_start
@@ -779,6 +788,19 @@ netmonitor: tools/netmonitor.c
 mkicons: tools/mkicons.c include/icon_abi.h user/apps/browser/svg_raster.c user/apps/browser/svg_raster.h
 	gcc -O2 -Wall -Wextra -Iinclude -o $@ tools/mkicons.c user/apps/browser/svg_raster.c -lm
 
+jsstrip: tools/jsstrip.c
+	gcc -O2 -Wall -Wextra -o $@ $<
+
+# The browser prelude is embedded without its comments and indentation
+# (tools/jsstrip.c): ~3.5 KB of gzip in the rootfs pack.
+$(BR)/js_prelude.min.js: user/apps/browser/js_prelude.js jsstrip
+	@mkdir -p $(@D)
+	./jsstrip $< $@
+
+$(BR)/js_prelude.o: user/apps/browser/js_prelude.S $(BR)/js_prelude.min.js
+	@mkdir -p $(@D)
+	$(AS) $(ASFLAGS) -I$(BR) -o $@ $<
+
 mkcursors: tools/mkcursors.c include/cursor_abi.h
 	gcc -O2 -Wall -Wextra -Iinclude -o $@ $<
 
@@ -1249,7 +1271,7 @@ clean:
 	      cmds.pack cmds-lite.pack cmds_pack_gz.bin cmds_lite_gz.bin \
 	      rootfs.bin rootfs-full.bin cmds.img \
 	      firmware/*.ucode firmware/*.tbl firmware/*.bin cursors/*.cur icons/*.icn \
-	      mkpack mkrootfs mkrtwtbl mkcursors mkicons cursor_test kexec_send netkexec_send netmonitor \
+	      mkpack mkrootfs mkrtwtbl mkcursors mkicons jsstrip cursor_test kexec_send netkexec_send netmonitor \
 	      browser-host host-curl \
 	      ufont_test ufont_test_asan svg_test touchpad_gesture_test \
 	      ujson_test uhttp_cookie_test chat_login_test tls_test wpa_test \

+ 1 - 0
assets/icons/adwaita/folder-download-symbolic.svg

@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 16 16"><path fill="#2e3436" d="M7.984375 0c-.550781 0-1 .449219-1 1v8.585938L4.691406 7.292969C4.503906 7.105469 4.25 7 3.984375 7s-.519531.105469-.707031.292969c-.390625.390625-.390625 1.023437 0 1.414062l4 4c.390625.390625 1.023437.390625 1.414062 0l4-4c.390625-.390625.390625-1.023437 0-1.414062s-1.023437-.390625-1.414062 0L8.984375 9.585938V1c0-.550781-.449219-1-1-1m-6 14v2h12v-2zm0 0"/></svg>

+ 27 - 1
docs/cpu.html

@@ -157,6 +157,31 @@
 			the intended century. Boards without ACPI get no century write and
 			keep the 1970–2069 read window.
 		</p>
+		<p>
+			It also caches the FADT power-management blocks and scans the DSDT
+			(or an SSDT) for <code>\_S5</code>. The <code>poweroff</code> command
+			read-modify-writes the sleep type into PM1a/PM1b, keeping the existing
+			<code>SCI_EN</code> bit set — writing only the sleep bits clears it,
+			and some real chipsets then ignore the request. It writes
+			<code>SLP_TYP</code> first and <code>SLP_EN</code> in a second write.
+			Intel-style southbridges clear <code>SMI_EN.SLP_SMI_EN</code> (bit 4
+			at <code>PMBASE+0x30</code>): while that bit is set the chipset turns
+			the <code>SLP_EN</code> write into an SMI instead of a power
+			transition. NVIDIA nForce/MCP boards (the ION) run S5 through the
+			firmware SMM instead: the kernel writes the sleep state into the
+			BIOS NVS (<code>ASSB=5</code>, Linux <code>AOTB</code>/<code>OSTP</code>,
+			<code>AAXB=0</code>) and arms <code>PS1S</code>/<code>PS1E</code> in
+			the SMI block, matching the DSDT's <code>_PTS(5)</code>, before the
+			<code>SLP_EN</code> write. If <code>SCI_EN</code> is clear it first
+			enables ACPI mode through the FADT SMI command (or the conventional
+			<code>0xB2</code>/<code>0xF1</code> pair). BIOS and UEFI boots share
+			this path because both hand the kernel the same ACPI tables; only the
+			RSDP discovery differs (EBDA scan versus the loader's boot info).
+			Emulators whose tables do not decode <code>\_S5</code> fall back to
+			the Bochs/QEMU shutdown ports. A failed poweroff returns to the
+			desktop instead of halting, and the boot/poweroff log carries the
+			PM1, <code>\_S5</code> and <code>SCI_EN</code> state.
+		</p>
 		<ol>
 			<li>Copy the AP trampoline to <code>0x6000</code> (SIPI vector <code>0x06</code>).</li>
 			<li>Allocate an AP idle PCB and kernel stack via <code>process_init_ap()</code>.</li>
@@ -379,7 +404,8 @@
 			<li><code>kernel/process.c</code>, <code>kernel/process.h</code> — PCBs and lifecycle</li>
 			<li><code>kernel/switch.S</code> — context switch</li>
 			<li><code>kernel/tss.c</code>, <code>kernel/tss.h</code> — per-CPU TSS</li>
-			<li><code>kernel/acpi.c</code>, <code>kernel/ioapic.c</code>, <code>kernel/lapic.c</code>, <code>kernel/smp.c</code> — SMP and IOAPIC masking</li>
+			<li><code>kernel/acpi.c</code>, <code>kernel/ioapic.c</code>, <code>kernel/lapic.c</code>, <code>kernel/smp.c</code> — SMP, IOAPIC masking and the FADT S5 shutdown data</li>
+			<li><code>kernel/poweroff.c</code> — ACPI S5 poweroff with the emulator port fallback</li>
 			<li><code>kernel/ap_tramp.S</code> — AP startup blob</li>
 			<li><code>kernel/timer.S</code>, <code>kernel/idle.c</code>, <code>kernel/power.c</code></li>
 			<li><code>kernel/thermal.c</code> — Intel DTS and AMD D18F3xA4 sampling</li>

+ 1 - 1
docs/development.html

@@ -239,7 +239,7 @@
 					<tr><td><code>make test-chat</code></td><td>Host tests (ASan/UBSan) for the chat client's JSON parser, cookie jar and the OIDC login page/reply/config parsers.</td></tr>
 					<tr><td><code>make test-chat-e2e</code></td><td>Boots QEMU with an NE2000 on slirp, starts <code>tools/mock_chat.py</code> and drives <code>chat</code> through QMP: native login, send, live poll, read marker, older paging, browse/join, new DM, saved-session resume and sign-out.  <code>CHAT_E2E=--totp|--consent|--passkey|--wrong</code> runs a login variant.</td></tr>
 					<tr><td><code>make compat-serve</code></td><td>Serve the browser compatibility ladder from <code>testdata/browser/compat/</code> on port 8000 for the board or QEMU guest.</td></tr>
-					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display, and <code>--keys 'clo{down}{enter}'</code> types into it (one key per 100 ms; <code>{enter}</code>, <code>{esc}</code>, <code>{tab}</code>, <code>{bs}</code>, <code>{del}</code>, arrows, <code>{ctrl-l}</code>, <code>{wait}</code>, <code>{click:X,Y}</code> for a left click at canvas coordinates, and <code>{move:X,Y}</code> to only move the pointer, for hover). Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
+					<tr><td><code>make browser-host</code></td><td>Build the Linux SDL3 development harness (<code>browser-host</code> and its <code>host-curl</code> helper). It implements the ring-3 <code>SYS_*</code> ABI with host files, BSD sockets, <code>fork/exec</code> and an SDL3 window, so pages render and accept input without QEMU. Run <code>./browser-host [--size WxH] [--root DIR] URL|FILE</code>; <code>--headless --wait 3000 --shot out.ppm</code> writes the canvas without a display, and <code>--keys 'clo{down}{enter}'</code> types into it (one key per 100 ms; <code>{enter}</code>, <code>{esc}</code>, <code>{tab}</code>, <code>{bs}</code>, <code>{del}</code>, arrows, <code>{ctrl-l}</code>, <code>{wait}</code>, <code>{click:X,Y}</code> for a left click at canvas coordinates, <code>{rclick:X,Y}</code> for a right click (context menus), and <code>{move:X,Y}</code> to only move the pointer, for hover). Needs the 32-bit SDL3/Wayland libraries (<code>lib32-sdl3</code>, <code>lib32-wayland</code>, <code>lib32-libxkbcommon</code>).</td></tr>
 					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
 			</table>

+ 1 - 1
docs/drivers.html

@@ -290,7 +290,7 @@
 				<tbody>
 					<tr><td>UHCI</td><td>PCI I/O ports</td><td>1</td><td>Frame list at <code>0x3000</code>; control QH plus one QH per interrupt slot.</td></tr>
 					<tr><td>OHCI</td><td>PCI MMIO</td><td>up to 4</td><td>HCCA from the page allocator, static ED/TD sets in the uncacheable <code>ohci_dma_page</code>, TDs start at <code>CC = NotAccessed</code>. Before reset it requests SMM ownership (<code>HcCommandStatus.OCR</code>, clear <code>HcControl.IR</code>) and disables the AMD southbridge USB SMI on <code>1002:4385</code>.</td></tr>
-					<tr><td>EHCI</td><td>PCI MMIO</td><td>up to 4</td><td>Async QH/qTD schedule, page-allocated descriptors, polling only, no periodic list. The async-advance doorbell (<code>IAAD</code>) is rung after an idle gap and before cancelling a stuck transfer; the MCP79 can otherwise keep a halted QH's old qTD cached and never fetch a USB disk's first read after enumeration.</td></tr>
+					<tr><td>EHCI</td><td>PCI MMIO</td><td>up to 4</td><td>Async QH/qTD schedule, page-allocated descriptors, polling only, no periodic list. The async-advance doorbell (<code>IAAD</code>) is rung after an idle gap and before cancelling a stuck transfer; the MCP79 can otherwise keep a halted QH's old qTD cached and never fetch a USB disk's first read after enumeration. A bulk-IN qTD is armed with exactly the starting call's length and is not pre-armed for a later chunk, so a device that ends a 512-byte sector transfer without a zero-length packet still completes.</td></tr>
 					<tr><td>xHCI</td><td>PCI MMIO</td><td>—</td><td>USB2 and USB3 root ports; direct SuperSpeed devices use a 512-byte EP0 and the port speed in the slot context (USB3 hubs are not decoded). Halts and waits for <code>HCH</code> around <code>HCRST</code>; EP0 max packet is the speed's fixed value (8/64/512), and a full-speed EP0 is corrected with Evaluate Context after the first descriptor read (the VIA VL805 on the 970A-DS3P babbled on a high-speed stick otherwise); a SuperSpeed port is not PED-disabled before its reset; failed control transfers are always logged with their completion code; EP0 stages are encoded as one TD per stage (EDK2 style) because chained control TDs stall on Braswell.</td></tr>
 				</tbody>
 			</table>

+ 1 - 0
docs/filesystems.html

@@ -316,6 +316,7 @@
 			<li><strong>8.3 names.</strong> The FAT driver creates and reads short names only; long names need VFAT LFN write support.</li>
 			<li><strong>WiFi credentials.</strong> A successful WiFi connect adds the network to a most-recently-used list of up to 16 SSID/passphrase records in <code>WIFI.CFG</code>; the boot-time <code>wifi autoconnect</code> helper scans and joins the strongest saved network it finds. <code>wifi saved</code> lists them and <code>wifi forget [ssid]</code> removes one. The file is plaintext and 8.3, like the rest of the volume.</li>
 			<li><strong>Chat session.</strong> The Chat client stores its server and session cookie in <code>CHAT.CFG</code> when this volume is mounted; without it the client falls back to the RAM-only <code>/share/chat.cfg</code>. The cookie is a bearer credential, and the password is never stored.</li>
+			<li><strong>Wallpaper.</strong> The image viewer's <em>Background</em> action writes the pre-scaled RGB565 desktop image to <code>WALLPAPR.BIN</code> here when this volume is mounted; the WM loads it at boot and after every change. Without <code>/data</code> the image goes to the RAM-only <code>/share/wallpaper</code>.</li>
 			<li><strong>Fixed start.</strong> P4 starts at LBA 34816. A BIOS-only install leaves the space between P2 and P4 unpartitioned, and a later disk clone does not resize P4.</li>
 			<li><strong>Mount settings.</strong> The <code>disks</code> app saves the mount policies in <code>MOUNTS.CFG</code>; the boot scan applies them (see below).</li>
 			<li><strong>No fsck.</strong> Like the other FAT mounts, the volume has no journal, repair tool or permissions; it is writable by every process.</li>

+ 11 - 6
docs/graphics.html

@@ -156,7 +156,12 @@
 			A normal window has no visible frame; an invisible resize band
 			(1 px inside, 3 px outside its outer edge) is the resize grab
 			area, and the active title bar uses the toolkit's highlight
-			colour.
+			colour. 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.
 			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
@@ -467,7 +472,7 @@
 			</div>
 			<div class="card">
 				<h3>view</h3>
-				<p>Image viewer with fit, 1:1, zoom, pan, EXIF orientation and animated GIF playback.</p>
+				<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>clock / colors / settime</h3>
@@ -475,7 +480,7 @@
 			</div>
 			<div class="card">
 				<h3>browser</h3>
-				<p>HTML/CSS renderer with flex rows, auto-fit and <code>repeat(N, 1fr)</code> card grids, <code>aspect-ratio</code> frames, inline-block runs, inline SVG icons, basic tables and inline SVG diagrams. It decodes inline images at their laid-out bounds (a JPEG gets a reduced IDCT) in the fetch helper, caches a display-size bitmap per image so repaints are 1:1, and fetches through the same helper; image repaints are coalesced and <code>/share/IMGSTAT</code> reports where a load spent its time. Inline and external scripts run on the vendored QuickJS engine (ES2025), and forms render and submit natively. The largest ring-3 application in the tree.</p>
+				<p>HTML/CSS renderer with flex rows, auto-fit and <code>repeat(N, 1fr)</code> card grids, <code>aspect-ratio</code> frames, inline-block runs, inline SVG icons, basic tables and inline SVG diagrams. It decodes inline images at their laid-out bounds (a JPEG gets a reduced IDCT) in the fetch helper, caches a display-size bitmap per image so repaints are 1:1, and fetches through the same helper; image repaints are coalesced and <code>/share/IMGSTAT</code> reports where a load spent its time. Inline and external scripts run on the vendored QuickJS engine (ES2025), and forms render and submit natively. Right-clicking the page opens a context menu that saves images, link targets or the page itself into <code>/data/DOWNLOAD</code> (or <code>/share/DOWNLOAD</code>); a toolbar download button shows live progress and the download history. The largest ring-3 application in the tree.</p>
 			</div>
 		</div>
 	</section>
@@ -502,8 +507,8 @@
 		<h2>UI icons</h2>
 		<p>
 			ngui's icons (<code>ngui_icon()</code>, <code>ngui_icon_button()</code>:
-			back/forward, reload and home in the browser toolbar, folder/file/drive
-			in <code>files</code>) and the WM's top-bar network/battery
+			back/forward, reload, home and downloads in the browser toolbar,
+			folder/file/drive in <code>files</code>) and the WM's top-bar network/battery
 			indicators are GNOME Adwaita symbolic icons
 			(adwaita-icon-theme 51, LGPL-3 or CC-BY-SA-3.0).  The unchanged
 			<code>*-symbolic.svg</code> files live in
@@ -513,7 +518,7 @@
 			8-bit coverage mask and writes one <code>NBICO1</code> bundle,
 			<code>/ramfs/icons/adwaita16.icn</code> (layout in
 			<span class="file">include/icon_abi.h</span>): a 16-byte header and
-			24 masks, ~6.2&nbsp;KB raw and ~1.3&nbsp;KB gzip, so both the USB
+			25 masks, ~6.3&nbsp;KB raw and ~1.4&nbsp;KB gzip, so both the USB
 			and the floppy pack carry it.
 		</p>
 		<ul>

+ 1 - 1
docs/index.html

@@ -159,7 +159,7 @@
 			<li><strong>Identity-mapped paging.</strong> Physical and virtual addresses are equal. There is no per-process address space or isolation.</li>
 			<li><strong>1 GB lowmem, 4 GB highmem.</strong> The identity map ends where ring-3 space starts (<code>0x40000000</code>); RAM up to 4 GB backs ring-3 pages through per-CPU <code>kmap</code> slots.</li>
 			<li><strong>Hardcoded low memory.</strong> Boot info, the E820 map, the framebuffer block and the AP trampoline have fixed addresses that every boot path must honour.</li>
-			<li><strong>No firmware runtime.</strong> <code>reboot</code> and <code>poweroff</code> use legacy ports; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
+			<li><strong>No firmware runtime.</strong> <code>reboot</code> resets through the keyboard controller and <code>poweroff</code> writes ACPI S5 from the FADT/DSDT; UEFI runtime services are not called after <code>ExitBootServices</code>.</li>
 		</ul>
 		<div class="warn">
 			<p><strong>Fresh memory is not zeroed.</strong> <code>mm_alloc_page</code> and <code>kmalloc</code> return whatever RAM contained. Every structure read before it is written must be cleared on allocation; QEMU hides this because its RAM starts clear.</p>

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
docs/network.html


Разница между файлами не показана из-за своего большого размера
+ 2 - 1
docs/userland.html


+ 2 - 1
host/main.c

@@ -6,7 +6,8 @@
  * --keys types into a headless window, one key every 100 ms from 300 ms
  * after the first frame: plain characters, plus {enter} {esc} {tab} {bs}
  * {del} {up} {down} {left} {right} {ctrl-l}, {wait} (a 1 s pause) and
- * {click:X,Y} (a left click at canvas coordinates X,Y) and {move:X,Y}
+ * {click:X,Y} (a left click at canvas coordinates X,Y),
+ * {rclick:X,Y} (a right click) and {move:X,Y}
  * (move the pointer there without a click, for hover).
  */
 #include <signal.h>

+ 14 - 7
host/window_headless.c

@@ -108,11 +108,12 @@ void host_headless_pump(unsigned int timeout_ms)
 		usleep(timeout_ms * 1000u);
 }
 
-/* --keys `{click:X,Y}`: the pointer moves there and a left press is
- * queued, its release on the next event poll; `{move:X,Y}` only moves
- * it (hover). */
+/* --keys `{click:X,Y}` / `{rclick:X,Y}`: the pointer moves there and a
+ * left/right press is queued, its release on the next event poll;
+ * `{move:X,Y}` only moves it (hover). */
 static int ptr_x, ptr_y;
 static unsigned int ptr_buttons;
+static unsigned int click_button;   /* bit0 left, bit1 right */
 static int click_pending;       /* 1 press queued, 2 release queued */
 
 int host_headless_pointer(struct win_pointer *out)
@@ -132,13 +133,14 @@ int host_headless_event(struct win_event *out)
 		return 0;
 	out->x = ptr_x;
 	out->y = ptr_y;
+	out->button = click_button;
 	if (click_pending == 1) {
 		out->type = WIN_EV_POINTER_DOWN;
-		ptr_buttons = 1;
+		ptr_buttons |= click_button;
 		click_pending = 2;
 	} else {
 		out->type = WIN_EV_POINTER_UP;
-		ptr_buttons = 0;
+		ptr_buttons &= ~click_button;
 		click_pending = 0;
 	}
 	out->buttons = ptr_buttons;
@@ -185,11 +187,16 @@ int host_headless_key(void)
 		key_due = now + 300;
 		return 0;
 	}
-	if (code == '{' && !strncmp(key_pos, "click:", 6)) {
+	if (code == '{' && (!strncmp(key_pos, "click:", 6) ||
+			    !strncmp(key_pos, "rclick:", 7))) {
 		const char *end = strchr(key_pos, '}');
+		int right = key_pos[0] == 'r';
 
-		if (sscanf(key_pos + 6, "%d,%d", &ptr_x, &ptr_y) == 2)
+		if (sscanf(key_pos + (right ? 7 : 6), "%d,%d",
+			   &ptr_x, &ptr_y) == 2) {
+			click_button = right ? 2u : 1u;
 			click_pending = 1;
+		}
 		key_pos = end ? end + 1 : key_pos + strlen(key_pos);
 		key_due = now + 300;
 		return 0;

+ 3 - 2
host/window_sdl3.c

@@ -55,7 +55,7 @@ static int pop_key(void)
 	return k;
 }
 
-static void push_event(unsigned int type, int x, int y)
+static void push_event(unsigned int type, int x, int y, unsigned int button)
 {
 	unsigned int next = (ev_head + 1) % EVQ_MAX;
 	struct win_event *ev;
@@ -67,6 +67,7 @@ static void push_event(unsigned int type, int x, int y)
 	ev->x = x;
 	ev->y = y;
 	ev->buttons = mouse_buttons;
+	ev->button = button;
 	ev_head = next;
 }
 
@@ -238,7 +239,7 @@ static void handle_event(SDL_Event *e)
 				mouse_buttons &= ~bit;
 			push_event(e->type == SDL_EVENT_MOUSE_BUTTON_DOWN ?
 				   WIN_EV_POINTER_DOWN : WIN_EV_POINTER_UP,
-				   mouse_x, mouse_y);
+				   mouse_x, mouse_y, bit);
 		}
 		break;
 	}

+ 2 - 1
include/icon_abi.h

@@ -35,7 +35,8 @@
 	X(NET_WIFI_3,    "wifi-3",  "network-wireless-signal-good-symbolic") \
 	X(NET_WIFI_4,    "wifi-4",  "network-wireless-signal-excellent-symbolic") \
 	X(NET_WIFI_OFF,  "wifi-off", "network-wireless-offline-symbolic") \
-	X(NET_USB,       "usb",     "phone-symbolic")
+	X(NET_USB,       "usb",     "phone-symbolic")               \
+	X(DOWNLOAD,      "download", "folder-download-symbolic")
 
 /* The NBICO1 bundle, read by ngui and the WM's uwm_lib. */
 #define ICON_BUNDLE_PATH "/ramfs/icons/adwaita16.icn"

+ 2 - 0
include/syscall.h

@@ -123,6 +123,8 @@
 				  WM only: cursor for its chrome/drags */
 #define SYS_WM_MOUSE_CAPTURE 121 /* (int on) -> 0/-1; WM only: own the pointer
 				    while it drags or resizes a window */
+#define SYS_WM_WALLPAPER  123 /* (int op) -> 0/<0; op 1 = a client installed a
+				 new wallpaper, bump wm_status.wallpaper_seq */
 
 /* Storage management (see sys_fs.c, the `disks` app).  SYS_BLK_READ reads one
  * raw 512-byte sector of block device `index` (SYS_BLKDEV order) so ring 3

+ 21 - 0
include/wm_abi.h

@@ -69,6 +69,26 @@ struct wm_status {
 	unsigned int backlight_present;
 	unsigned int backlight_level;
 	unsigned int backlight_seq;
+	/* Bumped when a client installs a new wallpaper (SYS_WM_WALLPAPER);
+	 * the WM reloads its copy when this changes. */
+	unsigned int wallpaper_seq;
+};
+
+/* Wallpaper file: one header followed by tightly packed RGB565 pixels,
+ * width * height * 2 bytes.  The viewer pre-scales to at most 1440x810 and
+ * the WM stretches the stored image to the framebuffer, so no image decoder
+ * is linked into the WM.  The installed data volume wins over the RAM copy. */
+#define WM_WALLPAPER_MAGIC "NBWAL1\0"
+#define WM_WALLPAPER_DATA  "/data/WALLPAPR.BIN"
+#define WM_WALLPAPER_SHARE "/share/wallpaper"
+#define WM_WALLPAPER_MAX_W 1440
+#define WM_WALLPAPER_MAX_H 810
+
+struct wm_wallpaper_hdr {
+	char magic[8];
+	unsigned int width;
+	unsigned int height;
+	unsigned int reserved;
 };
 
 struct wm_window_info {
@@ -155,6 +175,7 @@ struct win_event {
 	unsigned int type;         /* WIN_EV_POINTER_* */
 	int x, y;                  /* content-relative */
 	unsigned int buttons;      /* buttons after the event */
+	unsigned int button;       /* button that changed: bit0 left, bit1 right */
 };
 
 #endif

+ 395 - 9
kernel/acpi.c

@@ -9,7 +9,10 @@
 #include "acpi.h"
 #include "bootinfo.h"
 #include "paging.h"
+#include "pci.h"
 #include "serial.h"
+#include "sys_fs.h"
+#include "timer.h"
 
 struct acpi_rsdp {
 	char signature[8];
@@ -51,6 +54,29 @@ static int acpi_ok;
  * when the firmware points at a real CMOS register. */
 static unsigned int rtc_century_reg;
 
+/* FADT power-management state for ACPI S5 (soft off).  The PM1 control
+ * blocks are I/O ports on every x86 machine this kernel targets; the S5
+ * sleep type comes from the DSDT's \_S5 package.  Without it the only
+ * shutdown path is the emulator's Bochs/QEMU port. */
+static int fadt_ok;
+static unsigned int fadt_pm1a_cnt;
+static unsigned int fadt_pm1b_cnt;
+static unsigned int fadt_pm1a_evt;
+static unsigned int fadt_pm1_cnt_len;
+static unsigned int fadt_smi_cmd;
+static unsigned int fadt_acpi_enable;
+static unsigned int fadt_flags;
+static unsigned int dsdt_addr;
+static unsigned int ssdt_addr[4];
+static unsigned int nssdt;
+static unsigned int s5a;
+static unsigned int s5b;
+static int s5_ok;
+static const unsigned char *dsdt_ptr;
+static unsigned int dsdt_len;
+
+static void scan_s5_addr(unsigned int addr, int strict);
+
 /* Kernel address of a firmware table range (write-back RAM mapping). */
 static void *table_ptr(unsigned int addr, unsigned int len)
 {
@@ -136,7 +162,181 @@ static const struct acpi_rsdp *find_rsdp(void)
 	return 0;
 }
 
-static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
+/* True when a table signature is one of the four-character ACPI ids. */
+static int sig_is(const struct acpi_sdt *t, const char *sig)
+{
+	return t->signature[0] == sig[0] && t->signature[1] == sig[1] &&
+	       t->signature[2] == sig[2] && t->signature[3] == sig[3];
+}
+
+/* Decode and skip an AML PkgLength field (one to four bytes). */
+static int aml_pkg_length(const unsigned char *p, unsigned int len,
+			  unsigned int *used)
+{
+	unsigned int follow;
+
+	if (!len)
+		return -1;
+	follow = (p[0] >> 6) & 3;
+	if (len < follow + 1)
+		return -1;
+	*used = follow + 1;
+	return 0;
+}
+
+/* Decode one integer package element (0, 1, Byte, Word or DWord prefix). */
+static int s5_elem(const unsigned char *p, unsigned int len, unsigned int *v)
+{
+	if (!len)
+		return -1;
+	switch (p[0]) {
+	case 0x00:
+		*v = 0;
+		return 1;
+	case 0x01:
+		*v = 1;
+		return 1;
+	case 0x0A:
+		if (len < 2)
+			return -1;
+		*v = p[1];
+		return 2;
+	case 0x0B:
+		if (len < 3)
+			return -1;
+		*v = p[1] | ((unsigned int)p[2] << 8);
+		return 3;
+	case 0x0C:
+		if (len < 5)
+			return -1;
+		*v = p[1] | ((unsigned int)p[2] << 8) |
+		     ((unsigned int)p[3] << 16) | ((unsigned int)p[4] << 24);
+		return 5;
+	default:
+		return -1;
+	}
+}
+
+/* Find \_S5 in one DSDT/SSDT image and decode its PM1a/PM1b sleep types.
+ * The AML Name string is 08 5F 53 35 5F (optionally with a root prefix
+ * 5C); the package's first two integers are the PM1a/PM1b SLP_TYP values.
+ * Anything that does not decode cleanly is ignored: guessing a type could
+ * enter S3/S4 instead of powering the machine off. */
+static void scan_s5(const unsigned char *tbl, unsigned int len)
+{
+	unsigned int i;
+
+	if (s5_ok)
+		return;
+	for (i = 0; i + 5 < len; i++) {
+		const unsigned char *p;
+		unsigned int rem, used, nel, v1, v2;
+		int n;
+
+		if (tbl[i] != 0x08)
+			continue;
+		if (tbl[i + 1] == 0x5C && tbl[i + 2] == '_' &&
+		    tbl[i + 3] == 'S' && tbl[i + 4] == '5' &&
+		    tbl[i + 5] == '_')
+			p = tbl + i + 6;
+		else if (tbl[i + 1] == '_' && tbl[i + 2] == 'S' &&
+			 tbl[i + 3] == '5' && tbl[i + 4] == '_')
+			p = tbl + i + 5;
+		else
+			continue;
+		rem = len - (unsigned int)(p - tbl);
+		if (!rem || *p != 0x12)        /* PackageOp */
+			continue;
+		p++;
+		rem--;
+		if (aml_pkg_length(p, rem, &used) != 0)
+			continue;
+		p += used;
+		rem -= used;
+		if (!rem)
+			continue;
+		nel = *p++;
+		rem--;
+		if (nel < 1)
+			continue;
+		n = s5_elem(p, rem, &v1);
+		if (n < 0 || (v1 & ~7u))
+			continue;
+		p += n;
+		rem -= (unsigned int)n;
+		v2 = v1;
+		if (nel >= 2 && rem) {
+			n = s5_elem(p, rem, &v2);
+			if (n < 0 || (v2 & ~7u))
+				continue;
+		}
+		s5a = v1;
+		s5b = v2;
+		s5_ok = 1;
+		return;
+	}
+}
+
+/* Map one DSDT/SSDT by address, validate it and scan for \_S5.  The DSDT
+ * pointed to by the FADT is scanned even with a bad checksum (some firmware
+ * ships one and still expects the OS to use the table); SSDTs from the RSDT
+ * were already checksum-validated by the table walk. */
+static void scan_s5_addr(unsigned int addr, int strict)
+{
+	const struct acpi_sdt *t;
+	unsigned int len;
+
+	if (s5_ok || !addr || !range_ok(addr, sizeof(struct acpi_sdt)))
+		return;
+	t = table_ptr(addr, sizeof(struct acpi_sdt));
+	if (!t)
+		return;
+	if (!sig_is(t, "DSDT") && !sig_is(t, "SSDT"))
+		return;
+	len = t->length;
+	if (len < sizeof(struct acpi_sdt) || len > 0x100000u ||
+	    !range_ok(addr, len))
+		return;
+	t = table_ptr(addr, len);
+	if (!t)
+		return;
+	if (!sum_ok((const unsigned char *)t, len) && strict)
+		return;
+	if (addr == dsdt_addr) {
+		dsdt_ptr = (const unsigned char *)t;
+		dsdt_len = len;
+	}
+	scan_s5((const unsigned char *)t, len);
+}
+
+/* Cache the FADT fields the S5 shutdown needs. */
+static void parse_fadt(const unsigned char *t, unsigned int len)
+{
+	unsigned long long x;
+
+	if (len < 109 || fadt_ok)
+		return;
+	fadt_ok = 1;
+	fadt_pm1a_cnt = *(const unsigned int *)(t + 64);
+	fadt_pm1b_cnt = *(const unsigned int *)(t + 68);
+	fadt_pm1a_evt = *(const unsigned int *)(t + 56);
+	fadt_pm1_cnt_len = t[89];
+	fadt_smi_cmd = *(const unsigned int *)(t + 48);
+	fadt_acpi_enable = t[52];
+	if (len >= 116)
+		fadt_flags = *(const unsigned int *)(t + 112);
+	/* ACPI 2.0+ firmware may publish the DSDT only in X_DSDT. */
+	if (len >= 148) {
+		x = *(const unsigned long long *)(t + 140);
+		if (x && (unsigned int)(x >> 32) == 0)
+			dsdt_addr = (unsigned int)x;
+	}
+	if (!dsdt_addr)
+		dsdt_addr = *(const unsigned int *)(t + 40);
+}
+
+/* Walk the RSDT/XSDT once: pick the MADT, cache the FADT and scan for \_S5. */
+static const struct acpi_sdt *scan_tables(const struct acpi_rsdp *rsdp)
 {
 	unsigned int addr, len, i, step;
 	const struct acpi_sdt *sdt;
@@ -191,8 +391,7 @@ static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
 		t = table_ptr(taddr, tlen);
 		if (!t || !sum_ok((const unsigned char *)t, tlen))
 			continue;
-		if (t->signature[0] == 'F' && t->signature[1] == 'A' &&
-		    t->signature[2] == 'C' && t->signature[3] == 'P') {
+		if (sig_is(t, "FACP")) {
 			/* FADT "century" is at offset 108 (ACPI 2.0+); 0 means
 			 * the firmware does not provide a century register. */
 			if (tlen >= 109) {
@@ -202,13 +401,28 @@ static const struct acpi_sdt *find_madt(const struct acpi_rsdp *rsdp)
 				if (c >= 0x0E && c <= 0x7F)
 					rtc_century_reg = c;
 			}
+			parse_fadt((const unsigned char *)t, tlen);
+			continue;
+		}
+		if (sig_is(t, "DSDT")) {
+			if (!dsdt_addr)
+				dsdt_addr = taddr;
+			continue;
+		}
+		if (sig_is(t, "SSDT")) {
+			if (nssdt < 4)
+				ssdt_addr[nssdt++] = taddr;
 			continue;
 		}
-		if (t->signature[0] == 'A' && t->signature[1] == 'P' &&
-		    t->signature[2] == 'I' && t->signature[3] == 'C' &&
-		    !madt)
+		if (sig_is(t, "APIC") && !madt)
 			madt = t;
 	}
+
+	/* \_S5 normally lives in the DSDT; some firmware splits it into an
+	 * SSDT.  Scan after the walk so the FADT's DSDT pointer is known. */
+	scan_s5_addr(dsdt_addr, 0);
+	for (i = 0; i < nssdt && !s5_ok; i++)
+		scan_s5_addr(ssdt_addr[i], 1);
 	return madt;
 }
 
@@ -276,16 +490,35 @@ int acpi_init(void)
 	ncpu = 0;
 	nioapics = 0;
 	rtc_century_reg = 0;
+	fadt_ok = 0;
+	fadt_pm1a_cnt = 0;
+	fadt_pm1b_cnt = 0;
+	fadt_pm1a_evt = 0;
+	fadt_pm1_cnt_len = 0;
+	fadt_smi_cmd = 0;
+	fadt_acpi_enable = 0;
+	fadt_flags = 0;
+	dsdt_addr = 0;
+	nssdt = 0;
+	dsdt_ptr = 0;
+	dsdt_len = 0;
+	s5a = 0;
+	s5b = 0;
+	s5_ok = 0;
 	bsp_apic = cpuid_apic_id();
-	if (bsp_apic == 0xFFFFFFFFu)
-		return 0;
 
 	rsdp = find_rsdp();
 	if (!rsdp) {
 		serial_puts(SERIAL_COM1, "acpi: no RSDP, staying UP\n");
 		return 0;
 	}
-	madt = find_madt(rsdp);
+	/* Walk the tables even when the CPU has no APIC: the FADT also
+	 * carries the S5 shutdown registers. */
+	madt = scan_tables(rsdp);
+	if (bsp_apic == 0xFFFFFFFFu) {
+		serial_puts(SERIAL_COM1, "acpi: no CPUID APIC, staying UP\n");
+		return 0;
+	}
 	if (!madt) {
 		serial_puts(SERIAL_COM1, "acpi: no MADT, staying UP\n");
 		return 0;
@@ -346,10 +579,163 @@ unsigned int acpi_rtc_century_reg(void)
 	return rtc_century_reg;
 }
 
+/* Put the machine into ACPI S5 (soft off) through the FADT PM1 control
+ * blocks.  Returns 0 when the SLP_EN sequence was issued, -1 when the
+ * firmware does not provide a usable path.  The caller must halt either
+ * way: a machine that ignores the write will just keep running. */
+static unsigned int pm1_cnt_read(unsigned int port)
+{
+	if (fadt_pm1_cnt_len >= 4)
+		return port_inl((unsigned short)port);
+	return port_inw((unsigned short)port);
+}
+
+static void pm1_cnt_put(unsigned int port, unsigned int v)
+{
+	if (fadt_pm1_cnt_len >= 4)
+		port_outl((unsigned short)port, v);
+	else
+		port_outw((unsigned short)port, (unsigned short)v);
+}
+
+/* Set the sleep type and optionally SLP_EN.  SCI_EN and the other live bits
+ * are preserved: clearing SCI_EN can make a real chipset ignore the request.
+ * The type is written first and SLP_EN in a second write because some
+ * chipsets sample SLP_TYP only when SLP_EN is asserted. */
+static void pm1_cnt_set(unsigned int port, unsigned int type, int enable)
+{
+	unsigned int v = pm1_cnt_read(port);
+
+	v &= ~(7u << 10);
+	v |= type << 10;
+	if (enable)
+		v |= 1u << 13;
+	pm1_cnt_put(port, v);
+}
+
+/* The ION/nForce DSDT's _PTS(5): record the sleep state in the BIOS NVS
+ * (ASSB/AOTB/AAXB/OSTP at 0xCFF9E064, field offsets from the DSDT's BIOS
+ * OperationRegion) and arm PS1S/PS1E in the SMI block at 0x4400.  The SMM
+ * reads that state when SLP_EN is written; arming PS1E without it hangs. */
+static void nvidia_s5_prepare(unsigned int smi_base)
+{
+	unsigned char *nvs;
+	unsigned char b;
+
+	nvs = ioremap(0xCFF9E064u, 0x100, IOREMAP_RAM);
+	if (!nvs)
+		return;
+	nvs[0x31] = 5;                        /* ASSB: S5 */
+	nvs[0x32] = 3;                        /* AOTB: OSFL() for Linux */
+	*(unsigned int *)(nvs + 0x33) = 0;    /* AAXB */
+	nvs[0x4D] = 1;                        /* OSTP: OSYS() for Linux */
+	port_outb(0x80, 5);                   /* DBG8 */
+	if (smi_base <= 0xFFC0u) {
+		b = port_inb((unsigned short)(smi_base + 1));
+		port_outb((unsigned short)(smi_base + 1),
+			  (unsigned char)(b | 0x80));
+		b = port_inb((unsigned short)(smi_base + 5));
+		port_outb((unsigned short)(smi_base + 5),
+			  (unsigned char)(b | 0x80));
+	}
+}
+
+int acpi_poweroff(void)
+{
+	unsigned int t0, sci, smi, cmd;
+
+	if (!fadt_ok || !s5_ok)
+		return -1;
+	if (fadt_flags & (1u << 4))        /* HW_REDUCED_ACPI */
+		return -1;
+	if (!fadt_pm1a_cnt || fadt_pm1a_cnt > 0xFFFFu)
+		return -1;
+
+	/* Some firmware still has ACPI in legacy mode (SCI_EN clear), where
+	 * PM1_CNT writes are ignored.  Do the SMI handshake first; the FADT
+	 * SMI_CMD is authoritative, but a few boards leave it zero and still
+	 * use the conventional 0xB2/0xF1 pair. */
+	sci = pm1_cnt_read(fadt_pm1a_cnt) & 1;
+	if (!sci) {
+		smi = fadt_smi_cmd;
+		cmd = fadt_acpi_enable;
+		if (!smi || smi > 0xFFFFu)
+			smi = 0xB2;
+		if (!cmd)
+			cmd = 0xF1;
+		port_outb((unsigned short)smi, (unsigned char)cmd);
+		t0 = get_ticks_ms();
+		while (get_ticks_ms() - t0 < 3000) {
+			if (pm1_cnt_read(fadt_pm1a_cnt) & 1)
+				break;
+		}
+		sci = pm1_cnt_read(fadt_pm1a_cnt) & 1;
+	}
+
+	serial_puts(SERIAL_COM1, "poweroff: S5 ");
+	serial_putdec(SERIAL_COM1, s5a);
+	serial_puts(SERIAL_COM1, "/");
+	serial_putdec(SERIAL_COM1, s5b);
+	serial_puts(SERIAL_COM1, " pm1a ");
+	serial_puthex(SERIAL_COM1, fadt_pm1a_cnt);
+	if (fadt_pm1b_cnt) {
+		serial_puts(SERIAL_COM1, " pm1b ");
+		serial_puthex(SERIAL_COM1, fadt_pm1b_cnt);
+	}
+	serial_puts(SERIAL_COM1, " sci ");
+	serial_putdec(SERIAL_COM1, sci);
+	serial_puts(SERIAL_COM1, "\n");
+
+	/* Set SLP_TYP first, then assert SLP_EN in a separate write. */
+	pm1_cnt_set(fadt_pm1a_cnt, s5a, 0);
+	if (fadt_pm1b_cnt && fadt_pm1b_cnt <= 0xFFFFu)
+		pm1_cnt_set(fadt_pm1b_cnt, s5b, 0);
+	/* Intel-style southbridges route SLP_EN through an SMI while
+	 * SMI_EN.SLP_SMI_EN (bit 4 at PMBASE+0x30) is set, so clear it.
+	 * NVIDIA nForce/MCP parts go through their firmware SMM as the
+	 * DSDT's _PTS(5) describes: nvidia_s5_prepare() records the sleep
+	 * state in the BIOS NVS and arms PS1S/PS1E before SLP_EN. */
+	if (fadt_smi_cmd < 0x4000u) {
+		if (fadt_pm1a_evt && fadt_pm1a_evt <= 0xFFC0u) {
+			unsigned int se =
+				port_inl((unsigned short)(fadt_pm1a_evt + 0x30));
+
+			port_outl((unsigned short)(fadt_pm1a_evt + 0x30),
+				  se & ~(1u << 4));
+		}
+	} else {
+		nvidia_s5_prepare(fadt_smi_cmd - 0x2Eu);
+	}
+	pm1_cnt_set(fadt_pm1a_cnt, s5a, 1);
+	if (fadt_pm1b_cnt && fadt_pm1b_cnt <= 0xFFFFu)
+		pm1_cnt_set(fadt_pm1b_cnt, s5b, 1);
+	return 0;
+}
+
+int acpi_dump_dsdt(const char *path)
+{
+	if (!dsdt_ptr || !dsdt_len)
+		return -1;
+	return sys_write_file(path, dsdt_ptr, dsdt_len);
+}
+
 void acpi_dump(void)
 {
 	unsigned int i;
 
+	if (fadt_ok) {
+		serial_puts(SERIAL_COM1, "acpi: fadt pm1a ");
+		serial_puthex(SERIAL_COM1, fadt_pm1a_cnt);
+		serial_puts(SERIAL_COM1, " s5 ");
+		if (s5_ok) {
+			serial_putdec(SERIAL_COM1, s5a);
+			serial_puts(SERIAL_COM1, "/");
+			serial_putdec(SERIAL_COM1, s5b);
+		} else {
+			serial_puts(SERIAL_COM1, "?");
+		}
+		serial_puts(SERIAL_COM1, "\n");
+	}
 	if (!acpi_ok) {
 		serial_puts(SERIAL_COM1, "acpi: unavailable, 1 cpu\n");
 		return;

+ 7 - 0
kernel/acpi.h

@@ -24,6 +24,13 @@ unsigned int acpi_ioapic_base(unsigned int index);
  * firmware does not provide one (old non-ACPI hardware). */
 unsigned int acpi_rtc_century_reg(void);
 
+/* Put the machine into ACPI S5 (soft off).  Returns 0 when the S5 write was
+ * issued, -1 when the firmware provides no usable S5 path. */
+int acpi_poweroff(void);
+
+/* Write the DSDT (as mapped at boot) to a VFS path, for diagnostics. */
+int acpi_dump_dsdt(const char *path);
+
 void acpi_dump(void);
 
 #endif

+ 17 - 7
kernel/ehci.c

@@ -146,7 +146,8 @@ struct ehci_bulk {
 	unsigned int addr;
 	unsigned int ep;
 	unsigned int mps;
-	unsigned int buf_len;
+	unsigned int buf_len;       /* capacity of the HCD's IN bounce buffer */
+	unsigned int armed_len;     /* length the current IN qTD was armed with */
 	unsigned int toggle;
 	unsigned int arm_ms;
 	int armed;
@@ -450,6 +451,7 @@ static void bulk_reset(struct ehci_bulk *b)
 	b->ep = 0;
 	b->mps = 0;
 	b->buf_len = 0;
+	b->armed_len = 0;
 	b->toggle = 0;
 }
 
@@ -464,6 +466,7 @@ static void bulk_configure(struct ehci_bulk *b, unsigned int addr,
 	b->ep = ep;
 	b->mps = mps;
 	b->buf_len = buf_len;
+	b->armed_len = 0;
 	b->toggle = 0;                  /* first packet is DATA0 */
 	qh_init(b->qh);                 /* keeps the link pointer out of it */
 	qh_configure(b->qh, addr, ep, mps, 0);
@@ -596,7 +599,7 @@ static int ehci_bulk_in(unsigned int ctrl, unsigned int addr,
 {
 	struct ehci_ctrl *c;
 	struct ehci_bulk *b;
-	unsigned int token, raw, packets, actual, i;
+	unsigned int token, raw, packets, actual, i, alen;
 
 	if (ctrl >= n_ctrls || !buf || !len)
 		return -1;
@@ -612,7 +615,16 @@ static int ehci_bulk_in(unsigned int ctrl, unsigned int addr,
 	bulk_configure(b, addr, ep, mps, EHCI_RX_MAX);
 
 	if (!b->armed) {
-		qtd_fill(b->qtd, c->rx_buf, b->buf_len, QTD_PID_IN, 0);
+		/* Arm exactly the length this call is waiting for.  A device
+		 * that ends a transfer which is an exact multiple of the max
+		 * packet size without a zero-length packet leaves a larger
+		 * qTD active forever (the ION's SanDisk does this for every
+		 * 512-byte sector read).  Do not pre-arm the next transfer:
+		 * the next call's length can be smaller, because a BOT data
+		 * stage's final chunk need not fill the whole bounce buffer. */
+		alen = len > EHCI_RX_MAX ? EHCI_RX_MAX : len;
+		b->armed_len = alen;
+		qtd_fill(b->qtd, c->rx_buf, alen, QTD_PID_IN, 0);
 		bulk_arm(b);
 		return 0;
 	}
@@ -630,8 +642,8 @@ static int ehci_bulk_in(unsigned int ctrl, unsigned int addr,
 		return -1;
 	}
 
-	raw = QTD_LEN(token) <= b->buf_len ?
-		b->buf_len - QTD_LEN(token) : 0;
+	raw = QTD_LEN(token) <= b->armed_len ?
+		b->armed_len - QTD_LEN(token) : 0;
 	actual = raw;
 	if (actual > len)
 		actual = len;
@@ -644,8 +656,6 @@ static int ehci_bulk_in(unsigned int ctrl, unsigned int addr,
 	b->toggle ^= packets & 1u;
 
 	qh_disarm(b->qh);
-	qtd_fill(b->qtd, c->rx_buf, b->buf_len, QTD_PID_IN, 0);
-	bulk_arm(b);
 	return (int)actual;
 }
 

+ 25 - 9
kernel/poweroff.c

@@ -1,15 +1,31 @@
-/* Poweroff command: shut down the virtual machine (QEMU/Bochs ACPI port). */
+/* Poweroff command: ACPI S5 on real hardware, Bochs/QEMU ports as fallback.
+ *
+ * The ACPI path parses the FADT and the DSDT \_S5 package (acpi.c) and
+ * sets SLP_TYP|SLP_EN in the PM1a/PM1b control blocks.  The Bochs/QEMU
+ * ports are kept for emulators without usable ACPI tables.  If no path
+ * works the command returns instead of halting, so the desktop survives a
+ * failed poweroff and the netlog/kworker can still report the reason. */
 
-static inline void outw(unsigned short port, unsigned short v)
+#include "acpi.h"
+#include "pci.h"
+#include "serial.h"
+#include "timer.h"
+
+static void wait_ms(unsigned int ms)
 {
-	__asm__ volatile ("outw %0, %%dx" : : "a"(v), "d"(port));
+	unsigned int t0 = get_ticks_ms();
+
+	while (get_ticks_ms() - t0 < ms)
+		__asm__ volatile ("hlt");
 }
 
-void program_poweroff_main(void)
+void program_poweroff_main(const char *arg)
 {
-	/* Bochs/QEMU "ACPI" shutdown — see https://wiki.osdev.org/Shutdown */
-	outw(0x604, 0x2000);
-	outw(0xB004, 0x2000);
-	for (;;)
-		__asm__ volatile ("hlt");
+	(void)arg;
+	if (acpi_poweroff() == 0)
+		wait_ms(1000);
+	port_outw(0x604, 0x2000);
+	port_outw(0xB004, 0x2000);
+	wait_ms(200);
+	serial_puts(SERIAL_COM1, "poweroff: failed\n");
 }

+ 8 - 0
kernel/sys_wm.c

@@ -309,3 +309,11 @@ int sys_wm_mouse_capture(int on)
 {
 	return wm_server_set_pointer_capture(on);
 }
+
+int sys_wm_wallpaper(int op)
+{
+	if (op != 1)
+		return -1;
+	wm_server_wallpaper_changed();
+	return 0;
+}

+ 1 - 0
kernel/sys_wm.h

@@ -32,6 +32,7 @@ int sys_win_resize_self(unsigned int w, unsigned int h);
 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);
 
 /* Set once the first application window (the boot terminal) has presented
  * a frame; kernel_main waits for it before the USB bring-up. */

+ 2 - 0
kernel/syscall.c

@@ -361,6 +361,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_wm_set_cursor((int)a1);
 	case SYS_WM_MOUSE_CAPTURE:
 		return sys_wm_mouse_capture((int)a1);
+	case SYS_WM_WALLPAPER:
+		return sys_wm_wallpaper((int)a1);
 	case SYS_SCREEN_INFO: {
 		struct sys_screen *out = (struct sys_screen *)a1;
 

+ 17 - 11
kernel/terminal.c

@@ -2,6 +2,7 @@
    Commands are spawned as separate processes for preemptive multitasking. */
 
 #include "io.h"
+#include "acpi.h"
 #include "backlight.h"
 #include "power.h"
 #include "bootcon.h"
@@ -16,7 +17,7 @@
 #include "timer.h"
 
 extern void program_reboot_main(void);
-extern void program_poweroff_main(void);
+extern void program_poweroff_main(const char *arg);
 extern void program_display_main(void);
 extern void program_gfxbench_main(void);
 extern void program_serial_loop_main(const char *arg);
@@ -60,6 +61,7 @@ struct kcmd {
 /* The terminal's spawn/path helpers are defined later in this file. */
 
 static int cmd_bootlog(struct term *t, const char *args);
+static int cmd_acpidump(struct term *t, const char *args);
 static int cmd_dbg(struct term *t, const char *args);
 static int cmd_format(struct term *t, const char *args);
 static int cmd_install(struct term *t, const char *args);
@@ -71,7 +73,6 @@ static int cmd_kexec(struct term *t, const char *args);
 static int cmd_keytest(struct term *t, const char *args);
 static int cmd_kill(struct term *t, const char *args);
 static int cmd_backlight(struct term *t, const char *args);
-static int cmd_poweroff(struct term *t, const char *args);
 static int cmd_ps(struct term *t, const char *args);
 static int cmd_renice(struct term *t, const char *args);
 static int cmd_sched(struct term *t, const char *args);
@@ -83,8 +84,9 @@ static int cmd_serial(struct term *t, const char *args);
 static const struct kcmd cmds[] = {
 	{ "help",       "help",                          CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_help },
 	{ "bootlog",    "bootlog",                       CK_CUSTOM, CMD_BUILTIN, 0, 0, 0, cmd_bootlog },
+	{ "acpidump",   "acpidump",                      CK_CUSTOM, 0, 0, 0, 0, cmd_acpidump },
 	{ "reboot",     "reboot",                        CK_CUSTOM, 0, 0, 0, 0, cmd_reboot },
-	{ "poweroff",   "poweroff",                      CK_CUSTOM, 0, 0, 0, 0, cmd_poweroff },
+	{ "poweroff",   "poweroff",                      CK_SPAWN_ARG, 0, 0, program_poweroff_main, 0, 0 },
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_main, 0, 0, 0 },
 	{ "backlight",  "backlight [0-100|up|down]",     CK_CUSTOM, 0, 0, 0, 0, cmd_backlight },
@@ -156,6 +158,18 @@ static void help_print(void)
 
 
 
+/* Save the mapped DSDT to /share for offline analysis (acpidump). */
+static int cmd_acpidump(struct term *t, const char *args)
+{
+	(void)t;
+	(void)args;
+	if (acpi_dump_dsdt("/share/DSDT.BIN") == 0)
+		io_putstr("acpi: saved /share/DSDT.BIN\n");
+	else
+		io_putstr("acpi: dump failed\n");
+	return 0;
+}
+
 /* Dump the whole boot console text captured by bootcon_puts().  The ring-3
  * terminal keeps scrollback, so no paging is needed; sleep briefly every
  * 512 bytes so the terminal can drain its tty ring while we write. */
@@ -319,14 +333,6 @@ static int cmd_kill(struct term *t, const char *args)
 	return 0;
 }
 
-static int cmd_poweroff(struct term *t, const char *args)
-{
-	(void)t;
-	(void)args;
-	program_poweroff_main();
-	return 0;
-}
-
 static int cmd_ps(struct term *t, const char *args)
 {
 	(void)t;

+ 8 - 4
kernel/usb_hcd.h

@@ -79,10 +79,14 @@ struct usb_hcd_ops {
 	void (*int_in_stop)(unsigned int slot);
 
 	/* Bulk transfers (USB Ethernet / mass storage).  bulk_in is
-	 * start-or-poll: the first call arms the transfer and returns 0,
-	 * later calls return the frame length, 0 while NAKed, or -1.  A
-	 * delivered chunk stays in the caller's buffer until the next call,
-	 * which re-arms the transfer.  May be NULL. */
+	 * start-or-poll: the first call arms the transfer and returns 0;
+	 * later calls return the completed length, 0 while it is still in
+	 * progress, or -1.  The transfer is armed with exactly that call's
+	 * length, so a device that ends an exact multiple of the max packet
+	 * size without a zero-length packet still completes; the next call
+	 * after a completion arms a new transfer with its own length.  The
+	 * delivered chunk is copied into the caller's buffer before the
+	 * return.  May be NULL. */
 	int (*bulk_out)(unsigned int ctrl, unsigned int addr,
 			unsigned int ep, unsigned int mps,
 			const unsigned char *buf, unsigned int len);

+ 35 - 13
kernel/wm.c

@@ -52,6 +52,7 @@ static int wm_frame_active;
 static int wm_first_frame;
 static int wm_boot_ready;
 static int wm_boot_logged;
+static unsigned int wm_wallpaper_seq;
 static unsigned int wm_last_start;
 static unsigned int wm_last_seen;
 
@@ -978,7 +979,8 @@ int wm_server_close(unsigned int index)
 }
 
 static void wm_queue_ptr_event(struct window *w, unsigned int type,
-			       int x, int y, unsigned int buttons)
+			       int x, int y, unsigned int buttons,
+			       unsigned int button)
 {
 	unsigned int next = (w->ptr_head + 1) % 8;
 
@@ -988,6 +990,7 @@ static void wm_queue_ptr_event(struct window *w, unsigned int type,
 	w->ptr_events[w->ptr_head].x = x;
 	w->ptr_events[w->ptr_head].y = y;
 	w->ptr_events[w->ptr_head].buttons = buttons;
+	w->ptr_events[w->ptr_head].button = button;
 	w->ptr_head = next;
 	/* Wake a window blocked in SYS_WIN_KEY_WAIT so a click (e.g. on the
 	 * terminal's scrollbar) is handled now, not on the next poll timeout. */
@@ -1008,26 +1011,36 @@ static void wm_route_pointer(unsigned int mx, unsigned int my,
 		return;
 	}
 
-	if (press & 1) {
-		int edges = 0;
-		int idx = wm_resize_target((int)mx, (int)my, &edges);
+	if (press & 3) {
+		int idx = wm_ptr_capture;
 
-		if (idx >= 0 && !edges) {
+		if (idx < 0) {
+			int edges = 0;
+
+			idx = wm_resize_target((int)mx, (int)my, &edges);
+			if (edges)
+				idx = -1;
+		}
+		if (idx >= 0 && idx < (int)MAX_WINDOWS) {
 			struct window *w = &windows[idx];
 			int cx = (int)mx - win_content_x(w);
 			int cy = (int)my - win_content_y(w);
 
-			if (w->canvas_window && cx >= 0 && cy >= 0 &&
-			    cx < (int)w->canvas.w && cy < (int)w->canvas.h &&
-			    (w->popover ||
-			     !win_in_resize_border(w, mx, my))) {
+			/* A second button pressed after a capture may leave the
+			 * content, but still belongs to the window that owns the
+			 * pointer. */
+			if (w->used && w->canvas_window &&
+			    (wm_ptr_capture == idx ||
+			     (cx >= 0 && cy >= 0 && cx < (int)w->canvas.w &&
+			      cy < (int)w->canvas.h &&
+			      (w->popover || !win_in_resize_border(w, mx, my))))) {
 				wm_queue_ptr_event(w, WIN_EV_POINTER_DOWN,
-						   cx, cy, buttons);
+						   cx, cy, buttons, press & 3);
 				wm_ptr_capture = idx;
 			}
 		}
 	}
-	if ((release & 1) && wm_ptr_capture >= 0) {
+	if ((release & 3) && wm_ptr_capture >= 0) {
 		struct window *w = &windows[wm_ptr_capture];
 
 		if (w->used && w->canvas_window) {
@@ -1035,9 +1048,10 @@ static void wm_route_pointer(unsigned int mx, unsigned int my,
 			int cy = (int)my - win_content_y(w);
 
 			wm_queue_ptr_event(w, WIN_EV_POINTER_UP,
-					   cx, cy, buttons);
+					   cx, cy, buttons, release & 3);
 		}
-		wm_ptr_capture = -1;
+		if (!(buttons & 3))
+			wm_ptr_capture = -1;
 	}
 	wm_ptr_buttons = buttons;
 }
@@ -1102,6 +1116,7 @@ int wm_server_poll(struct wm_status *out)
 		out->backlight_level = level > 0 ? (unsigned int)level : 0;
 		out->backlight_seq = backlight_seq();
 	}
+	out->wallpaper_seq = wm_wallpaper_seq;
 	wm_full_redraw = 0;
 	return 0;
 }
@@ -1111,6 +1126,13 @@ void wm_server_boot_ready(void)
 	wm_boot_ready = 1;
 }
 
+/* SYS_WM_WALLPAPER: a client (the image viewer) wrote a new wallpaper file.
+ * Bumping the sequence makes the WM reload it and repaint the desktop. */
+void wm_server_wallpaper_changed(void)
+{
+	wm_wallpaper_seq++;
+}
+
 int wm_server_begin(void)
 {
 	if (!wm_server_is_wm() || wm_frame_active)

+ 1 - 0
kernel/wm.h

@@ -93,6 +93,7 @@ int  wm_server_win_resize_self(unsigned int cw, unsigned int ch);
 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);
 void wm_server_boot_ready(void);
 struct window *wm_focused_window(void);
 int  wm_is_focused(const struct window *w);

+ 175 - 0
tools/jsstrip.c

@@ -0,0 +1,175 @@
+/* jsstrip: drop comments, indentation and blank lines from the browser's
+ * JavaScript prelude before it is embedded (js_prelude.S), so the source
+ * can stay commented without costing rootfs pack space.
+ *
+ * Usage: jsstrip <in.js> <out.js>
+ *
+ * Deliberately not a minifier: names stay and line breaks are kept (ASI and
+ * error line numbers stay sane).  Within a line a run of blanks (or a
+ * removed comment) survives as one space only where dropping it could join
+ * two tokens: between identifier characters, "+ +"/"- -", next to a '/',
+ * and a digit before '.'.  String and regex literals are copied verbatim;
+ * a template literal is refused because `${}` nesting is not tracked (the
+ * prelude has none). */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static const char *src;
+static long len, pos;
+static int line = 1;
+
+static int ident(char c)
+{
+	return c == '_' || c == '$' || (unsigned char)c >= 0x80 ||
+	       (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
+	       (c >= 'A' && c <= 'Z');
+}
+
+static int need_space(char a, char b)
+{
+	return (ident(a) && ident(b)) || ((a == '+' || a == '-') && a == b) ||
+	       a == '/' || b == '/' || (b == '.' && a >= '0' && a <= '9');
+}
+
+static void die(const char *msg)
+{
+	fprintf(stderr, "jsstrip: line %d: %s\n", line, msg);
+	exit(1);
+}
+
+/* A '/' starts a regex unless the previous significant token can end an
+ * expression (identifier, number, ')' or ']'); "return /x/" etc. is
+ * handled by the keyword check. */
+static int regex_allowed(const char *out, long n)
+{
+	long i = n, j;
+
+	while (i > 0 && (out[i - 1] == ' ' || out[i - 1] == '\n'))
+		i--;
+	if (i == 0)
+		return 1;
+	if (out[i - 1] == ')' || out[i - 1] == ']')
+		return 0;
+	j = i;
+	while (j > 0 && (out[j - 1] == '_' || out[j - 1] == '$' ||
+			 (out[j - 1] >= '0' && out[j - 1] <= '9') ||
+			 (out[j - 1] >= 'a' && out[j - 1] <= 'z') ||
+			 (out[j - 1] >= 'A' && out[j - 1] <= 'Z')))
+		j--;
+	if (j == i)
+		return 1;	/* punctuation */
+	return (i - j == 6 && !memcmp(out + j, "return", 6)) ||
+	       (i - j == 6 && !memcmp(out + j, "typeof", 6)) ||
+	       (i - j == 4 && !memcmp(out + j, "case", 4)) ||
+	       (i - j == 2 && !memcmp(out + j, "in", 2));
+}
+
+int main(int argc, char **argv)
+{
+	FILE *f;
+	char *out;
+	long n = 0;
+	int bol = 1;	/* at the beginning of an output line */
+	int gap = 0;	/* blanks or a comment since the last output char */
+
+	if (argc != 3) {
+		fprintf(stderr, "usage: jsstrip in.js out.js\n");
+		return 2;
+	}
+	f = fopen(argv[1], "rb");
+	if (!f || fseek(f, 0, SEEK_END) || (len = ftell(f)) < 0)
+		die("cannot read input");
+	rewind(f);
+	src = malloc(len + 1);
+	out = malloc(len + 1);
+	if (!src || !out || fread((char *)src, 1, len, f) != (size_t)len)
+		die("cannot read input");
+	fclose(f);
+
+	while (pos < len) {
+		char c = src[pos];
+
+		if (c == '\n') {
+			line++;
+			pos++;
+			/* drop empty lines */
+			if (!bol)
+				out[n++] = '\n';
+			bol = 1;
+			gap = 0;
+			continue;
+		}
+		if (c == ' ' || c == '\t' || c == '\r') {
+			pos++;
+			gap = 1;
+			continue;
+		}
+		if (c == '/' && pos + 1 < len && src[pos + 1] == '/') {
+			while (pos < len && src[pos] != '\n')
+				pos++;
+			continue;
+		}
+		if (c == '/' && pos + 1 < len && src[pos + 1] == '*') {
+			pos += 2;
+			while (pos + 1 < len &&
+			       !(src[pos] == '*' && src[pos + 1] == '/')) {
+				/* keep a newline a multi-line comment spanned, so
+				 * a comment cannot join two statements */
+				if (src[pos] == '\n') {
+					line++;
+					if (!bol) {
+						out[n++] = '\n';
+						bol = 1;
+					}
+				}
+				pos++;
+			}
+			if (pos + 1 >= len)
+				die("unterminated comment");
+			pos += 2;
+			gap = 1;
+			continue;
+		}
+		if (c == '`')
+			die("template literals are not supported");
+		if (gap && !bol && need_space(out[n - 1], c))
+			out[n++] = ' ';
+		gap = 0;
+		bol = 0;
+		if (c == '"' || c == '\'' ||
+		    (c == '/' && regex_allowed(out, n))) {
+			char q = c, d;
+			int cclass = 0;	/* inside a regex [...] a '/' is literal */
+
+			out[n++] = src[pos++];
+			for (;;) {
+				if (pos >= len || src[pos] == '\n')
+					die("unterminated string or regex");
+				d = src[pos];
+				out[n++] = src[pos++];
+				if (d == '\\') {
+					if (pos >= len)
+						die("unterminated literal");
+					out[n++] = src[pos++];
+				} else if (q == '/' && d == '[') {
+					cclass = 1;
+				} else if (q == '/' && d == ']') {
+					cclass = 0;
+				} else if (d == q && !cclass) {
+					break;
+				}
+			}
+			continue;
+		}
+		out[n++] = src[pos++];
+	}
+	while (n > 0 && out[n - 1] == '\n')
+		n--;
+	out[n++] = '\n';
+
+	f = fopen(argv[2], "wb");
+	if (!f || fwrite(out, 1, n, f) != (size_t)n || fclose(f))
+		die("cannot write output");
+	return 0;
+}

Разница между файлами не показана из-за своего большого размера
+ 972 - 14
user/apps/browser/browser.c


+ 3 - 2
user/apps/browser/js_prelude.S

@@ -1,8 +1,9 @@
 /* Embeds js_prelude.js (the browser's Web API layer) as a NUL-terminated
- * string for js_browser.c. */
+ * string for js_browser.c.  The build strips its comments and indentation
+ * first (tools/jsstrip.c -> build/user/apps/browser/js_prelude.min.js). */
 	.section .rodata
 	.globl js_prelude_source
 js_prelude_source:
-	.incbin "js_prelude.js"
+	.incbin "js_prelude.min.js"
 	.byte 0
 	.section .note.GNU-stack,"",@progbits

+ 489 - 0
user/apps/browser/js_prelude.js

@@ -1228,7 +1228,46 @@ Object.defineProperty(nodeproto, "content", { configurable: true,
 function toNode(n) {
 	return typeof n === "object" && n !== null ? n : doc.createTextNode(String(n));
 }
+/* Constraint validation (no UI: reportValidity only answers): required,
+ * min/maxlength, pattern, email/url syntax, number min/max and
+ * setCustomValidity().  A form is valid when all its controls are. */
+function validity(e) {
+	var t = String(e.type || "").toLowerCase(), v = String(e.value || ""),
+	    a = function (n) { return e.getAttribute(n); }, r = {}, p;
+	if (e.disabled || /^(hidden|submit|button|reset|image)$/.test(t)) {
+		r.valid = true;
+		return r;
+	}
+	r.customError = !!e.__nb_cv;
+	r.valueMissing = e.hasAttribute("required") &&
+		(/^(checkbox|radio)$/.test(t) ? !e.checked : v === "");
+	if (v) {
+		r.tooShort = v.length < +(a("minlength") || 0);
+		r.tooLong = a("maxlength") !== null && v.length > +a("maxlength");
+		p = a("pattern");
+		try { r.patternMismatch = p !== null && !new RegExp("^(?:" + p + ")$").test(v); } catch (x) {}
+		r.typeMismatch = t === "email" ? !/^[^\s@]+@[^\s@]+$/.test(v) :
+			t === "url" && !/^[a-z][\w+.-]*:/i.test(v);
+		r.rangeUnderflow = t === "number" && a("min") !== null && +v < +a("min");
+		r.rangeOverflow = t === "number" && a("max") !== null && +v > +a("max");
+	}
+	r.valid = !Object.keys(r).some(function (k) { return r[k]; });
+	return r;
+}
+function checkValidity() {
+	var l = /^form$/i.test(this.tagName) ?
+		this.querySelectorAll("input,select,textarea") : [this], i;
+	for (i = 0; i < l.length; i++)
+		if (!validity(l[i]).valid) return false;
+	return true;
+}
+Object.defineProperty(nodeproto, "validity", { configurable: true,
+	get: function () { return validity(this); } });
 Object.assign(nodeproto, {
+	checkValidity: checkValidity,
+	reportValidity: checkValidity,
+	setCustomValidity: function (m) { this.__nb_cv = String(m); },
+
 	setAttributeNS: function (ns, n, v) {
 		this.setAttribute(String(n).replace(/^[^:]*:/, ""), v);
 	},
@@ -1662,6 +1701,456 @@ class PerformanceObserver {
 PerformanceObserver.supportedEntryTypes = [];
 def("PerformanceObserver", PerformanceObserver);
 
+/* ---- Intl: QuickJS has none.  A small en-US-only subset; every locale
+ * argument is accepted and ignored, and dates are formatted in UTC (the
+ * libc's only zone, so Date's local getters agree). ---- */
+(function () {
+var MON = "January February March April May June July August September October November December".split(" "),
+	DAY = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");
+function opt(o) { return o == null ? {} : Object(o); }
+function ctor(f, p) {
+	f.prototype = p;
+	f.supportedLocalesOf = function (l) {
+		return [].concat(l === undefined ? [] : l).map(String);
+	};
+	return f;
+}
+function parts2s(p) { return p.map(function (x) { return x.value; }).join(""); }
+function pad2(n) { return (n < 10 ? "0" : "") + n; }
+
+var CUR = { USD: "$", EUR: "€", GBP: "£", JPY: "¥", INR: "₹" };
+var UNIT = { byte: "byte", kilobyte: "kB", megabyte: "MB", gigabyte: "GB",
+	terabyte: "TB", petabyte: "PB", bit: "bit", kilobit: "kb",
+	megabit: "Mb", gigabit: "Gb", millisecond: "ms", second: "sec",
+	minute: "min", hour: "hr", day: "day", week: "wk", month: "mth",
+	year: "yr", percent: "%", meter: "m", kilometer: "km",
+	celsius: "°C" };
+function NumberFormat(l, o) {
+	if (!(this instanceof NumberFormat)) return new NumberFormat(l, o);
+	o = opt(o);
+	var st = o.style || "decimal", cur = st === "currency" ?
+		String(o.currency).toUpperCase() : undefined,
+	    dmin = cur ? (cur === "JPY" ? 0 : 2) : 0,
+	    dmax = cur ? dmin : st === "percent" ? 0 : 3,
+	    mn = o.minimumFractionDigits, mx = o.maximumFractionDigits;
+	if (mn === undefined) mn = mx === undefined ? dmin : Math.min(dmin, mx);
+	if (mx === undefined) mx = Math.max(mn, dmax);
+	this.o = { locale: "en-US", numberingSystem: "latn", style: st,
+		currency: cur, currencyDisplay: o.currencyDisplay || "symbol",
+		unit: o.unit, unitDisplay: o.unitDisplay || "short",
+		minimumIntegerDigits: o.minimumIntegerDigits || 1,
+		minimumFractionDigits: +mn, maximumFractionDigits: +mx,
+		maximumSignificantDigits: o.maximumSignificantDigits,
+		useGrouping: o.useGrouping === undefined ? "auto" : o.useGrouping,
+		notation: o.notation || "standard",
+		signDisplay: o.signDisplay || "auto" };
+}
+ctor(NumberFormat, {
+	formatToParts: function (x) {
+		var o = this.o, p = [], v = Number(x), neg = v < 0 ||
+			Object.is(v, -0), sfx = "", s, i, k;
+		function add(t, s) { if (s) p.push({ type: t, value: s }); }
+		if (isNaN(v)) return [{ type: "nan", value: "NaN" }];
+		v = Math.abs(v);
+		if (o.style === "percent") v *= 100;
+		function rnd(v) {
+			var sig = o.maximumSignificantDigits ||
+				(o.notation === "compact" && v < 99.5 ? 2 : 0), f, s;
+			if (sig) v = +v.toPrecision(sig);
+			f = sig ? Math.max(0, sig - 1 - Math.floor(Math.log10(v || 1))) :
+				o.notation === "compact" ? 0 : o.maximumFractionDigits;
+			s = v.toFixed(Math.min(f, 20));
+			while (/\.\d*0$/.test(s) && s.length - s.indexOf(".") - 1 >
+			       (sig ? 0 : o.minimumFractionDigits))
+				s = s.slice(0, -1);
+			return s.replace(/\.$/, "");
+		}
+		if (!isFinite(v)) s = "\u221e";
+		else if (o.notation === "compact") {
+			for (k = 0; k < 4 && +rnd(v / Math.pow(1000, k)) >= 1000; k++);
+			s = rnd(v / Math.pow(1000, k));
+			sfx = k ? "KMBT"[k - 1] : "";
+		} else s = rnd(v);
+		i = s.split(".");
+		while (i[0].length < o.minimumIntegerDigits) i[0] = "0" + i[0];
+		var sd = o.signDisplay, zero = +s === 0 || s === "0";
+		if (sd === "never" || (sd === "exceptZero" || sd === "negative") && zero)
+			neg = false;
+		add(neg ? "minusSign" : "plusSign", neg ? "-" :
+			sd === "always" || sd === "exceptZero" && !zero ? "+" : "");
+		if (o.currency) {
+			var sym = o.currencyDisplay === "code" ? o.currency + " " :
+				CUR[o.currency] || o.currency + " ";
+			add("currency", sym);
+		}
+		if (o.useGrouping !== false && !/^∞/.test(s) &&
+			(o.useGrouping !== "min2" || i[0].length > 4))
+			i[0].split(/(?=(?:\d{3})+$)/).forEach(function (d, n) {
+				if (n) add("group", ",");
+				add("integer", d);
+			});
+		else add(isFinite(v) ? "integer" : "infinity", i[0]);
+		if (i[1]) { add("decimal", "."); add("fraction", i[1]); }
+		add("compact", sfx);
+		if (o.style === "percent") add("percentSign", "%");
+		if (o.style === "unit") {
+			var u = o.unit, d = o.unitDisplay, w = UNIT[u] || u;
+			if (d === "long") w = " " + u + (+s === 1 ? "" : "s");
+			else w = (d === "narrow" ? "" : " ") + w +
+				(u === "day" && +s !== 1 && d !== "narrow" ? "s" : "");
+			add("unit", w);
+		}
+		return p;
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+Object.defineProperty(NumberFormat.prototype, "format", { get: function () {
+	var self = this;
+	return function (x) { return parts2s(self.formatToParts(x)); };
+} });
+
+var DFIELDS = ["weekday", "year", "month", "day"],
+	TFIELDS = ["dayPeriod", "hour", "minute", "second",
+		   "fractionalSecondDigits"];
+var DSTY = { full: { weekday: "long", month: "long", day: "numeric",
+		     year: "numeric" },
+	     long: { month: "long", day: "numeric", year: "numeric" },
+	     medium: { month: "short", day: "numeric", year: "numeric" },
+	     short: { month: "numeric", day: "numeric", year: "2-digit" } };
+function has(o, l) { return l.some(function (k) { return o[k] !== undefined; }); }
+/* need/def: "date"/"time"/"any", "date"/"time"/"all" (ECMA-402
+ * ToDateTimeOptions). */
+function dtopts(o, need, def) {
+	var r = {}, k;
+	o = opt(o);
+	for (k in o) r[k] = o[k];
+	if (o.dateStyle || o.timeStyle) {
+		if (o.dateStyle) Object.assign(r, DSTY[o.dateStyle]);
+		if (o.timeStyle) {
+			r.hour = "numeric"; r.minute = "2-digit";
+			if (o.timeStyle !== "short") r.second = "2-digit";
+			if (/full|long/.test(o.timeStyle)) r.timeZoneName = "short";
+		}
+	} else if (!(need !== "time" && has(o, DFIELDS) ||
+		     need !== "date" && has(o, TFIELDS))) {
+		if (def !== "time") r.year = r.month = r.day = "numeric";
+		if (def !== "date") r.hour = r.minute = r.second = "numeric";
+	}
+	r.locale = "en-US"; r.calendar = "gregory"; r.numberingSystem = "latn";
+	r.timeZone = "UTC";
+	if (r.hour) {
+		r.hour12 = o.hour12 !== undefined ? !!o.hour12 :
+			!/h2[34]/.test(o.hourCycle);
+		r.hourCycle = r.hour12 ? "h12" : "h23";
+	}
+	return r;
+}
+function DateTimeFormat(l, o) {
+	if (!(this instanceof DateTimeFormat)) return new DateTimeFormat(l, o);
+	this.o = this.o || dtopts(o, "any", "date");
+}
+function dtparts(o, d) {
+	var p = [], t = new Date(+d), h, m, n, txt;
+	function add(ty, v) { p.push({ type: ty, value: String(v) }); }
+	function lit(v) { add("literal", v); }
+	if (isNaN(t)) throw new RangeError("Invalid time value");
+	m = t.getUTCMonth(); n = t.getUTCFullYear();
+	function yr() { add("year", o.year === "2-digit" ? pad2(n % 100) : n); }
+	function dy() { add("day", o.day === "2-digit" ? pad2(t.getUTCDate()) : t.getUTCDate()); }
+	if (o.weekday) {
+		txt = DAY[t.getUTCDay()];
+		add("weekday", o.weekday === "long" ? txt : o.weekday === "narrow" ? txt[0] : txt.slice(0, 3));
+		if (o.month || o.day || o.year) lit(", ");
+	}
+	if (/^(long|short|narrow)$/.test(o.month)) {
+		txt = MON[m];
+		add("month", o.month === "long" ? txt : o.month === "narrow" ? txt[0] : txt.slice(0, 3));
+		if (o.day) { lit(" "); dy(); }
+		if (o.year) { lit(o.day ? ", " : " "); yr(); }
+	} else {
+		[["month", o.month], ["day", o.day], ["year", o.year]].forEach(function (f) {
+			if (!f[1]) return;
+			if (p.length && p[p.length - 1].type !== "literal") lit("/");
+			if (f[0] === "month") add("month", f[1] === "2-digit" ? pad2(m + 1) : m + 1);
+			else if (f[0] === "day") dy();
+			else yr();
+		});
+	}
+	if (o.hour || o.minute || o.second) {
+		if (p.length) lit(o.dateStyle && /full|long/.test(o.dateStyle) && o.timeStyle ? " at " : ", ");
+		h = t.getUTCHours();
+		if (o.hour) {
+			n = o.hour12 ? h % 12 || 12 : h;
+			add("hour", o.hour === "2-digit" || !o.hour12 ? pad2(n) : n);
+		}
+		if (o.minute) {
+			if (o.hour) lit(":");
+			add("minute", o.hour || o.minute === "2-digit" ? pad2(t.getUTCMinutes()) : t.getUTCMinutes());
+		}
+		if (o.second) {
+			if (o.hour || o.minute) lit(":");
+			add("second", o.hour || o.minute || o.second === "2-digit" ? pad2(t.getUTCSeconds()) : t.getUTCSeconds());
+		}
+		if (o.fractionalSecondDigits) {
+			lit(".");
+			add("fractionalSecond", String(1000 + t.getUTCMilliseconds()).slice(1, 1 + o.fractionalSecondDigits));
+		}
+		if (o.hour && o.hour12) { lit(" "); add("dayPeriod", h < 12 ? "AM" : "PM"); }
+	}
+	if (o.timeZoneName) { lit(" "); add("timeZoneName", "UTC"); }
+	return p;
+}
+ctor(DateTimeFormat, {
+	formatToParts: function (d) {
+		return dtparts(this.o, d === undefined ? Date.now() : d);
+	},
+	formatRange: function (a, b) {
+		return this.format(a) + " – " + this.format(b);
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+Object.defineProperty(DateTimeFormat.prototype, "format", { get: function () {
+	var self = this;
+	return function (d) { return parts2s(self.formatToParts(d)); };
+} });
+function dtf(need, def) {
+	return function (l, o) {
+		if (isNaN(this)) return "Invalid Date";
+		var f = Object.create(DateTimeFormat.prototype);
+		f.o = dtopts(o, need, def);
+		return f.format(this);
+	};
+}
+Date.prototype.toLocaleString = dtf("any", "all");
+Date.prototype.toLocaleDateString = dtf("date", "date");
+Date.prototype.toLocaleTimeString = dtf("time", "time");
+Number.prototype.toLocaleString = function (l, o) {
+	return NumberFormat(l, o).format(this);
+};
+
+var RTU = { second: "sec.", minute: "min.", hour: "hr.", day: "day",
+	week: "wk.", month: "mo.", quarter: "qtr.", year: "yr." };
+function RelativeTimeFormat(l, o) {
+	o = opt(o);
+	this.o = { locale: "en-US", numberingSystem: "latn",
+		style: o.style || "long", numeric: o.numeric || "always" };
+}
+ctor(RelativeTimeFormat, {
+	format: function (v, u) {
+		v = Number(v);
+		u = String(u).replace(/s$/, "");
+		if (!RTU[u]) throw new RangeError("Invalid unit: " + u);
+		if (this.o.numeric === "auto" && (v === 0 || Math.abs(v) === 1 &&
+						 u !== "second" && u !== "minute" && u !== "hour")) {
+			if (u === "second") return "now";
+			if (u === "day") return v ? v < 0 ? "yesterday" : "tomorrow" : "today";
+			return (v ? v < 0 ? "last " : "next " : "this ") + u;
+		}
+		var a = Math.abs(v), w = this.o.style === "long" || u === "day" ?
+			u + (a === 1 ? "" : "s") : u === "quarter" && a !== 1 ?
+			"qtrs." : RTU[u],
+		    s = NumberFormat().format(a) + " " + w;
+		return v < 0 || Object.is(v, -0) ? s + " ago" : "in " + s;
+	},
+	formatToParts: function (v, u) {
+		return [{ type: "literal", value: this.format(v, u) }];
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+
+var DUR = [["years", "yr", "y"], ["months", "mth", "mo"], ["weeks", "wk", "w"],
+	   ["days", "day", "d"], ["hours", "hr", "h"], ["minutes", "min", "m"],
+	   ["seconds", "sec", "s"], ["milliseconds", "ms", "ms"],
+	   ["microseconds", "μs", "μs"],
+	   ["nanoseconds", "ns", "ns"]];
+function DurationFormat(l, o) {
+	o = opt(o);
+	this.o = { locale: "en-US", numberingSystem: "latn",
+		style: o.style || "short" };
+}
+ctor(DurationFormat, {
+	format: function (d) {
+		var st = this.o.style, out = [];
+		d = opt(d);
+		if (st === "digital") {
+			var hms = [d.hours || 0, pad2(d.minutes || 0), pad2(d.seconds || 0)].join(":");
+			out = DUR.slice(0, 4).filter(function (u) { return d[u[0]]; })
+				.map(function (u) { return d[u[0]] + " " + u[0].slice(0, d[u[0]] === 1 ? -1 : undefined); });
+			out.push(hms);
+			return out.join(", ");
+		}
+		DUR.forEach(function (u) {
+			var v = d[u[0]];
+			if (!v) return;
+			out.push(st === "narrow" ? v + u[2] : v + " " +
+				(st === "long" ? u[0].slice(0, Math.abs(v) === 1 ? -1 : undefined) :
+				 u[1] + (u[1] === "day" && v !== 1 ? "s" : "")));
+		});
+		return out.join(st === "narrow" ? " " : ", ");
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+
+var LANG = { en: "English", de: "German", fr: "French", es: "Spanish",
+	it: "Italian", nl: "Dutch", pt: "Portuguese", ru: "Russian",
+	zh: "Chinese", ja: "Japanese", ko: "Korean", pl: "Polish",
+	tr: "Turkish", cs: "Czech", da: "Danish", sv: "Swedish",
+	fi: "Finnish", nb: "Norwegian Bokmål", no: "Norwegian",
+	uk: "Ukrainian", hu: "Hungarian", el: "Greek", ro: "Romanian",
+	vi: "Vietnamese", id: "Indonesian", ar: "Arabic", he: "Hebrew",
+	hi: "Hindi", fa: "Persian", sk: "Slovak", bg: "Bulgarian",
+	hr: "Croatian", sr: "Serbian", sl: "Slovenian", et: "Estonian",
+	lv: "Latvian", lt: "Lithuanian", ca: "Catalan", gl: "Galician",
+	eu: "Basque", th: "Thai", ms: "Malay", ta: "Tamil", bn: "Bangla",
+	"en-US": "American English", "en-GB": "British English",
+	"pt-BR": "Brazilian Portuguese", "pt-PT": "European Portuguese",
+	"es-MX": "Mexican Spanish", "fr-CA": "Canadian French" };
+var REG = { US: "United States", GB: "United Kingdom", DE: "Germany",
+	FR: "France", ES: "Spain", IT: "Italy", NL: "Netherlands",
+	BR: "Brazil", PT: "Portugal", CN: "China", TW: "Taiwan",
+	JP: "Japan", IN: "India", CA: "Canada", AU: "Australia",
+	AT: "Austria", CH: "Switzerland", RU: "Russia" };
+function DisplayNames(l, o) {
+	o = opt(o);
+	this.o = { locale: "en-US", style: o.style || "long",
+		type: o.type, fallback: o.fallback || "code" };
+}
+ctor(DisplayNames, {
+	of: function (c) {
+		c = String(c);
+		var t = this.o.type, s = c.split(/[-_]/), r;
+		if (t === "region") r = REG[c.toUpperCase()];
+		else if (t === "language") {
+			r = LANG[s[0].toLowerCase() + "-" + s[1]] || LANG[s[0].toLowerCase()];
+			if (r && s[1] && !LANG[s[0].toLowerCase() + "-" + s[1]]) r = REG[s[1].toUpperCase()] ?
+				r + " (" + REG[s[1].toUpperCase()] + ")" : r + " (" + s[1] + ")";
+		}
+		return r || (this.o.fallback === "none" ? undefined : c);
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+
+/* Collation: case- and accent-blind first (ICU's primary strength), then
+ * accents, then lower before upper; digit runs compare by value when
+ * numeric is set. */
+function fold(s) {
+	return /^[\x00-\x7f]*$/.test(s) ? s : s.normalize("NFD").replace(/[̀-ͯ]/g, "");
+}
+/* Code-point order within a class; ICU's classes order whitespace,
+ * punctuation/symbols, digits, letters. */
+function cls(c) {
+	return c <= 32 ? 0 : c >= 48 && c <= 57 ? 2 : c >= 65 && c <= 90 ||
+		c >= 97 && c <= 122 || c > 127 ? 3 : 1;
+}
+function cmp(a, b, num) {
+	var i = 0, j = 0, x, y, m, n;
+	while (i < a.length && j < b.length) {
+		x = a.charCodeAt(i); y = b.charCodeAt(j);
+		if (num && cls(x) === 2 && cls(y) === 2) {
+			m = /^0*(\d*)/.exec(a.slice(i).match(/^\d+/)[0])[1];
+			n = /^0*(\d*)/.exec(b.slice(j).match(/^\d+/)[0])[1];
+			if (m.length !== n.length) return m.length < n.length ? -1 : 1;
+			if (m !== n) return m < n ? -1 : 1;
+			i += a.slice(i).match(/^\d+/)[0].length;
+			j += b.slice(j).match(/^\d+/)[0].length;
+			continue;
+		}
+		if (x !== y) return cls(x) - cls(y) || (x < y ? -1 : 1);
+		i++; j++;
+	}
+	return i < a.length ? 1 : j < b.length ? -1 : 0;
+}
+function Collator(l, o) {
+	if (!(this instanceof Collator)) return new Collator(l, o);
+	o = opt(o);
+	var r = this.o = { locale: "en-US", usage: o.usage || "sort",
+		sensitivity: o.sensitivity || "variant",
+		ignorePunctuation: !!o.ignorePunctuation,
+		numeric: !!o.numeric, caseFirst: o.caseFirst || "false",
+		collation: "default" };
+	this.compare = function (a, b) {
+		a = String(a); b = String(b);
+		if (r.ignorePunctuation) {
+			a = a.replace(/[\s!-/:-@[-`{-~]/g, "");
+			b = b.replace(/[\s!-/:-@[-`{-~]/g, "");
+		}
+		var fa = fold(a), fb = fold(b),
+		    c = cmp(fa.toLowerCase(), fb.toLowerCase(), r.numeric);
+		if (c || r.sensitivity === "base") return c;
+		if (r.sensitivity !== "case" && (c = cmp(a.toLowerCase(), b.toLowerCase(), r.numeric)))
+			return c;
+		if (r.sensitivity === "accent") return 0;
+		c = -cmp(r.sensitivity === "case" ? fa : a, r.sensitivity === "case" ? fb : b, r.numeric);
+		return r.caseFirst === "upper" ? -c : c;
+	};
+}
+ctor(Collator, {
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+var coll0 = new Collator();
+String.prototype.localeCompare = function (t, l, o) {
+	return (o ? new Collator(l, o) : coll0).compare(this, t);
+};
+
+function PluralRules(l, o) {
+	o = opt(o);
+	this.o = { locale: "en-US", type: o.type || "cardinal",
+		pluralCategories: o.type === "ordinal" ?
+			["few", "one", "two", "other"] : ["one", "other"] };
+}
+ctor(PluralRules, {
+	select: function (n) {
+		n = Math.abs(Number(n));
+		if (this.o.type !== "ordinal") return n === 1 ? "one" : "other";
+		var a = n % 10, b = n % 100;
+		return a === 1 && b !== 11 ? "one" : a === 2 && b !== 12 ? "two" :
+			a === 3 && b !== 13 ? "few" : "other";
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+
+function ListFormat(l, o) {
+	o = opt(o);
+	this.o = { locale: "en-US", type: o.type || "conjunction",
+		style: o.style || "long" };
+}
+ctor(ListFormat, {
+	format: function (l) {
+		var a = Array.from(l || [], String), t = this.o.type,
+		    w = t === "disjunction" ? " or " : t === "unit" ? ", " :
+			this.o.style === "long" ? " and " : this.o.style === "short" ? " & " : ", ";
+		if (t === "unit" && this.o.style === "narrow") return a.join(" ");
+		if (a.length < 3) return a.join(w);
+		return a.slice(0, -1).join(", ") + (t === "unit" || w === ", " ?
+			", " : "," + w) + a[a.length - 1];
+	},
+	resolvedOptions: function () { return Object.assign({}, this.o); }
+});
+
+function Locale(t) {
+	var s = String(t).split(/[-_]/);
+	this.baseName = String(t).replace(/_/g, "-");
+	this.language = s[0].toLowerCase();
+	this.region = s.length > 1 && /^[A-Za-z]{2}$|^\d{3}$/.test(s[s.length - 1]) ?
+		s[s.length - 1].toUpperCase() : undefined;
+}
+Locale.prototype.toString = function () { return this.baseName; };
+Locale.prototype.maximize = Locale.prototype.minimize = function () { return this; };
+
+def("Intl", Object.defineProperty({
+	DateTimeFormat: DateTimeFormat, NumberFormat: NumberFormat,
+	RelativeTimeFormat: RelativeTimeFormat, DurationFormat: DurationFormat,
+	DisplayNames: DisplayNames, Collator: Collator,
+	PluralRules: PluralRules, ListFormat: ListFormat, Locale: Locale,
+	getCanonicalLocales: function (l) {
+		return [].concat(l === undefined ? [] : l).map(String);
+	},
+	supportedValuesOf: function (k) {
+		return k === "timeZone" ? ["UTC"] : k === "calendar" ? ["gregory"] : [];
+	}
+}, Symbol.toStringTag, { value: "Intl", configurable: true }));
+})();
+
 /* ---- CSS namespace ----
  * escape() is the CSSOM serialization of an identifier; supports() gives
  * the cascade's own @supports answer (true unless it asks for selector()),

+ 61 - 9
user/apps/curl/ucmd_curl.c

@@ -75,6 +75,7 @@ struct fetch_paths {
 	char done[FETCH_PATH_MAX];
 	char post[FETCH_PATH_MAX];
 	char px[FETCH_PATH_MAX];
+	char prog[FETCH_PATH_MAX];
 };
 static struct fetch_paths fp;
 
@@ -126,6 +127,7 @@ static void fetch_paths_init(unsigned int session, int slot)
 	fetch_path(fp.done, sizeof(fp.done), "done", session, slot);
 	fetch_path(fp.post, sizeof(fp.post), "post", session, slot);
 	fetch_path(fp.px, sizeof(fp.px), "px", session, slot);
+	fetch_path(fp.prog, sizeof(fp.prog), "prog", session, slot);
 }
 
 /* Optional decode in the fetch helper.  The browser's UI thread only has
@@ -381,16 +383,37 @@ static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
 	u_syscall3(SYS_WRITE_FILE, (int)fp.meta, (int)meta, (int)n);
 }
 
-/* Fetch one URL through a possibly reused keep-alive connection. */
+/* Progress for the browser's download manager: the helper writes the bytes
+ * received so far while the body is still arriving.  `total` is 0 when the
+ * server sent no Content-Length. */
+static void write_progress(const char *path, unsigned int seq,
+			   unsigned int got, unsigned int total)
+{
+	static char buf[80];
+	unsigned int n = 0;
+
+	app_dec(buf, &n, seq, sizeof(buf));
+	app_ch(buf, &n, '\n', sizeof(buf));
+	app_dec(buf, &n, got, sizeof(buf));
+	app_ch(buf, &n, '\n', sizeof(buf));
+	app_dec(buf, &n, total, sizeof(buf));
+	app_ch(buf, &n, '\n', sizeof(buf));
+	u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)n);
+}
+
+/* Fetch one URL through a possibly reused keep-alive connection.  `prog`
+ * (with `prog_seq`) turns on progress publishing for a download. */
 static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 			 const char *method, const char *ctype,
 			 const char *post, unsigned int post_len,
 			 unsigned char *buf, unsigned int *outlen,
 			 unsigned int *outtrunc, int *outerr,
-			 struct fetch_times *times)
+			 struct fetch_times *times, unsigned int open_flags,
+			 const char *prog, unsigned int prog_seq)
 {
 	unsigned int total = 0;
 	unsigned int t0 = u_ticks_ms(), t1, tfirst = 0;
+	unsigned int last_prog = 0;
 	int rv, trunc = 0, err = 0;
 
 	*outlen = 0;
@@ -406,13 +429,13 @@ static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 	if (!ctype || !ctype[0])
 		ctype = "application/x-www-form-urlencoded";
 	uhttp_set_method(h, method, post, post_len, ctype);
-	rv = uhttp_open(h, url, UHTTP_GZIP, 0);
+	rv = uhttp_open(h, url, open_flags, 0);
 	if (rv == UHTTP_ERR_BUSY) {
 		int tries;
 
 		for (tries = 0; tries < 50 && rv == UHTTP_ERR_BUSY; tries++) {
 			u_sleep_ms(20);
-			rv = uhttp_open(h, url, UHTTP_GZIP, 0);
+			rv = uhttp_open(h, url, open_flags, 0);
 		}
 	}
 	t1 = u_ticks_ms();
@@ -424,13 +447,29 @@ static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 		*outerr = rv;
 		return;
 	}
+	if (prog && h->resp.have_length)
+		write_progress(prog, prog_seq, 0, h->resp.content_length);
+	last_prog = u_ticks_ms();
 	for (;;) {
-		rv = uhttp_read(h, buf + total, cap - total,
+		unsigned int want = cap - total;
+
+		/* A download reads in small slices so the progress file
+		 * changes while the body is still arriving; uhttp_read()
+		 * fills its whole buffer otherwise. */
+		if (prog && want > 16u * 1024u)
+			want = 16u * 1024u;
+		rv = uhttp_read(h, buf + total, want,
 				UHTTP_IDLE_TIMEOUT_MS);
 		if (rv > 0) {
 			if (!tfirst)
 				tfirst = u_ticks_ms();
 			total += (unsigned int)rv;
+			if (prog && (unsigned int)(u_ticks_ms() - last_prog) >= 100) {
+				last_prog = u_ticks_ms();
+				write_progress(prog, prog_seq, total,
+					       h->resp.have_length ?
+					       h->resp.content_length : 0);
+			}
 			if (total >= cap) {
 				trunc = 1;
 				break;
@@ -441,6 +480,9 @@ static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 			err = rv;
 		break;
 	}
+	if (prog)
+		write_progress(prog, prog_seq, total,
+			       h->resp.have_length ? h->resp.content_length : 0);
 	*outlen = total;
 	*outtrunc = (unsigned int)trunc;
 	*outerr = err;
@@ -494,8 +536,8 @@ static void fetch_once(void)
 
 	uhttp_init(&h);
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
-	helper_fetch(&h, req + i, cap, 0, 0, 0, 0, buf, &body_len, &body_trunc, &err,
-		     &times);
+	helper_fetch(&h, req + i, cap, 0, 0, 0, 0, buf, &body_len,
+		     &body_trunc, &err, &times, UHTTP_GZIP, 0, 0);
 	if (body_len)
 		u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
 			   (int)body_len);
@@ -560,7 +602,7 @@ static void fetch_serve(const char *arg)
 		unsigned int seq = 0, cap = 0, body_len = 0, body_trunc = 0;
 		unsigned int post_len = 0, jar_changes;
 		unsigned int dec_w = 0, dec_h = 0;
-		int decode = 0;
+		int decode = 0, download = 0;
 		int is_post = 0;
 		struct fetch_px px;
 		char method[12], ctype[96];
@@ -615,6 +657,12 @@ static void fetch_serve(const char *arg)
 					i++;
 				decode = 1;
 			}
+			/* "DL <url>": a browser download.  No gzip and a progress
+			 * file while the body arrives. */
+			if (!decode && !strncmp(req + i, "DL ", 3)) {
+				download = 1;
+				i += 3;
+			}
 			/* "X <method> <body length> <content type or -> <url>":
 			 * any method, for the browser's fetch()/XHR. */
 			if (!decode && !strncmp(req + i, "X ", 2)) {
@@ -696,9 +744,13 @@ static void fetch_serve(const char *arg)
 		 * jar-less request after the OIDC login POST drops the
 		 * interaction cookie ("authorization request has expired"). */
 		h.jar = &fetch_jar;
+		if (download)
+			u_syscall1(SYS_UNLINK, (int)fp.prog);
 		helper_fetch(&h, url, cap, method[0] ? method : 0, ctype,
 			     post_len ? (char *)post : 0, post_len,
-			     buf, &body_len, &body_trunc, &err, &times);
+			     buf, &body_len, &body_trunc, &err, &times,
+			     download ? 0 : UHTTP_GZIP,
+			     download ? fp.prog : 0, seq);
 		if (fetch_jar.changes != jar_changes)
 			jar_save();
 		if (body_len)

+ 2 - 1
user/apps/term/ucmd_term.c

@@ -475,7 +475,8 @@ static void handle_pointer(void)
 	struct win_pointer p;
 
 	while (u_win_event(&e) == 1) {
-		if (e.type == WIN_EV_POINTER_DOWN) {
+		if (e.type == WIN_EV_POINTER_DOWN &&
+		    ((e.button ? e.button : e.buttons) & 1)) {
 			if (e.x >= (int)(wi.width - SB_W) && e.y >= 0 &&
 			    e.y < (int)wi.height) {
 				unsigned int track_h, thumb_h, thumb_y;

+ 111 - 0
user/apps/view/ucmd_view.c

@@ -5,6 +5,7 @@
  * and draws it with fit/1:1/zoom/pan support. */
 
 #include <stdlib.h>
+#include <string.h>
 
 #include "ucmd_lib.h"
 #include "ngui.h"
@@ -21,6 +22,7 @@
 #define VIEW_ID_ONE    2
 #define VIEW_ID_OUT    3
 #define VIEW_ID_IN     4
+#define VIEW_ID_WALL   5
 
 #define VIEW_BG        NGUI_RGB(24, 26, 32)
 #define VIEW_VIEW_BG   NGUI_RGB(16, 17, 21)
@@ -48,6 +50,8 @@ struct viewer {
 	unsigned int gif_frames, gif_index, gif_delay, gif_next_ms;
 	int last_w, last_h;
 	char err[64];
+	char notice[40];
+	unsigned int notice_until;
 	char name[20];
 	char title[20];
 	int dirty;
@@ -226,11 +230,106 @@ static void view_zoom_step(struct ngui *ui, int in)
 	view_set_scale(ui, s);
 }
 
+static void view_notice(const char *s)
+{
+	s_copy(v.notice, s, sizeof(v.notice));
+	v.notice_until = u_ticks_ms() + 4000;
+	v.dirty = 1;
+}
+
+/* Pre-render the image as a screen-aspect RGB565 wallpaper (at most
+ * 1440x810) and hand it to the WM.  The WM has no image decoder; it only
+ * scales this buffer to the desktop.  A mounted data volume gets the
+ * persistent copy, otherwise the RAM copy is used. */
+static void view_set_wallpaper(void)
+{
+	const char *magic = WM_WALLPAPER_MAGIC;
+	const char *path = WM_WALLPAPER_SHARE;
+	struct wm_wallpaper_hdr *h;
+	struct sys_stat st;
+	struct img_blit b;
+	unsigned char *buf;
+	unsigned int sw, sh, tw, th, pixbytes, total, i;
+	unsigned long long sx, sy, scale, dw, dh;
+
+	if (!v.have_img) {
+		view_notice("No image to use");
+		return;
+	}
+	if (u_screen_size(&sw, &sh) != 0 || !sw || !sh) {
+		view_notice("Cannot read screen size");
+		return;
+	}
+	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;
+	buf = (unsigned char *)malloc(total);
+	if (!buf) {
+		view_notice("Not enough memory");
+		return;
+	}
+	memset(buf, 0, total);
+	h = (struct wm_wallpaper_hdr *)buf;
+	for (i = 0; i < sizeof(h->magic); i++)
+		h->magic[i] = magic[i];
+	h->width = tw;
+	h->height = th;
+
+	/* Cover the screen, cropping the longer source axis. */
+	sx = (((unsigned long long)tw << 16) + v.iw - 1) / v.iw;
+	sy = (((unsigned long long)th << 16) + v.ih - 1) / v.ih;
+	scale = sx > sy ? sx : sy;
+	if (!scale)
+		scale = 1;
+	dw = ((unsigned long long)v.iw * scale) >> 16;
+	dh = ((unsigned long long)v.ih * scale) >> 16;
+	memset(&b, 0, sizeof(b));
+	b.dst = (unsigned short *)(buf + 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(&v.img, &b);
+
+	if (u_stat("/data", &st) == 0 && st.is_dir)
+		path = WM_WALLPAPER_DATA;
+	if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)total) < 0) {
+		free(buf);
+		view_notice("Cannot save wallpaper");
+		return;
+	}
+	u_syscall1(SYS_WM_WALLPAPER, 1);
+	free(buf);
+	view_notice("Wallpaper set");
+}
+
 static void format_status(char *buf, unsigned int cap)
 {
 	unsigned int n = 0;
 
 	buf[0] = '\0';
+	if (v.notice[0]) {
+		s_copy(buf, v.notice, cap);
+		return;
+	}
 	if (v.have_img) {
 		unsigned int scale = view_scale(&v.ui);
 
@@ -313,6 +412,12 @@ static void draw_toolbar(struct ngui *ui, struct ngui_rect r)
 		v.dirty = 1;
 	}
 	x += 32;
+	if (v.have_img && x + 90 < r.x + r.w) {
+		b = (struct ngui_rect){x, by, 84, 20};
+		if (ngui_button(ui, VIEW_ID_WALL, b, "Background"))
+			view_set_wallpaper();
+		x += 89;
+	}
 	if (v.have_img && x + 70 < r.x + r.w) {
 		char z[16];
 		unsigned int n = 0;
@@ -573,6 +678,10 @@ void _start(const char *arg)
 		int k;
 		unsigned int now = u_ticks_ms();
 
+		if (v.notice[0] && (int)(now - v.notice_until) >= 0) {
+			v.notice[0] = '\0';
+			v.dirty = 1;
+		}
 		if (v.gif_frames > 1 &&
 		    (int)(now - v.gif_next_ms) >= 0) {
 			unsigned int d = v.gif_delay;
@@ -614,6 +723,8 @@ void _start(const char *arg)
 			} else if (k == '-' || k == '_') {
 				view_zoom_step(ui, 0);
 				v.dirty = 1;
+			} else if (k == 'b' || k == 'B') {
+				view_set_wallpaper();
 			} else if (k == NGUI_KEY_LEFT || k == NGUI_KEY_RIGHT ||
 				   k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
 				if (v.have_img) {

+ 209 - 7
user/apps/wm/ucmd_wm.c

@@ -53,6 +53,25 @@ struct uwin {
 static struct usurf screen;
 static struct uwin wins[WM_MAX_WINDOWS];
 static unsigned int fbw, fbh;
+
+/* Desktop wallpaper: the viewer stores a header plus RGB565 pixels; the WM
+ * only has to stretch that small buffer to the framebuffer, so no image
+ * decoder is linked in.  The static buffer avoids pulling malloc into the
+ * WM and stays within the 4 MB user image window. */
+#define WALL_MAP_MAX 2048
+static unsigned char wall_data[sizeof(struct wm_wallpaper_hdr) +
+	(unsigned int)WM_WALLPAPER_MAX_W * WM_WALLPAPER_MAX_H * 2u + 512];
+static unsigned int wall_w, wall_h;
+static int wall_ready;
+static unsigned int wall_seq_seen;
+static int wall_boot_seen;
+static int wall_retries;
+static unsigned int wall_retry_ms;
+static unsigned short wall_xmap[WALL_MAP_MAX];
+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];
 static int drag_id = -1;
 static int drag_dx, drag_dy;
 static int drag_mx, drag_my;       /* press position, for restore-on-drag */
@@ -197,6 +216,8 @@ static int sm_power_open;
 static int sm_start_hot;
 static int sm_hot;              /* hovered app index, -1 = none */
 static int sm_power_hot;        /* 0 none, 1 Power, 2 Reboot, 3 Power off */
+static int poweroff_pid;        /* the kcmd spawned by Power off */
+static unsigned int poweroff_deadline;
 
 static void sm_layout_get(struct sm_layout *l);
 static void sm_draw(void);
@@ -852,12 +873,148 @@ static unsigned int rect_sub(struct orect *out, const struct orect *r,
 	return n;
 }
 
+static void wall_build_maps(void)
+{
+	unsigned int i;
+
+	if (screen.bpp == 32) {
+		for (i = 0; i < 65536; i++) {
+			unsigned int r = (i >> 11) & 31;
+			unsigned int g = (i >> 5) & 63;
+			unsigned int b = i & 31;
+
+			wall_rgb32[i] = 0xFF000000u |
+				((r << 3 | r >> 2) << 16) |
+				((g << 2 | g >> 4) << 8) |
+				(b << 3 | b >> 2);
+		}
+	}
+	for (i = 0; i < WALL_MAP_MAX; i++) {
+		unsigned int sx = 0, sy = 0;
+
+		if (fbw && i < fbw)
+			sx = (unsigned int)((unsigned long long)i * wall_w / fbw);
+		if (fbh && i < fbh)
+			sy = (unsigned int)((unsigned long long)i * wall_h / fbh);
+		if (sx >= wall_w)
+			sx = wall_w - 1;
+		if (sy >= wall_h)
+			sy = wall_h - 1;
+		wall_xmap[i] = (unsigned short)sx;
+		wall_ymap[i] = (unsigned short)sy;
+	}
+}
+
+static int wall_magic_ok(const struct wm_wallpaper_hdr *h)
+{
+	unsigned int i;
+
+	for (i = 0; i < sizeof(h->magic); i++)
+		if (h->magic[i] != WM_WALLPAPER_MAGIC[i])
+			return 0;
+	return 1;
+}
+
+/* Read the persistent copy first, then the RAM copy.  The FAT driver may
+ * write a final partial sector past the requested length, so wall_data has
+ * 512 bytes of slack and the read is capped one sector below its size. */
+static void wall_load(void)
+{
+	static const char *const paths[] = {
+		WM_WALLPAPER_DATA, WM_WALLPAPER_SHARE
+	};
+	struct wm_wallpaper_hdr *h = (struct wm_wallpaper_hdr *)wall_data;
+	unsigned int i, pixbytes;
+	int rn;
+
+	wall_ready = 0;
+	for (i = 0; i < sizeof(paths) / sizeof(paths[0]); i++) {
+		rn = u_syscall3(SYS_READ_FILE, (int)paths[i], (int)wall_data,
+				(int)(sizeof(wall_data) - 512));
+		if (rn < (int)sizeof(*h) || !wall_magic_ok(h))
+			continue;
+		if (!h->width || !h->height ||
+		    h->width > WM_WALLPAPER_MAX_W ||
+		    h->height > WM_WALLPAPER_MAX_H)
+			continue;
+		pixbytes = h->width * h->height * 2u;
+		if ((unsigned int)rn < sizeof(*h) + pixbytes)
+			continue;
+		wall_w = h->width;
+		wall_h = h->height;
+		wall_ready = 1;
+		wall_build_maps();
+		return;
+	}
+}
+
+/* Paint the desktop part of one damage rectangle. */
+static void wall_draw(int x, int y, unsigned int w, unsigned int h)
+{
+	const unsigned short *src = (const unsigned short *)(wall_data +
+		sizeof(struct wm_wallpaper_hdr));
+	int x0 = x, y0 = y, x1 = x + (int)w, y1 = y + (int)h;
+	unsigned int yy, xx;
+
+	if (!wall_ready) {
+		usurf_fill(&screen, x, y, w, h, COL_BG);
+		return;
+	}
+	if (x0 < 0) x0 = 0;
+	if (y0 < 0) y0 = 0;
+	if (x1 > (int)fbw) x1 = (int)fbw;
+	if (y1 > (int)fbh) y1 = (int)fbh;
+	if (x1 > WALL_MAP_MAX) x1 = WALL_MAP_MAX;
+	if (y1 > WALL_MAP_MAX) y1 = WALL_MAP_MAX;
+	if (x1 <= x0 || y1 <= y0)
+		return;
+	usurf_pixels += (unsigned int)(x1 - x0) * (unsigned int)(y1 - y0);
+	for (yy = (unsigned int)y0; yy < (unsigned int)y1; yy++) {
+		const unsigned short *srow = src + (unsigned int)wall_ymap[yy] *
+						 wall_w;
+
+		/* d points at the start of the row; the loops index it with
+		 * absolute screen x.  Pointing d at x0 and still indexing with
+		 * x shifted every damage rect's wallpaper right by x0, which
+		 * left old window pixels in the uncovered strip and made
+		 * dragging windows leave a trail. */
+		if (screen.bpp == 16) {
+			unsigned short *d = (unsigned short *)(screen.px +
+				(unsigned long)yy * screen.pitch);
+
+			for (xx = (unsigned int)x0; xx < (unsigned int)x1; xx++)
+				d[xx] = srow[wall_xmap[xx]];
+		} else if (screen.bpp == 32) {
+			unsigned int *d = (unsigned int *)(screen.px +
+				(unsigned long)yy * screen.pitch);
+
+			for (xx = (unsigned int)x0; xx < (unsigned int)x1; xx++)
+				d[xx] = wall_rgb32[srow[wall_xmap[xx]]];
+		} else {
+			unsigned char *d = screen.px +
+				(unsigned long)yy * screen.pitch + x0 * 3;
+
+			for (xx = (unsigned int)x0; xx < (unsigned int)x1; xx++) {
+				unsigned int c = srow[wall_xmap[xx]];
+				unsigned int r = (c >> 11) & 31;
+				unsigned int g = (c >> 5) & 63;
+				unsigned int b = c & 31;
+
+				d[0] = (unsigned char)(b << 3 | b >> 2);
+				d[1] = (unsigned char)(g << 2 | g >> 4);
+				d[2] = (unsigned char)(r << 3 | r >> 2);
+				d += 3;
+			}
+		}
+	}
+}
+
 /* Back-to-front repaint, used only if the visible-region list overflows. */
 static void draw_rect_naive(int x, int y, unsigned int w, unsigned int h)
 {
 	unsigned int i;
 
-	usurf_fill(&screen, x, y, w, h, COL_BG);
+	wall_draw(x, y, w, h);
 	for (i = 0; i < WM_MAX_WINDOWS; i++)
 		if (wins[i].info.used && !wins[i].info.focused &&
 		    !wins[i].info.popover &&
@@ -904,7 +1061,7 @@ static void draw_rect(int x, int y, unsigned int w, unsigned int h)
 	dmg.y = y0;
 	dmg.w = (unsigned int)(x1 - x0);
 	dmg.h = (unsigned int)(y1 - y0);
-	usurf_fill(&screen, dmg.x, dmg.y, dmg.w, dmg.h, COL_BG);
+	wall_draw(dmg.x, dmg.y, dmg.w, dmg.h);
 
 	n = build_order(order);
 	for (i = 0; i < n; i++) {
@@ -1229,10 +1386,18 @@ static void move_window_pixels(struct uwin *u, int ox, int oy, int nx, int ny)
 		draw_rect(pieces[k].x, pieces[k].y, pieces[k].w, pieces[k].h);
 	present.count = 0;
 	present.immediate = 1;
-	add_rect(&present, nx, ny, u->info.w, u->info.h);
-	for (k = 0; k < np; k++)
-		add_rect(&present, pieces[k].x, pieces[k].y,
-			 pieces[k].w, pieces[k].h);
+	/* Present the union of the old and new rectangles as one rect.
+	 * The shadow is correct for all of it, and one rect cannot be cut
+	 * off by the kernel's four-entry present list. */
+	{
+		int ux0 = ox < nx ? ox : nx;
+		int uy0 = oy < ny ? oy : ny;
+		int ux1 = (ox > nx ? ox : nx) + (int)u->info.w;
+		int uy1 = (oy > ny ? oy : ny) + (int)u->info.h;
+
+		add_rect(&present, ux0, uy0, (unsigned int)(ux1 - ux0),
+			 (unsigned int)(uy1 - uy0));
+	}
 	wm_overlays(&present);
 	u_wm_present(&present);
 }
@@ -2291,9 +2456,16 @@ static void handle_mouse(struct wm_status *st)
 				if (u_spawn_kcmd("reboot", "", 0) < 0)
 					bar_notice("reboot failed");
 			} else if (hit == SM_HIT_POWEROFF) {
+				int pid;
+
 				sm_close();
-				if (u_spawn_kcmd("poweroff", "", 0) < 0)
+				pid = u_spawn_kcmd("poweroff", "", 0);
+				if (pid < 0) {
 					bar_notice("poweroff failed");
+				} else {
+					poweroff_pid = pid;
+					poweroff_deadline = u_ticks_ms() + 6000;
+				}
 			} else if (hit >= 0) {
 				sm_launch(hit);
 			} else if (hit != SM_HIT_MENU) {
@@ -2527,6 +2699,7 @@ void _start(const char *arg)
 	usurf_font_attach(&screen, "/ramfs/fonts/sans.ttf", 14);
 	fbw = si.width;
 	fbh = si.height;
+	wall_load();
 	for (i = 0; i < WM_MAX_WINDOWS; i++) {
 		wins[i].info.used = 0;
 		wins[i].mapped = 0;
@@ -2538,6 +2711,35 @@ void _start(const char *arg)
 
 		if (u_wm_poll(&st) != 0)
 			u_exit(1);
+		/* 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 &&
+		    (int)(u_ticks_ms() - poweroff_deadline) >= 0) {
+			bar_notice("poweroff failed");
+			poweroff_pid = 0;
+		}
+		if (st.wallpaper_seq != wall_seq_seen) {
+			wall_seq_seen = st.wallpaper_seq;
+			wall_load();
+			full_redraw = 1;
+		}
+		/* The WM starts before the storage scan, so the first load may not
+		 * see /data yet.  Reload when boot_ready says the mounts are up,
+		 * and retry for ten seconds for the deferred USB /data volume. */
+		if (st.boot_ready && !wall_boot_seen) {
+			wall_boot_seen = 1;
+			wall_retries = 0;
+			wall_retry_ms = u_ticks_ms() + 1000;
+			wall_load();
+			full_redraw = 1;
+		} else if (wall_boot_seen && !wall_ready && wall_retries < 10 &&
+			   (int)(u_ticks_ms() - wall_retry_ms) >= 0) {
+			wall_retries++;
+			wall_retry_ms += 1000;
+			wall_load();
+			if (wall_ready)
+				full_redraw = 1;
+		}
 		if (st.full_redraw)
 			full_redraw = 1;
 		usurf_pixels = 0;

+ 29 - 8
user/lib/ngui/ngui.c

@@ -210,6 +210,7 @@ int ngui_begin(struct ngui *ui)
 
 	ui->dirty = 0;
 	ui->pressed = ui->released = 0;
+	ui->right_pressed = ui->right_released = 0;
 	ui->clicked = 0;
 	ui->focus_claimed = 0;
 	ui->hot = 0;
@@ -256,14 +257,33 @@ int ngui_begin(struct ngui *ui)
 		if (r != 1)
 			break;
 		if (ev.type == WIN_EV_POINTER_DOWN) {
-			ui->pressed |= 1;
-			ui->press_x = ev.x;
-			ui->press_y = ev.y;
-			ui->clicked = 1;
+			unsigned int b = ev.button ? ev.button : ev.buttons;
+
+			if (b & 1) {
+				ui->pressed |= 1;
+				ui->press_x = ev.x;
+				ui->press_y = ev.y;
+				ui->clicked = 1;
+			}
+			if (b & 2) {
+				ui->right_pressed |= 1;
+				ui->right_press_x = ev.x;
+				ui->right_press_y = ev.y;
+			}
 		} else if (ev.type == WIN_EV_POINTER_UP) {
-			ui->released |= 1;
-			ui->release_x = ev.x;
-			ui->release_y = ev.y;
+			unsigned int b = ev.button ? ev.button :
+				(~ev.buttons & 3);
+
+			if (b & 1) {
+				ui->released |= 1;
+				ui->release_x = ev.x;
+				ui->release_y = ev.y;
+			}
+			if (b & 2) {
+				ui->right_released |= 1;
+				ui->right_release_x = ev.x;
+				ui->right_release_y = ev.y;
+			}
 		}
 	}
 
@@ -323,7 +343,8 @@ int ngui_begin(struct ngui *ui)
 	ui->last_inside = ui->inside;
 	ui->last_focused = ui->focused;
 
-	if (ui->pressed || ui->released)
+	if (ui->pressed || ui->released || ui->right_pressed ||
+	    ui->right_released)
 		want = 1;
 	if (want)
 		ui->motion_pending = 0;

+ 7 - 1
user/lib/ngui/ngui.h

@@ -162,11 +162,17 @@ struct ngui {
 	/* Scroll accumulated since the previous frame, in pixels. */
 	int scroll_x, scroll_y;
 
-	/* Press/release edges collected by ngui_begin(). */
+	/* Press/release edges collected by ngui_begin().  `pressed` and
+	 * `released` are the left button; the right-button edges let an app
+	 * open a context menu without taking the normal click path. */
 	unsigned int pressed;
 	unsigned int released;
+	unsigned int right_pressed;
+	unsigned int right_released;
 	int press_x, press_y;
 	int release_x, release_y;
+	int right_press_x, right_press_y;
+	int right_release_x, right_release_y;
 	int clicked;
 	int focus_claimed;
 

Некоторые файлы не были показаны из-за большого количества измененных файлов