omarchy icon indicating copy to clipboard operation
omarchy copied to clipboard

Add kinetic/inertial scrolling for touchpad

Open sudo-WearTherinG opened this issue 3 months ago • 2 comments

System details

HP Notebook - 15-da0327tu

What's wrong?

The two-finger scrolling itself works, but there is no kinetic/inertial scrolling.

Currently, when I scroll with two fingers and lift my fingers from the touchpad after quick gesture, the scrolling doesn't register. On other desktop environments such as Windows, the page continues scrolling briefly based on the speed of the gesture, similar to how scrolling works on phones and modern touchpads.

Please add/fix kinetic (inertial/momentum) scrolling for two-finger touchpad scrolling.

sudo-WearTherinG avatar Aug 31 '26 10:08 sudo-WearTherinG

Same thing bothered me on a Dell XPS 14 (Synaptics 06CB:D01D touchpad), Omarchy 4.0.5, Hyprland 0.56.2, mostly in terminals. Built a small workaround that has been working well, so sharing it here in case it is useful as a starting point.

Neither libinput nor Hyprland has kinetic scrolling. On Wayland it is up to each app, and GTK apps or Firefox do their own, but terminals (foot, Alacritty, kitty, Ghostty) have none.

How the workaround does it:

  • A small Python daemon (python-evdev) runs as a systemd user service. It reads the touchpad read-only, without grabbing it, so libinput scrolling stays untouched.
  • When two fingers lift mid-flick, it measures the speed over the last 60 ms. If that is above a threshold and mostly vertical, it keeps scrolling through a uinput virtual wheel (REL_WHEEL_HI_RES) with exponential decay.
  • Touching the pad again stops it immediately, like on macOS.
  • It only acts when the focused window class matches an allowlist, terminals by default, so apps with their own momentum don't get it twice. Also works inside tmux, since it sends ordinary wheel events.
  • Access is a udev uaccess rule on the touchpad event node and /dev/uinput, so only the logged-in user can read the touchpad, and it doesn't need the whole input group.

Questions before turning it into a PR:

  1. Is a Python daemon acceptable, or would you rather have it in another language?
  2. Should it be opt-in, e.g. omarchy toggle touchpad-momentum, or on by default?
  3. Terminals only by default, or every window except an exclusion list?

If this direction fits, I'm happy to make it generic (match any touchpad with ENV{ID_INPUT_TOUCHPAD}=="1", setup plus migration) and send a PR.

Current script and udev rule
# /etc/udev/rules.d/70-touchpad-momentum.rules
SUBSYSTEM=="input", KERNEL=="event*", ATTRS{name}=="VEN_06CB:00 06CB:D01D Touchpad", TAG+="uaccess"
KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"
#!/usr/bin/python3 -I
"""Momentum ("kinetic") scrolling after a two-finger touchpad flick, like macOS.

Libinput and Hyprland only scroll while fingers move; momentum is left to each
app, and terminals don't do it. This daemon reads the touchpad (read-only, no
grab, so normal scrolling is untouched). When two fingers lift mid-flick over a
window whose class matches TPM_CLASSES, it keeps scrolling through a virtual
wheel (uinput) with exponential slow-down. Touching the pad again stops it.

Needs python-evdev and read access to the touchpad node: a udev uaccess rule,
see ~/.github/setup/touchpad-momentum.sh. Tunables come from the environment,
see ~/.config/touchpad-momentum.env.
"""
import glob, json, math, os, re, select, socket, sys, time
from collections import deque

import evdev
from evdev import ecodes as e

def env(name, default):
    return type(default)(os.environ.get(name, default))

GAIN = env("TPM_GAIN", 22.0)          # wheel units (120 = one notch) per mm of finger travel
TAU = env("TPM_TAU", 0.35)            # seconds for the speed to drop to 37%
MIN_SPEED = env("TPM_MIN_SPEED", 70.0)  # mm/s at lift-off needed to start momentum
MAX_SPEED = env("TPM_MAX_SPEED", 30000.0)  # cap, wheel units/s
DIRECTION = env("TPM_DIRECTION", 1)   # 1 = traditional (finger up = page down), -1 = natural
CLASSES = re.compile(os.environ.get(
    "TPM_CLASSES", r"^(foot|footclient|org\.omarchy\.agent|Alacritty|kitty|com\.mitchellh\.ghostty|org\.wezfurlong\.wezterm)$"))
NAME = re.compile(os.environ.get("TPM_DEVICE", r"Touchpad"))
WINDOW = 0.06   # seconds of finger history used for the lift-off speed
HZ = 120

FINGER_KEYS = {e.BTN_TOOL_FINGER: 1, e.BTN_TOOL_DOUBLETAP: 2, e.BTN_TOOL_TRIPLETAP: 3,
               e.BTN_TOOL_QUADTAP: 4, e.BTN_TOOL_QUINTTAP: 5}

def find_touchpad():
    for path in evdev.list_devices():
        try:
            dev = evdev.InputDevice(path)
        except OSError:
            continue
        abs_codes = dict(dev.capabilities().get(e.EV_ABS, []))
        if NAME.search(dev.name) and e.ABS_MT_POSITION_Y in abs_codes:
            return dev
        dev.close()
    return None

def hypr_class():
    """Class of the focused window (focus follows the mouse here), or ''."""
    run = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
    sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
    socks = [f"{run}/hypr/{sig}/.socket.sock"] if sig else []
    socks += sorted(glob.glob(f"{run}/hypr/*/.socket.sock"), key=os.path.getmtime, reverse=True)
    for path in socks:
        try:
            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
                s.settimeout(0.2)
                s.connect(path)
                s.sendall(b"j/activewindow")
                data = b""
                while chunk := s.recv(65536):
                    data += chunk
            return json.loads(data or b"{}").get("class", "")
        except (OSError, ValueError):
            continue
    return ""

def main():
    pad = find_touchpad()
    if pad is None:
        print("no readable touchpad found, nothing to do", file=sys.stderr)
        return 0
    res_y = pad.absinfo(e.ABS_MT_POSITION_Y).resolution or 1   # units per mm
    res_x = pad.absinfo(e.ABS_MT_POSITION_X).resolution or 1
    wheel = evdev.UInput({e.EV_KEY: [e.BTN_LEFT],
                          e.EV_REL: [e.REL_X, e.REL_Y, e.REL_WHEEL, e.REL_WHEEL_HI_RES]},
                         name="touchpad-momentum")
    print(f"watching {pad.path} ({pad.name}), res {res_x}x{res_y}/mm", file=sys.stderr)

    slot, slots = 0, {}            # slot -> [tracking_id, x, y]
    fingers = prev_fingers = 0
    history = deque()              # (t, x_mm, y_mm) while exactly two fingers are down
    speed = 0.0                    # current momentum, wheel units/s (0 = idle)
    acc = 0.0                      # sub-unit remainder of hi-res wheel
    notch = 0.0                    # hi-res units since the last legacy REL_WHEEL click
    last_tick = 0.0

    while True:
        timeout = 1 / HZ if speed else None
        if select.select([pad.fd], [], [], timeout)[0]:
            for ev in pad.read():
                if ev.type == e.EV_ABS:
                    if ev.code == e.ABS_MT_SLOT:
                        slot = ev.value
                    elif ev.code == e.ABS_MT_TRACKING_ID:
                        if ev.value < 0:
                            slots.pop(slot, None)
                        else:
                            slots[slot] = [ev.value, None, None]
                    elif ev.code in (e.ABS_MT_POSITION_X, e.ABS_MT_POSITION_Y) and slot in slots:
                        slots[slot][1 if ev.code == e.ABS_MT_POSITION_X else 2] = ev.value
                elif ev.type == e.EV_KEY and ev.code in FINGER_KEYS:
                    if ev.value:
                        fingers = FINGER_KEYS[ev.code]
                    elif fingers == FINGER_KEYS[ev.code]:
                        fingers = 0
                elif ev.type == e.EV_SYN and ev.code == e.SYN_REPORT:
                    t = ev.timestamp()
                    if fingers > prev_fingers:
                        speed = acc = 0.0      # any new touch stops momentum
                    pts = [(x, y) for _, x, y in slots.values() if x is not None and y is not None]
                    if fingers == 2 and len(pts) == 2:
                        history.append((t, sum(p[0] for p in pts) / 2 / res_x,
                                        sum(p[1] for p in pts) / 2 / res_y))
                        while history and history[0][0] < t - 0.25:
                            history.popleft()
                    elif prev_fingers == 2 and history:
                        speed = flick_speed(history, t)
                        if speed:
                            cls = hypr_class()
                            print(f"flick {-speed / GAIN / DIRECTION:+.0f} mm/s in {cls or '?'}"
                                  + ("" if CLASSES.search(cls) else " (skipped)"), file=sys.stderr)
                            if not CLASSES.search(cls):
                                speed = 0.0
                        acc, last_tick = 0.0, time.monotonic()
                        history.clear()
                    if fingers != 2:
                        history.clear()
                    prev_fingers = fingers

        if speed:
            now = time.monotonic()
            dt, last_tick = now - last_tick, now
            speed *= math.exp(-dt / TAU)
            acc += speed * dt
            step = int(acc)
            if step:
                acc -= step
                notch += step
                wheel.write(e.EV_REL, e.REL_WHEEL_HI_RES, step)
                clicks = int(notch / 120)
                if clicks:
                    notch -= clicks * 120
                    wheel.write(e.EV_REL, e.REL_WHEEL, clicks)
                wheel.syn()
            if abs(speed) < 40:
                speed = acc = 0.0

def flick_speed(history, t_lift):
    """Wheel speed (units/s) for a lift at t_lift, or 0 if it wasn't a vertical flick."""
    t1, x1, y1 = history[-1]
    if t_lift - t1 > 0.05:              # fingers rested before lifting
        return 0.0
    recent = [h for h in history if h[0] >= t1 - WINDOW]
    t0, x0, y0 = recent[0]
    if len(recent) < 3 or t1 - t0 < 0.015:
        return 0.0
    vx, vy = (x1 - x0) / (t1 - t0), (y1 - y0) / (t1 - t0)
    if abs(vy) < MIN_SPEED or abs(vy) < 2 * abs(vx):
        return 0.0
    # traditional scrolling: finger up (vy < 0) = wheel away from you (positive)
    return max(-MAX_SPEED, min(MAX_SPEED, -vy * GAIN * DIRECTION))

if __name__ == "__main__":
    sys.exit(main())

xsi-dbachmann avatar Oct 20 '26 07:10 xsi-dbachmann

+1, and I think touchpad momentum should be the default for all scrolling in Omarchy. GTK apps and browsers already glide after a flick, but Omarchy's own Quickshell surfaces (the menu in shell/plugins/menu/Menu.qml, the clipboard and other popups) and Omawrite stop dead as soon as the fingers lift, so the desktop feels inconsistent.

Qt Quick doesn't add touchpad momentum on Wayland by itself, but a small WheelHandler can: move the list 1:1 while the fingers are down, track the speed, and call Flickable.flick() on Qt.ScrollEnd. Mouse wheel notches (no pixelDelta) keep scrolling normally. This is what I use in my clipboard plugin:

// KineticScroll.qml: touchpad momentum for a Flickable/ListView
import QtQuick

WheelHandler {
  id: handler
  required property Flickable flickable
  property real wheelStep: 120
  property real velocity: 0   // px/s, smoothed
  property real lastTime: 0

  target: null
  acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad

  function scrollBy(dy) {
    var f = flickable
    var maxY = f.originY + Math.max(0, f.contentHeight - f.height)
    f.contentY = Math.max(f.originY, Math.min(maxY, f.contentY + dy))
  }

  onWheel: function(event) {
    var now = Date.now()
    if (event.phase === Qt.ScrollEnd) {
      // only glide if the fingers were still moving when lifted
      if (now - lastTime < 80 && Math.abs(velocity) > 50) flickable.flick(0, velocity)
      velocity = 0
      return
    }
    if (event.phase === Qt.ScrollBegin) { velocity = 0; lastTime = now }
    if (event.pixelDelta.y !== 0) {          // touchpad
      flickable.cancelFlick()
      var dt = Math.max(1, now - lastTime)
      velocity = 0.7 * velocity + 0.3 * (event.pixelDelta.y * 1000 / dt)
      lastTime = now
      scrollBy(-event.pixelDelta.y)
    } else if (event.angleDelta.y !== 0) {   // mouse wheel notch
      flickable.cancelFlick()
      scrollBy(-event.angleDelta.y / 120 * wheelStep)
    }
  }
}

Use it inside the view, e.g. on the menu's ListView:

ListView {
  id: list
  flickDeceleration: 2500
  KineticScroll { flickable: list }
}

The menu's ListView (around line 1173 of Menu.qml) currently only sets boundsBehavior: StopAtBounds, so adding this would be a small, low-risk change. A shared component in the shell would let every Omarchy surface get the same scrolling. Omawrite's Flickable in src/Main.qml (omacom/omawrite) could use the same handler.

Related: #7361 (menu touchpad scroll speed).

roehrbacher avatar Oct 20 '26 17:10 roehrbacher