Просмотр исходного кода

Add touchpad tap gestures and corner right-click

The Elan clickpad has no right button, so derive one from the report's
finger bitmask.  Track each contact sequence and synthesize a short
button press on release: two or more fingers is a right click, a single
finger starting in the bottom-right zone (right 25% x bottom 25% of the
device's max X/Y) is a right click, and a single finger elsewhere is a
left click.  The press is held for 120 ms so commands polling
SYS_WIN_POINTER sample it.

Query the native max-X/Y commands after wake to give the corner zone a
physical frame, with the 12-bit range as a fallback.

Latch a physical clickpad press at its leading edge: a press whose
finger starts in the bottom-right zone reports the right button, other
presses report left, and the choice holds for the whole press.  Physical
presses suppress the synthetic tap so a click is never reported twice.

Extend `touchpad` with status output and the `rightclick
off|tap|corner|both` and `tapclick on|off` options.  Update AGENTS.md and
the drivers page.

Validated with a host harness around touchpad.c (one-finger, two-finger
and corner taps, swipe rejection, mode combinations, physical
corner/non-corner presses and the press latch) and confirmed working on
the HP Chromebook 11 G5.
Johannes Zellner 1 неделя назад
Родитель
Сommit
c31ad46c90
5 измененных файлов с 426 добавлено и 32 удалено
  1. 31 14
      AGENTS.md
  2. 25 7
      docs/drivers.html
  3. 2 2
      terminal.c
  4. 365 7
      touchpad.c
  5. 3 2
      touchpad.h

+ 31 - 14
AGENTS.md

@@ -592,13 +592,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `touchpad_init()` runs from `mouse_init()` at boot (it maps the I2C
   `touchpad_init()` runs from `mouse_init()` at boot (it maps the I2C
   window before processes clone the page directory), resets the device,
   window before processes clone the page directory), resets the device,
   consumes the 2-byte acknowledgement, reads the HID descriptor, selects
   consumes the 2-byte acknowledgement, reads the HID descriptor, selects
-  absolute mode (`0x0300 = 1`) and wakes it (`0x0800`).  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.  `mouseinfo` lists the Elan VID/PID and `touchpad` prints the
-  probe result.
+  absolute mode (`0x0300 = 1`), wakes it (`0x0800`) and then queries the
+  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
+  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.
+  `touchpad` prints the probe/status and takes
+  `rightclick off|tap|corner|both` / `tapclick on|off`; `mouseinfo` lists
+  the Elan VID/PID.
 - **USB**: `usb.c/h` — controller-agnostic core: device enumeration,
 - **USB**: `usb.c/h` — controller-agnostic core: device enumeration,
   descriptor parsing, hub recursion, bus scans, per-controller addresses, the
   descriptor parsing, hub recursion, bus scans, per-controller addresses, the
   hotplug watcher and the interrupt-IN consumers (mouse + keyboard).  It keeps
   hotplug watcher and the interrupt-IN consumers (mouse + keyboard).  It keeps
@@ -1000,7 +1010,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>`,
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
-`display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad`, `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]`, `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).
 `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
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -1708,12 +1718,19 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     MuJS but are not a complete POSIX libc.
     MuJS but are not a complete POSIX libc.
 
 
 28. The Elan touchpad is polled at 40 Hz because its report GPIO (GPNC bank
 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 and the
-    clickpad bit are used: there is no multitouch, two-finger scrolling,
-    tap-to-click, drag-lock or pressure/size handling, and the 1/2 delta
-    scale is fixed (no pointer-acceleration curve).  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.
+    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
+    back-to-back, so a GPIO interrupt (or a larger minimum gap) is the
+    prerequisite for a higher report rate.
 
 
 29. Airmont/Braswell power management: the governor caps at the maximum
 29. Airmont/Braswell power management: the governor caps at the maximum
     non-turbo pstate (N3060: 20 = 1600 MHz) and never requests turbo pstate
     non-turbo pstate (N3060: 20 = 1600 MHz) and never requests turbo pstate

+ 25 - 7
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>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>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>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; no GPIO interrupt driver</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>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>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>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>
 					<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,16 +361,34 @@
 			wake the device (<code>0x0800</code>). Resetting last leaves it
 			wake the device (<code>0x0800</code>). Resetting last leaves it
 			silent until the next power cycle.</li>
 			silent until the next power cycle.</li>
 			<li><strong>Reports.</strong> The Elan vendor report <code>0x5D</code>
 			<li><strong>Reports.</strong> The Elan vendor report <code>0x5D</code>
-			carries a finger bitmask and five bytes per finger (X/Y high bits, X
-			low, Y low, size, pressure). Successive absolute positions become
-			PS/2 deltas; the clickpad bit becomes the left button.</li>
+			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
+			(<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
+			turned into a synthetic button press: two fingers is a right click,
+			one finger starting in the bottom-right zone (right 25% x bottom
+			25% of the pad) is a right click, and one finger elsewhere is a
+			left click. The press is held for 120 ms so applications polling
+			<code>SYS_WIN_POINTER</code> sample it. Taps shorter than two 25 ms
+			samples, longer than 300 ms, moved more than 60 coordinate units,
+			or accompanied by a physical clickpad press are ignored.</li>
+			<li><strong>Physical clickpad.</strong> The single clickpad button
+			is latched at its leading edge: a press whose finger starts in the
+			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>Polling.</strong> The report GPIO has no driver yet, so
 			<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
 			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
 			device, which is why the poll is throttled rather than run flat
 			out.</li>
 			out.</li>
-			<li><strong>Discovery.</strong> <code>touchpad</code> prints the
-			probe result; <code>mouseinfo</code> lists the Elan vendor/product
-			ID next to the PS/2 and USB backends.</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>
 		</ul>
 		</ul>
 	</section>
 	</section>
 
 

+ 2 - 2
terminal.c

@@ -20,7 +20,7 @@ extern void program_display_main(void);
 extern void program_gfxbench_main(void);
 extern void program_gfxbench_main(void);
 extern void program_serial_loop_main(const char *arg);
 extern void program_serial_loop_main(const char *arg);
 extern void program_lsusb_main(void);
 extern void program_lsusb_main(void);
-extern void program_touchpad_main(void);
+extern void program_touchpad_main(const char *arg);
 extern void program_netdev_main(const char *arg);
 extern void program_netdev_main(const char *arg);
 extern void program_format_main(const char *arg);
 extern void program_format_main(const char *arg);
 extern void program_install_main(const char *arg);
 extern void program_install_main(const char *arg);
@@ -85,7 +85,7 @@ static const struct kcmd cmds[] = {
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "gfxbench",   "gfxbench",                      CK_SPAWN, 0, program_gfxbench_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 },
 	{ "lsusb",      "lsusb",                         CK_SPAWN, 0, program_lsusb_main, 0, 0, 0 },
-	{ "touchpad",   "touchpad",                      CK_SPAWN, 0, program_touchpad_main, 0, 0, 0 },
+	{ "touchpad",   "touchpad [rightclick ...]",     CK_SPAWN_ARG, 0, 0, program_touchpad_main, 0, 0 },
 	{ "netdev",     "netdev [name]",                 CK_SPAWN_ARG, 0, 0, program_netdev_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 },
 	{ "format",     "format <device> [size]",        CK_CUSTOM, 0, 0, 0, 0, cmd_format },
 	{ "install",    "install <target> [source]",     CK_CUSTOM, 0, 0, 0, 0, cmd_install },
 	{ "install",    "install <target> [source]",     CK_CUSTOM, 0, 0, 0, 0, cmd_install },

+ 365 - 7
touchpad.c

@@ -11,9 +11,14 @@
  * rate it keeps up with, and the pointer still moves smoothly.
  * rate it keeps up with, and the pointer still moves smoothly.
  *
  *
  * Init follows Linux's elan_i2c: reset, consume the 2-byte reset
  * Init follows Linux's elan_i2c: reset, consume the 2-byte reset
- * acknowledgement, read the HID descriptor, select absolute mode (0x0300)
- * and wake the device (0x0800).  Resetting last leaves it silent until the
- * next power cycle.
+ * 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.
  */
  */
 
 
 #include "touchpad.h"
 #include "touchpad.h"
@@ -38,9 +43,32 @@
 #define TP_DW_COMP_TYPE		0x44570140u
 #define TP_DW_COMP_TYPE		0x44570140u
 #define TP_REPORT_ID		0x5d
 #define TP_REPORT_ID		0x5d
 
 
+#define TP_MAX_X_REG		0x0106
+#define TP_MAX_Y_REG		0x0107
+#define TP_ABS_MAX		4095
+
 #define TP_MAX_INPUT		64
 #define TP_MAX_INPUT		64
 #define TP_POLL_MS		25
 #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_base;
 static unsigned int tp_addr = TP_ADDR;
 static unsigned int tp_addr = TP_ADDR;
 static int tp_present;
 static int tp_present;
@@ -49,6 +77,8 @@ static unsigned int tp_max_in = 34;
 static unsigned int tp_cmd_reg = TP_CMD_REG;
 static unsigned int tp_cmd_reg = TP_CMD_REG;
 static unsigned short tp_vendor;
 static unsigned short tp_vendor;
 static unsigned short tp_product;
 static unsigned short tp_product;
+static int tp_max_x = TP_ABS_MAX;
+static int tp_max_y = TP_ABS_MAX;
 static const char *tp_err;
 static const char *tp_err;
 static unsigned int tp_err_val;
 static unsigned int tp_err_val;
 
 
@@ -56,6 +86,30 @@ static int tp_last_x, tp_last_y, tp_acc_x, tp_acc_y;
 static int tp_down, tp_last_buttons;
 static int tp_down, tp_last_buttons;
 static unsigned int tp_next_poll;
 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;
+
+static void put_dec(unsigned int v);
+static const char *rc_name(void);
+
 static void put_hex16(unsigned int v)
 static void put_hex16(unsigned int v)
 {
 {
 	static const char hex[] = "0123456789ABCDEF";
 	static const char hex[] = "0123456789ABCDEF";
@@ -76,6 +130,37 @@ static void print_summary(void)
 	io_puthex(tp_base);
 	io_puthex(tp_base);
 	io_putstr(" addr 0x");
 	io_putstr(" addr 0x");
 	io_puthex(tp_addr);
 	io_puthex(tp_addr);
+	io_putstr(" max ");
+	put_dec((unsigned int)tp_max_x);
+	io_putchar('x');
+	put_dec((unsigned int)tp_max_y);
+	io_putchar('\n');
+}
+
+static void print_status(void)
+{
+	print_summary();
+	io_putstr("touchpad: rightclick ");
+	io_putstr(rc_name());
+	io_putstr(" tapclick ");
+	io_putstr(tp_tapclick ? "on" : "off");
+	io_putstr(" corner x>=");
+	put_dec((unsigned int)(tp_max_x * TP_CORNER_X_PCT / 100));
+	io_putstr(" y<=");
+	put_dec((unsigned int)(tp_max_y * TP_CORNER_Y_PCT / 100));
+	io_putstr("\n");
+	io_putstr("touchpad: last f=");
+	put_dec((unsigned int)tp_stat_fingers);
+	if (tp_stat_f1) {
+		io_putstr(" x=");
+		put_dec((unsigned int)tp_stat_x);
+		io_putstr(" y=");
+		put_dec((unsigned int)tp_stat_y);
+	}
+	io_putstr(" taps left=");
+	put_dec(tp_synth_left);
+	io_putstr(" right=");
+	put_dec(tp_synth_right);
 	io_putchar('\n');
 	io_putchar('\n');
 }
 }
 
 
@@ -92,6 +177,79 @@ static unsigned int get16(const unsigned char *p)
 	return (unsigned int)p[0] | ((unsigned int)p[1] << 8);
 	return (unsigned int)p[0] | ((unsigned int)p[1] << 8);
 }
 }
 
 
+static void put_dec(unsigned int v)
+{
+	char buf[11];
+	unsigned int i = 0;
+
+	if (!v) {
+		io_putchar('0');
+		return;
+	}
+	while (v) {
+		buf[i++] = (char)('0' + v % 10);
+		v /= 10;
+	}
+	while (i)
+		io_putchar(buf[--i]);
+}
+
+/* Match one whitespace-delimited word at s (end or space after it). */
+static int word_is(const char *s, const char *word)
+{
+	while (*word) {
+		if (*s != *word)
+			return 0;
+		s++;
+		word++;
+	}
+	return *s == '\0' || *s == ' ';
+}
+
+static const char *skip_spaces(const char *s)
+{
+	while (*s == ' ')
+		s++;
+	return s;
+}
+
+static unsigned int word_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s[n] && s[n] != ' ')
+		n++;
+	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";
+	}
+}
+
 static int hid_read_reg(unsigned int addr, unsigned int reg,
 static int hid_read_reg(unsigned int addr, unsigned int reg,
 			unsigned char *buf, unsigned int len)
 			unsigned char *buf, unsigned int len)
 {
 {
@@ -120,6 +278,27 @@ static int hid_write_reg(unsigned int addr, unsigned int reg, unsigned int val)
 	return i2c_dw_transfer(tp_base, addr, b, 4, 0, 0);
 	return i2c_dw_transfer(tp_base, addr, b, 4, 0, 0);
 }
 }
 
 
+/* Native Elan max-coordinate commands (the same read-cmd path Linux
+ * elan_i2c uses).  They give the corner zone a physical frame instead of
+ * assuming the full 12-bit range; on failure keep the 4095 fallback. */
+static void query_limits(void)
+{
+	unsigned char v[2];
+
+	if (hid_read_reg(tp_addr, TP_MAX_X_REG, v, 2) == 0) {
+		unsigned int m = get16(v) & 0x0fff;
+
+		if (m >= 256)
+			tp_max_x = (int)m;
+	}
+	if (hid_read_reg(tp_addr, TP_MAX_Y_REG, v, 2) == 0) {
+		unsigned int m = get16(v) & 0x0fff;
+
+		if (m >= 256)
+			tp_max_y = (int)m;
+	}
+}
+
 static int probe_controller(unsigned int base)
 static int probe_controller(unsigned int base)
 {
 {
 	unsigned char desc[TP_HID_DESC_LEN + 2];
 	unsigned char desc[TP_HID_DESC_LEN + 2];
@@ -181,6 +360,10 @@ static int probe_controller(unsigned int base)
 	hid_write_reg(TP_ADDR, tp_cmd_reg, TP_CMD_WAKE);
 	hid_write_reg(TP_ADDR, tp_cmd_reg, TP_CMD_WAKE);
 	msleep(60);
 	msleep(60);
 
 
+	/* Query the limits with the device awake (Linux reads them after
+	 * initialize()/wake and before enabling reports). */
+	query_limits();
+
 	tp_present = 1;
 	tp_present = 1;
 	tp_err = 0;
 	tp_err = 0;
 	print_summary();
 	print_summary();
@@ -234,6 +417,88 @@ unsigned short touchpad_product(void)
 	return tp_product;
 	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)
 {
 {
 	unsigned char buf[TP_MAX_INPUT];
 	unsigned char buf[TP_MAX_INPUT];
@@ -243,6 +508,16 @@ int touchpad_poll(int *buttons, int *dx, int *dy)
 		return 0;
 		return 0;
 
 
 	now = get_ticks_ms();
 	now = get_ticks_ms();
+
+	/* 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;
+		return 1;
+	}
+
 	if ((int)(now - tp_next_poll) < 0)
 	if ((int)(now - tp_next_poll) < 0)
 		return 0;
 		return 0;
 	tp_next_poll = now + TP_POLL_MS;
 	tp_next_poll = now + TP_POLL_MS;
@@ -254,7 +529,8 @@ int touchpad_poll(int *buttons, int *dx, int *dy)
 	 * and then the report, so locate the 0x5D report ID instead of
 	 * and then the report, so locate the 0x5D report ID instead of
 	 * trusting a fixed offset.  Layout after it (Linux hid-elan.c):
 	 * 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
 	 * touch info (f5..f1 at bits 7..3, clickpad at bit 0), then 5
-	 * bytes per finger: x11:8/y11:9, x7:0, y7:0, size, pressure. */
+	 * 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++)
 	for (b = 0; b < 6 && b + 4 < tp_max_in; b++)
 		if (buf[b] == TP_REPORT_ID)
 		if (buf[b] == TP_REPORT_ID)
 			break;
 			break;
@@ -267,7 +543,31 @@ int touchpad_poll(int *buttons, int *dx, int *dy)
 		int x = ((int)(xh & 0xf0) << 4) | buf[b + 3];
 		int x = ((int)(xh & 0xf0) << 4) | buf[b + 3];
 		int y = ((int)(xh & 0x0f) << 8) | buf[b + 4];
 		int y = ((int)(xh & 0x0f) << 8) | buf[b + 4];
 
 
-		*buttons = ti & 0x01;
+		{
+			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 */
 		if (!(ti & 0x08)) {		/* finger 1 lifted */
 			tp_down = 0;
 			tp_down = 0;
 			tp_acc_x = 0;
 			tp_acc_x = 0;
@@ -312,7 +612,7 @@ int touchpad_poll(int *buttons, int *dx, int *dy)
 	}
 	}
 }
 }
 
 
-void program_touchpad_main(void)
+void program_touchpad_main(const char *arg)
 {
 {
 	if (!tp_present) {
 	if (!tp_present) {
 		io_putstr("touchpad: absent (");
 		io_putstr("touchpad: absent (");
@@ -324,5 +624,63 @@ void program_touchpad_main(void)
 		io_putstr(")\n");
 		io_putstr(")\n");
 		return;
 		return;
 	}
 	}
-	print_summary();
+
+	arg = arg ? skip_spaces(arg) : 0;
+	if (!arg || !*arg) {
+		print_status();
+		return;
+	}
+
+	while (*arg) {
+		if (word_is(arg, "rightclick")) {
+			const char *v = skip_spaces(arg + 10);
+
+			if (!*v) {
+				io_putstr("touchpad: rightclick ");
+				io_putstr(rc_name());
+				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 {
+				io_putstr("touchpad: rightclick off|tap|corner|both\n");
+				return;
+			}
+			io_putstr("touchpad: rightclick ");
+			io_putstr(rc_name());
+			io_putchar('\n');
+			arg = skip_spaces(v + word_len(v));
+		} else if (word_is(arg, "tapclick")) {
+			const char *v = skip_spaces(arg + 8);
+
+			if (!*v) {
+				io_putstr("touchpad: tapclick ");
+				io_putstr(tp_tapclick ? "on" : "off");
+				io_putchar('\n');
+				return;
+			}
+			if (word_is(v, "on"))
+				tp_tapclick = 1;
+			else if (word_is(v, "off"))
+				tp_tapclick = 0;
+			else {
+				io_putstr("touchpad: tapclick on|off\n");
+				return;
+			}
+			io_putstr("touchpad: tapclick ");
+			io_putstr(tp_tapclick ? "on" : "off");
+			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");
+			return;
+		}
+	}
 }
 }

+ 3 - 2
touchpad.h

@@ -21,8 +21,9 @@ unsigned int touchpad_addr(void);
 unsigned short touchpad_vendor(void);
 unsigned short touchpad_vendor(void);
 unsigned short touchpad_product(void);
 unsigned short touchpad_product(void);
 
 
-/* `touchpad` kernel command: print the cached probe result. */
-void program_touchpad_main(void);
+/* `touchpad` kernel command: print status, or set the tap gestures with
+ * `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;
 /* Poll one input report.  Returns 1 when the deltas or buttons changed;
  * values use the mouse layer's PS/2 convention (+dy is up). */
  * values use the mouse layer's PS/2 convention (+dy is up). */