summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/gui/Trackpad.zig142
-rw-r--r--src/gui/gui.zig182
-rw-r--r--src/gui/macos_trackpad.h21
-rw-r--r--src/gui/macos_trackpad.m176
4 files changed, 490 insertions, 31 deletions
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];
+}