summaryrefslogtreecommitdiff
path: root/src/gui/macos_trackpad.m
blob: 64806b9e903fda9faf290d24d96b025f0eb8bde0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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];
}