Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qiostextinputoverlay.mm
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#import <UIKit/UIGestureRecognizerSubclass.h>
6#import <UIKit/UITextView.h>
7
8#include <QtGui/QGuiApplication>
9#include <QtGui/QInputMethod>
10#include <QtGui/QStyleHints>
11
12#include <QtGui/private/qinputmethod_p.h>
13#include <QtCore/private/qobject_p.h>
14#include <QtCore/private/qcore_mac_p.h>
15
16#include "qiosglobal.h"
19#include "qioswindow.h"
20#include "quiview.h"
21
22#include <utility> // for std::pair
23
24typedef std::pair<int, int> SelectionPair;
25typedef void (^Block)(void);
26
27static const CGFloat kKnobWidth = 10;
28
30{
31 return static_cast<QInputMethodPrivate *>(QObjectPrivate::get(QGuiApplication::inputMethod()))->platformInputContext();
32}
33
35{
36 if (!QGuiApplication::focusObject())
37 return {};
38
39 QInputMethodQueryEvent query(Qt::ImAnchorPosition | Qt::ImCursorPosition);
40 QGuiApplication::sendEvent(QGuiApplication::focusObject(), &query);
41 int anchorPos = query.value(Qt::ImAnchorPosition).toInt();
42 int cursorPos = query.value(Qt::ImCursorPosition).toInt();
43 return {anchorPos, cursorPos};
44}
45
46static bool hasSelection()
47{
48 SelectionPair selection = querySelection();
49 return selection.first != selection.second;
50}
51
53{
54 [CATransaction begin];
55 [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
56 block();
57 [CATransaction commit];
58}
59
60// -------------------------------------------------------------------------
61/**
62 QIOSEditMenu is just a wrapper class around UIMenuController to
63 ease showing and hiding it correctly.
64 */
65@interface QIOSEditMenu : NSObject
66@property (nonatomic, assign) BOOL visible;
67@property (nonatomic, readonly) BOOL isHiding;
68@property (nonatomic, readonly) BOOL shownByUs;
69@property (nonatomic, assign) BOOL reshowAfterHidden;
70@end
71
72@implementation QIOSEditMenu
73
74- (instancetype)init
75{
76 if (self = [super init]) {
77 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
78
79 [center addObserverForName:UIMenuControllerWillHideMenuNotification
80 object:nil queue:nil usingBlock:^(NSNotification *) {
81 _isHiding = YES;
82 }];
83
84 [center addObserverForName:UIMenuControllerDidHideMenuNotification
85 object:nil queue:nil usingBlock:^(NSNotification *) {
86 _isHiding = NO;
87 _shownByUs = NO;
88 if (self.reshowAfterHidden) {
89 // To not abort an ongoing hide transition when showing the menu, you can set
90 // reshowAfterHidden to wait until the transition finishes before reshowing it.
91 self.reshowAfterHidden = NO;
92 dispatch_async(dispatch_get_main_queue (), ^{ self.visible = YES; });
93 }
94 }];
95 [center addObserverForName:UIKeyboardDidHideNotification object:nil queue:nil
96 usingBlock:^(NSNotification *) {
97 self.visible = NO;
98 }];
99
100 }
101
102 return self;
103}
104
105- (void)dealloc
106{
107 [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil];
108 [super dealloc];
109}
110
111- (BOOL)visible
112{
113 return [UIMenuController sharedMenuController].menuVisible;
114}
115
116- (void)setVisible:(BOOL)visible
117{
118 if (visible == self.visible)
119 return;
120
121 if (visible) {
122 // UIMenuController is a singleton that can be shown (and hidden) from anywhere.
123 // Try to keep track of whether or not is was shown by us (the gesture recognizers
124 // in this file) to avoid closing it if it was opened from elsewhere.
125 _shownByUs = YES;
126 // Note that the contents of the edit menu is decided by
127 // first responder, which is normally QIOSTextResponder.
128 QRectF cr = QPlatformInputContext::cursorRectangle();
129 QRectF ar = QPlatformInputContext::anchorRectangle();
130
131 CGRect targetRect = cr.united(ar).toCGRect();
132 UIView *focusView = reinterpret_cast<UIView *>(qApp->focusWindow()->winId());
133 [[UIMenuController sharedMenuController] setTargetRect:targetRect inView:focusView];
134 [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
135 } else {
136 [[UIMenuController sharedMenuController] setMenuVisible:NO animated:YES];
137 }
138}
139
140@end
141
142void showEditMenu(UIView *focusView, QPoint touchPos)
143{
144 const Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier;
145 QWindow *qtWindow = quiview_cast(focusView).platformWindow->window();
146 const auto globalTouchPos = qtWindow->mapToGlobal(touchPos);
147 const bool contextMenuEventAccepted = QWindowSystemInterface::handleContextMenuEvent<
148 QWindowSystemInterface::SynchronousDelivery>(qtWindow,
149 QIOSIntegration::instance()->touchDevice(), touchPos,
150 globalTouchPos, keyboardModifiers);
151
152 if (!contextMenuEventAccepted) {
153 // Fall back to show the default platform menu, like we did
154 // before we started sending context menu events. This is
155 // to be backwards compatible with Widgets and Quick items.
156 QIOSTextInputOverlay::s_editMenu.visible = YES;
157 }
158}
159
160// -------------------------------------------------------------------------
161
162@interface QIOSLoupeLayer : CALayer
163@property (nonatomic, retain) UIView *targetView;
164@property (nonatomic, assign) CGPoint focalPoint;
165@property (nonatomic, assign) BOOL visible;
166@end
167
168@implementation QIOSLoupeLayer {
169 UIView *_snapshotView;
170 BOOL _pendingSnapshotUpdate;
171 UIView *_loupeImageView;
172 CALayer *_containerLayer;
173 CGFloat _loupeOffset;
174 QTimer _updateTimer;
175}
176
177- (instancetype)initWithSize:(CGSize)size cornerRadius:(CGFloat)cornerRadius bottomOffset:(CGFloat)bottomOffset
178{
179 if (self = [super init]) {
180 _loupeOffset = bottomOffset + (size.height / 2);
181 _snapshotView = nil;
182 _pendingSnapshotUpdate = YES;
183 _updateTimer.setInterval(100);
184 _updateTimer.setSingleShot(true);
185 QObject::connect(&_updateTimer, &QTimer::timeout, [self](){ [self updateSnapshot]; });
186
187 // Create own geometry and outer shadow
188 self.frame = CGRectMake(0, 0, size.width, size.height);
189 self.cornerRadius = cornerRadius;
190 self.shadowColor = [[UIColor grayColor] CGColor];
191 self.shadowOffset = CGSizeMake(0, 1);
192 self.shadowRadius = 2.0;
193 self.shadowOpacity = 0.75;
194 self.transform = CATransform3DMakeScale(0, 0, 0);
195
196 // Create container view for the snapshots
197 _containerLayer = [[CALayer new] autorelease];
198 _containerLayer.frame = self.bounds;
199 _containerLayer.cornerRadius = cornerRadius;
200 _containerLayer.masksToBounds = YES;
201 [self addSublayer:_containerLayer];
202
203 // Create inner loupe shadow
204 const CGFloat inset = 30;
205 CALayer *topShadeLayer = [[CALayer new] autorelease];
206 topShadeLayer.frame = CGRectOffset(CGRectInset(self.bounds, -inset, -inset), 0, inset / 2);
207 topShadeLayer.borderWidth = inset / 2;
208 topShadeLayer.cornerRadius = cornerRadius;
209 topShadeLayer.borderColor = [[UIColor blackColor] CGColor];
210 topShadeLayer.shadowColor = [[UIColor blackColor] CGColor];
211 topShadeLayer.shadowOffset = CGSizeMake(0, 0);
212 topShadeLayer.shadowRadius = 15.0;
213 topShadeLayer.shadowOpacity = 0.6;
214 // Keep the shadow inside the loupe
215 CALayer *mask = [[CALayer new] autorelease];
216 mask.frame = CGRectOffset(self.bounds, inset, inset / 2);
217 mask.backgroundColor = [[UIColor blackColor] CGColor];
218 mask.cornerRadius = cornerRadius;
219 topShadeLayer.mask = mask;
220 [self addSublayer:topShadeLayer];
221
222 // Create border around the loupe. We need to do this in a separate
223 // layer (as opposed to on self) to not draw the border on top of
224 // overlapping external children (arrow).
225 CALayer *borderLayer = [[CALayer new] autorelease];
226 borderLayer.frame = self.bounds;
227 borderLayer.borderWidth = 0.75;
228 borderLayer.cornerRadius = cornerRadius;
229 borderLayer.borderColor = [[UIColor lightGrayColor] CGColor];
230 [self addSublayer:borderLayer];
231 }
232
233 return self;
234}
235
236- (void)dealloc
237{
238 _targetView = nil;
239 [super dealloc];
240}
241
242- (void)setVisible:(BOOL)visible
243{
244 if (_visible == visible)
245 return;
246
247 _visible = visible;
248
249 dispatch_async(dispatch_get_main_queue (), ^{
250 // Setting transform later, since CA will not perform an animation if
251 // changing values directly after init, and if the scale ends up empty.
252 self.transform = _visible ? CATransform3DMakeScale(1, 1, 1) : CATransform3DMakeScale(0.0, 0.0, 1);
253 });
254}
255
256- (void)updateSnapshot
257{
258 _pendingSnapshotUpdate = YES;
259 [self setNeedsDisplay];
260}
261
262- (void)setFocalPoint:(CGPoint)point
263{
264 _focalPoint = point;
265 [self updateSnapshot];
266
267 // Schedule a delayed update as well to ensure that we end up with a correct
268 // snapshot of the cursor, since QQuickRenderThread lags a bit behind
269 _updateTimer.start();
270}
271
272- (void)display
273{
274 // Take a snapshow of the target view, magnify the area around the focal
275 // point, and add the snapshow layer as a child of the container layer
276 // to make it look like a loupe. Then place this layer at the position of
277 // the focal point with the requested offset.
278 executeBlockWithoutAnimation(^{
279 if (_pendingSnapshotUpdate) {
280 UIView *newSnapshot = [_targetView snapshotViewAfterScreenUpdates:NO];
281 [_snapshotView.layer removeFromSuperlayer];
282 [_snapshotView release];
283 _snapshotView = [newSnapshot retain];
284 [_containerLayer addSublayer:_snapshotView.layer];
285 _pendingSnapshotUpdate = NO;
286 }
287
288 self.position = CGPointMake(_focalPoint.x, _focalPoint.y - _loupeOffset);
289
290 const CGFloat loupeScale = 1.5;
291 CGFloat x = -(_focalPoint.x * loupeScale) + self.frame.size.width / 2;
292 CGFloat y = -(_focalPoint.y * loupeScale) + self.frame.size.height / 2;
293 CGFloat w = _targetView.frame.size.width * loupeScale;
294 CGFloat h = _targetView.frame.size.height * loupeScale;
295 _snapshotView.layer.frame = CGRectMake(x, y, w, h);
296 });
297}
298
299@end
300
301// -------------------------------------------------------------------------
302
303@interface QIOSHandleLayer : CALayer <CAAnimationDelegate>
304@property (nonatomic, assign) CGRect cursorRectangle;
305@property (nonatomic, assign) CGFloat handleScale;
306@property (nonatomic, assign) BOOL visible;
307@property (nonatomic, copy) Block onAnimationDidStop;
308@end
309
310@implementation QIOSHandleLayer {
311 CALayer *_handleCursorLayer;
312 CALayer *_handleKnobLayer;
313 Qt::Edge _selectionEdge;
314}
315
316@dynamic handleScale;
317
318- (instancetype)initWithKnobAtEdge:(Qt::Edge)selectionEdge
319{
320 if (self = [super init]) {
321 CGColorRef bgColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.9 alpha:1].CGColor;
322 _selectionEdge = selectionEdge;
323 self.handleScale = 0;
324
325 _handleCursorLayer = [[CALayer new] autorelease];
326 _handleCursorLayer.masksToBounds = YES;
327 _handleCursorLayer.backgroundColor = bgColor;
328 [self addSublayer:_handleCursorLayer];
329
330 _handleKnobLayer = [[CALayer new] autorelease];
331 _handleKnobLayer.masksToBounds = YES;
332 _handleKnobLayer.backgroundColor = bgColor;
333 _handleKnobLayer.cornerRadius = kKnobWidth / 2;
334 [self addSublayer:_handleKnobLayer];
335 }
336 return self;
337}
338
339+ (BOOL)needsDisplayForKey:(NSString *)key
340{
341 if ([key isEqualToString:@"handleScale"])
342 return YES;
343 return [super needsDisplayForKey:key];
344}
345
346- (id<CAAction>)actionForKey:(NSString *)key
347{
348 if ([key isEqualToString:@"handleScale"]) {
349 if (_visible) {
350 // The handle should "bounce" in when becoming visible
351 CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:key];
352 [animation setDuration:0.5];
353 animation.values = @[@(0.0f), @(1.3f), @(1.3f), @(1.0f)];
354 animation.keyTimes = @[@(0.0f), @(0.3f), @(0.9f), @(1.0f)];
355 return animation;
356 } else {
357 CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:key];
358 [animation setDelegate:self];
359 animation.fromValue = [self valueForKey:key];
360 [animation setDuration:0.2];
361 return animation;
362 }
363 }
364 return [super actionForKey:key];
365}
366
367- (void)animationDidStop:(CAAnimation *)animation finished:(BOOL)flag
368{
369 Q_UNUSED(animation);
370 Q_UNUSED(flag);
371 if (self.onAnimationDidStop)
372 self.onAnimationDidStop();
373}
374
375- (void)setVisible:(BOOL)visible
376{
377 if (visible == _visible)
378 return;
379
380 _visible = visible;
381
382 self.handleScale = visible ? 1 : 0;
383}
384
385- (void)setCursorRectangle:(CGRect)cursorRect
386{
387 if (CGRectEqualToRect(_cursorRectangle, cursorRect))
388 return;
389
390 _cursorRectangle = cursorRect;
391
392 executeBlockWithoutAnimation(^{
393 [self setNeedsDisplay];
394 [self displayIfNeeded];
395 });
396}
397
398- (void)display
399{
400 CGFloat cursorWidth = 2;
401 CGPoint origin = _cursorRectangle.origin;
402 CGSize size = _cursorRectangle.size;
403 CGFloat scale = ((QIOSHandleLayer *)[self presentationLayer]).handleScale;
404 CGFloat edgeAdjustment = (_selectionEdge == Qt::LeftEdge) ? 0.5 - cursorWidth : -0.5;
405
406 CGFloat cursorX = origin.x + (size.width / 2) + edgeAdjustment;
407 CGFloat cursorY = origin.y;
408 CGFloat knobX = cursorX - (kKnobWidth - cursorWidth) / 2;
409 CGFloat knobY = origin.y + ((_selectionEdge == Qt::LeftEdge) ? -kKnobWidth : size.height);
410
411 _handleCursorLayer.frame = CGRectMake(cursorX, cursorY, cursorWidth, size.height);
412 _handleKnobLayer.frame = CGRectMake(knobX, knobY, kKnobWidth, kKnobWidth);
413 _handleCursorLayer.transform = CATransform3DMakeScale(1, scale, scale);
414 _handleKnobLayer.transform = CATransform3DMakeScale(scale, scale, scale);
415}
416
417@end
418
419// -------------------------------------------------------------------------
420
421/**
422 QIOSLoupeRecognizer is only a base class from which other recognisers
423 below will inherit. It takes care of creating and showing a magnifier
424 glass depending on the current gesture state.
425 */
426@interface QIOSLoupeRecognizer : UIGestureRecognizer <UIGestureRecognizerDelegate>
427@property (nonatomic, assign) QPointF focalPoint;
428@property (nonatomic, assign) BOOL dragTriggersGesture;
429@property (nonatomic, readonly) UIView *focusView;
430@end
431
432@implementation QIOSLoupeRecognizer {
433 QIOSLoupeLayer *_loupeLayer;
434 UIView *_desktopView;
435 CGPoint _firstTouchPoint;
436 CGPoint _lastTouchPoint;
437 QTimer _triggerStateBeganTimer;
438 int _originalCursorFlashTime;
439}
440
441- (instancetype)init
442{
443 if (self = [super initWithTarget:self action:@selector(gestureStateChanged)]) {
444 self.enabled = NO;
445 _triggerStateBeganTimer.setInterval(QGuiApplication::styleHints()->startDragTime());
446 _triggerStateBeganTimer.setSingleShot(true);
447 QObject::connect(&_triggerStateBeganTimer, &QTimer::timeout, [=](){
448 self.state = UIGestureRecognizerStateBegan;
449 });
450 }
451
452 return self;
453}
454
455- (void)setEnabled:(BOOL)enabled
456{
457 if (enabled == self.enabled)
458 return;
459
460 [super setEnabled:enabled];
461
462 if (enabled) {
463 _focusView = [reinterpret_cast<UIView *>(qApp->focusWindow()->winId()) retain];
464 _desktopView = [presentationWindow(nullptr).rootViewController.view retain];
465 Q_ASSERT(_focusView && _desktopView && _desktopView.superview);
466 [_desktopView addGestureRecognizer:self];
467 } else {
468 [_desktopView removeGestureRecognizer:self];
469 [_desktopView release];
470 _desktopView = nil;
471 [_focusView release];
472 _focusView = nil;
473 _triggerStateBeganTimer.stop();
474 if (_loupeLayer) {
475 [_loupeLayer removeFromSuperlayer];
476 [_loupeLayer release];
477 _loupeLayer = nil;
478 }
479 }
480}
481
482- (void)gestureStateChanged
483{
484 switch (self.state) {
485 case UIGestureRecognizerStateBegan:
486 // Stop cursor blinking, and show the loupe
487 _originalCursorFlashTime = QGuiApplication::styleHints()->cursorFlashTime();
488 QGuiApplication::styleHints()->setCursorFlashTime(0);
489 if (!_loupeLayer)
490 [self createLoupe];
491 [self updateFocalPoint:QPointF::fromCGPoint(_lastTouchPoint)];
492 _loupeLayer.visible = YES;
493 QIOSTextInputOverlay::s_editMenu.visible = NO;
494 break;
495 case UIGestureRecognizerStateChanged:
496 // Tell the sub class to move the loupe to the correct position
497 [self updateFocalPoint:QPointF::fromCGPoint(_lastTouchPoint)];
498 break;
499 case UIGestureRecognizerStateEnded: {
500 // Restore cursor blinking, and hide the loupe
501 QGuiApplication::styleHints()->setCursorFlashTime(_originalCursorFlashTime);
502 const QPoint touchPos = QPointF::fromCGPoint(_lastTouchPoint).toPoint();
503 showEditMenu(_focusView, touchPos);
504 _loupeLayer.visible = NO;
505 break;
506 }
507 default:
508 _loupeLayer.visible = NO;
509 break;
510 }
511}
512
513- (void)createLoupe
514{
515 // We magnify the desktop view. But the loupe itself will be added as a child
516 // of the desktop view's parent, so it doesn't become a part of what we magnify.
517 _loupeLayer = [[self createLoupeLayer] retain];
518 _loupeLayer.targetView = _desktopView;
519 [_desktopView.superview.layer addSublayer:_loupeLayer];
520}
521
522- (QPointF)focalPoint
523{
524 return QPointF::fromCGPoint([_loupeLayer.targetView convertPoint:_loupeLayer.focalPoint toView:_focusView]);
525}
526
527- (void)setFocalPoint:(QPointF)point
528{
529 _loupeLayer.focalPoint = [_loupeLayer.targetView convertPoint:point.toCGPoint() fromView:_focusView];
530}
531
532- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
533{
534 [super touchesBegan:touches withEvent:event];
535 if ([event allTouches].count > 1) {
536 // We only support text selection with one finger
537 self.state = UIGestureRecognizerStateFailed;
538 return;
539 }
540
541 _firstTouchPoint = [static_cast<UITouch *>([touches anyObject]) locationInView:_focusView];
542 _lastTouchPoint = _firstTouchPoint;
543
544 // If the touch point is accepted by the sub class (e.g touch on cursor), we start a
545 // press'n'hold timer that eventually will move the state to UIGestureRecognizerStateBegan.
546 if ([self acceptTouchesBegan:QPointF::fromCGPoint(_firstTouchPoint)])
547 _triggerStateBeganTimer.start();
548 else
549 self.state = UIGestureRecognizerStateFailed;
550}
551
552- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
553{
554 [super touchesMoved:touches withEvent:event];
555 _lastTouchPoint = [static_cast<UITouch *>([touches anyObject]) locationInView:_focusView];
556
557 if (self.state == UIGestureRecognizerStatePossible) {
558 // If the touch was moved too far before the timer triggered (meaning that this
559 // is a drag, not a press'n'hold), we should either fail, or trigger the gesture
560 // immediately, depending on self.dragTriggersGesture.
561 int startDragDistance = QGuiApplication::styleHints()->startDragDistance();
562 int dragDistance = hypot(_firstTouchPoint.x - _lastTouchPoint.x, _firstTouchPoint.y - _lastTouchPoint.y);
563 if (dragDistance > startDragDistance) {
564 _triggerStateBeganTimer.stop();
565 self.state = self.dragTriggersGesture ? UIGestureRecognizerStateBegan : UIGestureRecognizerStateFailed;
566 }
567 } else {
568 self.state = UIGestureRecognizerStateChanged;
569 }
570}
571
572- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
573{
574 [super touchesEnded:touches withEvent:event];
575 _triggerStateBeganTimer.stop();
576 _lastTouchPoint = [static_cast<UITouch *>([touches anyObject]) locationInView:_focusView];
577 self.state = self.state == UIGestureRecognizerStatePossible ? UIGestureRecognizerStateFailed : UIGestureRecognizerStateEnded;
578}
579
580- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
581{
582 [super touchesCancelled:touches withEvent:event];
583 _triggerStateBeganTimer.stop();
584 _lastTouchPoint = [static_cast<UITouch *>([touches anyObject]) locationInView:_focusView];
585 self.state = UIGestureRecognizerStateCancelled;
586}
587
588// Methods implemented by subclasses:
589
590- (BOOL)acceptTouchesBegan:(QPointF)touchPoint
591{
592 Q_UNUSED(touchPoint);
593 Q_UNREACHABLE();
594 return NO;
595}
596
597- (QIOSLoupeLayer *)createLoupeLayer
598{
599 Q_UNREACHABLE();
600 return nullptr;
601}
602
603- (void)updateFocalPoint:(QPointF)touchPoint
604{
605 Q_UNUSED(touchPoint);
606 Q_UNREACHABLE();
607}
608
609@end
610
611// -------------------------------------------------------------------------
612
613/**
614 This recognizer will be active when there's no selection. It will trigger if
615 the user does a press and hold, which will start a session where the user can move
616 the cursor around with his finger together with a magnifier glass.
617 */
618@interface QIOSCursorRecognizer : QIOSLoupeRecognizer
619@end
620
621@implementation QIOSCursorRecognizer
622
623- (QIOSLoupeLayer *)createLoupeLayer
624{
625 return [[[QIOSLoupeLayer alloc] initWithSize:CGSizeMake(120, 120) cornerRadius:60 bottomOffset:4] autorelease];
626}
627
628- (BOOL)acceptTouchesBegan:(QPointF)touchPoint
629{
630 QRectF inputRect = QPlatformInputContext::inputItemRectangle();
631 return !hasSelection() && inputRect.contains(touchPoint);
632}
633
634- (void)updateFocalPoint:(QPointF)touchPoint
635{
636 self.focalPoint = touchPoint;
637
638 const int currentCursorPos = QInputMethod::queryFocusObject(Qt::ImCursorPosition, QVariant()).toInt();
639 const int newCursorPos = QPlatformInputContext::queryFocusObject(Qt::ImCursorPosition, touchPoint).toInt();
640 if (newCursorPos != currentCursorPos)
641 QPlatformInputContext::setSelectionOnFocusObject(touchPoint, touchPoint);
642}
643
644@end
645
646// -------------------------------------------------------------------------
647
648/**
649 This recognizer will watch for selections, and draw handles as overlay
650 on the sides. If the user starts dragging on a handle (or do a press and
651 hold), it will show a magnifier glass that follows the handle as it moves.
652 */
653@interface QIOSSelectionRecognizer : QIOSLoupeRecognizer
654@end
655
656@implementation QIOSSelectionRecognizer {
657 CALayer *_clipRectLayer;
658 QIOSHandleLayer *_cursorLayer;
659 QIOSHandleLayer *_anchorLayer;
660 QPointF _touchOffset;
661 bool _dragOnCursor;
662 bool _dragOnAnchor;
663 bool _multiLine;
664 QTimer _updateSelectionTimer;
665 QMetaObject::Connection _cursorConnection;
666 QMetaObject::Connection _anchorConnection;
667 QMetaObject::Connection _clipRectConnection;
668}
669
670- (instancetype)init
671{
672 if (self = [super init]) {
673 self.delaysTouchesBegan = YES;
674 self.dragTriggersGesture = YES;
675 _multiLine = QInputMethod::queryFocusObject(Qt::ImHints, QVariant()).toUInt() & Qt::ImhMultiLine;
676 _updateSelectionTimer.setInterval(1);
677 _updateSelectionTimer.setSingleShot(true);
678 QObject::connect(&_updateSelectionTimer, &QTimer::timeout, [self](){ [self updateSelection]; });
679 }
680
681 return self;
682}
683
684- (void)setEnabled:(BOOL)enabled
685{
686 if (enabled == self.enabled)
687 return;
688
689 [super setEnabled:enabled];
690
691 if (enabled) {
692 // Create a layer that clips the handles inside the input field
693 _clipRectLayer = [CALayer new];
694 _clipRectLayer.masksToBounds = YES;
695 [self.focusView.layer addSublayer:_clipRectLayer];
696
697 // Create the handle layers, and add them to the clipped input rect layer
698 _cursorLayer = [[[QIOSHandleLayer alloc] initWithKnobAtEdge:Qt::RightEdge] autorelease];
699 _anchorLayer = [[[QIOSHandleLayer alloc] initWithKnobAtEdge:Qt::LeftEdge] autorelease];
700 bool selection = hasSelection();
701 _cursorLayer.visible = selection;
702 _anchorLayer.visible = selection;
703 [_clipRectLayer addSublayer:_cursorLayer];
704 [_clipRectLayer addSublayer:_anchorLayer];
705
706 // iOS text input will sometimes set a temporary text selection to perform operations
707 // such as backspace (select last character + cut selection). To avoid briefly showing
708 // the selection handles for such cases, and to avoid calling updateSelection when
709 // both handles and clip rectangle change, we use a timer to wait a cycle before we update.
710 // (Note that since QTimer::start is overloaded, we need some extra syntax for the connections).
711 QInputMethod *im = QGuiApplication::inputMethod();
712 void(QTimer::*start)(void) = &QTimer::start;
713 _cursorConnection = QObject::connect(im, &QInputMethod::cursorRectangleChanged, &_updateSelectionTimer, start);
714 _anchorConnection = QObject::connect(im, &QInputMethod::anchorRectangleChanged, &_updateSelectionTimer, start);
715 _clipRectConnection = QObject::connect(im, &QInputMethod::inputItemClipRectangleChanged, &_updateSelectionTimer, start);
716
717 [self updateSelection];
718 } else {
719 // Fade out the handles by setting visible to NO, and wait for the animations
720 // to finish before removing the clip rect layer, including the handles.
721 // Create a local variable to hold the clipRectLayer while the animation is
722 // ongoing to ensure that any subsequent calls to setEnabled does not interfere.
723 // Also, declare it as __block to stop it from being automatically retained, which
724 // would cause a cyclic dependency between clipRectLayer and the block.
725 __block CALayer *clipRectLayer = _clipRectLayer;
726 __block int handleCount = 2;
727 Block block = ^{
728 if (--handleCount == 0) {
729 [clipRectLayer removeFromSuperlayer];
730 [clipRectLayer release];
731 }
732 };
733
734 _cursorLayer.onAnimationDidStop = block;
735 _anchorLayer.onAnimationDidStop = block;
736 _cursorLayer.visible = NO;
737 _anchorLayer.visible = NO;
738
739 _clipRectLayer = 0;
740 _cursorLayer = 0;
741 _anchorLayer = 0;
742 _updateSelectionTimer.stop();
743
744 QObject::disconnect(_cursorConnection);
745 QObject::disconnect(_anchorConnection);
746 QObject::disconnect(_clipRectConnection);
747
748 if (QIOSTextInputOverlay::s_editMenu.shownByUs)
749 QIOSTextInputOverlay::s_editMenu.visible = NO;
750 }
751}
752
753- (QIOSLoupeLayer *)createLoupeLayer
754{
755 CGSize loupeSize = CGSizeMake(123, 33);
756 CGSize arrowSize = CGSizeMake(25, 12);
757 CGFloat loupeOffset = arrowSize.height + 20;
758
759 // Create loupe and arrow layers
760 QIOSLoupeLayer *loupeLayer = [[[QIOSLoupeLayer alloc] initWithSize:loupeSize cornerRadius:5 bottomOffset:loupeOffset] autorelease];
761 CAShapeLayer *arrowLayer = [[[CAShapeLayer alloc] init] autorelease];
762
763 // Build a triangular path to both draw and mask the arrow layer as a triangle
764 UIBezierPath *path = [[UIBezierPath new] autorelease];
765 [path moveToPoint:CGPointMake(0, 0)];
766 [path addLineToPoint:CGPointMake(arrowSize.width / 2, arrowSize.height)];
767 [path addLineToPoint:CGPointMake(arrowSize.width, 0)];
768
769 arrowLayer.frame = CGRectMake((loupeSize.width - arrowSize.width) / 2, loupeSize.height - 1, arrowSize.width, arrowSize.height);
770 arrowLayer.path = path.CGPath;
771 arrowLayer.backgroundColor = [[UIColor whiteColor] CGColor];
772 arrowLayer.strokeColor = [[UIColor lightGrayColor] CGColor];
773 arrowLayer.lineWidth = 0.75 * 2;
774 arrowLayer.fillColor = nil;
775
776 CAShapeLayer *mask = [[CAShapeLayer new] autorelease];
777 mask.frame = arrowLayer.bounds;
778 mask.path = path.CGPath;
779 arrowLayer.mask = mask;
780
781 [loupeLayer addSublayer:arrowLayer];
782
783 return loupeLayer;
784}
785
786- (BOOL)acceptTouchesBegan:(QPointF)touchPoint
787{
788 if (!hasSelection())
789 return NO;
790
791 // Accept the touch if it "overlaps" with any of the handles
792 const int handleRadius = 50;
793 QPointF cursorCenter = QPlatformInputContext::cursorRectangle().center();
794 QPointF anchorCenter = QPlatformInputContext::anchorRectangle().center();
795 QPointF cursorOffset = QPointF(cursorCenter.x() - touchPoint.x(), cursorCenter.y() - touchPoint.y());
796 QPointF anchorOffset = QPointF(anchorCenter.x() - touchPoint.x(), anchorCenter.y() - touchPoint.y());
797 double cursorDist = hypot(cursorOffset.x(), cursorOffset.y());
798 double anchorDist = hypot(anchorOffset.x(), anchorOffset.y());
799
800 if (cursorDist > handleRadius && anchorDist > handleRadius)
801 return NO;
802
803 if (cursorDist < anchorDist) {
804 _touchOffset = cursorOffset;
805 _dragOnCursor = YES;
806 _dragOnAnchor = NO;
807 } else {
808 _touchOffset = anchorOffset;
809 _dragOnCursor = NO;
810 _dragOnAnchor = YES;
811 }
812
813 return YES;
814}
815
816- (void)updateFocalPoint:(QPointF)touchPoint
817{
818 touchPoint += _touchOffset;
819
820 // Get the text position under the touch
821 SelectionPair selection = querySelection();
822 int touchTextPos = QPlatformInputContext::queryFocusObject(Qt::ImCursorPosition, touchPoint).toInt();
823
824 // Ensure that the handles cannot be dragged past each other
825 if (_dragOnCursor)
826 selection.second = (touchTextPos > selection.first) ? touchTextPos : selection.first + 1;
827 else
828 selection.first = (touchTextPos < selection.second) ? touchTextPos : selection.second - 1;
829
830 // Set new selection
831 QList<QInputMethodEvent::Attribute> imAttributes;
832 imAttributes.append(QInputMethodEvent::Attribute(
833 QInputMethodEvent::Selection, selection.first, selection.second - selection.first, QVariant()));
834 QInputMethodEvent event(QString(), imAttributes);
835 QGuiApplication::sendEvent(qApp->focusObject(), &event);
836
837 // Move loupe to new position
838 QRectF handleRect = _dragOnCursor ?
839 QPlatformInputContext::cursorRectangle() :
840 QPlatformInputContext::anchorRectangle();
841 self.focalPoint = QPointF(touchPoint.x(), handleRect.center().y());
842}
843
844- (void)updateSelection
845{
846 if (!hasSelection()) {
847 if (_cursorLayer.visible) {
848 _cursorLayer.visible = NO;
849 _anchorLayer.visible = NO;
850 }
851 if (QIOSTextInputOverlay::s_editMenu.shownByUs)
852 QIOSTextInputOverlay::s_editMenu.visible = NO;
853 return;
854 }
855
856 if (!_cursorLayer.visible && QIOSTextInputOverlay::s_editMenu.isHiding) {
857 // Since the edit menu is hiding and this is the first selection thereafter, we
858 // assume that the selection came from the user tapping on a menu item. In that
859 // case, we reshow the menu after it has closed (but then with selection based
860 // menu items, as specified by first responder).
861 QIOSTextInputOverlay::s_editMenu.reshowAfterHidden = YES;
862 }
863
864 // Adjust handles and input rect to match the new selection
865 QRectF inputRect = QPlatformInputContext::inputItemClipRectangle();
866 CGRect cursorRect = QPlatformInputContext::cursorRectangle().toCGRect();
867 CGRect anchorRect = QPlatformInputContext::anchorRectangle().toCGRect();
868
869 if (!_multiLine) {
870 // Resize the layer a bit bigger to ensure that the handles are
871 // not cut if if they are otherwise visible inside the clip rect.
872 int margin = kKnobWidth + 5;
873 inputRect.adjust(-margin / 2, -margin, margin / 2, margin);
874 }
875
876 executeBlockWithoutAnimation(^{ _clipRectLayer.frame = inputRect.toCGRect(); });
877 _cursorLayer.cursorRectangle = [self.focusView.layer convertRect:cursorRect toLayer:_clipRectLayer];
878 _anchorLayer.cursorRectangle = [self.focusView.layer convertRect:anchorRect toLayer:_clipRectLayer];
879 _cursorLayer.visible = YES;
880 _anchorLayer.visible = YES;
881}
882
883@end
884
885// -------------------------------------------------------------------------
886
887/**
888 This recognizer will show the edit menu if the user taps inside the input
889 item without changing the cursor position, or hide it if it's already visible
890 and the user taps anywhere on the screen.
891 */
892@interface QIOSTapRecognizer : UITapGestureRecognizer
893@end
894
895@implementation QIOSTapRecognizer {
896 int _cursorPosOnPress;
897 bool _menuShouldBeVisible;
898 UIView *_focusView;
899}
900
901- (instancetype)init
902{
903 if (self = [super initWithTarget:self action:@selector(gestureStateChanged)]) {
904 self.enabled = NO;
905 }
906
907 return self;
908}
909
910- (void)setEnabled:(BOOL)enabled
911{
912 if (enabled == self.enabled)
913 return;
914
915 [super setEnabled:enabled];
916
917 if (enabled) {
918 _focusView = [reinterpret_cast<UIView *>(qApp->focusWindow()->winId()) retain];
919 [_focusView addGestureRecognizer:self];
920 } else {
921 [_focusView removeGestureRecognizer:self];
922 [_focusView release];
923 _focusView = nil;
924 }
925}
926
927- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
928{
929 [super touchesBegan:touches withEvent:event];
930
931 QRectF inputRect = QPlatformInputContext::inputItemClipRectangle();
932 QPointF touchPos = QPointF::fromCGPoint([static_cast<UITouch *>([touches anyObject]) locationInView:_focusView]);
933 const bool touchInsideInputArea = inputRect.contains(touchPos);
934
935 if (touchInsideInputArea && hasSelection()) {
936 // When we have a selection and the user taps inside the input area, we stop
937 // tracking, and let Qt handle the event like normal. Unless the selection
938 // recogniser is triggered instead (if the touch is on top of the selection
939 // handles) this will typically result in Qt clearing the selection, which in
940 // turn will make the selection recogniser hide the menu.
941 self.state = UIGestureRecognizerStateFailed;
942 return;
943 }
944
945 if (QIOSTextInputOverlay::s_editMenu.visible) {
946 // When the menu is visible and there is no selection, we should always
947 // hide it, regardless of where the user tapped on the screen. We achieve
948 // this by continue tracking so that we receive a touchesEnded call.
949 // But note, we only want to hide the menu, and not clear the selection.
950 // Only when the user taps inside the input area do we want to clear the
951 // selection as well. This is different from native behavior, but done so
952 // deliberately for cross-platform consistency. This will let the user click on
953 // e.g "Bold" and "Italic" buttons elsewhere in the UI to modify the selected text.
954 return;
955 }
956
957 if (!touchInsideInputArea) {
958 // If the menu is not showing, and the touch is outside the input
959 // area, there is nothing left for this recogniser to do.
960 self.state = UIGestureRecognizerStateFailed;
961 return;
962 }
963
964 // When no menu is showing, and the touch is inside the input
965 // area, we check if we should show it. We want to do so if
966 // the tap doesn't result in the cursor changing position.
967 _cursorPosOnPress = QInputMethod::queryFocusObject(Qt::ImCursorPosition, QVariant()).toInt();
968}
969
970- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
971{
972 if (QIOSTextInputOverlay::s_editMenu.visible) {
973 _menuShouldBeVisible = false;
974 } else {
975 QPointF touchPos = QPointF::fromCGPoint([static_cast<UITouch *>([touches anyObject]) locationInView:_focusView]);
976 int cursorPosOnRelease = QPlatformInputContext::queryFocusObject(Qt::ImCursorPosition, touchPos).toInt();
977
978 if (cursorPosOnRelease == _cursorPosOnPress) {
979 // We've recognized a gesture to open the menu, but we don't know
980 // whether the user tapped a control that was overlaid our input
981 // area, since we don't do any granular hit-testing in touchesBegan.
982 // To ensure that the gesture doesn't eat touch events that should
983 // have reached another UI control we report the gesture as failed
984 // here, and then manually show the menu at the next runloop pass.
985 _menuShouldBeVisible = true;
986 self.state = UIGestureRecognizerStateFailed;
987 dispatch_async(dispatch_get_main_queue(), ^{
988 if (_menuShouldBeVisible)
989 showEditMenu(_focusView, touchPos.toPoint());
990 else
991 QIOSTextInputOverlay::s_editMenu.visible = false;
992 });
993 } else {
994 // The menu is hidden, and the cursor will change position once
995 // Qt receive the touch release. We therefore fail so that we
996 // don't block the touch event from further processing.
997 self.state = UIGestureRecognizerStateFailed;
998 }
999 }
1000
1001 [super touchesEnded:touches withEvent:event];
1002}
1003
1004- (void)gestureStateChanged
1005{
1006 if (self.state != UIGestureRecognizerStateEnded)
1007 return;
1008
1009 QIOSTextInputOverlay::s_editMenu.visible = _menuShouldBeVisible;
1010}
1011
1012@end
1013
1014// -------------------------------------------------------------------------
1015
1016QT_BEGIN_NAMESPACE
1017
1018QIOSEditMenu *QIOSTextInputOverlay::s_editMenu = nullptr;
1019
1020QIOSTextInputOverlay::QIOSTextInputOverlay()
1021 : m_cursorRecognizer(nullptr)
1022 , m_selectionRecognizer(nullptr)
1023 , m_openMenuOnTapRecognizer(nullptr)
1024{
1025 if (qt_apple_isApplicationExtension()) {
1026 qWarning() << "text input overlays disabled in application extensions";
1027 return;
1028 }
1029
1030 connect(qApp, &QGuiApplication::focusObjectChanged, this, &QIOSTextInputOverlay::updateFocusObject);
1031}
1032
1033QIOSTextInputOverlay::~QIOSTextInputOverlay()
1034{
1035 if (qApp)
1036 disconnect(qApp, 0, this, 0);
1037}
1038
1039void QIOSTextInputOverlay::updateFocusObject()
1040{
1041 // Destroy old recognizers since they were created with
1042 // dependencies to the old focus object (focus view).
1043 if (m_cursorRecognizer) {
1044 m_cursorRecognizer.enabled = NO;
1045 [m_cursorRecognizer release];
1046 m_cursorRecognizer = nullptr;
1047 }
1048 if (m_selectionRecognizer) {
1049 m_selectionRecognizer.enabled = NO;
1050 [m_selectionRecognizer release];
1051 m_selectionRecognizer = nullptr;
1052 }
1053 if (m_openMenuOnTapRecognizer) {
1054 m_openMenuOnTapRecognizer.enabled = NO;
1055 [m_openMenuOnTapRecognizer release];
1056 m_openMenuOnTapRecognizer = nullptr;
1057 }
1058
1059 if (s_editMenu) {
1060 [s_editMenu release];
1061 s_editMenu = nullptr;
1062 }
1063
1064 const QVariant hintsVariant = QGuiApplication::inputMethod()->queryFocusObject(Qt::ImHints, QVariant());
1065 const Qt::InputMethodHints hints = Qt::InputMethodHints(hintsVariant.toUInt());
1066 if (hints & Qt::ImhNoTextHandles)
1067 return;
1068
1069 // The focus object can emit selection updates (e.g from mouse drag), and
1070 // accept modifying it through IM when dragging on the handles, even if it
1071 // doesn't accept text input and IM in general (and hence return false from
1072 // inputMethodAccepted()). This is the case for read-only text fields.
1073 // Therefore, listen for selection changes also when the focus object
1074 // reports that it's ImReadOnly (which we take as a hint that it's actually
1075 // a text field, and that selections therefore might happen). But since
1076 // we have no guarantee that the focus object can actually accept new selections
1077 // through IM (and since we also need to respect if the input accepts selections
1078 // in the first place), we only support selections started by the text field (e.g from
1079 // mouse drag), even if we in theory could also start selections from a loupe.
1080
1081 const bool inputAccepted = platformInputContext()->inputMethodAccepted();
1082 const bool readOnly = QGuiApplication::inputMethod()->queryFocusObject(Qt::ImReadOnly, QVariant()).toBool();
1083
1084 if (inputAccepted || readOnly) {
1085 if (!(hints & Qt::ImhNoEditMenu))
1086 s_editMenu = [QIOSEditMenu new];
1087 m_selectionRecognizer = [QIOSSelectionRecognizer new];
1088 m_openMenuOnTapRecognizer = [QIOSTapRecognizer new];
1089 m_selectionRecognizer.enabled = YES;
1090 m_openMenuOnTapRecognizer.enabled = YES;
1091 }
1092
1093 if (inputAccepted) {
1094 m_cursorRecognizer = [QIOSCursorRecognizer new];
1095 m_cursorRecognizer.enabled = YES;
1096 }
1097}
1098
1099QT_END_NAMESPACE
static SelectionPair querySelection()
static const CGFloat kKnobWidth
static bool hasSelection()
std::pair< int, int > SelectionPair
static void executeBlockWithoutAnimation(Block block)
void(^) Block(void)
static QPlatformInputContext * platformInputContext()