Explorar o código

Add touchpad two-finger scrolling and a shared scroll path

Split the Elan tap/click state into touchpad_gesture.c/h so hardware
backends only decode contacts.  The engine now also turns two-finger
centroid movement into pixel scrolling, freezes the pointer while two
fingers are down, and suppresses the right tap once a gesture scrolls.
Natural direction is the default; `touchpad scroll ...` configures it.

Aggregate scroll from the touchpad and the PS/2 IntelliMouse wheel in
mouse.c, route it to the canvas window under the pointer in the WM, and
expose it through SYS_WIN_SCROLL in pixels.  ngui loads the delta in
ngui_begin() and ngui_scroll_wheel() applies it to a pane.

Wire scrolling into the browser (bypassing its cached page blit while a
delta is pending), files, gallery's nested pane, editor and terminal
scrollback.  Add the host gesture test target and update AGENTS.md and
the architecture pages.

Validated with make test-touchpad, a headless QEMU PS/2 wheel test
through the WM into the terminal, and on the HP Chromebook 11 G5 EE.
Johannes Zellner hai 1 semana
pai
achega
a13542af1d
Modificáronse 32 ficheiros con 1019 adicións e 300 borrados
  1. 1 0
      .gitignore
  2. 35 24
      AGENTS.md
  3. 13 4
      Makefile
  4. 3 0
      browser.c
  5. 2 0
      docs/development.html
  6. 20 8
      docs/drivers.html
  7. 7 2
      docs/graphics.html
  8. 1 1
      docs/userland.html
  9. 12 0
      gallery.c
  10. 40 4
      mouse.c
  11. 3 0
      mouse.h
  12. 21 0
      ngui.c
  13. 6 0
      ngui.h
  14. 14 0
      sys_wm.c
  15. 1 0
      sys_wm.h
  16. 2 0
      syscall.c
  17. 1 0
      syscall.h
  18. 1 1
      terminal.c
  19. 141 246
      touchpad.c
  20. 4 3
      touchpad.h
  21. 272 0
      touchpad_gesture.c
  22. 104 0
      touchpad_gesture.h
  23. 178 0
      touchpad_gesture_test.c
  24. 51 4
      ucmd_edit.c
  25. 1 0
      ucmd_files.c
  26. 5 0
      ucmd_lib.h
  27. 15 0
      ucmd_term.c
  28. 3 1
      usbhid.c
  29. 3 2
      usbhid.h
  30. 50 0
      wm.c
  31. 3 0
      wm.h
  32. 6 0
      wm_abi.h

+ 1 - 0
.gitignore

@@ -15,6 +15,7 @@ img_test_asan
 text_canvas_test
 ufont_test
 ufont_test_asan
+touchpad_gesture_test
 libc.a
 malloc_test
 format_test

+ 35 - 24
AGENTS.md

@@ -79,6 +79,7 @@ make test-libc  # host tests for ring-3 malloc, stdio, math, div64 and setjmp
 make test-mujs  # host smoke test for the vendored MuJS engine
 make test-font  # host TrueType parser/rasterizer specimen test
 make test-font-asan  # ASan/UBSan variant
+make test-touchpad  # host tests for the contact gesture engine
 make compat-serve  # serve the browser A/B ladder on port 8000
 make fonts      # regenerate fonts/*.ttf with pyftsubset + system fonts
 make clean
@@ -327,7 +328,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `usurf_pixels`.  The WM writes the last two-second interval to
   `/share/wmstats` (`frames`, `ms`, `max`, `px`) for on-target measurement.
   `SYS_WIN_INFO`, `SYS_WIN_ACK_RESIZE`, `SYS_WIN_POINTER`, `SYS_WIN_EVENT`,
-  `SYS_WIN_KEY_WAIT` and the generic `SYS_KEY_POLL` handle input.  The WM
+  `SYS_WIN_SCROLL`, `SYS_WIN_KEY_WAIT` and the generic `SYS_KEY_POLL` handle
+  input.  `SYS_WIN_SCROLL` returns scroll accumulated for the canvas window
+  under the pointer, in pixels (`+dy` = later content), so every client sees
+  one unit independent of whether it came from the touchpad or a wheel.  The WM
   composites the front canvas; presented frames carry monotonic seq
   counters, so the WM can never lose one.  Closing a window kills its owner;
   the reaper frees the canvas.  `clock`, `colors`, `settime`,
@@ -582,10 +586,13 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   may have been inside a scheduler critical section when INIT arrived) and then
   jumps; the new kernel starts the APs again from scratch.
 - **Mouse**: `mouse.c/h` — cursor move/draw shared by the PS/2 path
-  (IntelliMouse, Cirrus/Radeon hardware cursor) and the USB backend;
-  `usbhid.c/h` — USB HID boot devices: find + configure a mouse and/or
-  keyboard, arm their interrupt endpoints, decode mouse reports and inject
-  keyboard scancodes, watch for plug/unplug.
+  (IntelliMouse including the 4th-byte wheel, Cirrus/Radeon hardware
+  cursor) and the USB backend.  Scroll from every backend accumulates in
+  `mouse_scroll_y` and `mouse_scroll_take()` hands it to the WM in pixels;
+  one PS/2 wheel notch is 48 px.  `usbhid.c/h` — USB HID boot devices: find
+  + configure a mouse and/or keyboard, arm their interrupt endpoints, decode
+  mouse reports and inject keyboard scancodes, watch for plug/unplug (boot
+  protocol has no wheel field, so the USB wheel output stays 0 for now).
 - **I2C touchpad**: `i2c.c/h` — polled Synopsys DesignWare APB I2C master
   for the Braswell LPSS blocks (fast mode, component-type probe, explicit
   LPSS reset-release so the FIFO drains); `touchpad.c/h` — Elan
@@ -597,19 +604,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   native max-X/Y commands (`0x0106`/`0x0107`).  The report line is a GPIO with
   no driver, so `touchpad_poll()` reads the input register every 25 ms
   (back-to-back reads stall the device), parses the Elan `0x5D` vendor
-  report (finger bitmask plus five bytes per finger) and feeds
-  absolute-to-relative deltas and the clickpad bit into the mouse layer.
-  Finger 1 drives the pointer.  A short stationary tap synthesizes a
+  report (finger bitmask plus five bytes per packed finger) and feeds the
+  device-independent `touchpad_gesture.c/h` engine.  The engine owns
+  pointer scaling, taps, the physical-button latch and two-finger
+  scrolling, so another touchpad backend only has to decode its own
+  reports into up to two contacts.  A short stationary tap synthesizes a
   button press: two fingers -> right click, one finger in the bottom-right
   zone (`x >= 75%`, `y <= 25%`) -> right click, one finger elsewhere ->
   left click.  The device's raw Y axis grows upwards, so the bottom is the
   low end.  A physical clickpad press is also latched at its leading edge:
   in the bottom-right zone it becomes the right button, elsewhere the left
-  button, and the latch holds for the whole press.  The synthesized press
-  is held for 120 ms so commands polling `SYS_WIN_POINTER` can sample it.
+  button, and the latch holds for the whole press.  Two fingers that move
+  their centroid by more than ~30 device units scroll; the pointer freezes
+  while two or more fingers are down and re-anchors when one remains.
+  Natural scrolling (two fingers up = later content) is the default.
   `touchpad` prints the probe/status and takes
-  `rightclick off|tap|corner|both` / `tapclick on|off`; `mouseinfo` lists
-  the Elan VID/PID.
+  `rightclick off|tap|corner|both`, `tapclick on|off` and
+  `scroll on|off|natural|traditional`; `mouseinfo` lists the Elan VID/PID.
 - **USB**: `usb.c/h` — controller-agnostic core: device enumeration,
   descriptor parsing, hub recursion, bus scans, per-controller addresses, the
   hotplug watcher and the interrupt-IN consumers (mouse + keyboard).  It keeps
@@ -1012,7 +1023,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
-`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk), `install <target> [source]` (clone the live image; auto-detects the source, preferring `usb0`),
+`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk), `install <target> [source]` (clone the live image; auto-detects the source, preferring `usb0`),
 `ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), and `browser [url|file]` (disk app launcher).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -1720,17 +1731,17 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     MuJS but are not a complete POSIX libc.
 
 28. The Elan touchpad is polled at 40 Hz because its report GPIO (GPNC bank
-    index 18, level-low on setzer) has no driver.  Only finger 1 moves the
-    pointer; finger 2 is used only for the two-finger right tap.  There is
-    no two-finger scrolling, drag-lock or pressure/size handling, no
-    distinct three-finger gesture (3+ fingers count as a two-finger right
-    tap), and the 1/2 delta scale is fixed (no pointer-acceleration
-    curve).  Tap gestures are software-synthesized
-    (two-finger and bottom-right-corner right click, one-finger left
-    click) and need the contact to last at least two 25 ms samples; the
-    corner zone also remaps a physical clickpad press to the right button
-    and is a compile-time constant together with the tap thresholds in
-    `touchpad.c`.  The device stalls if the input register is read
+    index 18, level-low on setzer) has no driver.  The pointer follows one
+    contact; two-finger scrolling uses the centroid of the first two
+    contacts.  There is no inertia, no horizontal scroll, no drag-lock or
+    pressure/size handling, no distinct three-finger gesture (3+ fingers
+    count as a two-finger right tap), and the 1/2 device-unit delta scale
+    is fixed (no pointer-acceleration curve).  Tap gestures are
+    software-synthesized (two-finger and bottom-right-corner right click,
+    one-finger left click) and need the contact to last at least two 25 ms
+    samples; the corner zone also remaps a physical clickpad press to the
+    right button and the tap/scroll thresholds are in
+    `touchpad_gesture.c`.  The device stalls if the input register is read
     back-to-back, so a GPIO interrupt (or a larger minimum gap) is the
     prerequisite for a higher report rate.
 

+ 13 - 4
Makefile

@@ -66,7 +66,7 @@ EFI_LDFLAGS = -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan fonts kernel-dev kernel-net-dev rootfs
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan test-touchpad fonts kernel-dev kernel-net-dev rootfs
 
 all: floppy.img usb.img final.bin root.img
 
@@ -301,7 +301,10 @@ mouse.o: mouse.c mouse.h bootinfo.h cirrus.h cursor_shape.h radeon.h timer.h tou
 i2c.o: i2c.c i2c.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-touchpad.o: touchpad.c touchpad.h i2c.h io.h paging.h timer.h
+touchpad.o: touchpad.c touchpad.h touchpad_gesture.h i2c.h io.h paging.h timer.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+touchpad_gesture.o: touchpad_gesture.c touchpad_gesture.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 idle.o: idle.c idle.h power.h
@@ -397,7 +400,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netcore.h netdev.h n
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: kernel.ld vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
+kernel.elf: kernel.ld vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $(filter-out kernel.ld,$^)
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -635,6 +638,12 @@ ufont_test: $(UFONT_TEST_SRCS) ufont.h ufont_internal.h
 test-font: ufont_test
 	./ufont_test
 
+test-touchpad: touchpad_gesture_test
+	./touchpad_gesture_test
+
+touchpad_gesture_test: touchpad_gesture_test.c touchpad_gesture.c touchpad_gesture.h
+	gcc -O2 -Wall -Wextra -I. -o $@ touchpad_gesture_test.c touchpad_gesture.c
+
 test-font-asan: $(UFONT_TEST_SRCS) ufont.h ufont_internal.h
 	gcc -O1 -g -fsanitize=address,undefined -I. -o ufont_test_asan $(UFONT_TEST_SRCS)
 	./ufont_test_asan
@@ -1189,4 +1198,4 @@ kernel-net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan touchpad_gesture_test

+ 3 - 0
browser.c

@@ -7401,6 +7401,8 @@ static void draw_page(struct ngui_rect page)
 	if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
 	    page_cache_valid && layout_valid &&
 	    !ui.pressed && !(ui.buttons & 1) && !ui.released &&
+	    !(ui.scroll_y &&
+	      ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
 	    page_scroll.offset == page_cache_scroll &&
 	    page_cache_nnode == doc.nnode &&
 	    page_cache_x == page.x && page_cache_y == page.y &&
@@ -7449,6 +7451,7 @@ static void draw_page(struct ngui_rect page)
 	page_scroll.content_h = ch;
 	page_scroll.view_h = page.h;
 	ngui_scroll_begin(&ui, page, &page_scroll);
+	ngui_scroll_wheel(&ui, page, &page_scroll);
 	render_page(left, right, page.y + 4 - page_scroll.offset);
 	old_panel = ui.theme.panel_alt;
 	old_dim = ui.theme.text_dim;

+ 2 - 0
docs/development.html

@@ -181,6 +181,7 @@
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
 					<tr><td><code>make test-mujs</code></td><td>Host smoke test for the vendored MuJS engine: arithmetic, strings, Math, Date, JSON, exceptions and the run limit.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
+					<tr><td><code>make test-touchpad</code></td><td>Host tests for the device-independent contact gesture engine: taps, right-click zones, physical-button latch, two-finger scroll, direction and pointer re-anchoring.</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 fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
@@ -267,6 +268,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (32 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
+			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
 			<li><strong>Browser compatibility.</strong> <code>make compat-serve</code> serves the numbered A/B ladder in <code>testdata/browser/compat/</code>. Open the index on the board (or at <code>http://10.0.2.2:8000/</code> from a QEMU guest with user networking) and compare each pair; the index table records the current status.</li>
 			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line.</li>
 			<li><strong>Compositor stats.</strong> The ring-3 WM overwrites <code>/share/wmstats</code> every two seconds with <code>frames</code>, total and worst compositing time in milliseconds, and the pixels drawn in the interval. Read it in a terminal or fetch it over WebDAV to measure a target.</li>

+ 20 - 8
docs/drivers.html

@@ -85,7 +85,7 @@
 					<tr><td>USB</td><td><span class="file">usb.c</span> + <span class="file">uhci.c</span> <span class="file">ohci.c</span> <span class="file">ehci.c</span> <span class="file">xhci.c</span></td><td>PCI I/O ports or MMIO</td><td>Polled; hotplug watcher in the WM loop</td></tr>
 					<tr><td>Network</td><td><span class="file">e1000e.c</span> <span class="file">r8168.c</span> <span class="file">ne2000.c</span> <span class="file">asix.c</span></td><td>PCI or USB</td><td>Polled, one active receiver</td></tr>
 					<tr><td>PS/2</td><td><span class="file">mouse.c</span>, <span class="file">io.c</span></td><td>i8042</td><td>IRQ 1 keyboard, IRQ 12 mouse; polling fallback</td></tr>
-					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; software tap gestures; no GPIO interrupt driver</td></tr>
+					<tr><td>Touchpad</td><td><span class="file">i2c.c</span>, <span class="file">touchpad.c</span>, <span class="file">touchpad_gesture.c</span></td><td>LPSS DesignWare I2C, slave <code>0x15</code></td><td>Polled input register every 25 ms; software tap and two-finger scroll gestures; no GPIO interrupt driver</td></tr>
 					<tr><td>Serial</td><td><span class="file">serial.c</span></td><td>16550 UART, COM1</td><td>IRQ 4 ring buffer + polled transmitter</td></tr>
 					<tr><td>Thermal</td><td><span class="file">thermal.c</span></td><td>Intel DTS MSR</td><td>Sampled once a second from the scheduler tick</td></tr>
 					<tr><td>Board sensors / EC</td><td><span class="file">it87.c</span>, <span class="file">tpec.c</span>, <span class="file">ec.c</span>, <span class="file">cros_ec.c</span></td><td>Super I/O, ThinkPad H8 EC, Chrome OS EC (temps, fans, battery, AC, switches)</td><td>Polled; EC battery-index/FIFO/page-selector writes only</td></tr>
@@ -361,10 +361,11 @@
 			wake the device (<code>0x0800</code>). Resetting last leaves it
 			silent until the next power cycle.</li>
 			<li><strong>Reports.</strong> The Elan vendor report <code>0x5D</code>
-			carries a finger bitmask and five bytes per active finger (X/Y high
-			bits, X low, Y low, size, pressure). Finger 1 drives the pointer:
-			successive absolute positions become PS/2 deltas, and the clickpad
-			bit becomes the left button. The native max-X/Y commands
+			carries a finger bitmask and five packed bytes per active finger
+			(X/Y high bits, X low, Y low, size, pressure). The decoder feeds the
+			device-independent <span class="file">touchpad_gesture.c</span>
+			engine; a future PS/2 or USB touchpad backend only has to produce
+			the same two-contact frame. The native max-X/Y commands
 			(<code>0x0106</code>/<code>0x0107</code>) give the corner zone a
 			physical coordinate frame.</li>
 			<li><strong>Tap gestures.</strong> A short stationary contact is
@@ -380,15 +381,24 @@
 			bottom-right zone reports the right button, anywhere else reports
 			the left button, and the choice holds until the button is released
 			(so a corner drag stays a right drag).</li>
+			<li><strong>Two-finger scroll.</strong> With exactly two contacts,
+			the pointer freezes and the centroid movement accumulates. After
+			about 30 device units it becomes a scroll and emits movement / 2
+			in pixels; natural direction (two fingers up = later content) is
+			the default, and the two-finger right tap is suppressed once the
+			gesture has scrolled. The pointer re-anchors when one finger
+			remains. The <code>scroll on|off|natural|traditional</code> option
+			tunes it.</li>
 			<li><strong>Polling.</strong> The report GPIO has no driver yet, so
 			the input register is read every 25 ms. Back-to-back reads stall the
 			device, which is why the poll is throttled rather than run flat
 			out.</li>
 			<li><strong>Discovery and tuning.</strong> <code>touchpad</code>
 			prints the probe result, max coordinates, last report and synthesized
-			click counters, and takes <code>rightclick off|tap|corner|both</code>
-			or <code>tapclick on|off</code>; <code>mouseinfo</code> lists the
-			Elan vendor/product ID next to the PS/2 and USB backends.</li>
+			click counters, and takes <code>rightclick off|tap|corner|both</code>,
+			<code>tapclick on|off</code> or
+			<code>scroll on|off|natural|traditional</code>; <code>mouseinfo</code>
+			lists the Elan vendor/product ID next to the PS/2 and USB backends.</li>
 		</ul>
 	</section>
 
@@ -509,6 +519,8 @@
 			<li><code>usbhid.c</code>, <code>mouse.c</code>, <code>io.c</code> — input</li>
 			<li><code>i2c.c</code>, <code>i2c.h</code> — DesignWare/LPSS I2C master</li>
 			<li><code>touchpad.c</code>, <code>touchpad.h</code> — Elan HID-over-I2C touchpad</li>
+			<li><code>touchpad_gesture.c</code>, <code>touchpad_gesture.h</code> — device-independent contact gestures (tap, right-click zones, scroll)</li>
+			<li><code>touchpad_gesture_test.c</code> — host test (<code>make test-touchpad</code>)</li>
 			<li><code>serial.c</code>, <code>serial_ring_buf.c</code></li>
 			<li><code>thermal.c</code>, <code>it87.c</code>, <code>tpec.c</code>, <code>ec.c</code>, <code>cros_ec.c</code>, <code>power_src.c</code>, <code>mtrr.c</code></li>
 			<li><code>rtc.c</code> — CMOS wall clock read/write</li>

+ 7 - 2
docs/graphics.html

@@ -232,9 +232,14 @@
 		<p>
 			<code>SYS_WIN_CREATE</code> creates a generic canvas window. Input is
 			exposed through <code>SYS_WIN_POINTER</code> (content-relative
-			position, button mask, focus) and <code>SYS_WIN_EVENT</code>, which
-			queues press/release edges and a capture window. A click that starts
+			position, button mask, focus), <code>SYS_WIN_EVENT</code>, which
+			queues press/release edges and a capture window, and
+			<code>SYS_WIN_SCROLL</code>, which returns wheel/touchpad scroll
+			accumulated for the window under the pointer in pixels
+			(<code>+dy</code> is later content). A click that starts
 			in a window still receives its release after the pointer leaves.
+			The ngui helper <code>ngui_scroll_wheel()</code> applies the delta
+			to a pane when the pointer is over it.
 			The WM process itself is special: it maps the screen shadow at
 			<code>0x58000000</code> and each front canvas at
 			<code>0x59000000 + index × 4 MB</code>, which is how it composites

+ 1 - 1
docs/userland.html

@@ -223,7 +223,7 @@
 					<tr><td>Files</td><td>5–11, 48, 98</td><td>whole-file read/write, list, unlink, mkdir/rmdir, mounts, cwd, stat</td></tr>
 					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102–103, 107</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, Chrome EC sensors, AC/battery</td></tr>
 					<tr><td>Network</td><td>17–47, 106</td><td>NIC config/acquire, raw frames, DHCP/DNS/NTP, TCP client, ARP, cwd</td></tr>
-					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize</td></tr>
+					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87, 109</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize/scroll</td></tr>
 					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90, 108</td><td>TTY, spawn, getpid, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
 				</tbody>

+ 12 - 0
gallery.c

@@ -116,6 +116,8 @@ static const char *const list_items[LIST_ROWS] = {
 static struct ngui ui;
 static struct ngui_scroll page;
 static struct ngui_scroll list_scroll;
+static struct ngui_rect scroll_pane_rect;
+static int scroll_pane_valid;
 static struct ngui_input name_in;
 static struct ngui_input email_in;
 static struct ngui_input events_in;
@@ -902,6 +904,7 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 	int help_x, help_w;
 	int i;
 
+	scroll_pane_valid = 0;
 	if (pane_w > 520)
 		pane_w = 520;
 	if (pane_w < 260)
@@ -912,6 +915,8 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 		return;
 
 	pane = rect_make(x, card.y + 40, pane_w, pane_h);
+	scroll_pane_rect = pane;
+	scroll_pane_valid = 1;
 	ngui_text_ellipsis(g, rect_make(x, top, card.w - 2 * CARD_PAD, 16),
 			   x, top,
 			   "A nested pane: click a row, drag its scrollbar.",
@@ -920,6 +925,7 @@ static void draw_scroll(struct ngui *g, struct ngui_rect card)
 	list_scroll.content_h = LIST_ROWS * LIST_ROW_H;
 	ngui_fill_rect(g, pane, g->theme.bg);
 	ngui_scroll_begin(g, pane, &list_scroll);
+	ngui_scroll_wheel(g, pane, &list_scroll);
 
 	if (g->pressed && ngui_rect_contains(&pane, g->press_x, g->press_y) &&
 	    g->press_x < pane.x + pane.w - 9) {
@@ -1085,6 +1091,12 @@ static void draw_body(struct ngui *g, struct ngui_rect body)
 	page.content_h = sec_content_h;
 	ngui_fill_rect(g, body, g->theme.bg);
 	ngui_scroll_begin(g, body, &page);
+	/* Leave wheel scroll for the nested pane when the pointer is over it;
+	 * the rect comes from the previous frame, before this one redraws it. */
+	if (!(scroll_pane_valid &&
+	      ngui_rect_contains(&scroll_pane_rect, g->mouse_x, g->mouse_y)))
+		ngui_scroll_wheel(g, body, &page);
+	scroll_pane_valid = 0;
 
 	for (i = 0; i < SEC_COUNT; i++) {
 		int sy = body.y - page.offset + sec_y[i];

+ 40 - 4
mouse.c

@@ -23,6 +23,10 @@
 #define MOUSE_CUR_W CURSOR_SHAPE_WIDTH
 #define MOUSE_CUR_H CURSOR_SHAPE_HEIGHT
 
+/* One PS/2 wheel notch in scroll pixels; touchpads emit pixels directly. */
+#define MOUSE_WHEEL_PX 48
+#define MOUSE_SCROLL_MAX 100000
+
 static int mouse_present_flag;
 static int mouse_streaming_flag;
 static int mouse_auto_draw = 1;   /* 0 while a WM frame owns the shadow */
@@ -30,6 +34,7 @@ static unsigned int mouse_id;
 static int mouse_cursor_flag;
 static unsigned int mouse_pkt_size;
 static unsigned int mouse_buttons;  /* bit0=left bit1=right bit2=middle */
+static int mouse_scroll_x, mouse_scroll_y;
 static int mouse_hw_cursor;         /* 1 = Cirrus, 2 = Radeon, 3 = Intel */
 static int mouse_irq_mode;          /* PS/2 AUX IRQ12 owns packet input */
 static int mouse_aux_irq_ok;        /* controller config accepted AUX IRQ */
@@ -428,6 +433,15 @@ static void mouse_move(int dx, int dy)
 	}
 }
 
+static void mouse_scroll_add(int dy)
+{
+	mouse_scroll_y += dy;
+	if (mouse_scroll_y > MOUSE_SCROLL_MAX)
+		mouse_scroll_y = MOUSE_SCROLL_MAX;
+	else if (mouse_scroll_y < -MOUSE_SCROLL_MAX)
+		mouse_scroll_y = -MOUSE_SCROLL_MAX;
+}
+
 /* Decode one complete PS/2 packet from pkt[] (3 or 4 bytes). */
 static void mouse_handle_packet(void)
 {
@@ -443,6 +457,13 @@ static void mouse_handle_packet(void)
 	if ((b0 & 0xC0) != 0)
 		return;
 	mouse_move(dx, dy);
+	if (mouse_pkt_size >= 4) {
+		/* IntelliMouse wheel: +1 is toward the user (later content). */
+		int wheel = (int)(signed char)pkt[3];
+
+		if (wheel)
+			mouse_scroll_add(wheel * MOUSE_WHEEL_PX);
+	}
 }
 
 /* IRQ12: PS/2 AUX data.  With a hardware cursor the position update is just
@@ -479,8 +500,8 @@ void mouse_poll_update(void)
 {
 	unsigned int guard = 0;
 	unsigned int usb_buttons = 0;
-	int usb_dx = 0, usb_dy = 0;
-	int tp_buttons = 0, tp_dx = 0, tp_dy = 0;
+	int usb_dx = 0, usb_dy = 0, usb_scroll = 0;
+	int tp_buttons = 0, tp_dx = 0, tp_dy = 0, tp_scroll = 0;
 
 	/* The cursor is set up for whichever backend shows up first (PS/2
 	   is probed at boot, USB may attach later). */
@@ -490,15 +511,19 @@ void mouse_poll_update(void)
 
 	/* USB HID mouse: reports arrive through the armed interrupt
 	   endpoint; the backend also handles hotplug/detach. */
-	if (usbhid_poll(&usb_buttons, &usb_dx, &usb_dy)) {
+	if (usbhid_poll(&usb_buttons, &usb_dx, &usb_dy, &usb_scroll)) {
 		mouse_buttons = usb_buttons;
 		mouse_move(usb_dx, usb_dy);
+		if (usb_scroll)
+			mouse_scroll_add(usb_scroll);
 	}
 
 	/* Built-in touchpad: absolute positions converted to deltas. */
-	if (touchpad_poll(&tp_buttons, &tp_dx, &tp_dy)) {
+	if (touchpad_poll(&tp_buttons, &tp_dx, &tp_dy, &tp_scroll)) {
 		mouse_buttons = tp_buttons;
 		mouse_move(tp_dx, tp_dy);
+		if (tp_scroll)
+			mouse_scroll_add(tp_scroll);
 	}
 
 	if (mouse_irq_mode)
@@ -588,6 +613,17 @@ unsigned int mouse_buttons_state(void)
 	return mouse_buttons;
 }
 
+void mouse_scroll_take(int *dx, int *dy)
+{
+	unsigned int flags = mouse_irq_save();
+
+	*dx = mouse_scroll_x;
+	*dy = mouse_scroll_y;
+	mouse_scroll_x = 0;
+	mouse_scroll_y = 0;
+	mouse_irq_restore(flags);
+}
+
 void mouse_redraw_cursor(void)
 {
 	if (!mouse_cursor_flag || mouse_hw_cursor)

+ 3 - 0
mouse.h

@@ -24,6 +24,9 @@ unsigned int mouse_get_x(void);
 unsigned int mouse_get_y(void);
 /* Button state bitmask: bit0 = left, bit1 = right, bit2 = middle. */
 unsigned int mouse_buttons_state(void);
+/* Consume accumulated wheel/touchpad scroll in pixels.  Positive dy means
+ * later content (a wheel-down event under natural scrolling). */
+void mouse_scroll_take(int *dx, int *dy);
 /* Restore the saved background under the cursor (erase the cursor). Call
    before a scene redraw so mouse_redraw_cursor() re-saves a clean background. */
 void mouse_cursor_erase(void);

+ 21 - 0
ngui.c

@@ -184,6 +184,7 @@ int ngui_begin(struct ngui *ui)
 {
 	struct win_info wi;
 	struct win_pointer wp;
+	struct win_scroll ws;
 	struct win_event ev;
 	unsigned int now;
 	int want = ui->dirty;
@@ -222,6 +223,15 @@ int ngui_begin(struct ngui *ui)
 		ui->focused = 0;
 	}
 
+	if (u_win_scroll(&ws) == 1) {
+		ui->scroll_x = ws.dx;
+		ui->scroll_y = ws.dy;
+		if (ws.dx || ws.dy)
+			want = 1;
+	} else {
+		ui->scroll_x = ui->scroll_y = 0;
+	}
+
 	for (i = 0; i < 16; i++) {
 		int r = u_win_event(&ev);
 
@@ -1706,6 +1716,17 @@ void ngui_scroll_end(struct ngui *ui, struct ngui_rect r,
 	}
 }
 
+int ngui_scroll_wheel(struct ngui *ui, struct ngui_rect r,
+		      struct ngui_scroll *s)
+{
+	if (!ui->scroll_y ||
+	    !ngui_rect_contains(&r, ui->mouse_x, ui->mouse_y))
+		return 0;
+	ngui_scroll_to(s, s->offset + ui->scroll_y);
+	ui->scroll_y = 0;
+	return 1;
+}
+
 int ngui_scroll_keys(struct ngui *ui, struct ngui_scroll *s)
 {
 	int k = ngui_key_peek(ui);

+ 6 - 0
ngui.h

@@ -116,6 +116,8 @@ struct ngui {
 	unsigned int buttons;
 	int inside;
 	int focused;
+	/* Scroll accumulated since the previous frame, in pixels. */
+	int scroll_x, scroll_y;
 
 	/* Press/release edges collected by ngui_begin(). */
 	unsigned int pressed;
@@ -238,6 +240,10 @@ void ngui_scroll_begin(struct ngui *ui, struct ngui_rect r,
 		       struct ngui_scroll *s);
 void ngui_scroll_end(struct ngui *ui, struct ngui_rect r,
 		     struct ngui_scroll *s);
+/* Apply pending wheel/touchpad scroll to s when the pointer is over r and
+ * consume it.  Call after ngui_scroll_begin() set view_h/content_h. */
+int  ngui_scroll_wheel(struct ngui *ui, struct ngui_rect r,
+		       struct ngui_scroll *s);
 void ngui_scroll_to(struct ngui_scroll *s, int offset);
 void ngui_scroll_ensure_visible(struct ngui_scroll *s, int y, int h);
 int  ngui_scroll_keys(struct ngui *ui, struct ngui_scroll *s);

+ 14 - 0
sys_wm.c

@@ -228,6 +228,20 @@ int sys_win_event(struct win_event *out)
 	return r;
 }
 
+int sys_win_scroll(struct win_scroll *out)
+{
+	struct win_scroll s;
+	int r;
+
+	if (!user_ok(out, sizeof(s), 1))
+		return -1;
+	zero_struct(&s, sizeof(s));
+	r = wm_server_win_scroll(&s);
+	if (r >= 0)
+		copy_to_user(out, &s, sizeof(s));
+	return r;
+}
+
 int sys_wm_resize(unsigned int index, const struct wm_size *in)
 {
 	struct wm_size s;

+ 1 - 0
sys_wm.h

@@ -25,6 +25,7 @@ int sys_win_info(struct win_info *out);
 int sys_win_ack_resize(void);
 int sys_win_pointer(struct win_pointer *out);
 int sys_win_event(struct win_event *out);
+int sys_win_scroll(struct win_scroll *out);
 int sys_wm_resize(unsigned int index, const struct wm_size *in);
 int sys_win_key_wait(unsigned int timeout_ms);
 

+ 2 - 0
syscall.c

@@ -292,6 +292,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_win_pointer((struct win_pointer *)a1);
 	case SYS_WIN_EVENT:
 		return sys_win_event((struct win_event *)a1);
+	case SYS_WIN_SCROLL:
+		return sys_win_scroll((struct win_scroll *)a1);
 	case SYS_MEM_ALLOC:
 		return sys_mem_alloc((unsigned int)a1);
 	case SYS_MEM_GROW:

+ 1 - 0
syscall.h

@@ -114,6 +114,7 @@
 #define SYS_WIN_ACK_RESIZE 85  /* () -> 0/-1; swap in the pending canvas */
 #define SYS_WIN_POINTER    86  /* (struct win_pointer *out) -> 0/-1 */
 #define SYS_WIN_EVENT      87  /* (struct win_event *out) -> 1 event, 0 none */
+#define SYS_WIN_SCROLL     109 /* (struct win_scroll *out) -> 1 delta, 0 none, -1 */
 
 /* Per-process anonymous heap (see sys_mem.c).  One growable arena at
  * USER_HEAP_BASE (0x60000000), at most USER_HEAP_MAX (32 MB), freed when the

+ 1 - 1
terminal.c

@@ -85,7 +85,7 @@ static const struct kcmd cmds[] = {
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_main, 0, 0, 0 },
 	{ "lsusb",      "lsusb",                         CK_SPAWN, 0, program_lsusb_main, 0, 0, 0 },
-	{ "touchpad",   "touchpad [rightclick ...]",     CK_SPAWN_ARG, 0, 0, program_touchpad_main, 0, 0 },
+	{ "touchpad",   "touchpad [rightclick|tapclick|scroll]", CK_SPAWN_ARG, 0, 0, program_touchpad_main, 0, 0 },
 	{ "netdev",     "netdev [name]",                 CK_SPAWN_ARG, 0, 0, program_netdev_main, 0, 0 },
 	{ "format",     "format <device> [size]",        CK_CUSTOM, 0, 0, 0, 0, cmd_format },
 	{ "install",    "install <target> [source]",     CK_CUSTOM, 0, 0, 0, 0, cmd_install },

+ 141 - 246
touchpad.c

@@ -14,14 +14,13 @@
  * acknowledgement, read the HID descriptor and the max-X/Y commands, select
  * absolute mode (0x0300) and wake the device (0x0800).
  *
- * The clickpad has no right button, so a short stationary tap is turned into
- * a synthetic click: two fingers (or one finger in the bottom-right corner)
- * is a right click, one finger elsewhere is a left click.  The press is held
- * briefly so ring-3 commands polling SYS_WIN_POINTER sample it.  Resetting
- * last leaves the device silent until the next power cycle.
+ * Report decoding is Elan-specific; the contact behaviour (pointer deltas,
+ * taps, the physical-button latch and two-finger scrolling) lives in
+ * touchpad_gesture.c so another touchpad driver can reuse it.
  */
 
 #include "touchpad.h"
+#include "touchpad_gesture.h"
 #include "i2c.h"
 #include "io.h"
 #include "paging.h"
@@ -50,25 +49,6 @@
 #define TP_MAX_INPUT		64
 #define TP_POLL_MS		25
 
-/* Tap gestures.  The report is polled at 40 Hz, so a tap must last at least
- * two samples to be seen; the movement cap keeps a swipe from clicking. */
-#define TP_TAP_MIN_MS		40
-#define TP_TAP_MAX_MS		300
-#define TP_TAP_MOVE		60
-#define TP_CLICK_HOLD_MS	120
-
-/* Software right button zones: right 25% x bottom 25% of the pad.  The raw
- * Elan Y axis grows upwards, so the bottom is the low end. */
-#define TP_CORNER_X_PCT		75
-#define TP_CORNER_Y_PCT		25
-
-enum {
-	TP_RC_OFF = 0,
-	TP_RC_TAP = 1,
-	TP_RC_CORNER = 2,
-	TP_RC_BOTH = TP_RC_TAP | TP_RC_CORNER
-};
-
 static unsigned int tp_base;
 static unsigned int tp_addr = TP_ADDR;
 static int tp_present;
@@ -82,28 +62,10 @@ static int tp_max_y = TP_ABS_MAX;
 static const char *tp_err;
 static unsigned int tp_err_val;
 
-static int tp_last_x, tp_last_y, tp_acc_x, tp_acc_y;
-static int tp_down, tp_last_buttons;
+static struct tpg_state tp_gesture;
+static int tp_last_buttons;
 static unsigned int tp_next_poll;
 
-/* Gesture configuration and synthesized-click state. */
-static unsigned int tp_rc_mode = TP_RC_BOTH;
-static int tp_tapclick = 1;
-static int tp_phys_raw;             /* clickpad bit from the last report */
-static int tp_phys_btn;             /* latched button: 0, 0x01 or 0x02 */
-static unsigned int tp_click_btn;
-static unsigned int tp_click_release_ms;
-static unsigned int tp_synth_left, tp_synth_right;
-
-/* One contact sequence: from the first finger down to the last finger up. */
-static int tp_gesture_active;
-static unsigned int tp_gesture_t0;
-static int tp_gesture_x0, tp_gesture_y0;
-static int tp_gesture_started;
-static int tp_gesture_moved;
-static int tp_gesture_two;
-static int tp_gesture_phys;
-
 /* Last report, for the `touchpad` status command. */
 static int tp_stat_fingers, tp_stat_f1, tp_stat_x, tp_stat_y;
 
@@ -139,16 +101,25 @@ static void print_summary(void)
 
 static void print_status(void)
 {
+	unsigned int opts = tpg_options(&tp_gesture);
+
 	print_summary();
 	io_putstr("touchpad: rightclick ");
 	io_putstr(rc_name());
 	io_putstr(" tapclick ");
-	io_putstr(tp_tapclick ? "on" : "off");
+	io_putstr((opts & TPG_TAPCLICK) ? "on" : "off");
+	io_putstr(" scroll ");
+	io_putstr((opts & TPG_SCROLL) ? "on" : "off");
+	if (opts & TPG_SCROLL) {
+		io_putchar(' ');
+		io_putstr((opts & TPG_SCROLL_INVERT) ?
+			  "traditional" : "natural");
+	}
 	io_putstr(" corner x>=");
-	put_dec((unsigned int)(tp_max_x * TP_CORNER_X_PCT / 100));
+	put_dec((unsigned int)(tp_max_x * TPG_CORNER_X_PCT / 100));
 	io_putstr(" y<=");
-	put_dec((unsigned int)(tp_max_y * TP_CORNER_Y_PCT / 100));
-	io_putstr("\n");
+	put_dec((unsigned int)(tp_max_y * TPG_CORNER_Y_PCT / 100));
+	io_putchar('\n');
 	io_putstr("touchpad: last f=");
 	put_dec((unsigned int)tp_stat_fingers);
 	if (tp_stat_f1) {
@@ -158,9 +129,9 @@ static void print_status(void)
 		put_dec((unsigned int)tp_stat_y);
 	}
 	io_putstr(" taps left=");
-	put_dec(tp_synth_left);
+	put_dec(tp_gesture.taps_left);
 	io_putstr(" right=");
-	put_dec(tp_synth_right);
+	put_dec(tp_gesture.taps_right);
 	io_putchar('\n');
 }
 
@@ -222,32 +193,18 @@ static unsigned int word_len(const char *s)
 	return n;
 }
 
-static int finger_count(unsigned int ti)
-{
-	unsigned int mask = (ti >> 3) & 0x1f;
-	int n = 0;
-
-	while (mask) {
-		n += (int)(mask & 1);
-		mask >>= 1;
-	}
-	return n;
-}
-
-static int in_corner(int x, int y)
-{
-	return x >= tp_max_x * TP_CORNER_X_PCT / 100 &&
-	       y <= tp_max_y * TP_CORNER_Y_PCT / 100;
-}
-
 static const char *rc_name(void)
 {
-	switch (tp_rc_mode) {
-	case TP_RC_OFF:    return "off";
-	case TP_RC_TAP:    return "tap";
-	case TP_RC_CORNER: return "corner";
-	default:           return "both";
-	}
+	unsigned int m = tpg_options(&tp_gesture) &
+			 (TPG_RIGHT_TAP | TPG_RIGHT_CORNER);
+
+	if (m == TPG_RIGHT_TAP)
+		return "tap";
+	if (m == TPG_RIGHT_CORNER)
+		return "corner";
+	if (m == (TPG_RIGHT_TAP | TPG_RIGHT_CORNER))
+		return "both";
+	return "off";
 }
 
 static int hid_read_reg(unsigned int addr, unsigned int reg,
@@ -363,6 +320,7 @@ static int probe_controller(unsigned int base)
 	/* Query the limits with the device awake (Linux reads them after
 	 * initialize()/wake and before enabling reports). */
 	query_limits();
+	tpg_init(&tp_gesture, tp_max_x, tp_max_y, 2);
 
 	tp_present = 1;
 	tp_err = 0;
@@ -417,93 +375,16 @@ unsigned short touchpad_product(void)
 	return tp_product;
 }
 
-/* Track one contact sequence and turn a short, stationary tap into a
- * synthetic button press.  The Elan report packs the touch info byte
- * (f5..f1 at bits 7..3, clickpad at bit 0) and five bytes per finger, so
- * the finger mask alone tells us whether this was a one- or two-finger
- * tap.  Only finger 1 drives the pointer, and its data is valid only while
- * its presence bit is set. */
-static void touchpad_gesture(unsigned int ti, int x, int y, unsigned int now)
-{
-	int fingers = finger_count(ti);
-	int f1 = (ti & 0x08) != 0;
-	unsigned int duration;
-
-	tp_stat_fingers = fingers;
-	tp_stat_f1 = f1;
-	if (f1) {
-		tp_stat_x = x;
-		tp_stat_y = y;
-	}
-
-	if (fingers) {
-		if (!tp_gesture_active) {
-			tp_gesture_active = 1;
-			tp_gesture_t0 = now;
-			tp_gesture_started = 0;
-			tp_gesture_moved = 0;
-			tp_gesture_two = 0;
-			tp_gesture_phys = 0;
-		}
-		if (f1) {
-			if (!tp_gesture_started) {
-				tp_gesture_started = 1;
-				tp_gesture_x0 = x;
-				tp_gesture_y0 = y;
-			} else {
-				int ddx = x - tp_gesture_x0;
-				int ddy = y - tp_gesture_y0;
-
-				if (ddx < 0)
-					ddx = -ddx;
-				if (ddy < 0)
-					ddy = -ddy;
-				if (ddx > TP_TAP_MOVE || ddy > TP_TAP_MOVE)
-					tp_gesture_moved = 1;
-			}
-		}
-		if (fingers >= 2)
-			tp_gesture_two = 1;
-		if (ti & 0x01)
-			tp_gesture_phys = 1;
-		return;
-	}
-
-	if (!tp_gesture_active)
-		return;
-
-	tp_gesture_active = 0;
-	duration = now - tp_gesture_t0;
-	if (duration < TP_TAP_MIN_MS || duration > TP_TAP_MAX_MS ||
-	    tp_gesture_moved || tp_gesture_phys)
-		return;
-
-	if (tp_gesture_two) {
-		if (!(tp_rc_mode & TP_RC_TAP))
-			return;
-		tp_click_btn = 0x02;
-		tp_synth_right++;
-	} else if (tp_gesture_started &&
-		   (tp_rc_mode & TP_RC_CORNER) &&
-		   in_corner(tp_gesture_x0, tp_gesture_y0)) {
-		tp_click_btn = 0x02;
-		tp_synth_right++;
-	} else if (tp_tapclick) {
-		tp_click_btn = 0x01;
-		tp_synth_left++;
-	} else {
-		return;
-	}
-	/* Hold the synthetic press long enough for a ring-3 app polling
-	 * SYS_WIN_POINTER (typically every 10-16 ms) to sample it. */
-	tp_click_release_ms = now + TP_CLICK_HOLD_MS;
-}
-
-int touchpad_poll(int *buttons, int *dx, int *dy)
+int touchpad_poll(int *buttons, int *dx, int *dy, int *scroll)
 {
 	unsigned char buf[TP_MAX_INPUT];
 	unsigned int now, b;
+	struct tpg_result res;
 
+	*buttons = 0;
+	*dx = 0;
+	*dy = 0;
+	*scroll = 0;
 	if (!tp_present)
 		return 0;
 
@@ -511,10 +392,10 @@ int touchpad_poll(int *buttons, int *dx, int *dy)
 
 	/* The synthetic tap press is released by time, whether or not a new
 	 * report arrives (the finger is already up). */
-	if (tp_click_btn && (int)(now - tp_click_release_ms) >= 0) {
-		tp_click_btn = 0;
-		*buttons = (unsigned int)tp_phys_btn;
-		tp_last_buttons = *buttons;
+	tpg_tick(&tp_gesture, now, &res);
+	if (res.buttons != (unsigned int)tp_last_buttons) {
+		tp_last_buttons = (int)res.buttons;
+		*buttons = res.buttons;
 		return 1;
 	}
 
@@ -529,87 +410,58 @@ int touchpad_poll(int *buttons, int *dx, int *dy)
 	 * and then the report, so locate the 0x5D report ID instead of
 	 * trusting a fixed offset.  Layout after it (Linux hid-elan.c):
 	 * touch info (f5..f1 at bits 7..3, clickpad at bit 0), then 5
-	 * bytes per active finger: x11:8/y11:9, x7:0, y7:0, size,
-	 * pressure. */
-	for (b = 0; b < 6 && b + 4 < tp_max_in; b++)
+	 * bytes per *active* finger (packed): x11:8/y11:9, x7:0, y7:0,
+	 * size, pressure. */
+	for (b = 0; b < 6 && b + 6 < tp_max_in; b++)
 		if (buf[b] == TP_REPORT_ID)
 			break;
-	if (b >= 6 || b + 4 >= tp_max_in)
+	if (b >= 6 || b + 6 >= tp_max_in)
 		return 0;
 
 	{
+		struct tpg_frame f;
 		unsigned int ti = buf[b + 1];
-		unsigned int xh = buf[b + 2];
-		int x = ((int)(xh & 0xf0) << 4) | buf[b + 3];
-		int y = ((int)(xh & 0x0f) << 8) | buf[b + 4];
-
-		{
-			int raw = (ti & 0x01) != 0;
-			int f1 = (ti & 0x08) != 0;
-
-			if (raw) {
-				/* Latch at the leading edge: a physical
-				 * clickpad press in the bottom-right zone is
-				 * the right button, anywhere else the left
-				 * button, for the whole press (so a corner
-				 * drag stays a right drag). */
-				if (!tp_phys_raw) {
-					tp_phys_btn = 0x01;
-					if ((tp_rc_mode & TP_RC_CORNER) && f1 &&
-					    in_corner(x, y))
-						tp_phys_btn = 0x02;
-				}
-			} else {
-				tp_phys_btn = 0;
-			}
-			tp_phys_raw = raw;
-		}
-
-		touchpad_gesture(ti, x, y, now);
-		*buttons = (unsigned int)tp_phys_btn | tp_click_btn;
-
-		if (!(ti & 0x08)) {		/* finger 1 lifted */
-			tp_down = 0;
-			tp_acc_x = 0;
-			tp_acc_y = 0;
-			if (tp_last_buttons != *buttons) {
-				tp_last_buttons = *buttons;
-				return 1;
+		unsigned int off = b + 2;
+		unsigned int i, n = 0;
+
+		f.count = 0;
+		f.mask = 0;
+		f.button = ti & 0x01;
+		f.now_ms = now;
+		for (i = 0; i < 5; i++) {
+			if (!(ti & (0x08u << i)))
+				continue;
+			f.count++;
+			if (n < TPG_CONTACTS && off + 4 < tp_max_in) {
+				unsigned int xh = buf[off];
+
+				f.contact[n].x = ((int)(xh & 0xf0) << 4) |
+						 buf[off + 1];
+				f.contact[n].y = ((int)(xh & 0x0f) << 8) |
+						 buf[off + 2];
+				f.mask |= 1u << n;
+				n++;
 			}
-			return 0;
-		}
-		if (!tp_down) {
-			tp_down = 1;
-			tp_last_x = x;
-			tp_last_y = y;
-			*dx = 0;
-			*dy = 0;
-		} else {
-			tp_acc_x += x - tp_last_x;
-			/* The Elan's Y axis increases upwards, already the
-			 * PS/2 convention: dragging up gives a positive dy. */
-			tp_acc_y += y - tp_last_y;
-			tp_last_x = x;
-			tp_last_y = y;
-			*dx = tp_acc_x / 2;
-			tp_acc_x -= *dx * 2;
-			*dy = tp_acc_y / 2;
-			tp_acc_y -= *dy * 2;
+			off += 5;
 		}
-		if (*dx > 64)
-			*dx = 64;
-		if (*dx < -64)
-			*dx = -64;
-		if (*dy > 64)
-			*dy = 64;
-		if (*dy < -64)
-			*dy = -64;
-		if (tp_last_buttons != *buttons) {
-			tp_last_buttons = *buttons;
-			return 1;
+		tp_stat_fingers = (int)f.count;
+		tp_stat_f1 = (f.mask & 1u) != 0;
+		if (f.mask & 1u) {
+			tp_stat_x = f.contact[0].x;
+			tp_stat_y = f.contact[0].y;
 		}
-		return *dx || *dy;
+		tpg_frame(&tp_gesture, &f, &res);
+	}
+
+	*buttons = res.buttons;
+	*dx = res.dx;
+	*dy = res.dy;
+	*scroll = res.scroll;
+	if (res.buttons != (unsigned int)tp_last_buttons) {
+		tp_last_buttons = (int)res.buttons;
+		return 1;
 	}
+	return res.dx || res.dy || res.scroll;
 }
 
 void program_touchpad_main(const char *arg)
@@ -632,6 +484,8 @@ void program_touchpad_main(const char *arg)
 	}
 
 	while (*arg) {
+		unsigned int opts = tpg_options(&tp_gesture);
+
 		if (word_is(arg, "rightclick")) {
 			const char *v = skip_spaces(arg + 10);
 
@@ -641,18 +495,20 @@ void program_touchpad_main(const char *arg)
 				io_putchar('\n');
 				return;
 			}
-			if (word_is(v, "off"))
-				tp_rc_mode = TP_RC_OFF;
-			else if (word_is(v, "tap"))
-				tp_rc_mode = TP_RC_TAP;
-			else if (word_is(v, "corner"))
-				tp_rc_mode = TP_RC_CORNER;
-			else if (word_is(v, "both"))
-				tp_rc_mode = TP_RC_BOTH;
-			else {
+			opts &= ~(TPG_RIGHT_TAP | TPG_RIGHT_CORNER);
+			if (word_is(v, "off")) {
+				/* keep both bits clear */
+			} else if (word_is(v, "tap")) {
+				opts |= TPG_RIGHT_TAP;
+			} else if (word_is(v, "corner")) {
+				opts |= TPG_RIGHT_CORNER;
+			} else if (word_is(v, "both")) {
+				opts |= TPG_RIGHT_TAP | TPG_RIGHT_CORNER;
+			} else {
 				io_putstr("touchpad: rightclick off|tap|corner|both\n");
 				return;
 			}
+			tpg_set_options(&tp_gesture, opts);
 			io_putstr("touchpad: rightclick ");
 			io_putstr(rc_name());
 			io_putchar('\n');
@@ -662,24 +518,63 @@ void program_touchpad_main(const char *arg)
 
 			if (!*v) {
 				io_putstr("touchpad: tapclick ");
-				io_putstr(tp_tapclick ? "on" : "off");
+				io_putstr((opts & TPG_TAPCLICK) ? "on" : "off");
 				io_putchar('\n');
 				return;
 			}
 			if (word_is(v, "on"))
-				tp_tapclick = 1;
+				opts |= TPG_TAPCLICK;
 			else if (word_is(v, "off"))
-				tp_tapclick = 0;
+				opts &= ~TPG_TAPCLICK;
 			else {
 				io_putstr("touchpad: tapclick on|off\n");
 				return;
 			}
+			tpg_set_options(&tp_gesture, opts);
 			io_putstr("touchpad: tapclick ");
-			io_putstr(tp_tapclick ? "on" : "off");
+			io_putstr((opts & TPG_TAPCLICK) ? "on" : "off");
+			io_putchar('\n');
+			arg = skip_spaces(v + word_len(v));
+		} else if (word_is(arg, "scroll")) {
+			const char *v = skip_spaces(arg + 6);
+
+			if (!*v) {
+				io_putstr("touchpad: scroll ");
+				io_putstr((opts & TPG_SCROLL) ? "on" : "off");
+				if (opts & TPG_SCROLL) {
+					io_putchar(' ');
+					io_putstr((opts & TPG_SCROLL_INVERT) ?
+						  "traditional" : "natural");
+				}
+				io_putchar('\n');
+				return;
+			}
+			if (word_is(v, "on")) {
+				opts |= TPG_SCROLL;
+			} else if (word_is(v, "off")) {
+				opts &= ~TPG_SCROLL;
+			} else if (word_is(v, "natural")) {
+				opts |= TPG_SCROLL;
+				opts &= ~TPG_SCROLL_INVERT;
+			} else if (word_is(v, "traditional")) {
+				opts |= TPG_SCROLL;
+				opts |= TPG_SCROLL_INVERT;
+			} else {
+				io_putstr("touchpad: scroll on|off|natural|traditional\n");
+				return;
+			}
+			tpg_set_options(&tp_gesture, opts);
+			io_putstr("touchpad: scroll ");
+			io_putstr((opts & TPG_SCROLL) ? "on" : "off");
+			if (opts & TPG_SCROLL) {
+				io_putchar(' ');
+				io_putstr((opts & TPG_SCROLL_INVERT) ?
+					  "traditional" : "natural");
+			}
 			io_putchar('\n');
 			arg = skip_spaces(v + word_len(v));
 		} else {
-			io_putstr("touchpad: usage: touchpad [rightclick off|tap|corner|both | tapclick on|off]\n");
+			io_putstr("touchpad: usage: touchpad [rightclick off|tap|corner|both | tapclick on|off | scroll on|off|natural|traditional]\n");
 			return;
 		}
 	}

+ 4 - 3
touchpad.h

@@ -25,8 +25,9 @@ unsigned short touchpad_product(void);
  * `rightclick off|tap|corner|both` / `tapclick on|off`. */
 void program_touchpad_main(const char *arg);
 
-/* Poll one input report.  Returns 1 when the deltas or buttons changed;
- * values use the mouse layer's PS/2 convention (+dy is up). */
-int touchpad_poll(int *buttons, int *dx, int *dy);
+/* Poll one input report.  Returns 1 when the deltas, scroll or buttons
+ * changed; pointer values use the mouse layer's PS/2 convention (+dy is up),
+ * scroll is in pixels (+ = later content). */
+int touchpad_poll(int *buttons, int *dx, int *dy, int *scroll);
 
 #endif

+ 272 - 0
touchpad_gesture.c

@@ -0,0 +1,272 @@
+/* Device-independent touchpad contact gestures.  See touchpad_gesture.h. */
+#include "touchpad_gesture.h"
+
+#define TPG_TAP_MIN_MS		40
+#define TPG_TAP_MAX_MS		300
+#define TPG_CLICK_HOLD_MS	120
+#define TPG_POINTER_MAX		64
+
+static int abs_int(int v)
+{
+	return v < 0 ? -v : v;
+}
+
+static void set_limits(struct tpg_state *s)
+{
+	s->tap_move = s->max_x / 50;
+	if (s->tap_move < 16)
+		s->tap_move = 16;
+	s->scroll_start = s->max_x / 100;
+	if (s->scroll_start < 8)
+		s->scroll_start = 8;
+}
+
+static int in_corner(const struct tpg_state *s, int x, int y)
+{
+	return x >= s->max_x * TPG_CORNER_X_PCT / 100 &&
+	       y <= s->max_y * TPG_CORNER_Y_PCT / 100;
+}
+
+void tpg_init(struct tpg_state *s, int max_x, int max_y, int units_per_px)
+{
+	s->max_x = max_x > 0 ? max_x : 4095;
+	s->max_y = max_y > 0 ? max_y : 4095;
+	s->units_per_px = units_per_px > 0 ? units_per_px : 1;
+	s->opts = TPG_DEFAULT_OPTIONS;
+	set_limits(s);
+
+	s->btn_raw = 0;
+	s->btn_latched = 0;
+	s->synth_btn = 0;
+	s->synth_release_ms = 0;
+	s->taps_left = 0;
+	s->taps_right = 0;
+
+	s->active = 0;
+	s->start_ms = 0;
+	s->start_x = s->start_y = 0;
+	s->started = 0;
+	s->moved = 0;
+	s->two = 0;
+	s->physical = 0;
+	s->scrolled = 0;
+	s->last_count = 0;
+
+	s->last_x = s->last_y = 0;
+	s->have_last = 0;
+	s->acc_x = s->acc_y = 0;
+
+	s->scroll_have = 0;
+	s->scroll_last_y = 0;
+	s->scroll_total = 0;
+	s->scroll_acc = 0;
+}
+
+void tpg_set_limits(struct tpg_state *s, int max_x, int max_y)
+{
+	s->max_x = max_x > 0 ? max_x : 4095;
+	s->max_y = max_y > 0 ? max_y : 4095;
+	set_limits(s);
+}
+
+void tpg_set_options(struct tpg_state *s, unsigned int opts)
+{
+	s->opts = opts;
+}
+
+unsigned int tpg_options(const struct tpg_state *s)
+{
+	return s->opts;
+}
+
+void tpg_tick(struct tpg_state *s, unsigned int now_ms,
+	      struct tpg_result *r)
+{
+	r->dx = r->dy = r->scroll = 0;
+	if (s->synth_btn && (int)(now_ms - s->synth_release_ms) >= 0)
+		s->synth_btn = 0;
+	r->buttons = (unsigned int)s->btn_latched | s->synth_btn;
+}
+
+void tpg_frame(struct tpg_state *s, const struct tpg_frame *f,
+	       struct tpg_result *r)
+{
+	unsigned int count = f->count;
+	unsigned int mask = f->mask;
+	unsigned int now = f->now_ms;
+	int has0 = (mask & 1u) && count >= 1;
+	int has1 = (mask & 2u) && count >= 2;
+	int c0x = has0 ? f->contact[0].x : 0;
+	int c0y = has0 ? f->contact[0].y : 0;
+
+	r->dx = r->dy = r->scroll = 0;
+
+	if (s->synth_btn && (int)(now - s->synth_release_ms) >= 0)
+		s->synth_btn = 0;
+
+	/* Latch the physical clickpad button at its leading edge.  A press
+	 * whose finger is in the right-click zone reports the right button
+	 * for the whole press; everything else is the left button. */
+	if (f->button) {
+		if (!s->btn_raw) {
+			s->btn_latched = 0x01;
+			if ((s->opts & TPG_RIGHT_CORNER) && has0 &&
+			    in_corner(s, c0x, c0y))
+				s->btn_latched = 0x02;
+		}
+		s->physical = 1;
+	} else {
+		s->btn_latched = 0;
+	}
+	s->btn_raw = f->button != 0;
+
+	if (count) {
+		if (!s->active) {
+			s->active = 1;
+			s->start_ms = now;
+			s->started = 0;
+			s->moved = 0;
+			s->two = 0;
+			s->physical = f->button != 0;
+			s->scrolled = 0;
+			s->scroll_have = 0;
+			s->scroll_total = 0;
+			s->scroll_acc = 0;
+			s->have_last = 0;
+			s->acc_x = s->acc_y = 0;
+		}
+		if (count >= 2)
+			s->two = 1;
+
+		/* The active finger packed into contact[0] can change when a
+		 * finger lifts.  Re-anchor the tap movement check so a
+		 * two-finger tap followed by an early first-finger lift is
+		 * not mistaken for a drag. */
+		if (s->last_count && count != s->last_count)
+			s->started = 0;
+
+		if (has0) {
+			if (!s->started) {
+				s->started = 1;
+				s->start_x = c0x;
+				s->start_y = c0y;
+			} else if (abs_int(c0x - s->start_x) > s->tap_move ||
+				   abs_int(c0y - s->start_y) > s->tap_move) {
+				s->moved = 1;
+			}
+		}
+	}
+
+	/* Pointer motion only with exactly one contact; two fingers are
+	 * either a tap or a scroll, so the pointer must not drift. */
+	if (count == 1 && has0) {
+		if (!s->have_last) {
+			s->last_x = c0x;
+			s->last_y = c0y;
+			s->have_last = 1;
+		} else {
+			int dx, dy;
+
+			s->acc_x += c0x - s->last_x;
+			s->acc_y += c0y - s->last_y;
+			s->last_x = c0x;
+			s->last_y = c0y;
+			dx = s->acc_x / s->units_per_px;
+			s->acc_x -= dx * s->units_per_px;
+			dy = s->acc_y / s->units_per_px;
+			s->acc_y -= dy * s->units_per_px;
+			if (dx > TPG_POINTER_MAX)
+				dx = TPG_POINTER_MAX;
+			if (dx < -TPG_POINTER_MAX)
+				dx = -TPG_POINTER_MAX;
+			if (dy > TPG_POINTER_MAX)
+				dy = TPG_POINTER_MAX;
+			if (dy < -TPG_POINTER_MAX)
+				dy = -TPG_POINTER_MAX;
+			r->dx = dx;
+			r->dy = dy;
+		}
+	} else {
+		s->have_last = 0;
+		s->acc_x = s->acc_y = 0;
+	}
+
+	/* Two-finger scroll.  The centroid movement is accumulated until it
+	 * clears the start threshold, which keeps a stationary two-finger tap
+	 * from scrolling. */
+	if (count == 2 && has0 && has1) {
+		int cy = (f->contact[0].y + f->contact[1].y) / 2;
+
+		if (!s->scroll_have) {
+			s->scroll_have = 1;
+			s->scroll_last_y = cy;
+			s->scroll_total = 0;
+		} else {
+			int d = cy - s->scroll_last_y;
+			int out;
+
+			s->scroll_last_y = cy;
+			if (!s->scrolled) {
+				s->scroll_total += d;
+				if (abs_int(s->scroll_total) >= s->scroll_start) {
+					s->scrolled = 1;
+					s->scroll_acc += s->scroll_total;
+				}
+			} else {
+				s->scroll_acc += d;
+			}
+			if (s->scrolled && (s->opts & TPG_SCROLL)) {
+				out = s->scroll_acc / s->units_per_px;
+				s->scroll_acc -= out * s->units_per_px;
+				if (s->opts & TPG_SCROLL_INVERT)
+					out = -out;
+				r->scroll = out;
+			}
+		}
+	} else {
+		s->scroll_have = 0;
+		s->scroll_total = 0;
+		s->scroll_acc = 0;
+	}
+
+	/* Last finger up: finish the contact sequence and synthesize a tap. */
+	if (!count && s->active) {
+		unsigned int duration = now - s->start_ms;
+		unsigned int click = 0;
+
+		s->active = 0;
+		if (!s->moved && !s->physical && !s->scrolled &&
+		    duration >= TPG_TAP_MIN_MS && duration <= TPG_TAP_MAX_MS) {
+			if (s->two) {
+				if (s->opts & TPG_RIGHT_TAP)
+					click = 0x02;
+			} else if (s->started &&
+				   (s->opts & TPG_RIGHT_CORNER) &&
+				   in_corner(s, s->start_x, s->start_y)) {
+				click = 0x02;
+			} else if (s->opts & TPG_TAPCLICK) {
+				click = 0x01;
+			}
+		}
+		if (click) {
+			s->synth_btn = click;
+			s->synth_release_ms = now + TPG_CLICK_HOLD_MS;
+			if (click == 0x02)
+				s->taps_right++;
+			else
+				s->taps_left++;
+		}
+		s->started = 0;
+		s->moved = 0;
+		s->two = 0;
+		s->physical = 0;
+		s->scrolled = 0;
+		s->scroll_have = 0;
+		s->scroll_total = 0;
+		s->have_last = 0;
+		s->acc_x = s->acc_y = 0;
+	}
+
+	s->last_count = count;
+	r->buttons = (unsigned int)s->btn_latched | s->synth_btn;
+}

+ 104 - 0
touchpad_gesture.h

@@ -0,0 +1,104 @@
+/* Device-independent touchpad contact gestures.
+ *
+ * A hardware driver decodes its reports into up to two contact positions plus
+ * the total contact count and the physical clickpad bit, and calls
+ * tpg_frame() once per report.  The engine owns pointer delta scaling, tap
+ * detection, the synthesized button press, the physical-button latch and
+ * two-finger scrolling, so a PS/2, I2C or USB touchpad backend only has to
+ * decode its own protocol.
+ *
+ * Scroll output is in pixels: positive means "toward later content" (the page
+ * moves up), matching a wheel-down event under natural scrolling.  The Elan
+ * and pointer delta scale defaults to 2 device units per pixel; a backend
+ * with a different resolution passes its own units_per_px to tpg_init().
+ */
+#ifndef TOUCHPAD_GESTURE_H
+#define TOUCHPAD_GESTURE_H
+
+#define TPG_CONTACTS		2
+
+/* Option bits. */
+#define TPG_TAPCLICK		0x01	/* one-finger tap = left click */
+#define TPG_RIGHT_TAP		0x02	/* two-finger tap = right click */
+#define TPG_RIGHT_CORNER	0x04	/* corner tap/press = right click */
+#define TPG_SCROLL		0x08	/* two-finger scroll */
+#define TPG_SCROLL_INVERT	0x10	/* traditional instead of natural */
+
+#define TPG_DEFAULT_OPTIONS	(TPG_TAPCLICK | TPG_RIGHT_TAP | \
+				 TPG_RIGHT_CORNER | TPG_SCROLL)
+
+/* Software right-button zone: right 25% x bottom 25% of the pad. */
+#define TPG_CORNER_X_PCT	75
+#define TPG_CORNER_Y_PCT	25
+
+struct tpg_contact {
+	int x, y;		/* absolute device coordinates */
+};
+
+struct tpg_frame {
+	unsigned int count;	/* total active contacts, 0..5 */
+	unsigned int mask;	/* bit 0/1: contact[] entry is present */
+	struct tpg_contact contact[TPG_CONTACTS];
+	int button;		/* physical clickpad/left button */
+	unsigned int now_ms;
+};
+
+struct tpg_result {
+	int dx, dy;		/* pointer motion, PS/2 convention (+dy up) */
+	int scroll;		/* pixels, positive = later content */
+	unsigned int buttons;	/* bit0 left, bit1 right, bit2 middle */
+};
+
+struct tpg_state {
+	int max_x, max_y;
+	int units_per_px;
+	unsigned int opts;
+	int tap_move;		/* max movement for a tap, device units */
+	int scroll_start;	/* movement before scrolling starts */
+
+	int btn_raw;
+	int btn_latched;	/* physical button: 0, 0x01 or 0x02 */
+	unsigned int synth_btn;
+	unsigned int synth_release_ms;
+	unsigned int taps_left;	/* synthesized tap counters (status) */
+	unsigned int taps_right;
+
+	/* One contact sequence, from first finger down to last finger up. */
+	int active;
+	unsigned int start_ms;
+	int start_x, start_y;
+	int started;
+	int moved;
+	int two;
+	int physical;
+	int scrolled;
+	unsigned int last_count;
+
+	/* Pointer delta accumulation. */
+	int last_x, last_y;
+	int have_last;
+	int acc_x, acc_y;
+
+	/* Two-finger scroll tracking. */
+	int scroll_have;
+	int scroll_last_y;
+	int scroll_total;
+	int scroll_acc;
+};
+
+void tpg_init(struct tpg_state *s, int max_x, int max_y, int units_per_px);
+void tpg_set_limits(struct tpg_state *s, int max_x, int max_y);
+void tpg_set_options(struct tpg_state *s, unsigned int opts);
+unsigned int tpg_options(const struct tpg_state *s);
+
+/* Feed one report.  r is fully overwritten. */
+void tpg_frame(struct tpg_state *s, const struct tpg_frame *f,
+	       struct tpg_result *r);
+
+/* Time-only poll: releases a synthesized tap press after its hold.  Call it
+ * between reports (and before the report throttle) so the release is
+ * delivered even though no new contact report is coming. */
+void tpg_tick(struct tpg_state *s, unsigned int now_ms,
+	      struct tpg_result *r);
+
+#endif

+ 178 - 0
touchpad_gesture_test.c

@@ -0,0 +1,178 @@
+/* Host-side checks for the device-independent touchpad gesture engine. */
+#include <stdio.h>
+
+#include "touchpad_gesture.h"
+
+static struct tpg_state tp;
+static int failures;
+
+static void check(const char *name, int cond)
+{
+	printf("%s: %s\n", cond ? "ok" : "FAIL", name);
+	if (!cond)
+		failures++;
+}
+
+static void frame(struct tpg_result *r, unsigned int count,
+		  int x0, int y0, int x1, int y1, int button,
+		  unsigned int now)
+{
+	struct tpg_frame f;
+
+	f.count = count;
+	f.mask = 0;
+	if (count >= 1)
+		f.mask |= 1u;
+	if (count >= 2)
+		f.mask |= 2u;
+	f.contact[0].x = x0;
+	f.contact[0].y = y0;
+	f.contact[1].x = x1;
+	f.contact[1].y = y1;
+	f.button = button;
+	f.now_ms = now;
+	tpg_frame(&tp, &f, r);
+}
+
+static unsigned int tick(unsigned int now)
+{
+	struct tpg_result r;
+
+	tpg_tick(&tp, now, &r);
+	return r.buttons;
+}
+
+static void reset(void)
+{
+	tpg_init(&tp, 3000, 2000, 2);
+}
+
+int main(void)
+{
+	struct tpg_result r;
+	unsigned int now;
+	int scroll;
+
+	reset();
+	check("default options include scroll and taps",
+	      (tpg_options(&tp) & (TPG_TAPCLICK | TPG_RIGHT_TAP |
+				   TPG_RIGHT_CORNER | TPG_SCROLL)) ==
+	      (TPG_TAPCLICK | TPG_RIGHT_TAP | TPG_RIGHT_CORNER | TPG_SCROLL));
+
+	/* One-finger tap -> left. */
+	now = 1000;
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now);
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now + 50);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 100);
+	check("one-finger tap emits left", r.buttons == 1);
+	check("one-finger tap releases", tick(now + 250) == 0);
+
+	/* Two-finger tap -> right. */
+	now = 2000;
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now);
+	frame(&r, 2, 1000, 1000, 1200, 1000, 0, now + 50);
+	frame(&r, 2, 1000, 1000, 1200, 1000, 0, now + 100);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 150);
+	check("two-finger tap emits right", r.buttons == 2);
+	check("two-finger tap releases", tick(now + 300) == 0);
+
+	/* Corner tap -> right; normal tap stays left. */
+	now = 3000;
+	frame(&r, 1, 2800, 200, 0, 0, 0, now);
+	frame(&r, 1, 2800, 200, 0, 0, 0, now + 50);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 100);
+	check("corner tap emits right", r.buttons == 2);
+	tick(now + 250);
+
+	/* Physical corner press -> right and latched; outside -> left. */
+	now = 4000;
+	frame(&r, 1, 2800, 200, 0, 0, 1, now);
+	check("physical corner press is right", r.buttons == 2);
+	frame(&r, 1, 1000, 1000, 0, 0, 1, now + 50);
+	check("physical corner latch survives movement", r.buttons == 2);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 100);
+	check("physical corner press releases", r.buttons == 0);
+
+	now = 5000;
+	frame(&r, 1, 1000, 1000, 0, 0, 1, now);
+	check("physical normal press is left", r.buttons == 1);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 50);
+
+	/* A moving one-finger contact is a pointer move, not a click. */
+	now = 6000;
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now);
+	frame(&r, 1, 1200, 1000, 0, 0, 0, now + 50);
+	check("one-finger drag moves the pointer", r.dx > 0);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 100);
+	check("one-finger drag does not click", r.buttons == 0);
+
+	/* Two-finger scroll: pointer frozen, positive pixel scroll, no click. */
+	now = 7000;
+	reset();
+	frame(&r, 2, 1000, 1000, 1400, 1000, 0, now);
+	scroll = 0;
+	frame(&r, 2, 1000, 1020, 1400, 1020, 0, now + 25);
+	frame(&r, 2, 1000, 1040, 1400, 1040, 0, now + 50);
+	frame(&r, 2, 1000, 1060, 1400, 1060, 0, now + 75);
+	scroll += r.scroll;
+	check("two-finger scroll does not move the pointer", !r.dx && !r.dy);
+	frame(&r, 2, 1000, 1100, 1400, 1100, 0, now + 100);
+	scroll += r.scroll;
+	frame(&r, 2, 1000, 1160, 1400, 1160, 0, now + 125);
+	scroll += r.scroll;
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 150);
+	check("two-finger scroll emits positive pixels", scroll > 0);
+	check("two-finger scroll does not click", r.buttons == 0);
+	check("two-finger scroll releases cleanly", tick(now + 300) == 0);
+
+	/* Traditional direction inverts the output. */
+	reset();
+	tpg_set_options(&tp, tpg_options(&tp) | TPG_SCROLL_INVERT);
+	now = 8000;
+	frame(&r, 2, 1000, 1000, 1400, 1000, 0, now);
+	frame(&r, 2, 1000, 1040, 1400, 1040, 0, now + 25);
+	frame(&r, 2, 1000, 1120, 1400, 1120, 0, now + 50);
+	check("traditional scroll inverts direction", r.scroll < 0);
+
+	/* Two-finger tap with the first slot lifting early still right-clicks. */
+	reset();
+	now = 9000;
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now);
+	frame(&r, 2, 1000, 1000, 1200, 1000, 0, now + 50);
+	frame(&r, 1, 1200, 1000, 0, 0, 0, now + 100);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 150);
+	check("two-finger tap survives first-slot lift", r.buttons == 2);
+
+	/* Pointer re-anchors after the second finger leaves. */
+	reset();
+	now = 10000;
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now);
+	frame(&r, 1, 1100, 1000, 0, 0, 0, now + 25);
+	frame(&r, 2, 1100, 1000, 1500, 1000, 0, now + 50);
+	frame(&r, 1, 1500, 1000, 0, 0, 0, now + 75);
+	check("returning to one finger re-anchors", r.dx == 0 && r.dy == 0);
+	frame(&r, 1, 1600, 1000, 0, 0, 0, now + 100);
+	check("pointer resumes after re-anchor", r.dx > 0);
+
+	/* Scroll disabled: no output and no accidental right-click. */
+	reset();
+	tpg_set_options(&tp, tpg_options(&tp) & ~TPG_SCROLL);
+	now = 11000;
+	frame(&r, 2, 1000, 1000, 1400, 1000, 0, now);
+	frame(&r, 2, 1000, 1040, 1400, 1040, 0, now + 25);
+	frame(&r, 2, 1000, 1120, 1400, 1120, 0, now + 50);
+	check("scroll off emits no scroll", r.scroll == 0);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 75);
+	check("scroll off still suppresses two-finger click", r.buttons == 0);
+
+	/* A long press is not a tap. */
+	reset();
+	now = 12000;
+	frame(&r, 1, 1000, 1000, 0, 0, 0, now);
+	frame(&r, 0, 0, 0, 0, 0, 0, now + 400);
+	check("long press does not click", r.buttons == 0);
+
+	printf(failures ? "FAILURES: %d\n" : "all gesture checks passed\n",
+	       failures);
+	return failures ? 1 : 0;
+}

+ 51 - 4
ucmd_edit.c

@@ -55,6 +55,8 @@ static char path[PATH_MAX];
 static char base_name[BASE_MAX];
 static unsigned int dirty;
 static unsigned int scroll_top;
+static int scroll_acc;
+static int view_locked;
 static unsigned int xoff;
 static int quit_armed;
 static char status_msg[STATUS_MAX];
@@ -481,16 +483,55 @@ static void draw_status(unsigned int line, unsigned int disp)
 	draw_string(x, y, right, rn, col_status_fg);
 }
 
+static unsigned int total_lines(void)
+{
+	unsigned int i, n = 1;
+
+	for (i = 0; i < len; i++)
+		if (text[i] == '\n')
+			n++;
+	return n;
+}
+
+static int handle_scroll(void)
+{
+	struct win_scroll ws;
+	unsigned int total, max_top;
+	int lines, top;
+
+	if (u_win_scroll(&ws) != 1 || !ws.dy)
+		return 0;
+	scroll_acc += ws.dy;
+	lines = scroll_acc / CELL_H;
+	scroll_acc -= lines * CELL_H;
+	if (!lines)
+		return 0;
+	total = total_lines();
+	max_top = total > text_rows ? total - text_rows : 0;
+	top = (int)scroll_top + lines;
+	if (top < 0)
+		top = 0;
+	if ((unsigned int)top > max_top)
+		top = (int)max_top;
+	if ((unsigned int)top == scroll_top)
+		return 0;
+	scroll_top = (unsigned int)top;
+	view_locked = 1;
+	return 1;
+}
+
 static void redraw(void)
 {
 	unsigned int line = cursor_line();
 	unsigned int start = line_start_for(line);
 	unsigned int disp = display_col_at(start, cur);
 
-	if (line < scroll_top)
-		scroll_top = line;
-	else if (line >= scroll_top + text_rows)
-		scroll_top = line - text_rows + 1;
+	if (!view_locked) {
+		if (line < scroll_top)
+			scroll_top = line;
+		else if (line >= scroll_top + text_rows)
+			scroll_top = line - text_rows + 1;
+	}
 	if (disp < xoff)
 		xoff = disp;
 	else if (disp >= xoff + cols)
@@ -507,6 +548,7 @@ static void redraw(void)
 /* 1 = quit, 0 = keep editing */
 static int handle_key(int k)
 {
+	view_locked = 0;
 	if (quit_armed) {
 		if (k == KEY_CTRL_Q)
 			return 1;
@@ -605,6 +647,8 @@ void _start(const char *arg)
 
 	cur = 0;
 	scroll_top = 0;
+	scroll_acc = 0;
+	view_locked = 0;
 	xoff = 0;
 	dirty = 0;
 	quit_armed = 0;
@@ -628,9 +672,12 @@ void _start(const char *arg)
 				cols = fb_w / CELL_W;
 				rows = fb_h / CELL_H;
 				text_rows = (rows > 2) ? rows - 2 : 1;
+				view_locked = 0;
 				got = 1;
 			}
 		}
+		if (handle_scroll())
+			got = 1;
 		while ((k = u_key_poll()) != 0) {
 			got = 1;
 			if (handle_key(k)) {

+ 1 - 0
ucmd_files.c

@@ -808,6 +808,7 @@ static void draw_list(struct ngui *g, struct ngui_rect r, unsigned int *action)
 	ngui_fill_rect(g, r, g->theme.bg);
 	list_scroll.content_h = (int)(entry_count * FM_ROW_H);
 	ngui_scroll_begin(g, r, &list_scroll);
+	ngui_scroll_wheel(g, r, &list_scroll);
 	scrolls = list_scroll.content_h > list_scroll.view_h;
 	row_w = r.w - (scrolls ? FM_SCROLL_W : 0);
 

+ 5 - 0
ucmd_lib.h

@@ -328,6 +328,11 @@ static inline int u_win_event(struct win_event *out)
 	return u_syscall1(SYS_WIN_EVENT, (int)out);
 }
 
+static inline int u_win_scroll(struct win_scroll *out)
+{
+	return u_syscall1(SYS_WIN_SCROLL, (int)out);
+}
+
 static inline int u_wm_resize(unsigned int index, unsigned int cw,
 			      unsigned int ch)
 {

+ 15 - 0
ucmd_term.c

@@ -63,6 +63,7 @@ static unsigned int row_cap = MAX_ROWS;
 static unsigned int row_first;    /* ring index of logical row 0 */
 static unsigned int row_count;    /* valid rows (always >= rows) */
 static unsigned int view;         /* rows scrolled back from the bottom */
+static int wheel_acc;             /* sub-row pixel scroll */
 static unsigned int cols = 64, rows = 32;
 static unsigned int cx, cy;
 static char line[LINE_MAX];
@@ -506,6 +507,20 @@ static void handle_pointer(void)
 			sb_set_from_y(p.y);
 		}
 	}
+
+	{
+		struct win_scroll ws;
+
+		if (u_win_scroll(&ws) == 1 && ws.dy) {
+			int lines;
+
+			wheel_acc += ws.dy;
+			lines = wheel_acc / 16;
+			wheel_acc -= lines * 16;
+			if (lines)
+				scroll_by(-lines);
+		}
+	}
 }
 
 /* ---- Rendering ---- */

+ 3 - 1
usbhid.c

@@ -375,13 +375,15 @@ static int dev_poll(struct hid_dev *d, unsigned int slot, unsigned char *buf,
 	return n;
 }
 
-int usbhid_poll(unsigned int *buttons, int *dx, int *dy)
+int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll)
 {
 	unsigned char buf[8];
 	unsigned int now, i, all_busy = 1;
 	unsigned int b = 0;
 	int n, x = 0, y = 0, got = 0;
 
+	if (scroll)
+		*scroll = 0;
 	if (!hcd_ok)
 		return 0;
 

+ 3 - 2
usbhid.h

@@ -16,8 +16,9 @@ void usbhid_init(void);
 
 /* Service both endpoints (called once per WM loop iteration from
    mouse_poll_update()).  Returns 1 when a mouse report is available and
-   fills buttons/dx/dy (PS/2 sign convention: dy > 0 = up). */
-int usbhid_poll(unsigned int *buttons, int *dx, int *dy);
+   fills buttons/dx/dy (PS/2 sign convention: dy > 0 = up) plus scroll in
+   pixels (currently always 0: boot-protocol mice have no wheel field). */
+int usbhid_poll(unsigned int *buttons, int *dx, int *dy, int *scroll);
 
 int usbhid_mouse_attached(void);
 int usbhid_keyboard_attached(void);

+ 50 - 0
wm.c

@@ -245,6 +245,7 @@ int wm_server_win_create(const struct win_create *in, struct win_info *out)
 	w->pending_back = 0;
 	w->pending_pages = 0;
 	w->resize_pending = 0;
+	w->scroll_x = w->scroll_y = 0;
 	w->canvas_dmg_x = w->canvas_dmg_y = 0;
 	w->canvas_dmg_w = w->canvas_dmg_h = 0;
 	w->pw = cw + 2;
@@ -470,6 +471,20 @@ int wm_server_win_event(struct win_event *out)
 	return 1;
 }
 
+int wm_server_win_scroll(struct win_scroll *out)
+{
+	int idx = wm_window_for_pid(current_proc()->pid);
+	struct window *w;
+
+	if (!out || idx < 0 || !windows[idx].canvas_window)
+		return -1;
+	w = &windows[idx];
+	out->dx = w->scroll_x;
+	out->dy = w->scroll_y;
+	w->scroll_x = w->scroll_y = 0;
+	return (out->dx || out->dy) ? 1 : 0;
+}
+
 int wm_server_resize(unsigned int index, unsigned int cw, unsigned int ch)
 {
 	struct window *w;
@@ -866,6 +881,40 @@ static void wm_route_pointer(unsigned int mx, unsigned int my,
 	wm_ptr_buttons = buttons;
 }
 
+/* Route wheel/touchpad scroll to the canvas window under the pointer.  The
+ * accumulator is drained by SYS_WIN_SCROLL, so a slow client can catch up. */
+static void wm_route_scroll(unsigned int mx, unsigned int my)
+{
+	int sdx, sdy;
+	int idx = wm_window_at((int)mx, (int)my);
+	struct window *w;
+	int cx, cy;
+
+	mouse_scroll_take(&sdx, &sdy);
+	if ((!sdx && !sdy) || idx < 0)
+		return;
+	w = &windows[idx];
+	if (!w->canvas_window)
+		return;
+	cx = (int)mx - w->x - 1;
+	cy = (int)my - w->y - 1 - WM_TITLE_H;
+	if (cx < 0 || cy < 0 || cx >= (int)w->canvas.w ||
+	    cy >= (int)w->canvas.h)
+		return;
+	w->scroll_x += sdx;
+	w->scroll_y += sdy;
+	if (w->scroll_x > 100000)
+		w->scroll_x = 100000;
+	else if (w->scroll_x < -100000)
+		w->scroll_x = -100000;
+	if (w->scroll_y > 100000)
+		w->scroll_y = 100000;
+	else if (w->scroll_y < -100000)
+		w->scroll_y = -100000;
+	/* Wake clients blocked in SYS_WIN_KEY_WAIT so they drain the scroll. */
+	wait_wake_one(&w->key_wq);
+}
+
 int wm_server_poll(struct wm_status *out)
 {
 	if (!wm_server_is_wm() || !out)
@@ -875,6 +924,7 @@ int wm_server_poll(struct wm_status *out)
 	out->mouse.y = mouse_get_y();
 	out->mouse.buttons = mouse_buttons_state();
 	wm_route_pointer(out->mouse.x, out->mouse.y, out->mouse.buttons);
+	wm_route_scroll(out->mouse.x, out->mouse.y);
 	out->full_redraw = wm_full_redraw ? 1 : 0;
 	out->boot_ready = wm_boot_ready ? 1 : 0;
 	out->kexec_busy = kexec_busy ? 1 : 0;

+ 3 - 0
wm.h

@@ -36,6 +36,8 @@ struct window {
 	/* Pointer press/release edges for a generic canvas window. */
 	struct win_event ptr_events[8];
 	unsigned int ptr_head, ptr_tail;
+	/* Scroll accumulated while the pointer is over the content. */
+	int scroll_x, scroll_y;
 	/* Content-relative damage union since the WM last ACKed a present. */
 	unsigned int canvas_dmg_x, canvas_dmg_y;
 	unsigned int canvas_dmg_w, canvas_dmg_h;
@@ -82,6 +84,7 @@ int  wm_server_key_poll(void);
 int  wm_server_key_wait(unsigned int timeout_ms);
 int  wm_server_win_pointer(struct win_pointer *out);
 int  wm_server_win_event(struct win_event *out);
+int  wm_server_win_scroll(struct win_scroll *out);
 void wm_server_boot_ready(void);
 struct window *wm_focused_window(void);
 int  wm_is_focused(const struct window *w);

+ 6 - 0
wm_abi.h

@@ -153,6 +153,12 @@ struct win_pointer {
 	unsigned int focused;
 };
 
+/* Scroll accumulated for this window since the previous call, in pixels.
+ * Positive dy means later content (wheel down under natural scrolling). */
+struct win_scroll {
+	int dx, dy;
+};
+
 #define WIN_EV_POINTER_DOWN 1
 #define WIN_EV_POINTER_UP   2