summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLTouchManager.m
blob: 518877e96fa02e636c254a9ac5fb11c79b9645f4 (plain)
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//
//  SDLTouchManager.m
//  SmartDeviceLink-iOS
//
//  Created by Muller, Alexander (A.) on 6/14/16.
//  Copyright © 2016 smartdevicelink. All rights reserved.
//

#import "SDLTouchManager.h"

#import "CGPoint_Util.h"
#import "dispatch_timer.h"

#import "SDLFocusableItemHitTester.h"
#import "SDLLogMacros.h"
#import "SDLNotificationConstants.h"
#import "SDLOnTouchEvent.h"
#import "SDLPinchGesture.h"
#import "SDLProxyListener.h"
#import "SDLRPCNotificationNotification.h"
#import "SDLTouch.h"
#import "SDLTouchCoord.h"
#import "SDLTouchEvent.h"
#import "SDLTouchManagerDelegate.h"


NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSUInteger, SDLPerformingTouchType) {
    SDLPerformingTouchTypeNone,
    SDLPerformingTouchTypeSingleTouch,
    SDLPerformingTouchTypeMultiTouch,
    SDLPerformingTouchTypePanningTouch
};

/*!
 *  @abstract
 *      Touch Manager will ignore touches that represent more than 2 fingers on the screen.
 */
static NSUInteger const MaximumNumberOfTouches = 2;

@interface SDLTouchManager ()

/*!
 *  @abstract
 *      First touch received from onOnTouchEvent.
 */
@property (nonatomic, strong, nullable) SDLTouch *firstTouch;

/*!
 *  @abstract
 *      Previous touch received from onOnTouchEvent.
 */
@property (nonatomic, strong, nullable) SDLTouch *previousTouch;

/*!
 * @abstract
 *      Cached previous single tap used for double tap detection.
 */
@property (nonatomic, strong, nullable) SDLTouch *singleTapTouch;

/*!
 *  @abstract
 *      Distance of a previously generated pinch event. Used to calculate the scale of zoom motion.
 */
@property (nonatomic, assign) CGFloat previousPinchDistance;

/*!
 *  @abstract
 *      Current in-progress pinch gesture.
 */
@property (nonatomic, strong, nullable) SDLPinchGesture *currentPinchGesture;

/*!
 *  @abstract
 *      Timer used for distinguishing between single & double taps.
 */
@property (nonatomic, strong, nullable) dispatch_source_t singleTapTimer;

/*!
 *  @abstract
 *      Current touch type being performed.
 */
@property (nonatomic, assign) SDLPerformingTouchType performingTouchType;

/**
 A hit tester that allows us to check for a view based on coordinates, if available.
 */
@property (nonatomic, weak, nullable) id<SDLFocusableItemHitTester> hitTester;

/**
 The last panning touch we received
 */
@property (nonatomic) CGPoint lastStoredTouchLocation;

/**
 The last panning touch that we notified the developer about
 */
@property (nonatomic) CGPoint lastNotifiedTouchLocation;

@end

@implementation SDLTouchManager

- (instancetype)initWithHitTester:(nullable id<SDLFocusableItemHitTester>)hitTester {
    self = [super init];
    if (!self) {
        return nil;
    }

    _hitTester = hitTester;
    _movementTimeThreshold = 0.05f;
    _tapTimeThreshold = 0.4f;
    _tapDistanceThreshold = 50.0f;
    _panDistanceThreshold = 8.0f;
    _touchEnabled = YES;
    _enableSyncedPanning = YES;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sdl_onTouchEvent:) name:SDLDidReceiveTouchEventNotification object:nil];

    return self;
}

#pragma mark - Public
- (void)cancelPendingTouches {
    [self sdl_cancelSingleTapTimer];
}

- (void)syncFrame {
    if (!self.isTouchEnabled || (!self.touchEventHandler && !self.touchEventDelegate)) {
        return;
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.performingTouchType == SDLPerformingTouchTypePanningTouch) {
            CGPoint storedTouchLocation = self.lastStoredTouchLocation;
            CGPoint notifiedTouchLocation = self.lastNotifiedTouchLocation;

            if (CGPointEqualToPoint(storedTouchLocation, CGPointZero) ||
                CGPointEqualToPoint(notifiedTouchLocation, CGPointZero) ||
                CGPointEqualToPoint(storedTouchLocation, notifiedTouchLocation)) {
                return;
            }

            if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:didReceivePanningFromPoint:toPoint:)]) {
                [self.touchEventDelegate touchManager:self
                           didReceivePanningFromPoint:notifiedTouchLocation
                                              toPoint:storedTouchLocation];

                self.lastNotifiedTouchLocation = storedTouchLocation;
            }
        } else if (self.performingTouchType == SDLPerformingTouchTypeMultiTouch) {
            if (self.previousPinchDistance == self.currentPinchGesture.distance) {
                return;
            }

            if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:didReceivePinchAtCenterPoint:withScale:)]) {
                CGFloat scale = self.currentPinchGesture.distance / self.previousPinchDistance;
                [self.touchEventDelegate touchManager:self
                         didReceivePinchAtCenterPoint:self.currentPinchGesture.center
                                            withScale:scale];
            }

            self.previousPinchDistance = self.currentPinchGesture.distance;
        }
    });
}

#pragma mark - SDLDidReceiveTouchEventNotification

/**
 *  Handles detecting the type and state of the gesture and notifies the appropriate delegate callbacks.

 *  @param notification     A SDLOnTouchEvent notification.
 */
- (void)sdl_onTouchEvent:(SDLRPCNotificationNotification *)notification {
    if (!self.isTouchEnabled
        || (!self.touchEventHandler && !self.touchEventDelegate)
        || ![notification.notification isKindOfClass:SDLOnTouchEvent.class]) {
        return;
    }

    SDLOnTouchEvent* onTouchEvent = (SDLOnTouchEvent*)notification.notification;

    SDLTouchType touchType = onTouchEvent.type;
    [onTouchEvent.event enumerateObjectsUsingBlock:^(SDLTouchEvent *touchEvent, NSUInteger idx, BOOL *stop) {
        SDLTouch *touch = [[SDLTouch alloc] initWithTouchEvent:touchEvent];

        if (self.touchEventHandler) {
            self.touchEventHandler(touch, touchType);
        }

        if (!self.touchEventDelegate || (touch.identifier > MaximumNumberOfTouches)) {
            return;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if ([onTouchEvent.type isEqualToEnum:SDLTouchTypeBegin]) {
                [self sdl_handleTouchBegan:touch];
            } else if ([onTouchEvent.type isEqualToEnum:SDLTouchTypeMove]) {
                [self sdl_handleTouchMoved:touch];
            } else if ([onTouchEvent.type isEqualToEnum:SDLTouchTypeEnd]) {
                [self sdl_handleTouchEnded:touch];
            } else if ([onTouchEvent.type isEqualToEnum:SDLTouchTypeCancel]) {
                [self sdl_handleTouchCanceled:touch];
            }
        });
    }];
}

#pragma mark - Private
/**
 *  Handles a BEGIN touch event sent by Core
 *
 *  @param touch Gesture information
 */
- (void)sdl_handleTouchBegan:(SDLTouch *)touch {
    _performingTouchType = SDLPerformingTouchTypeSingleTouch;

    switch (touch.identifier) {
        case SDLTouchIdentifierFirstFinger: {
            self.firstTouch = touch;
            self.previousTouch = touch;
        } break;
        case SDLTouchIdentifierSecondFinger: {
            _performingTouchType = SDLPerformingTouchTypeMultiTouch;
            self.currentPinchGesture = [[SDLPinchGesture alloc] initWithFirstTouch:self.previousTouch secondTouch:touch];
            self.previousPinchDistance = self.currentPinchGesture.distance;
            if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:pinchDidStartInView:atCenterPoint:)]) {
                    UIView *hitView = (self.hitTester != nil) ? [self.hitTester viewForPoint:self.currentPinchGesture.center] : nil;
                    [self.touchEventDelegate touchManager:self pinchDidStartInView:hitView atCenterPoint:self.currentPinchGesture.center];
            }
        } break;
    }
}

/**
 *  Handles a MOVE touch event sent by Core
 *
 *  @param touch Gesture information
 */
- (void)sdl_handleTouchMoved:(SDLTouch *)touch {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    if (!self.enableSyncedPanning &&
        ((touch.timeStamp - self.previousTouch.timeStamp) <= (self.movementTimeThreshold * NSEC_PER_USEC))) {
        return; // no-op
    }
#pragma clang diagnostic pop
    
    CGFloat xDelta = fabs(touch.location.x - self.firstTouch.location.x);
    CGFloat yDelta = fabs(touch.location.y - self.firstTouch.location.y);
    if (xDelta <= self.panDistanceThreshold && yDelta <= self.panDistanceThreshold) {
        return;
    }

    switch (self.performingTouchType) {
        case SDLPerformingTouchTypeMultiTouch: {
            switch (touch.identifier) {
                case SDLTouchIdentifierFirstFinger: {
                    self.currentPinchGesture.firstTouch = touch;
                } break;
                case SDLTouchIdentifierSecondFinger: {
                    self.currentPinchGesture.secondTouch = touch;
                } break;
            }

            if (!self.enableSyncedPanning) {
                [self syncFrame];
            }
        } break;
        case SDLPerformingTouchTypeSingleTouch: {
            self.lastNotifiedTouchLocation = touch.location;
            self.lastStoredTouchLocation = touch.location;

            _performingTouchType = SDLPerformingTouchTypePanningTouch;
            if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:panningDidStartInView:atPoint:)]) {
                    UIView *hitView = (self.hitTester != nil) ? [self.hitTester viewForPoint:touch.location] : nil;
                    [self.touchEventDelegate touchManager:self panningDidStartInView:hitView atPoint:touch.location];
            }
        } break;
        case SDLPerformingTouchTypePanningTouch: {
            if (!self.enableSyncedPanning) {
                [self syncFrame];
            }
            self.lastStoredTouchLocation = touch.location;
        } break;
        case SDLPerformingTouchTypeNone: break;
    }

    self.previousTouch = touch;
}

/**
 *  Handles a END touch type notification sent by Core
 *
 *  @param touch    Gesture information
 */
- (void)sdl_handleTouchEnded:(SDLTouch *)touch {
    switch (self.performingTouchType) {
        case SDLPerformingTouchTypeMultiTouch: {
            [self sdl_setMultiTouchFingerTouchForTouch:touch];
            if (self.currentPinchGesture.isValid) {
                if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:pinchDidEndInView:atCenterPoint:)]) {
                        UIView *hitView = (self.hitTester != nil) ? [self.hitTester viewForPoint:self.currentPinchGesture.center] : nil;
                        [self.touchEventDelegate touchManager:self pinchDidEndInView:hitView atCenterPoint:self.currentPinchGesture.center];
                        self.currentPinchGesture = nil;
                } else {
                    self.currentPinchGesture = nil;
                }
            }
        } break;
        case SDLPerformingTouchTypePanningTouch: {
            if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:panningDidEndInView:atPoint:)]) {
                    UIView *hitView = (self.hitTester != nil) ? [self.hitTester viewForPoint:touch.location] : nil;
                    [self.touchEventDelegate touchManager:self panningDidEndInView:hitView atPoint:touch.location];
            }
        } break;
        case SDLPerformingTouchTypeSingleTouch: {
            if (self.singleTapTimer == nil) {
                // Initial Tap
                self.singleTapTouch = touch;
                [self sdl_initializeSingleTapTimerAtPoint:self.singleTapTouch.location];
            } else {
                // Double Tap
                [self sdl_cancelSingleTapTimer];

                NSUInteger timeStampDelta = touch.timeStamp - self.singleTapTouch.timeStamp;
                CGFloat xDelta = fabs(touch.location.x - self.singleTapTouch.location.x);
                CGFloat yDelta = fabs(touch.location.y - self.singleTapTouch.location.y);

                if (timeStampDelta <= self.tapTimeThreshold * NSEC_PER_USEC && xDelta <= self.tapDistanceThreshold && yDelta <= self.tapDistanceThreshold) {
                    CGPoint centerPoint = CGPointCenterOfPoints(touch.location,
                                                                self.singleTapTouch.location);
                    if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:didReceiveDoubleTapForView:atPoint:)]) {
                            UIView *hitView = (self.hitTester != nil) ? [self.hitTester viewForPoint:centerPoint] : nil;
                            [self.touchEventDelegate touchManager:self didReceiveDoubleTapForView:hitView atPoint:centerPoint];
                    }
                }

                self.singleTapTouch = nil;
            }
        } break;
        case SDLPerformingTouchTypeNone: break;
    }

    self.firstTouch = nil;
    self.previousTouch = nil;
    _performingTouchType = SDLPerformingTouchTypeNone;
}

/**
 *  Handles a CANCEL touch event sent by CORE. A CANCEL touch event is sent when a gesture is interrupted during a video stream. This can happen when a system dialog box appears on the screen, such as when the user is alerted about an incoming phone call.
 *
 *  Pinch and pan gesture subscribers are notified if the gesture is canceled. Tap gestures are simply canceled without notification.
 *
 *  @param touch    Gesture information
 */
- (void)sdl_handleTouchCanceled:(SDLTouch *)touch {
    if (self.singleTapTimer != nil) {
        // Cancel any ongoing single tap timer
        [self sdl_cancelSingleTapTimer];
        self.singleTapTouch = nil;
    }

    switch (self.performingTouchType) {
        case SDLPerformingTouchTypeMultiTouch: {
            [self sdl_setMultiTouchFingerTouchForTouch:touch];
            if (self.currentPinchGesture.isValid) {
                if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:pinchCanceledAtCenterPoint:)]) {
                    [self.touchEventDelegate touchManager:self
                               pinchCanceledAtCenterPoint:self.currentPinchGesture.center];
                }
                self.currentPinchGesture = nil;
            }
        } break;
        case SDLPerformingTouchTypePanningTouch: {
            if ([self.touchEventDelegate respondsToSelector:@selector(touchManager:panningCanceledAtPoint:)]) {
                [self.touchEventDelegate touchManager:self
                               panningCanceledAtPoint:touch.location];
            }
        } break;
        case SDLPerformingTouchTypeSingleTouch: // fallthrough
        case SDLPerformingTouchTypeNone: break;
    }

    self.firstTouch = nil;
    self.previousTouch = nil;
    _performingTouchType = SDLPerformingTouchTypeNone;
}

#pragma mark - Helpers

/**
 *  Saves the pinch touch gesture to the correct finger
 *
 *  @param touch   Gesture information
 */
- (void)sdl_setMultiTouchFingerTouchForTouch:(SDLTouch *)touch {
    switch (touch.identifier) {
        case SDLTouchIdentifierFirstFinger: {
            self.currentPinchGesture.firstTouch = touch;
        } break;
        case SDLTouchIdentifierSecondFinger: {
            self.currentPinchGesture.secondTouch = touch;
        } break;
    }
}

/**
 *  Creates a timer used to detect the type of tap gesture (single or double tap)
 *
 *  @param point  Screen coordinates of the tap gesture
 */
- (void)sdl_initializeSingleTapTimerAtPoint:(CGPoint)point {
    __weak typeof(self) weakSelf = self;
    self.singleTapTimer = dispatch_create_timer(self.tapTimeThreshold, NO, ^{
        // If timer was not canceled by a second tap then only one tap detected
        typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.singleTapTouch = nil;
        [strongSelf sdl_cancelSingleTapTimer];
        if ([strongSelf.touchEventDelegate respondsToSelector:@selector(touchManager:didReceiveSingleTapForView:atPoint:)]) {
                UIView *hitView = (self.hitTester != nil) ? [self.hitTester viewForPoint:point] : nil;
                [strongSelf.touchEventDelegate touchManager:strongSelf didReceiveSingleTapForView:hitView atPoint:point];
        }
    });
}

/**
 *  Cancels a tap gesture timer
 */
- (void)sdl_cancelSingleTapTimer {
    if (self.singleTapTimer == NULL) {
        return;
    }
    dispatch_stop_timer(self.singleTapTimer);
    self.singleTapTimer = NULL;
}

@end

NS_ASSUME_NONNULL_END