diff options
Diffstat (limited to 'src/gui')
| -rw-r--r-- | src/gui/Trackpad.zig | 142 | ||||
| -rw-r--r-- | src/gui/gui.zig | 374 | ||||
| -rw-r--r-- | src/gui/macos_trackpad.h | 21 | ||||
| -rw-r--r-- | src/gui/macos_trackpad.m | 176 |
4 files changed, 664 insertions, 49 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 d3acf454..c12041c0 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -15,6 +15,7 @@ const file_watch = @import("../file_watch.zig"); const ShaderBuild = @import("../ShaderBuild.zig"); const deck = @import("deck.zig"); const Post = @import("Post.zig"); +const Trackpad = @import("Trackpad.zig"); const pet = @import("pet.zig"); const fonts = @import("../fonts.zig"); // the Font builtin's half of the seam const selection_pipe = @import("../selection_pipe.zig"); @@ -886,7 +887,6 @@ const Pty = struct { cmd: host_io.CommandWatch = .{}, }; - const RetiredShell = struct { pid: libc.pid_t = 0, kill_at: i64 = 0 }; const Queue = host_io.Inbox; @@ -1283,8 +1283,6 @@ test "GUI completion reset frees queued payloads and rejects late LSP workers" { try std.testing.expectEqual(@as(usize, 0), queue.take().len); } - - fn stopPipe() ![2]c_int { var fds: [2]c_int = undefined; if (libc.pipe(&fds) != 0) return error.PipeFailed; @@ -1295,7 +1293,6 @@ fn stopPipe() ![2]c_int { return fds; } - fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { while (true) { var fds = [_]libc.pollfd{ @@ -1312,8 +1309,6 @@ fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { } } - - test "GUI LSP query answers, and a newer one cancels it" { const gpa = std.testing.allocator; const io = std.testing.io; @@ -1338,7 +1333,6 @@ test "GUI LSP query answers, and a newer one cancels it" { try std.testing.expect(core.lsp_wait == null); } - test "GUI worker setup failures finish matching LSP and pipe requests" { const gpa = std.testing.allocator; var failing_vtable = std.testing.io.vtable.*; @@ -1436,6 +1430,8 @@ const Gui = struct { font_bytes: []u8 = &.{}, font_name: [255]u8 = @splat(0), font_name_len: u8 = 0, + remote_font_request: ?u64 = null, + trackpad: Trackpad = .{}, fallbacks: [max_fallback_fonts]?LoadedFallback = @splat(null), fallback_count: usize = 0, px: f32, @@ -1481,6 +1477,7 @@ 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, + program_wheel_x: f32 = 0, glide: Glide = .{}, /// PARDES_FRAMES_DEMO: the timedemo (FrameStats.named), its next step /// and when it started; null when none runs. @@ -1565,16 +1562,17 @@ const Gui = struct { /// device, the atlas, the font and the pipelines are every window's. The /// Gui holds the live window's; the others wait in `Shell.windows`. const window_fields = [_][:0]const u8{ - "window", "soft_renderer", "soft_texture", "soft_tex_w", "soft_tex_h", - "window_w", "window_h", "scroll_pane", "scroll_rect", "scroll_body_y", - "scroll_body_h", "scroll_held_px", "scroll_col", "scroll_row", "scroll_delta", - "scroll_lag", "scroll_edge", "scroll_edge_len", "scroll_notch", "program_wheel", - "glide", "pace_ns", "sel_glow", "hover_glow", "frame_arrival_ns", - "blink_due", "cursor_quad_alpha", "scene_tex", "scene_tex_w", "scene_tex_h", - "scene_failures", "scene_target_failed", "post", "pointer_present", "pointer_shape", - "pointer_mapped", "pointer_cell", "presented_images", "prepared_images", "touch", - "live_ctrl", "live_alt", "applied_window_opacity", "capture_tex", "capture_tex_w", - "capture_tex_h", "capture_xfer", "capture_xfer_size", "captured", "capture_dir", + "window", "soft_renderer", "soft_texture", "soft_tex_w", "soft_tex_h", + "window_w", "window_h", "scroll_pane", "scroll_rect", "scroll_body_y", + "scroll_body_h", "scroll_held_px", "scroll_col", "scroll_row", "scroll_delta", + "scroll_lag", "scroll_edge", "scroll_edge_len", "scroll_notch", "program_wheel", + "program_wheel_x", "glide", "pace_ns", "sel_glow", "hover_glow", + "frame_arrival_ns", "blink_due", "cursor_quad_alpha", "scene_tex", "scene_tex_w", + "scene_tex_h", "scene_failures", "scene_target_failed", "post", "pointer_present", + "pointer_shape", "pointer_mapped", "pointer_cell", "presented_images", "prepared_images", + "touch", "trackpad", "live_ctrl", "live_alt", "applied_window_opacity", + "capture_tex", "capture_tex_w", "capture_tex_h", "capture_xfer", "capture_xfer_size", + "captured", "capture_dir", }; const GuiWindow = blk: { @@ -1642,6 +1640,43 @@ fn acknowledgeGuiFont(g: *const Gui, core: *pardes.Pardes) void { _ = core.acknowledgeFont(guiFontName(g), size, .pixels); } +/// A replica's font is local raster state. It follows the remote request +/// without acknowledging or otherwise changing the replicated core. +fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator) bool { + const f = &core.settings.font; + const path = f.requested_path.get(); + const name = f.requested_name.get(); + if (path.len == 0 and name.len == 0) return false; + var hash = std.hash.Wyhash.init(0); + hash.update(path); + hash.update(name); + hash.update(std.mem.asBytes(&f.requested_size_hundredths)); + const request = hash.final(); + if (g.remote_font_request == request) return false; + g.remote_font_request = request; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const face = fonts.remote(arena.allocator(), path, name) orelse { + log.warn("remote font is not installed locally: {s}", .{name}); + return false; + }; + const bytes = filesystem.readFile(gpa, face.path) catch return false; + const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse { + gpa.free(bytes); + return false; + }; + c.ui_font_free(g.font); + if (g.font_bytes.len != 0) gpa.free(g.font_bytes); + g.font = font; + g.font_bytes = bytes; + if (f.requested_size_hundredths != 0) + g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100; + setGuiFontName(g, face.name); + refitFont(g, null); + log.info("remote font: {s} from {s}, {d} pixels", .{ guiFontName(g), face.path, g.px }); + return true; +} + fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { if (c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len))) |face| { g.fallbacks[0] = .{ .face = face }; @@ -2010,6 +2045,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; @@ -2055,6 +2091,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); @@ -2339,6 +2376,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); @@ -2685,7 +2723,7 @@ const Client = struct { core.frames.mark_render = core.frames.mark_update; r.draw(.{ .ctx = s, .f = present }); cl.link.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), false, cl.link.owed); + core.frames.record(pardes.FrameStats.nowNs(), r.animating(), cl.link.owed); core.present_skipped = skipped; core.needs_frame = needs; cl.link.drawn(s.presented); @@ -2716,6 +2754,8 @@ const OwnView = struct { fn run(v: *OwnView, core: *pardes.Pardes) anyerror!void { if (v.sev) |sev| return dispatch(v.g, v.in, sev); const g = v.g; + if (syncReplicaFont(g, core, v.s.gpa)) v.s.remote.?.link.dirty = true; + if (stepRemoteScroll(g, v.in, v.s.gpa)) v.s.remote.?.link.dirty = true; if (fitTaglineFont(g, core.settings.font.tagline_percent)) v.s.remote.?.link.dirty = true; const geom = windowCells(g); if (resizeOf(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) |ev| v.in.post(ev); @@ -2810,6 +2850,7 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ // session let it go to upgrade. The window stays as it is. while (true) { r.gmtoff = joined.gmtoff; + g.remote_font_request = null; const core = r.core(); shell.core = core; shell.gview = joined.view; @@ -2851,16 +2892,33 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ client.draw(&shell); drew = shell.presented; } + // Render-time motion belongs to this window. No daemon unit + // need arrive while a cursor lands or a focus glow fades. + const moving = r.animating() or g.sel_glow.fading or g.hover_glow.fading or g.post.animating(core.settings.shader_animation); + const minimized = !test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; + const blink = if (minimized) null else blinkNow(g, if (shell.surface) |frame| &frame.chrome else null); const predicting = r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0; var ms: c_int = if (test_mode) 16 else -1; if (demoDue(g)) |due| ms = if (ms < 0) due else @min(ms, due); if (predicting or link.owed) ms = if (ms < 0) frame_ms else @min(ms, frame_ms); + if (moving and !minimized) { + const frame_wait: c_int = @intCast(@max(1, (refreshNs(g) + std.time.ns_per_ms - 1) / std.time.ns_per_ms)); + ms = if (ms < 0) frame_wait else @min(ms, frame_wait); + } + if (blink) |b| { + const due: ?u64 = if (b.edge) refreshNs(g) else b.next_ns; + if (due) |ns| { + const wait: c_int = @intCast(@min(std.math.maxInt(c_int), ns / std.time.ns_per_ms + 1)); + ms = if (ms < 0) wait else @min(ms, wait); + } + } if (link.quietCheck()) |wait| ms = if (ms < 0) @intCast(wait) else @min(ms, @as(c_int, @intCast(wait))); // Idle, its frame drawn: the next input needs no copy taken. if (ms != 0) r.ready(); var sev = std.mem.zeroes(c.SDL_Event); g.input_seen = false; var got = c.SDL_WaitEventTimeout(&sev, ms); + const timed_out = !got; while (got) : (got = c.SDL_PollEvent(&sev)) { if (sev.type == c.SDL_EVENT_USER) continue; var one: OwnView = .{ .g = g, .in = &in, .s = &shell, .sev = &sev }; @@ -2875,6 +2933,7 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ _ = c.SDL_SetWindowTitle(g.window, "pardes"); } if (link.owed or r.echo.changed) link.dirty = true; + if (!minimized and (moving or (blink != null and (blink.?.edge or timed_out)))) link.dirty = true; if (r.diverged != null) link.quit = true; } if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); @@ -3473,6 +3532,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) { @@ -3564,7 +3629,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, @@ -3602,7 +3671,7 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { g.pad_x = m.x; g.pad_y = m.y; g.pointer_present = true; - 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 @@ -3610,6 +3679,15 @@ fn dispatch(g: *Gui, in: *Input, sev: *const c.SDL_Event) void { .right else null; + 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 = mouseCell(g, in.core, m.x, m.y) orelse { g.pointer_mapped = false; in.post(.pointer_leave); @@ -3636,6 +3714,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, @@ -3657,7 +3738,7 @@ 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)); }, - c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => in.post(.{ .pinch = sev.pinch.scale }), + c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => zoomTrackpad(g, in, sev.pinch.scale), c.SDL_EVENT_GAMEPAD_ADDED => { if (g.gamepad == null) g.gamepad = c.SDL_OpenGamepad(sev.gdevice.which); }, @@ -3968,13 +4049,16 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { while (g.program_wheel <= -1) : (g.program_wheel += 1) in.post(.{ .mouse = .{ .button = .wheel_up, .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 } }); } else if (in.remote != null) { - // ponytail: a replica client's wheel moves the view a - // whole row a turn, with no glide and no touchpad's - // fraction: its core's clock is the session's, which - // moves only as its units come. if (notchOf(w.y, w.integer_y)) |lines| { g.program_wheel = @floatFromInt(lines); - } else g.program_wheel = accumulateWheelDelta(g.program_wheel, w.y); + } else { + // Fractions are local raster state; whole rows are + // ordinary inputs, confirmed by the authority. + g.scroll_pane = id; + g.scroll_col = mc.col; + g.scroll_row = mc.row; + g.scroll_delta = accumulateWheelDelta(g.scroll_delta, w.y); + } while (g.program_wheel >= 1) : (g.program_wheel -= 1) in.post(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mc.col, .row = mc.row, .shift = true } }); while (g.program_wheel <= -1) : (g.program_wheel += 1) @@ -3999,20 +4083,118 @@ fn wheelAt(g: *Gui, in: *Input, w: WheelTurn, mc: MouseCell) void { in.post(.{ .mouse = .{ .button = .wheel_up, .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 } }); } } - 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, precise: bool = false, mods: PointerMods = .{} }; + +fn zoomTrackpad(g: *Gui, in: *Input, scale: f32) void { + const want = Trackpad.pinch(g.px, scale); + if (want == g.px) return; + g.px = want; + if (in.remote) |client| { + refitFont(g, null); + client.link.dirty = true; + } else { + refitFont(g, in.core); + if (in.core) |core| observeGuiFont(g, core); + } } -const WheelTurn = struct { x: f32 = 0, y: f32 = 0, integer_y: i32 = 0, mods: PointerMods = .{} }; +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| zoomTrackpad(g, in, want / g.px), + c.UI_TRACKPAD_HISTORY => { + if (ev.a == 0 or !std.math.isFinite(ev.a)) return; + const back = ev.a < 0; + const can_jump = if (in.core) |core| core.njumps > 0 and + (if (back) core.jcur > 0 else core.jcur + 1 < core.njumps) else false; + 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 => { + if (in.core) |core| { + const pane = core.panes[core.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) orelse g.pointer_cell orelse return; + 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 = mouseCell(g, in.core, ev.x, ev.y) orelse return; + g.pointer_present = true; + g.pointer_mapped = true; + g.pointer_cell = mc; + // 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 => {}, + } +} + +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; + core.panes[core.active].?.body.mode = .insert; + dispatchTrackpad(&g, &in, &ev); + core.panes[core.active].?.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); +} /// 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 }; @@ -4404,10 +4586,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, c.SDL_EVENT_PINCH_BEGIN, c.SDL_EVENT_PINCH_UPDATE => {}, else => return false, - } + }; if (s.took_input) { s.held = sev.*; return true; @@ -4561,7 +4744,7 @@ const Shell = struct { for (0..pardes.views.max) |i| { const k: u8 = @intCast(i); if (k != live and pardes.views.isOpen(s.core, k) and !pardes.views.isAway(s.core, k)) s.openAnotherWindow(k); - s.windowed |= @as(u8, 1) << @intCast(live); + s.windowed |= @as(u8, 1) << @intCast(live); } s.core.toView(live); s.follow(); @@ -4966,6 +5149,8 @@ fn pollFrame(ctx: ?*anyopaque) void { s.reconcilePtys(); const core = s.core; if (s.fs) |f| if (f.tick().pending) s.queue.push(.fs_ready); + // The authority owns its terminals even with its window closed. + pollCwds(core, s.ptys); const g = s.gui orelse { if (core.settings.window_opacity_pending) { var unchanged_opacity: u8 = 100; @@ -5008,7 +5193,6 @@ fn pollFrame(ctx: ?*anyopaque) void { refitFont(g, core); acknowledgeGuiFont(g, core); } - pollCwds(core, s.ptys); const geom = windowCells(g); if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g); stepScroll(g, core, s.gpa); @@ -5635,6 +5819,43 @@ fn pollCwds(core: *pardes.Pardes, ptys: *[pardes.MAX_PANES]?Pty) void { }; } +test "a detached GUI authority follows terminal directory changes with no window" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "child"); + var start_buf: [4096]u8 = undefined; + const start = start_buf[0..try tmp.dir.realPath(io, &start_buf)]; + var cwd_buf: [4096]u8 = undefined; + const expected = cwd_buf[0..try tmp.dir.realPathFile(io, "child", &cwd_buf)]; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + core.panes[0].?.shell_spoke = true; + _ = core.settings.shell.effective.set("/bin/sh"); + var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var ptys: [pardes.MAX_PANES]?Pty = @splat(null); + var gens: [pardes.MAX_PANES]u32 = @splat(1); + const rcs: host_io.Shell.PromptFiles = .{}; + var pipes: PipeTasks = .{}; + var watches: file_watch.Table = @splat(null); + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches }; + defer shell.shutdownPtys(); + const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80, null); + ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; + try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); + const until = std.Io.Clock.awake.now(io).toMilliseconds() + 2_000; + var actual: [4096]u8 = undefined; + while (std.Io.Clock.awake.now(io).toMilliseconds() < until) { + if (host_io.shellCwd(child.pid, &actual)) |cwd| if (std.mem.eql(u8, cwd, expected)) break; + try io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expectEqualStrings(expected, host_io.shellCwd(child.pid, &actual) orelse return error.MissingCwd); + pollFrame(&shell); + try std.testing.expectEqualStrings(expected, core.panes[0].?.cwd.owned); +} + fn accumulateWheelDelta(pending: f32, raw_y: f32) f32 { if (!std.math.isFinite(raw_y)) return pending; const next = pending - raw_y; @@ -6278,21 +6499,73 @@ fn resetScroll(g: *Gui) void { fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { stepGlide(g, core, gpa); - const id = g.scroll_pane orelse return; + var in: Input = .{ .core = core }; + _ = stepFractionalScroll(g, &in, gpa); +} + +fn stepRemoteScroll(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { + return stepFractionalScroll(g, in, gpa); +} + +test "detached trackpad scrolling keeps fractions local and queues whole rows for replication" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16 }); + defer core.deinit(); + _ = try core.setTestFile("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\neleven\ntwelve\nthirteen\nfourteen\nfifteen\nsixteen\nseventeen\neighteen\nnineteen\ntwenty\n"); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try core.render(arena.allocator()); + var client: Client = .{ .link = undefined, .io = std.testing.io, .gpa = gpa, .texts = .init(gpa) }; + defer client.deinit(); + var in: Input = .{ .core = core, .remote = &client }; + const id = core.active; + const r = core.rects[id]; + var g: Gui = undefined; + g.scroll_pane = id; + g.scroll_delta = 0.375; + g.scroll_lag = 0; + g.scroll_notch = 0; + g.scroll_edge = &.{}; + g.scroll_edge_len = 0; + g.glide = .{}; + g.scroll_col = r.x + config.GUTTER + 2; + g.scroll_row = core.bodyTop(core.panes[id].?, r) + 2; + defer gpa.free(g.scroll_edge); + const before = core.panes[id].?.scroll(); + try std.testing.expect(stepRemoteScroll(&g, &in, gpa)); + try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); + // The next row is fetched early; its inverse raster offset preserves + // the exact fraction under the finger until that row is fully exposed. + try std.testing.expectEqual(@as(f32, 0.375), @as(f32, @floatFromInt(client.pending.items.len)) + g.scroll_lag); + try std.testing.expectEqual(before, core.panes[id].?.scroll()); + core.update(client.pending.items[0]); + client.pending.clearRetainingCapacity(); + g.scroll_delta = 0.75; + try std.testing.expect(stepRemoteScroll(&g, &in, gpa)); + try std.testing.expectEqual(@as(usize, 1), client.pending.items.len); + try std.testing.expectEqual(before + 1, core.panes[id].?.scroll()); + try std.testing.expect(client.pending.items[0].mouse.shift); + core.update(client.pending.items[0]); + try std.testing.expectEqual(@as(f32, 1.125), @as(f32, @floatFromInt(core.panes[id].?.scroll() - before)) + g.scroll_lag); +} + +fn stepFractionalScroll(g: *Gui, in: *Input, gpa: std.mem.Allocator) bool { + const core = in.core orelse return false; + const id = g.scroll_pane orelse return false; const pane = core.panes[id] orelse { resetScroll(g); - return; + return false; }; const queued_delta = g.scroll_delta; g.scroll_delta = 0; if (queued_delta == 0) { if (g.scroll_lag == 0 and g.scroll_notch == 0 and !g.glide.moving()) resetScroll(g); - return; + return false; } const r = core.rects[id]; if (r.h <= pane.tag_rows) { resetScroll(g); - return; + return false; } const delta = boundScrollDelta(g.scroll_lag, queued_delta, r.h - pane.tag_rows); const st = applyScrollDelta(g.scroll_lag, delta); @@ -6301,7 +6574,7 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { const down = left > 0; left += if (down) -1 else 1; const was = pane.scroll(); - core.update(.{ + in.post(.{ .mouse = .{ .button = if (down) .wheel_down else .wheel_up, .kind = .press, @@ -6310,9 +6583,11 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { .shift = true, // pardes's own scroll, never a program's wheel }, }); - if (pane.scroll() == was) { + // A replica posts here and applies the batch after its view is + // parked again; its scroll cannot have changed yet. + if (in.remote == null and pane.scroll() == was) { resetScroll(g); - return; + return false; } } g.scroll_lag = st.lag; @@ -6341,6 +6616,7 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } } if (g.scroll_lag == 0) resetScroll(g); + return true; } fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { 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]; +} |
