diff options
| -rw-r--r-- | build.zig | 29 | ||||
| -rw-r--r-- | docs/typ/guide.typ | 11 | ||||
| -rw-r--r-- | src/gui/Trackpad.zig | 142 | ||||
| -rw-r--r-- | src/gui/gui.zig | 182 | ||||
| -rw-r--r-- | src/gui/macos_trackpad.h | 21 | ||||
| -rw-r--r-- | src/gui/macos_trackpad.m | 176 | ||||
| -rw-r--r-- | test/macos_trackpad.m | 165 |
7 files changed, 695 insertions, 31 deletions
@@ -916,6 +916,8 @@ pub fn build(b: *std.Build) void { if (platform == .gui) root_mod else null; // The static step's gui module is a gui shell too. const gui_shell_mods: [2]?*std.Build.Module = .{ gui_shell_mod, if (platform == .gui) static_mod else null }; + // SDL's headers, for the macOS trackpad adapter's test after the loop. + var sdl_include: ?std.Build.LazyPath = null; for (gui_shell_mods) |gui_shell_entry| if (gui_shell_entry) |gm| { // SDL's build asks a cross build for macOS for the SDK's paths. const sdk: ?std.Build.LazyPath = if (macos_sdk) |p| .{ .cwd_relative = p } else null; @@ -933,12 +935,26 @@ pub fn build(b: *std.Build) void { \\#define SDL_DISABLE_OLD_NAMES 1 \\#include <SDL3/SDL.h> \\#include "font.h" + \\#include "macos_trackpad.h" \\ ); const gui_c = b.addTranslateC(.{ .root_source_file = header, .target = target, .optimize = optimize }); gui_c.addIncludePath(dep.path("include")); gui_c.addIncludePath(b.path("src/gui")); gm.addImport("gui_c", gui_c.createModule()); + sdl_include = dep.path("include"); + if (target.result.os.tag == .macos) { + const arch = if (target.result.cpu.arch == .aarch64) "arm64" else @tagName(target.result.cpu.arch); + const shim = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O2", "-target", b.fmt("{s}-apple-macos13.0", .{arch}), "-I" }); + shim.addDirectoryArg(dep.path("include")); + shim.addArg("-c"); + shim.addFileArg(b.path("src/gui/macos_trackpad.m")); + // Header changes invalidate the independently compiled adapter. + shim.addFileInput(b.path("src/gui/macos_trackpad.h")); + shim.addArg("-o"); + gm.addObjectFile(shim.addOutputFileArg("macos_trackpad.o")); + gm.linkFramework("Cocoa", .{}); + } } const ft = freetype orelse continue; gm.linkLibrary(ft); @@ -997,6 +1013,19 @@ pub fn build(b: *std.Build) void { compileGlsl(b, name), }); }; + if (target.result.os.tag == .macos) if (sdl_include) |include| { + const adapter_test = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O1", "-framework", "Cocoa", "-I" }); + adapter_test.addDirectoryArg(include); + adapter_test.addFileArg(b.path("test/macos_trackpad.m")); + adapter_test.addFileInput(b.path("src/gui/macos_trackpad.m")); + adapter_test.addFileInput(b.path("src/gui/macos_trackpad.h")); + adapter_test.addArg("-o"); + const adapter_bin = adapter_test.addOutputFileArg("macos-trackpad-test"); + const run_adapter = std.Build.Step.Run.create(b, "run macos-trackpad-test"); + run_adapter.addFileArg(adapter_bin); + run_adapter.has_side_effects = true; + b.step("macos-trackpad-test", "test native SDL trackpad decoding and haptics without hardware").dependOn(&run_adapter.step); + }; if (platform == .macos) { const header = b.addTranslateC(.{ diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 41d59e53..df53d0b9 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -78,6 +78,17 @@ before #key("Ctrl-w") or #key("Alt-n"). A program that takes the mouse gets the plain click. +In the SDL window on macOS, including a remote session, two or three fingers +click #btn("B2") (#word("Exec")); a force click is #btn("B3") (#word("Look")). +Two-finger scrolling follows the trackpad with macOS momentum. A deliberate +pinch changes the window's font size at reduced gain; small pinch noise during +a twist is ignored. Rotation in normal mode steps through search matches, +with a haptic notch for each step. Horizontal page swipes, as configured in +macOS, run #word("Back") and #word("Forward") through the jump history, with a +haptic cue approaching the short swipe threshold and another pulse when +navigation is triggered. Shift or Option keeps horizontal +scrolling instead of history swipes. + #btn("B3") on `src/bar.c:12:5:` in a compiler's error opens `src/bar.c` at line 12, column 5. A click takes the word under it: letters, digits and `. - + / : @ _ ~`, less a trailing `:`. Drag to take exactly what you diff --git a/src/gui/Trackpad.zig b/src/gui/Trackpad.zig new file mode 100644 index 00000000..ef28d211 --- /dev/null +++ b/src/gui/Trackpad.zig @@ -0,0 +1,142 @@ +//! Mac trackpad policy, after AppKit decoding. Buttons use SDL's 1/2/3. +const std = @import("std"); +const Trackpad = @This(); + +fingers: usize = 0, +stream: ?u8 = null, +button: ?u8 = null, +forced: bool = false, +rotation: f32 = 0, +rotation_total: f32 = 0, +gesture: enum { none, pinch, rotate } = .none, +pinch_base: f32 = 0, +pinch_total: f32 = 1, + +pub fn countFingers(t: *Trackpad, count: usize) void { + if (count < 2 or t.fingers < 2) { + t.gesture = .none; + t.rotation_total = 0; + t.pinch_base = 0; + t.pinch_total = 1; + } + t.fingers = count; +} + +pub fn press(t: *Trackpad, stream: u8) u8 { + if (t.fingers == 0 or stream > 3) return stream; + t.stream = stream; + t.button = if (t.fingers >= 2) 2 else stream; + t.forced = false; + return t.button.?; +} + +pub fn release(t: *Trackpad, stream: u8) ?u8 { + if (t.stream != stream) return stream; + defer { + t.stream = null; + t.button = null; + t.forced = false; + } + return if (t.forced) null else t.button; +} + +/// The caller releases this button before issuing one Look click. The +/// physical release afterwards is swallowed, so it cannot become a chord. +pub fn force(t: *Trackpad, stage: f32) ?u8 { + if (stage < 2 or t.forced or t.button == null or t.button == 3) return null; + t.forced = true; + return t.button; +} + +pub fn rotate(t: *Trackpad, degrees: f32, phase: u32) i32 { + if (phase == 1 or phase == 3) { + t.rotation = 0; + t.rotation_total = 0; + } + if (phase == 3 or !std.math.isFinite(degrees)) return 0; + if (t.gesture == .pinch) return 0; + t.rotation_total += std.math.clamp(degrees, -640, 640); + if (@abs(t.rotation_total) >= 3) t.gesture = .rotate; + const next = t.rotation + std.math.clamp(degrees, -640, 640); + const ticks: i32 = @intFromFloat(@trunc(next / 10)); + t.rotation = next - @as(f32, @floatFromInt(ticks)) * 10; + return ticks; +} + +/// Ignore small magnification noise, especially while twisting. Once a +/// deliberate pinch wins, half the logarithmic gain makes fine zoom easier. +pub fn magnify(t: *Trackpad, size: f32, scale: f32, phase: u32) ?f32 { + if (phase == 1 or t.pinch_base == 0) { + t.pinch_base = size; + t.pinch_total = 1; + } + if (phase == 3) { + t.pinch_base = 0; + if (t.gesture == .pinch) t.gesture = .none; + return null; + } + if (t.gesture == .rotate or !std.math.isFinite(scale) or scale <= 0) return null; + t.pinch_total = std.math.clamp(t.pinch_total * scale, 0.01, 100); + if (t.gesture == .none) { + if (t.pinch_total > 1 / @as(f32, 1.1) and t.pinch_total < 1.1) return null; + t.gesture = .pinch; + } + return std.math.clamp(t.pinch_base * @sqrt(t.pinch_total), 8, 72); +} + +pub fn pinch(size: f32, scale: f32) f32 { + if (!std.math.isFinite(scale) or scale <= 0) return size; + return std.math.clamp(size * scale, 8, 72); +} + +test "Mac trackpad multi-finger buttons stay latched after the fingers lift" { + var t: Trackpad = .{}; + try std.testing.expectEqual(@as(u8, 3), t.press(3)); // real mouse + try std.testing.expectEqual(@as(?u8, 3), t.release(3)); + for ([_]usize{ 2, 3 }) |n| { + t.fingers = n; + try std.testing.expectEqual(@as(u8, 2), t.press(3)); + t.fingers = 0; + try std.testing.expectEqual(@as(?u8, 2), t.release(3)); + } +} + +test "Mac trackpad force click upgrades Exec once without a paste chord or stray release" { + var t: Trackpad = .{ .fingers = 2 }; + try std.testing.expectEqual(@as(u8, 2), t.press(3)); + try std.testing.expect(t.force(1) == null); + try std.testing.expectEqual(@as(?u8, 2), t.force(2)); + try std.testing.expect(t.force(2) == null); + try std.testing.expect(t.release(3) == null); + t.fingers = 1; + try std.testing.expectEqual(@as(u8, 1), t.press(1)); + try std.testing.expectEqual(@as(?u8, 1), t.release(1)); +} + +test "Mac trackpad rotate and pinch reject invalid input and reset cancelled gestures" { + var t: Trackpad = .{}; + try std.testing.expectEqual(@as(i32, 0), t.rotate(7, 1)); + try std.testing.expectEqual(@as(i32, 1), t.rotate(5, 0)); + try std.testing.expectEqual(@as(i32, -1), t.rotate(-12, 0)); + try std.testing.expectEqual(@as(i32, 0), t.rotate(9, 3)); + try std.testing.expectEqual(@as(f32, 0), t.rotation); + try std.testing.expectEqual(@as(f32, 18), pinch(18, 1)); + try std.testing.expectEqual(@as(f32, 36), pinch(18, 2)); + try std.testing.expectEqual(@as(f32, 72), pinch(18, 100)); + try std.testing.expectEqual(@as(f32, 18), pinch(18, std.math.nan(f32))); +} + +test "trackpad pinch ignores twist noise and uses gentler deliberate zoom" { + var t: Trackpad = .{}; + t.countFingers(2); + try std.testing.expect(t.magnify(18, 1, 1) == null); + for (0..5) |_| try std.testing.expect(t.magnify(18, 1.01, 0) == null); + _ = t.rotate(7, 1); + try std.testing.expect(t.magnify(18, 1.3, 0) == null); + t.countFingers(0); + t.countFingers(2); + const zoom = t.magnify(18, 1.2, 1) orelse return error.PinchNotRecognized; + try std.testing.expect(zoom > 18 and zoom < 20.5); + try std.testing.expectEqual(@as(i32, 0), t.rotate(30, 1)); + try std.testing.expect(t.magnify(zoom, 1, 3) == null); +} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 4e1f76dc..60cc6112 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -15,6 +15,7 @@ const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); const deck = @import("deck.zig"); const pet = @import("pet.zig"); +const Trackpad = @import("Trackpad.zig"); const JumpTrail = @import("../jump_trail.zig"); const Art = @import("../Art.zig"); const fonts = @import("../fonts.zig"); // the fallback faces @@ -576,6 +577,8 @@ const Gui = struct { words: Words = .{}, touch: Touch = .{}, + /// A Mac trackpad's gestures (macos_trackpad.m decodes them). + trackpad: Trackpad = .{}, /// The workspace tag's pet (Pet), on the window's own clock. pet_state: pet.State = .{}, /// The cursor's jump trail (JumpTrail), on the window's own clock. @@ -613,6 +616,8 @@ const Gui = struct { /// A touchpad's fraction toward the next turn sent to a program that /// owns the wheel (terminal.ownsWheel). program_wheel: f32 = 0, + /// A trackpad's horizontal fraction toward the next turn (wheelAt). + program_wheel_x: f32 = 0, glide: Glide = .{}, /// PARDES_FRAMES_DEMO: the timedemo (its script's steps), its next step /// and when it started; null when none runs. @@ -942,6 +947,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di } _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI", "1"); // SDL_HINT_JOYSTICK_HIDAPI _ = c.SDL_SetHint("SDL_JOYSTICK_HIDAPI_STEAMDECK", "1"); // ..._STEAMDECK + if (comptime builtin.os.tag == .macos) _ = c.SDL_SetHint(c.SDL_HINT_MAC_SCROLL_MOMENTUM, "1"); if (!c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_GAMEPAD)) { log.err("SDL_Init: {s}", .{c.SDL_GetError()}); return error.SdlInit; @@ -987,6 +993,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di return error.SdlInit; }; var window_slot: ?*c.SDL_Window = window; + if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); defer if (window_slot) |open| c.SDL_DestroyWindow(open); if (want_at) |at| _ = c.SDL_SetWindowPosition(window, at[0], at[1]); updateDisplayScale(window); @@ -1228,6 +1235,7 @@ fn closeWindow(g: *Gui) void { /// size the last one had. False when the display will not give one. fn reopenWindow(g: *Gui) bool { const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false; + if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window); if (g.soft_present) { g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse { c.SDL_DestroyWindow(window); @@ -2022,6 +2030,12 @@ const Input = struct { }; fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { + if (comptime builtin.os.tag == .macos) { + if (sev.type == c.ui_macos_trackpad_event_type()) { + dispatchTrackpad(g, in, @ptrCast(@alignCast(sev))); + return; + } + } // An input's time, for its latency to the frame that answers it // (FrameStats): SDL's stamp, moved onto the monotonic clock. switch (sev.type) { @@ -2066,21 +2080,7 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { c.SDLK_MINUS, c.SDLK_UNDERSCORE, c.SDLK_KP_MINUS => -font_px_step, else => 0, }; - if (step != 0) { - const want = std.math.clamp(g.px + step, font_px_min, font_px_max); - if (want != g.px) { - g.px = want; - // A client's view is sized by its next loop, as its input. - if (in.remote) |r| { - refitFont(g, null); - r.link.dirty = true; - } else { - refitFont(g, in.core); - observeGuiFont(g, in.core); - } - } - return; - } + if (step != 0) return setFontPx(g, in, std.math.clamp(g.px + step, font_px_min, font_px_max)); keyDown(in, sev.key.key, sev.key.mod); }, c.SDL_EVENT_KEY_UP => { @@ -2102,7 +2102,11 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { }, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => { const b = sev.button; - const button: pardes.Mouse.Button = switch (b.button) { + const raw_button = if (comptime builtin.os.tag == .macos) + (if (b.down) g.trackpad.press(b.button) else g.trackpad.release(b.button) orelse return) + else + b.button; + const button: pardes.Mouse.Button = switch (raw_button) { 1 => .left, 2 => .middle, 3 => .right, @@ -2120,7 +2124,7 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { }, c.SDL_EVENT_MOUSE_MOTION => { const m = sev.motion; - const held: ?pardes.Mouse.Button = if ((m.state & c.SDL_BUTTON_LMASK) != 0) + const physical_held: ?pardes.Mouse.Button = if ((m.state & c.SDL_BUTTON_LMASK) != 0) .left else if ((m.state & c.SDL_BUTTON_MMASK) != 0) .middle @@ -2128,6 +2132,16 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { .right else null; + // A trackpad's latched button (Trackpad.press), not SDL's. + const held: ?pardes.Mouse.Button = if (comptime builtin.os.tag == .macos) + (if (g.trackpad.forced) null else if (g.trackpad.button) |b| switch (b) { + 1 => .left, + 2 => .middle, + 3 => .right, + else => physical_held, + } else physical_held) + else + physical_held; const mc = pointAt(g, in.core, m.x, m.y); in.post(.{ .mouse = pointerMouse(held orelse .none, if (held != null) .drag else .motion, mc, pointerMods()) }); }, @@ -2139,6 +2153,9 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { }, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP, c.SDL_EVENT_FINGER_CANCELED => { const f = sev.tfinger; + // Indirect Mac touches are decoded by AppKit at the pointer, + // never as absolute positions across the window. + if (comptime builtin.os.tag == .macos) if (f.touchID == c.SDL_MOUSE_TOUCHID) return; const finger: Finger = .{ .kind = switch (sev.type) { c.SDL_EVENT_FINGER_DOWN => .down, @@ -2159,6 +2176,8 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { const fch: f32 = @floatFromInt(g.cell_h); handleFinger(&g.touch, in, finger, win_w, win_h, fcw, fch, @floatFromInt(g.tagline_width)); }, + // The window's font size; a Linux touchpad's pinch stays unused. + c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => if (comptime builtin.os.tag == .macos) setFontPx(g, in, Trackpad.pinch(g.px, sev.pinch.scale)), c.SDL_EVENT_GAMEPAD_ADDED => { if (g.gamepad == null) g.gamepad = c.SDL_OpenGamepad(sev.gdevice.which); }, @@ -2391,20 +2410,91 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { } } } - if (w.x != 0) in.post(.{ .mouse = .{ - .button = if (w.x > 0) .wheel_right else .wheel_left, - .kind = .press, - .col = mc.col, - .row = mc.row, - .tag_hit = mc.tag_hit, - .body_hit = mc.body_hit, - .ctrl = w.mods.ctrl, - .shift = w.mods.shift, - .alt = w.mods.alt, - } }); + var horizontal: i32 = if (w.x == 0 or !std.math.isFinite(w.x)) 0 else if (w.x > 0) 1 else -1; + if (w.precise and std.math.isFinite(w.x)) { + g.program_wheel_x += std.math.clamp(w.x, -64, 64); + horizontal = @intFromFloat(@trunc(g.program_wheel_x)); + g.program_wheel_x -= @floatFromInt(horizontal); + } + while (horizontal != 0) { + in.post(.{ .mouse = .{ + .button = if (horizontal > 0) .wheel_right else .wheel_left, + .kind = .press, + .col = mc.col, + .row = mc.row, + .tag_hit = mc.tag_hit, + .body_hit = mc.body_hit, + .ctrl = w.mods.ctrl, + .shift = w.mods.shift, + .alt = w.mods.alt, + } }); + horizontal += if (horizontal > 0) -1 else 1; + } } -const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, mods: PointerMods = .{} }; +/// `precise`: a Mac trackpad's columns (dispatchTrackpad), whose +/// horizontal fraction is kept toward the next turn. +const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, precise: bool = false, mods: PointerMods = .{} }; + +/// The window's font at `want` pixels: a key's step, a pinch. A client's +/// view is sized by its next loop, as its input. +fn setFontPx(g: *Gui, in: *Input, want: f32) void { + if (want == g.px) return; + g.px = want; + if (in.remote) |r| { + refitFont(g, null); + r.link.dirty = true; + } else { + refitFont(g, in.core); + observeGuiFont(g, in.core); + } +} + +/// A Mac trackpad's gesture, decoded by macos_trackpad.m (Trackpad.zig's +/// policy): fingers, a pinch's zoom, a swipe's Back/Forward, a rotation's +/// n/N, a force click's Look, and a two-finger scroll by the pixel. +fn dispatchTrackpad(g: *Gui, in: *Input, ev: *const c.UITrackpadEvent) void { + g.input_seen = true; + switch (ev.kind) { + c.UI_TRACKPAD_FINGERS => g.trackpad.countFingers(@intCast(@max(ev.fingers, 0))), + c.UI_TRACKPAD_PINCH => if (g.trackpad.magnify(g.px, ev.a, ev.phase)) |want| setFontPx(g, in, want), + c.UI_TRACKPAD_HISTORY => { + if (ev.a == 0 or !std.math.isFinite(ev.a)) return; + const back = ev.a < 0; + const jumps = &in.core.view().jumps; + const can_jump = jumps.n > 0 and (if (back) jumps.cur > 0 else jumps.cur + 1 < jumps.n); + in.post(.{ .command = if (back) "Back" else "Forward" }); + if (comptime builtin.os.tag == .macos) if (can_jump) c.ui_macos_trackpad_haptic(); + }, + c.UI_TRACKPAD_ROTATE => { + const pane = in.core.panes[in.core.view().active] orelse return; + // Search-step keys never become text in insert/raw mode. + if (pane.body.mode != .normal) return; + var ticks = g.trackpad.rotate(ev.a, ev.phase); + while (ticks != 0) { + in.post(.{ .key = .{ .cp = if (ticks > 0) 'N' else 'n' } }); + if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_haptic(); + ticks += if (ticks > 0) -1 else 1; + } + }, + c.UI_TRACKPAD_PRESSURE => { + const previous = g.trackpad.force(ev.a) orelse return; + const mc = mouseCell(g, in.core, ev.x, ev.y); + in.post(.{ .mouse = pointerMouse(if (previous == 2) .middle else .left, .release, mc, pointerMods()) }); + in.post(.{ .mouse = pointerMouse(.right, .press, mc, pointerMods()) }); + in.post(.{ .mouse = pointerMouse(.right, .release, mc, pointerMods()) }); + }, + c.UI_TRACKPAD_SCROLL => { + const mc = pointAt(g, in.core, ev.x, ev.y); + // AppKit reports points; the grid is measured in backing pixels. + const geometry = windowGeometry(g.window); + const rows = ev.b * geometry.pixel_h / geometry.window_h / @as(f32, @floatFromInt(g.cell_h)); + const cols = -ev.a * geometry.pixel_w / geometry.window_w / @as(f32, @floatFromInt(g.cell_w)); + wheelAt(g, in, .{ .x = cols, .y = rows, .precise = true, .mods = pointerMods() }, mc); + }, + else => {}, + } +} /// The modifiers held with a pointer event, as the core's Mouse carries them. const PointerMods = struct { ctrl: bool = false, shift: bool = false, alt: bool = false, super: bool = false }; @@ -2652,10 +2742,11 @@ const Shell = struct { fn split(s: *Shell, sev: *const c.SDL_Event) bool { if (sev.type != c.SDL_EVENT_USER) s.mail_only = false; if (!s.peers.recording) return false; - switch (sev.type) { + const native_gesture = if (comptime builtin.os.tag == .macos) sev.type == c.ui_macos_trackpad_event_type() else false; + if (!native_gesture) switch (sev.type) { c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_TEXT_INPUT, c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP, c.SDL_EVENT_MOUSE_MOTION, c.SDL_EVENT_MOUSE_WHEEL, c.SDL_EVENT_WINDOW_FOCUS_GAINED, c.SDL_EVENT_WINDOW_FOCUS_LOST, c.SDL_EVENT_WINDOW_MOUSE_LEAVE, c.SDL_EVENT_FINGER_DOWN, c.SDL_EVENT_FINGER_MOTION, c.SDL_EVENT_FINGER_UP => {}, else => return false, - } + }; if (s.took_input) { s.held = sev.*; return true; @@ -8858,3 +8949,32 @@ test "compact tag layers fill available width and clip at their physical edge" { try std.testing.expectApproxEqAbs(@as(f32, 0), instances[4].x1, 0.0001); try std.testing.expectApproxEqAbs(@as(f32, 6) / atlas_w, instances[4].u1 - instances[4].u0, 0.0001); } + +test "trackpad rotation never types search keys into an insert-mode file or raw terminal" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); + defer core.deinit(); + _ = try core.setTestFile("unchanged\n"); + var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; + defer client.deinit(); + var in: Input = .{ .core = core, .remote = &client }; + var g: Gui = undefined; + g.trackpad = .{}; + var ev: c.UITrackpadEvent = std.mem.zeroes(c.UITrackpadEvent); + ev.kind = c.UI_TRACKPAD_ROTATE; + ev.a = 20; + const pane = core.panes[core.view().active].?; + pane.body.mode = .insert; + dispatchTrackpad(&g, &in, &ev); + pane.body.mode = .tty; + dispatchTrackpad(&g, &in, &ev); + try std.testing.expectEqual(@as(usize, 0), client.pending.items.len); + ev.kind = c.UI_TRACKPAD_HISTORY; + ev.a = -1; + dispatchTrackpad(&g, &in, &ev); + ev.a = 1; + dispatchTrackpad(&g, &in, &ev); + try std.testing.expectEqual(@as(usize, 2), client.pending.items.len); + try std.testing.expectEqualStrings("Back", client.pending.items[0].command); + try std.testing.expectEqualStrings("Forward", client.pending.items[1].command); +} diff --git a/src/gui/macos_trackpad.h b/src/gui/macos_trackpad.h new file mode 100644 index 00000000..f5266084 --- /dev/null +++ b/src/gui/macos_trackpad.h @@ -0,0 +1,21 @@ +#ifndef PARDES_MACOS_TRACKPAD_H +#define PARDES_MACOS_TRACKPAD_H +#include <SDL3/SDL.h> + +enum { UI_TRACKPAD_FINGERS = 1, UI_TRACKPAD_PRESSURE, UI_TRACKPAD_ROTATE, + UI_TRACKPAD_PINCH, UI_TRACKPAD_SCROLL, UI_TRACKPAD_HISTORY }; +/* Same prefix as SDL_UserEvent; the rest lives inside SDL_Event's storage. */ +typedef struct { + Uint32 type, reserved; + Uint64 timestamp; + SDL_WindowID windowID; + int kind; + float x, y, a, b; + Uint32 phase; + int fingers; +} UITrackpadEvent; + +Uint32 ui_macos_trackpad_event_type(void); +void ui_macos_trackpad_attach(SDL_Window *window); +void ui_macos_trackpad_haptic(void); +#endif diff --git a/src/gui/macos_trackpad.m b/src/gui/macos_trackpad.m new file mode 100644 index 00000000..64806b9e --- /dev/null +++ b/src/gui/macos_trackpad.m @@ -0,0 +1,176 @@ +/* AppKit input missing from SDL's public event stream. The SDL view keeps its + * drawing, keyboard and mouse responder chain; only trackpad methods change. */ +#import <Cocoa/Cocoa.h> +#import <objc/runtime.h> +#include "macos_trackpad.h" +#include <string.h> +#include <math.h> + +static char window_key; +static char swipe_key, axis_key, suppress_momentum_key; +static Uint32 gesture_type; +static Class trackpad_class; +_Static_assert(sizeof(UITrackpadEvent) <= sizeof(SDL_Event), "trackpad event fits SDL"); + +Uint32 ui_macos_trackpad_event_type(void) { return gesture_type; } + +void ui_macos_trackpad_haptic(void) +{ + [[NSHapticFeedbackManager defaultPerformer] + performFeedbackPattern:NSHapticFeedbackPatternAlignment + performanceTime:NSHapticFeedbackPerformanceTimeNow]; +} + +static void send_gesture(NSView *view, NSEvent *event, int kind, float a, float b, int fingers) +{ + SDL_Window *window = (SDL_Window *)[objc_getAssociatedObject(view, &window_key) pointerValue]; + if (!window) return; + NSPoint point = [view convertPoint:event.locationInWindow fromView:nil]; + SDL_Event packet = {0}; + UITrackpadEvent decoded = {0}; + UITrackpadEvent *out = &decoded; + out->type = gesture_type; + out->timestamp = SDL_GetTicksNS(); + out->windowID = SDL_GetWindowID(window); + out->kind = kind; + out->x = point.x; + out->y = view.isFlipped ? point.y : NSHeight(view.bounds) - point.y; + out->a = a; + out->b = b; + out->fingers = fingers; + /* Stable decoded phases, independent of NSEventPhase's bit values. */ + if (kind == UI_TRACKPAD_ROTATE || kind == UI_TRACKPAD_PINCH || kind == UI_TRACKPAD_SCROLL) + out->phase = event.phase == NSEventPhaseBegan ? 1 : + event.phase == NSEventPhaseEnded ? 2 : + event.phase == NSEventPhaseCancelled ? 3 : 0; + memcpy(&packet, &decoded, sizeof(decoded)); + SDL_PushEvent(&packet); +} + +static void touches(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_FINGERS, 0, 0, + (int)[event touchesMatchingPhase:NSTouchPhaseTouching inView:nil].count); + /* Do not also emit SDL's absolute finger coordinates: those describe the + * trackpad surface, not a position inside this window. Scroll comes from + * scrollWheel:, including the system's momentum events. */ +} + +static void pressure(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_PRESSURE, event.stage, 0, 0); +} + +static void rotate(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_ROTATE, event.rotation, 0, 0); +} + +static void magnify(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + send_gesture(view, event, UI_TRACKPAD_PINCH, 1 + event.magnification, 0, 0); +} + +static void swipe(NSView *view, SEL selector, NSEvent *event) +{ + (void)selector; + /* NSEvent swipe deltaX: negative is right/back, positive left/forward. */ + if (event.deltaX != 0) + send_gesture(view, event, UI_TRACKPAD_HISTORY, event.deltaX, 0, 0); +} + +static void scroll(NSView *view, SEL selector, NSEvent *event) +{ + if (event.hasPreciseScrollingDeltas) { + if (event.phase == NSEventPhaseBegan) { + objc_setAssociatedObject(view, &axis_key, @0, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(view, &suppress_momentum_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + if ([objc_getAssociatedObject(view, &swipe_key) boolValue]) return; + if ([objc_getAssociatedObject(view, &suppress_momentum_key) boolValue]) return; + NSInteger axis = [objc_getAssociatedObject(view, &axis_key) integerValue]; + CGFloat x = fabs(event.scrollingDeltaX), y = fabs(event.scrollingDeltaY); + if (!axis && x + y >= 3) { + if (x > y * 1.5) axis = 1; + else if (y > x * 1.5) axis = 2; + objc_setAssociatedObject(view, &axis_key, @(axis), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + if (axis == 1 && (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseChanged) && + !(event.modifierFlags & (NSEventModifierFlagShift | NSEventModifierFlagOption)) && + [NSEvent isSwipeTrackingFromScrollEventsEnabled]) { + // AppKit supplies Safari-style completion/cancellation and honours + // the user's Swipe Between Pages preference. No guessed velocity. + objc_setAssociatedObject(view, &swipe_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + __weak NSView *weak_view = view; + __block BOOL cancelled = NO; + __block BOOL previewed = NO; + [event trackSwipeEventWithOptions:NSEventSwipeTrackingLockDirection | NSEventSwipeTrackingClampGestureAmount + dampenAmountThresholdMin:-1 max:1 + usingHandler:^(CGFloat amount, NSEventPhase phase, BOOL complete, BOOL *stop) { + NSView *target = weak_view; + if (!target) { *stop = YES; return; } + if (phase == NSEventPhaseCancelled) cancelled = YES; + // An early notch says the swipe is approaching the + // shorter commit distance, while the fingers still move. + if (!cancelled && !complete && !previewed && fabs(amount) >= 0.12) { + previewed = YES; + ui_macos_trackpad_haptic(); + } + const BOOL commit = !cancelled && phase != NSEventPhaseNone && fabs(amount) >= 0.25; + if (!commit && !cancelled && phase != NSEventPhaseEnded && !complete) return; + objc_setAssociatedObject(target, &swipe_key, @NO, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(target, &suppress_momentum_key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + // Commit during the physical swipe. AppKit's later + // animation to +/-1 must not set our trigger distance. + *stop = YES; + if (commit) + send_gesture(target, event, UI_TRACKPAD_HISTORY, amount > 0 ? 1 : -1, 0, 0); + }]; + return; + } + send_gesture(view, event, UI_TRACKPAD_SCROLL, + event.scrollingDeltaX, event.scrollingDeltaY, 0); + } else { + /* An ordinary mouse wheel retains SDL's discrete-notch handling. */ + [[view nextResponder] scrollWheel:event]; + } + (void)selector; +} + +void ui_macos_trackpad_attach(SDL_Window *window) +{ + NSWindow *native = (__bridge NSWindow *)SDL_GetPointerProperty( + SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL); + NSView *view = native.contentView; + if (!view) return; + if (!gesture_type) { + /* SDL_EVENT_USER is already the shell's queue wake. */ + Uint32 first = SDL_RegisterEvents(2); + if (!first) return; + gesture_type = first + 1; + } + if (!trackpad_class) { + trackpad_class = objc_allocateClassPair(object_getClass(view), "PardesSDLTrackpadView", 0); + if (!trackpad_class) return; + SEL touch_selectors[] = { @selector(touchesBeganWithEvent:), @selector(touchesMovedWithEvent:), + @selector(touchesEndedWithEvent:), @selector(touchesCancelledWithEvent:) }; + for (unsigned i = 0; i < 4; ++i) + class_addMethod(trackpad_class, touch_selectors[i], (IMP)touches, "v@:@"); + class_addMethod(trackpad_class, @selector(pressureChangeWithEvent:), (IMP)pressure, "v@:@"); + class_addMethod(trackpad_class, @selector(rotateWithEvent:), (IMP)rotate, "v@:@"); + class_addMethod(trackpad_class, @selector(magnifyWithEvent:), (IMP)magnify, "v@:@"); + class_addMethod(trackpad_class, @selector(swipeWithEvent:), (IMP)swipe, "v@:@"); + class_addMethod(trackpad_class, @selector(scrollWheel:), (IMP)scroll, "v@:@"); + objc_registerClassPair(trackpad_class); + } + objc_setAssociatedObject(view, &window_key, [NSValue valueWithPointer:window], OBJC_ASSOCIATION_RETAIN_NONATOMIC); + object_setClass(view, trackpad_class); + view.allowedTouchTypes = NSTouchTypeMaskIndirect; + view.wantsRestingTouches = YES; + view.pressureConfiguration = [[NSPressureConfiguration alloc] + initWithPressureBehavior:NSPressureBehaviorPrimaryDeepClick]; +} diff --git a/test/macos_trackpad.m b/test/macos_trackpad.m new file mode 100644 index 00000000..03c9d311 --- /dev/null +++ b/test/macos_trackpad.m @@ -0,0 +1,165 @@ +/* Exercise the real AppKit adapter without a window or a physical trackpad. + * Only SDL's event queue and window lookup are replaced with test doubles. */ +#import <Cocoa/Cocoa.h> +#include "../src/gui/macos_trackpad.m" +#include <assert.h> + +static id native_window; +static SDL_Event queued[32]; +static unsigned count; +SDL_PropertiesID SDL_GetWindowProperties(SDL_Window *window) { (void)window; return 1; } +void *SDL_GetPointerProperty(SDL_PropertiesID props, const char *name, void *fallback) +{ (void)props; (void)name; (void)fallback; return (__bridge void *)native_window; } +Uint32 SDL_RegisterEvents(int n) { (void)n; return SDL_EVENT_USER; } +Uint64 SDL_GetTicksNS(void) { return 100; } +SDL_WindowID SDL_GetWindowID(SDL_Window *window) { (void)window; return 42; } +bool SDL_PushEvent(SDL_Event *event) { assert(count < 32); queued[count++] = *event; return true; } + +@interface FakeNativeWindow : NSObject +@property NSView *contentView; +@end +@implementation FakeNativeWindow +@end + +@interface HapticSpy : NSObject <NSHapticFeedbackPerformer> +@property NSUInteger pulses; +@end +@implementation HapticSpy +- (void)performFeedbackPattern:(NSHapticFeedbackPattern)pattern performanceTime:(NSHapticFeedbackPerformanceTime)time +{ + assert(pattern == NSHapticFeedbackPatternAlignment); + assert(time == NSHapticFeedbackPerformanceTimeNow); + self.pulses++; +} +@end +static HapticSpy *haptic_spy; +static id fake_performer(id receiver, SEL selector) +{ (void)receiver; (void)selector; return haptic_spy; } +static BOOL swipe_enabled(id receiver, SEL selector) +{ (void)receiver; (void)selector; return YES; } + +@interface TrackpadEvent : NSEvent +@property NSUInteger fingerCount; +@property NSEventPhase testPhase; +@property BOOL precise; +@property BOOL horizontal, cancelled; +@property CGFloat progress, discreteDirection; +@end +@implementation TrackpadEvent +- (NSPoint)locationInWindow { return NSMakePoint(25, 40); } +- (NSEventPhase)phase { return self.testPhase; } +- (BOOL)hasPreciseScrollingDeltas { return self.precise; } +- (NSEventPhase)momentumPhase { return NSEventPhaseNone; } +- (NSEventModifierFlags)modifierFlags { return 0; } +- (CGFloat)deltaX { return self.discreteDirection; } +- (CGFloat)scrollingDeltaX { return self.horizontal ? 20 : 3; } +- (CGFloat)scrollingDeltaY { return self.horizontal ? 1 : 20; } +- (void)trackSwipeEventWithOptions:(NSEventSwipeTrackingOptions)options + dampenAmountThresholdMin:(CGFloat)min max:(CGFloat)max + usingHandler:(void (^)(CGFloat, NSEventPhase, BOOL, BOOL *))handler +{ + (void)options; assert(min == -1 && max == 1); + BOOL stop = NO; + handler(0.13, NSEventPhaseChanged, NO, &stop); + handler(0.18, NSEventPhaseChanged, NO, &stop); + if (self.cancelled) handler(self.progress, NSEventPhaseCancelled, NO, &stop); + else handler(self.progress, NSEventPhaseChanged, NO, &stop); + if (!stop) handler(0, NSEventPhaseEnded, NO, &stop); + if (!stop) handler(1, NSEventPhaseNone, YES, &stop); +} +- (NSInteger)stage { return 2; } +- (float)rotation { return 12; } +- (CGFloat)magnification { return 0.25; } +- (NSSet<NSTouch *> *)touchesMatchingPhase:(NSTouchPhase)phase inView:(NSView *)view +{ + (void)phase; (void)view; + NSMutableSet *result = [NSMutableSet set]; + for (NSUInteger i = 0; i < self.fingerCount; ++i) [result addObject:[NSObject new]]; + return (NSSet<NSTouch *> *)result; +} +@end + +int main(void) +{ + @autoreleasepool { + haptic_spy = [HapticSpy new]; + Method performer = class_getClassMethod([NSHapticFeedbackManager class], @selector(defaultPerformer)); + IMP original = method_setImplementation(performer, (IMP)fake_performer); + FakeNativeWindow *window = [FakeNativeWindow new]; + NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 400, 300)]; + window.contentView = view; + native_window = window; + ui_macos_trackpad_attach((SDL_Window *)1); + assert([NSStringFromClass(view.class) isEqualToString:@"PardesSDLTrackpadView"]); + assert(view.wantsRestingTouches); + TrackpadEvent *event = [TrackpadEvent new]; + event.fingerCount = 3; + [view touchesBeganWithEvent:event]; + UITrackpadEvent *packet = (UITrackpadEvent *)&queued[0]; + assert(packet->kind == UI_TRACKPAD_FINGERS && packet->fingers == 3); + assert(packet->windowID == 42 && packet->x == 25 && packet->y == 260); + event.precise = YES; + event.testPhase = NSEventPhaseBegan; + [view scrollWheel:event]; + packet = (UITrackpadEvent *)&queued[1]; + assert(packet->kind == UI_TRACKPAD_SCROLL && packet->a == 3 && packet->b == 20 && packet->phase == 1); + // System momentum has no finger phase. It must keep reaching SDL. + event.testPhase = NSEventPhaseNone; + [view scrollWheel:event]; + assert(((UITrackpadEvent *)&queued[2])->kind == UI_TRACKPAD_SCROLL); + [view pressureChangeWithEvent:event]; + assert(((UITrackpadEvent *)&queued[3])->kind == UI_TRACKPAD_PRESSURE); + assert(((UITrackpadEvent *)&queued[3])->a == 2); + [view rotateWithEvent:event]; + assert(((UITrackpadEvent *)&queued[4])->kind == UI_TRACKPAD_ROTATE); + assert(((UITrackpadEvent *)&queued[4])->a == 12); + [view magnifyWithEvent:event]; + assert(((UITrackpadEvent *)&queued[5])->kind == UI_TRACKPAD_PINCH); + assert(((UITrackpadEvent *)&queued[5])->a == 1.25); + event.discreteDirection = -1; + [view swipeWithEvent:event]; + assert(((UITrackpadEvent *)&queued[6])->kind == UI_TRACKPAD_HISTORY); + assert(((UITrackpadEvent *)&queued[6])->a == -1); + Method preference = class_getClassMethod([NSEvent class], @selector(isSwipeTrackingFromScrollEventsEnabled)); + IMP old_preference = method_setImplementation(preference, (IMP)swipe_enabled); + event.horizontal = YES; + event.progress = 0.25; + event.testPhase = NSEventPhaseBegan; + [view scrollWheel:event]; + assert(count == 8); + assert(haptic_spy.pulses == 1); // one early cue despite multiple progress events + assert(((UITrackpadEvent *)&queued[7])->kind == UI_TRACKPAD_HISTORY); + assert(((UITrackpadEvent *)&queued[7])->a == 1); + event.cancelled = YES; + event.progress = 1; // even later completion cannot undo cancellation + [view scrollWheel:event]; + assert(count == 8); // a cancelled swipe never navigates + event.cancelled = NO; + event.progress = 0.20; + [view scrollWheel:event]; + assert(count == 8); // below threshold never commits on release/animation + event.horizontal = NO; + [view scrollWheel:event]; + event.horizontal = YES; + event.testPhase = NSEventPhaseChanged; + [view scrollWheel:event]; + assert(((UITrackpadEvent *)&queued[9])->kind == UI_TRACKPAD_SCROLL); + event.testPhase = NSEventPhaseBegan; + event.progress = -0.25; + [view scrollWheel:event]; + assert(count == 11); + assert(((UITrackpadEvent *)&queued[10])->a == -1); + event.testPhase = NSEventPhaseChanged; + [view scrollWheel:event]; + event.testPhase = NSEventPhaseNone; + [view scrollWheel:event]; + assert(count == 11); // remaining movement/momentum cannot jump twice + method_setImplementation(preference, old_preference); + NSUInteger before = haptic_spy.pulses; + ui_macos_trackpad_haptic(); + method_setImplementation(performer, original); + assert(haptic_spy.pulses == before + 1); + puts("PASS native SDL trackpad adapter: touches, momentum, pressure, rotation, pinch, history/cancellation, haptics"); + } + return 0; +} |
