/
EventHandler.cpp
4908 lines (4045 loc) · 187 KB
/
EventHandler.cpp
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006-2020 Apple Inc. All rights reserved.
* Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2012 Digia Plc. and/or its subsidiary(-ies)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "EventHandler.h"
#include "AutoscrollController.h"
#include "BackForwardController.h"
#include "CachedImage.h"
#include "Chrome.h"
#include "ChromeClient.h"
#include "ComposedTreeAncestorIterator.h"
#include "ComposedTreeIterator.h"
#include "CursorList.h"
#include "DocumentInlines.h"
#include "DocumentMarkerController.h"
#include "DragController.h"
#include "DragEvent.h"
#include "DragState.h"
#include "Editing.h"
#include "Editor.h"
#include "EditorClient.h"
#include "ElementInlines.h"
#include "EventNames.h"
#include "FileList.h"
#include "FloatPoint.h"
#include "FloatRect.h"
#include "FocusController.h"
#include "FocusOptions.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "FrameSelection.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "FullscreenManager.h"
#include "HTMLDialogElement.h"
#include "HTMLDocument.h"
#include "HTMLFrameElement.h"
#include "HTMLFrameSetElement.h"
#include "HTMLHtmlElement.h"
#include "HTMLIFrameElement.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HTMLVideoElement.h"
#include "HitTestRequest.h"
#include "HitTestResult.h"
#include "Image.h"
#include "ImageOverlay.h"
#include "ImageOverlayController.h"
#include "InspectorInstrumentation.h"
#include "KeyboardEvent.h"
#include "KeyboardScrollingAnimator.h"
#include "Logging.h"
#include "MouseEvent.h"
#include "MouseEventWithHitTestResults.h"
#include "NotImplemented.h"
#include "Page.h"
#include "PageOverlayController.h"
#include "Pasteboard.h"
#include "PlatformEvent.h"
#include "PlatformKeyboardEvent.h"
#include "PlatformWheelEvent.h"
#include "PluginDocument.h"
#include "PointerEventTypeNames.h"
#include "PseudoClassChangeInvalidation.h"
#include "Range.h"
#include "RenderFrameSet.h"
#include "RenderImage.h"
#include "RenderLayer.h"
#include "RenderLayerScrollableArea.h"
#include "RenderListBox.h"
#include "RenderTextControlSingleLine.h"
#include "RenderView.h"
#include "RenderWidget.h"
#include "ResourceLoadObserver.h"
#include "RuntimeApplicationChecks.h"
#include "SVGDocument.h"
#include "SVGElementTypeHelpers.h"
#include "SVGNames.h"
#include "ScrollAnimator.h"
#include "ScrollLatchingController.h"
#include "Scrollbar.h"
#include "ScrollingEffectsController.h"
#include "SelectionRestorationMode.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "SpatialNavigation.h"
#include "StaticPasteboard.h"
#include "StyleCachedImage.h"
#include "TextEvent.h"
#include "TextIterator.h"
#include "TextRecognitionOptions.h"
#include "UserGestureIndicator.h"
#include "UserTypingGestureIndicator.h"
#include "ValidationMessageClient.h"
#include "VisibleUnits.h"
#include "WheelEvent.h"
#include "WheelEventDeltaFilter.h"
#include "WheelEventTestMonitor.h"
#include "WindowsKeyboardCodes.h"
#include <wtf/Assertions.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/SetForScope.h>
#include <wtf/StdLibExtras.h>
#if ENABLE(IOS_TOUCH_EVENTS)
#include "PlatformTouchEventIOS.h"
#endif
#if ENABLE(CONTENT_CHANGE_OBSERVER)
#include "DOMTimerHoldingTank.h"
#endif
#if ENABLE(TOUCH_EVENTS)
#include "TouchEvent.h"
#include "TouchList.h"
#endif
#if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
#include "PlatformTouchEvent.h"
#endif
#if ENABLE(MAC_GESTURE_EVENTS)
#include "PlatformGestureEventMac.h"
#endif
#if ENABLE(POINTER_LOCK)
#include "PointerLockController.h"
#endif
#if USE(APPLE_INTERNAL_SDK)
#include <WebKitAdditions/EventHandlerAdditions.cpp>
#else
static void addPointerTypeToHitTestRequest(OptionSet<WebCore::HitTestRequest::Type> &, String )
{
}
#endif
namespace WebCore {
using namespace HTMLNames;
#if ENABLE(DRAG_SUPPORT)
// The link drag hysteresis is much larger than the others because there
// needs to be enough space to cancel the link press without starting a link drag,
// and because dragging links is rare.
const int LinkDragHysteresis = 40;
const int ImageDragHysteresis = 5;
const int TextDragHysteresis = 3;
const int ColorDragHystersis = 3;
const int GeneralDragHysteresis = 3;
#if PLATFORM(MAC)
const Seconds EventHandler::TextDragDelay { 150_ms };
#else
const Seconds EventHandler::TextDragDelay { 0_s };
#endif
#endif // ENABLE(DRAG_SUPPORT)
#if ENABLE(IOS_GESTURE_EVENTS) || ENABLE(MAC_GESTURE_EVENTS)
const float GestureUnknown = 0;
#endif
#if ENABLE(IOS_TOUCH_EVENTS)
// FIXME: Share this constant with EventHandler and SliderThumbElement.
const unsigned InvalidTouchIdentifier = 0;
#endif
// Match key code of composition keydown event on windows.
// IE sends VK_PROCESSKEY which has value 229;
const int CompositionEventKeyCode = 229;
using namespace SVGNames;
#if !ENABLE(IOS_TOUCH_EVENTS)
// The amount of time to wait before sending a fake mouse event, triggered
// during a scroll. The short interval is used if the content responds to the mouse events
// in fakeMouseMoveDurationThreshold or less, otherwise the long interval is used.
const double fakeMouseMoveDurationThreshold = 0.01;
const Seconds fakeMouseMoveShortInterval = { 100_ms };
const Seconds fakeMouseMoveLongInterval = { 250_ms };
#endif
// The amount of time to wait for a cursor update on style and layout changes
// Set to 50Hz, no need to be faster than common screen refresh rate
static const Seconds cursorUpdateInterval { 20_ms };
const int maximumCursorSize = 128;
#if ENABLE(MOUSE_CURSOR_SCALE)
// It's pretty unlikely that a scale of less than one would ever be used. But all we really
// need to ensure here is that the scale isn't so small that integer overflow can occur when
// dividing cursor sizes (limited above) by the scale.
const double minimumCursorScale = 0.001;
#endif
class MaximumDurationTracker {
public:
explicit MaximumDurationTracker(double *maxDuration)
: m_maxDuration(maxDuration)
, m_start(MonotonicTime::now())
{
}
~MaximumDurationTracker()
{
*m_maxDuration = std::max(*m_maxDuration, (MonotonicTime::now() - m_start).seconds());
}
private:
double* m_maxDuration;
MonotonicTime m_start;
};
#if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
class SyntheticTouchPoint : public PlatformTouchPoint {
public:
// The default values are based on http://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
explicit SyntheticTouchPoint(const PlatformMouseEvent& event)
{
static constexpr int idDefaultValue = 0;
static constexpr int radiusYDefaultValue = 1;
static constexpr int radiusXDefaultValue = 1;
static constexpr float rotationAngleDefaultValue = 0.0f;
static constexpr float forceDefaultValue = 1.0f;
m_id = idDefaultValue; // There is only one active TouchPoint.
m_screenPos = event.globalPosition();
m_pos = event.position();
m_radiusY = radiusYDefaultValue;
m_radiusX = radiusXDefaultValue;
m_rotationAngle = rotationAngleDefaultValue;
m_force = forceDefaultValue;
PlatformEvent::Type type = event.type();
ASSERT(type == PlatformEvent::MouseMoved || type == PlatformEvent::MousePressed || type == PlatformEvent::MouseReleased);
switch (type) {
case PlatformEvent::MouseMoved:
m_state = TouchMoved;
break;
case PlatformEvent::MousePressed:
m_state = TouchPressed;
break;
case PlatformEvent::MouseReleased:
m_state = TouchReleased;
break;
default:
ASSERT_NOT_REACHED();
break;
}
}
};
class SyntheticSingleTouchEvent : public PlatformTouchEvent {
public:
explicit SyntheticSingleTouchEvent(const PlatformMouseEvent& event)
{
switch (event.type()) {
case PlatformEvent::MouseMoved:
m_type = TouchMove;
break;
case PlatformEvent::MousePressed:
m_type = TouchStart;
break;
case PlatformEvent::MouseReleased:
m_type = TouchEnd;
break;
default:
ASSERT_NOT_REACHED();
m_type = NoType;
break;
}
m_timestamp = event.timestamp();
m_modifiers = event.modifiers();
m_touchPoints.append(SyntheticTouchPoint(event));
}
};
#endif // ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
static inline ScrollGranularity wheelGranularityToScrollGranularity(unsigned deltaMode)
{
switch (deltaMode) {
case WheelEvent::DOM_DELTA_PAGE:
return ScrollGranularity::Page;
case WheelEvent::DOM_DELTA_LINE:
return ScrollGranularity::Line;
case WheelEvent::DOM_DELTA_PIXEL:
return ScrollGranularity::Pixel;
default:
return ScrollGranularity::Pixel;
}
}
#if (ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS_FAMILY))
static bool shouldGesturesTriggerActive()
{
// If the platform we're on supports GestureTapDown and GestureTapCancel then we'll
// rely on them to set the active state. Unfortunately there's no generic way to
// know in advance what event types are supported.
return false;
}
#endif
#if !PLATFORM(COCOA)
bool EventHandler::eventLoopHandleMouseUp(const MouseEventWithHitTestResults&)
{
return false;
}
#if ENABLE(DRAG_SUPPORT)
bool EventHandler::eventLoopHandleMouseDragged(const MouseEventWithHitTestResults&)
{
return false;
}
#endif
#endif
EventHandler::EventHandler(Frame& frame)
: m_frame(frame)
, m_hoverTimer(*this, &EventHandler::hoverTimerFired)
#if ENABLE(IMAGE_ANALYSIS)
, m_textRecognitionHoverTimer(*this, &EventHandler::textRecognitionHoverTimerFired, 250_ms)
#endif
, m_autoscrollController(makeUnique<AutoscrollController>())
#if !ENABLE(IOS_TOUCH_EVENTS)
, m_fakeMouseMoveEventTimer(*this, &EventHandler::fakeMouseMoveEventTimerFired)
#endif
#if ENABLE(CURSOR_VISIBILITY)
, m_autoHideCursorTimer(*this, &EventHandler::autoHideCursorTimerFired)
#endif
{
}
EventHandler::~EventHandler()
{
#if !ENABLE(IOS_TOUCH_EVENTS)
ASSERT(!m_fakeMouseMoveEventTimer.isActive());
#endif
#if ENABLE(CURSOR_VISIBILITY)
ASSERT(!m_autoHideCursorTimer.isActive());
#endif
}
#if ENABLE(DRAG_SUPPORT)
DragState& EventHandler::dragState()
{
static NeverDestroyed<DragState> state;
return state;
}
#endif
void EventHandler::clear()
{
m_hoverTimer.stop();
m_hasScheduledCursorUpdate = false;
#if !ENABLE(IOS_TOUCH_EVENTS)
m_fakeMouseMoveEventTimer.stop();
#endif
#if ENABLE(CURSOR_VISIBILITY)
cancelAutoHideCursorTimer();
#endif
#if ENABLE(IMAGE_ANALYSIS)
m_textRecognitionHoverTimer.stop();
#endif
m_resizeLayer = nullptr;
clearElementUnderMouse();
m_lastElementUnderMouse = nullptr;
m_lastMouseMoveEventSubframe = nullptr;
m_lastScrollbarUnderMouse = nullptr;
m_clickCount = 0;
m_clickNode = nullptr;
#if ENABLE(IOS_GESTURE_EVENTS)
m_gestureInitialDiameter = GestureUnknown;
m_gestureInitialRotation = GestureUnknown;
#endif
#if ENABLE(IOS_GESTURE_EVENTS) || ENABLE(MAC_GESTURE_EVENTS)
m_gestureLastDiameter = GestureUnknown;
m_gestureLastRotation = GestureUnknown;
m_gestureTargets.clear();
#endif
#if ENABLE(IOS_TOUCH_EVENTS)
m_touches.clear();
m_firstTouchID = InvalidTouchIdentifier;
m_touchEventTargetSubframe = nullptr;
#endif
m_frameSetBeingResized = nullptr;
#if ENABLE(DRAG_SUPPORT)
m_dragTarget = nullptr;
m_shouldOnlyFireDragOverEvent = false;
#endif
m_lastKnownMousePosition = std::nullopt;
m_lastKnownMouseGlobalPosition = { };
m_mousePressNode = nullptr;
m_mousePressed = false;
m_capturesDragging = false;
m_capturingMouseEventsElement = nullptr;
clearLatchedState();
#if ENABLE(TOUCH_EVENTS) && !ENABLE(IOS_TOUCH_EVENTS)
m_originatingTouchPointTargets.clear();
m_originatingTouchPointDocument = nullptr;
m_originatingTouchPointTargetKey = 0;
#endif
m_maxMouseMovedDuration = 0;
m_didStartDrag = false;
}
void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
{
if (nodeToBeRemoved.contains(m_clickNode.get()))
m_clickNode = nullptr;
}
static void setSelectionIfNeeded(FrameSelection& selection, const VisibleSelection& newSelection)
{
if (selection.selection() != newSelection && selection.shouldChangeSelection(newSelection))
selection.setSelection(newSelection, FrameSelection::defaultSetSelectionOptions(UserTriggered));
}
static inline bool dispatchSelectStart(Node* node)
{
if (!node || !node->renderer())
return true;
auto event = Event::create(eventNames().selectstartEvent, Event::CanBubble::Yes, Event::IsCancelable::Yes);
node->dispatchEvent(event);
return !event->defaultPrevented();
}
static Node* nodeToSelectOnMouseDownForNode(Node& targetNode)
{
if (ImageOverlay::isInsideOverlay(targetNode))
return nullptr;
if (RefPtr rootUserSelectAll = Position::rootUserSelectAllForNode(&targetNode))
return rootUserSelectAll.get();
if (targetNode.shouldSelectOnMouseDown())
return &targetNode;
return nullptr;
}
static VisibleSelection expandSelectionToRespectSelectOnMouseDown(Node& targetNode, const VisibleSelection& selection)
{
RefPtr nodeToSelect = nodeToSelectOnMouseDownForNode(targetNode);
if (!nodeToSelect)
return selection;
VisibleSelection newSelection(selection);
newSelection.setBase(positionBeforeNode(nodeToSelect.get()).upstream(CanCrossEditingBoundary));
newSelection.setExtent(positionAfterNode(nodeToSelect.get()).downstream(CanCrossEditingBoundary));
return newSelection;
}
bool EventHandler::updateSelectionForMouseDownDispatchingSelectStart(Node* targetNode, const VisibleSelection& selection, TextGranularity granularity)
{
if (Position::nodeIsUserSelectNone(targetNode))
return false;
if (!dispatchSelectStart(targetNode)) {
m_mouseDownMayStartSelect = false;
return false;
}
if (selection.isOrphan()) {
m_mouseDownMayStartSelect = false;
return false;
}
if (selection.isRange())
m_selectionInitiationState = ExtendedSelection;
else {
granularity = TextGranularity::CharacterGranularity;
m_selectionInitiationState = PlacedCaret;
}
m_frame.selection().setSelectionByMouseIfDifferent(selection, granularity);
return true;
}
void EventHandler::selectClosestWordFromHitTestResult(const HitTestResult& result, AppendTrailingWhitespace appendTrailingWhitespace)
{
RefPtr targetNode = result.targetNode();
VisibleSelection newSelection;
if (targetNode && targetNode->renderer()) {
VisiblePosition pos(targetNode->renderer()->positionForPoint(result.localPoint(), nullptr));
if (pos.isNotNull()) {
newSelection = VisibleSelection(pos);
newSelection.expandUsingGranularity(TextGranularity::WordGranularity);
}
if (appendTrailingWhitespace == ShouldAppendTrailingWhitespace && newSelection.isRange())
newSelection.appendTrailingWhitespace();
updateSelectionForMouseDownDispatchingSelectStart(targetNode.get(), expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), TextGranularity::WordGranularity);
}
}
static AppendTrailingWhitespace shouldAppendTrailingWhitespace(const MouseEventWithHitTestResults& result, const Frame& frame)
{
return (result.event().clickCount() == 2 && frame.editor().isSelectTrailingWhitespaceEnabled()) ? ShouldAppendTrailingWhitespace : DontAppendTrailingWhitespace;
}
#if !PLATFORM(COCOA)
VisibleSelection EventHandler::selectClosestWordFromHitTestResultBasedOnLookup(const HitTestResult&)
{
return VisibleSelection();
}
#endif
void EventHandler::selectClosestContextualWordFromHitTestResult(const HitTestResult& result, AppendTrailingWhitespace appendTrailingWhitespace)
{
RefPtr targetNode = result.targetNode();
VisibleSelection newSelection;
if (targetNode && targetNode->renderer()) {
newSelection = selectClosestWordFromHitTestResultBasedOnLookup(result);
if (newSelection.isNone()) {
VisiblePosition pos(targetNode->renderer()->positionForPoint(result.localPoint(), nullptr));
if (pos.isNotNull()) {
newSelection = VisibleSelection(pos);
newSelection.expandUsingGranularity(TextGranularity::WordGranularity);
}
}
if (appendTrailingWhitespace == ShouldAppendTrailingWhitespace && newSelection.isRange())
newSelection.appendTrailingWhitespace();
updateSelectionForMouseDownDispatchingSelectStart(targetNode.get(), expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), TextGranularity::WordGranularity);
}
}
void EventHandler::selectClosestContextualWordOrLinkFromHitTestResult(const HitTestResult& result, AppendTrailingWhitespace appendTrailingWhitespace)
{
// FIXME: In the editable case, word selection sometimes selects content that isn't underneath the mouse.
// If the selection is non-editable, we do word selection to make it easier to use the contextual menu items
// available for text selections. But only if we're above text.
if (!m_frame.selection().selection().isContentEditable() && !is<Text>(result.targetNode()))
return;
if (!m_frame.settings().textInteractionEnabled())
return;
RefPtr urlElement = result.URLElement();
if (!urlElement || !isDraggableLink(*urlElement)) {
if (RefPtr targetNode = result.targetNode(); targetNode && isEditableNode(*targetNode)) {
selectClosestWordFromHitTestResult(result, appendTrailingWhitespace);
return;
}
return selectClosestContextualWordFromHitTestResult(result, appendTrailingWhitespace);
}
if (RefPtr targetNode = result.targetNode(); targetNode && targetNode->renderer()) {
VisibleSelection newSelection;
VisiblePosition pos(targetNode->renderer()->positionForPoint(result.localPoint(), nullptr));
if (pos.isNotNull() && pos.deepEquivalent().deprecatedNode()->isDescendantOf(*urlElement))
newSelection = VisibleSelection::selectionFromContentsOfNode(urlElement.get());
updateSelectionForMouseDownDispatchingSelectStart(targetNode.get(), expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), TextGranularity::WordGranularity);
}
}
bool EventHandler::handleMousePressEventDoubleClick(const MouseEventWithHitTestResults& event)
{
if (event.event().button() != LeftButton)
return false;
if (m_frame.selection().isRange())
// A double-click when range is already selected
// should not change the selection. So, do not call
// selectClosestWordFromHitTestResult, but do set
// m_beganSelectingText to prevent handleMouseReleaseEvent
// from setting caret selection.
m_selectionInitiationState = ExtendedSelection;
else if (mouseDownMayStartSelect())
selectClosestWordFromHitTestResult(event.hitTestResult(), shouldAppendTrailingWhitespace(event, m_frame));
return true;
}
bool EventHandler::handleMousePressEventTripleClick(const MouseEventWithHitTestResults& event)
{
if (event.event().button() != LeftButton)
return false;
RefPtr targetNode = event.targetNode();
if (!(targetNode && targetNode->renderer() && mouseDownMayStartSelect()))
return false;
VisibleSelection newSelection;
VisiblePosition pos(targetNode->renderer()->positionForPoint(event.localPoint(), nullptr));
if (pos.isNotNull()) {
newSelection = VisibleSelection(pos);
newSelection.expandUsingGranularity(TextGranularity::ParagraphGranularity);
}
return updateSelectionForMouseDownDispatchingSelectStart(targetNode.get(), expandSelectionToRespectSelectOnMouseDown(*targetNode, newSelection), TextGranularity::ParagraphGranularity);
}
static uint64_t textDistance(const Position& start, const Position& end)
{
auto range = makeSimpleRange(start, end);
if (!range)
return 0;
return characterCount(*range, TextIteratorBehavior::EmitsCharactersBetweenAllVisiblePositions);
}
bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
{
Ref<Frame> protectedFrame(m_frame);
m_frame.document()->updateLayoutIgnorePendingStylesheets();
RefPtr targetNode = event.targetNode();
if (!targetNode || !targetNode->renderer() || !mouseDownMayStartSelect() || m_mouseDownDelegatedFocus)
return false;
// Extend the selection if the Shift key is down, unless the click is in a link.
bool extendSelection = event.event().shiftKey() && !event.isOverLink();
// Don't restart the selection when the mouse is pressed on an
// existing selection so we can allow for text dragging.
if (FrameView* view = m_frame.view()) {
LayoutPoint vPoint = view->windowToContents(event.event().position());
if (!extendSelection && m_frame.selection().contains(vPoint)) {
m_mouseDownWasSingleClickInSelection = true;
return false;
}
}
VisiblePosition visiblePosition(targetNode->renderer()->positionForPoint(event.localPoint(), nullptr));
if (visiblePosition.isNull())
visiblePosition = VisiblePosition(firstPositionInOrBeforeNode(targetNode.get()));
Position pos = visiblePosition.deepEquivalent();
VisibleSelection newSelection = m_frame.selection().selection();
TextGranularity granularity = TextGranularity::CharacterGranularity;
if (!m_frame.editor().client()->shouldAllowSingleClickToChangeSelection(*targetNode, newSelection))
return true;
if (extendSelection && newSelection.isCaretOrRange()) {
VisibleSelection selectionInUserSelectAll = expandSelectionToRespectSelectOnMouseDown(*targetNode, VisibleSelection(pos));
if (selectionInUserSelectAll.isRange()) {
if (selectionInUserSelectAll.start() < newSelection.start())
pos = selectionInUserSelectAll.start();
else if (newSelection.end() < selectionInUserSelectAll.end())
pos = selectionInUserSelectAll.end();
}
if (!m_frame.editor().behavior().shouldConsiderSelectionAsDirectional() && pos.isNotNull()) {
// See <rdar://problem/3668157> REGRESSION (Mail): shift-click deselects when selection
// was created right-to-left
Position start = newSelection.start();
Position end = newSelection.end();
int distanceToStart = textDistance(start, pos);
int distanceToEnd = textDistance(pos, end);
if (distanceToStart <= distanceToEnd)
newSelection = VisibleSelection(end, pos);
else
newSelection = VisibleSelection(start, pos);
} else
newSelection.setExtent(pos);
if (m_frame.selection().granularity() != TextGranularity::CharacterGranularity) {
granularity = m_frame.selection().granularity();
newSelection.expandUsingGranularity(m_frame.selection().granularity());
}
} else {
if (event.event().syntheticClickType() != SyntheticClickType::NoTap) {
auto adjustedVisiblePosition = wordBoundaryForPositionWithoutCrossingLine(visiblePosition).first;
if (adjustedVisiblePosition.isNotNull())
visiblePosition = WTFMove(adjustedVisiblePosition);
}
newSelection = expandSelectionToRespectSelectOnMouseDown(*targetNode, visiblePosition);
}
bool handled = updateSelectionForMouseDownDispatchingSelectStart(targetNode.get(), newSelection, granularity);
if (event.event().button() == MiddleButton) {
// Ignore handled, since we want to paste to where the caret was placed anyway.
handled = handlePasteGlobalSelection(event.event()) || handled;
}
return handled;
}
bool EventHandler::canMouseDownStartSelect(const MouseEventWithHitTestResults& event)
{
RefPtr node = event.targetNode();
if (Page* page = m_frame.page()) {
if (!page->chrome().client().shouldUseMouseEventForSelection(event.event()))
return false;
}
if (!node || !node->renderer())
return true;
if (ImageOverlay::isOverlayText(*node))
return node->renderer()->style().effectiveUserSelect() != UserSelect::None;
return node->canStartSelection() || Position::nodeIsUserSelectAll(node.get());
}
bool EventHandler::mouseDownMayStartSelect() const
{
if (!m_frame.settings().textInteractionEnabled())
return false;
return m_mouseDownMayStartSelect;
}
bool EventHandler::handleMousePressEvent(const MouseEventWithHitTestResults& event)
{
Ref<Frame> protectedFrame(m_frame);
#if ENABLE(DRAG_SUPPORT)
// Reset drag state.
dragState().source = nullptr;
#endif
#if !ENABLE(IOS_TOUCH_EVENTS)
cancelFakeMouseMoveEvent();
#endif
m_frame.document()->updateLayoutIgnorePendingStylesheets();
if (ScrollView* scrollView = m_frame.view()) {
if (scrollView->isPointInScrollbarCorner(event.event().position()))
return false;
}
bool singleClick = event.event().clickCount() <= 1;
// If we got the event back, that must mean it wasn't prevented,
// so it's allowed to start a drag or selection if it wasn't in a scrollbar.
m_mouseDownMayStartSelect = canMouseDownStartSelect(event) && !event.scrollbar();
#if ENABLE(DRAG_SUPPORT)
// Careful that the drag starting logic stays in sync with eventMayStartDrag()
// FIXME: eventMayStartDrag() does not check for shift key press, link or image event targets.
// Bug: https://bugs.webkit.org/show_bug.cgi?id=155390
// Single mouse down on links or images can always trigger drag-n-drop.
bool isImageOverlayText = ImageOverlay::isOverlayText(event.targetNode());
bool isMouseDownOnLinkOrImage = event.isOverLink() || (event.hitTestResult().image() && !isImageOverlayText);
m_mouseDownMayStartDrag = singleClick && (!event.event().shiftKey() || isMouseDownOnLinkOrImage) && shouldAllowMouseDownToStartDrag();
#endif
m_mouseDownWasSingleClickInSelection = false;
m_mouseDownEvent = event.event();
if (m_immediateActionStage != ImmediateActionStage::PerformedHitTest)
m_immediateActionStage = ImmediateActionStage::None;
if (event.isOverWidget() && passWidgetMouseDownEventToWidget(event))
return true;
if (is<SVGDocument>(*m_frame.document()) && downcast<SVGDocument>(*m_frame.document()).zoomAndPanEnabled()) {
if (event.event().shiftKey() && singleClick) {
m_svgPan = true;
downcast<SVGDocument>(*m_frame.document()).startPan(m_frame.view()->windowToContents(event.event().position()));
return true;
}
}
// We don't do this at the start of mouse down handling,
// because we don't want to do it until we know we didn't hit a widget.
if (singleClick)
focusDocumentView();
m_mousePressNode = event.targetNode();
m_frame.document()->setFocusNavigationStartingNode(event.targetNode());
#if ENABLE(DRAG_SUPPORT)
m_dragStartPosition = event.event().position();
#endif
m_mousePressed = true;
m_selectionInitiationState = HaveNotStartedSelection;
bool swallowEvent = false;
if (event.event().clickCount() == 2)
swallowEvent = handleMousePressEventDoubleClick(event);
else if (event.event().clickCount() >= 3)
swallowEvent = handleMousePressEventTripleClick(event);
else
swallowEvent = handleMousePressEventSingleClick(event);
m_mouseDownMayStartAutoscroll = mouseDownMayStartSelect()
|| (m_mousePressNode && m_mousePressNode->renderBox() && m_mousePressNode->renderBox()->canBeProgramaticallyScrolled());
return swallowEvent;
}
VisiblePosition EventHandler::selectionExtentRespectingEditingBoundary(const VisibleSelection& selection, const LayoutPoint& localPoint, Node* targetNode)
{
FloatPoint selectionEndPoint = localPoint;
RefPtr editableElement = selection.rootEditableElement();
if (!targetNode || !targetNode->renderer())
return VisiblePosition();
RefPtr adjustedTarget = targetNode;
if (editableElement && !editableElement->contains(targetNode)) {
if (!editableElement->renderer())
return VisiblePosition();
FloatPoint absolutePoint = targetNode->renderer()->localToAbsolute(FloatPoint(selectionEndPoint));
selectionEndPoint = editableElement->renderer()->absoluteToLocal(absolutePoint);
adjustedTarget = editableElement;
}
return adjustedTarget->renderer()->positionForPoint(LayoutPoint(selectionEndPoint), nullptr);
}
#if ENABLE(DRAG_SUPPORT)
#if !PLATFORM(IOS_FAMILY)
bool EventHandler::supportsSelectionUpdatesOnMouseDrag() const
{
return true;
}
bool EventHandler::shouldAllowMouseDownToStartDrag() const
{
return true;
}
#endif
bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis)
{
if (!m_mousePressed)
return false;
Ref<Frame> protectedFrame(m_frame);
if (handleDrag(event, checkDragHysteresis))
return true;
RefPtr targetNode = event.targetNode();
if (event.event().button() != LeftButton || !targetNode)
return false;
RenderObject* renderer = targetNode->renderer();
if (!renderer) {
RefPtr parent = targetNode->parentOrShadowHostElement();
if (!parent)
return false;
renderer = parent->renderer();
if (!renderer || !renderer->isListBox())
return false;
}
#if PLATFORM(COCOA) // FIXME: Why does this assertion fire on other platforms?
ASSERT(mouseDownMayStartSelect() || m_mouseDownMayStartAutoscroll);
#endif
m_mouseDownMayStartDrag = false;
if (m_mouseDownMayStartAutoscroll && !panScrollInProgress()) {
m_autoscrollController->startAutoscrollForSelection(renderer);
m_mouseDownMayStartAutoscroll = false;
}
if (m_selectionInitiationState != ExtendedSelection) {
HitTestResult result(m_mouseDownContentsPosition);
m_frame.document()->hitTest(HitTestRequest(), result);
updateSelectionForMouseDrag(result);
}
updateSelectionForMouseDrag(event.hitTestResult());
return true;
}
bool EventHandler::eventMayStartDrag(const PlatformMouseEvent& event) const
{
// This is a pre-flight check of whether the event might lead to a drag being started. Be careful
// that its logic needs to stay in sync with handleMouseMoveEvent() and the way we setMouseDownMayStartDrag
// in handleMousePressEvent
auto* document = m_frame.document();
if (!document)
return false;
if (event.button() != LeftButton || event.clickCount() != 1)
return false;
FrameView* view = m_frame.view();
if (!view)
return false;
Page* page = m_frame.page();
if (!page)
return false;
Ref<Frame> protectedFrame(m_frame);
updateDragSourceActionsAllowed();
constexpr OptionSet<HitTestRequest::Type> hitType { HitTestRequest::Type::ReadOnly, HitTestRequest::Type::DisallowUserAgentShadowContent };
HitTestResult result(view->windowToContents(event.position()));
document->hitTest(hitType, result);
DragState state;
RefPtr targetElement = result.targetElement();
return targetElement && page->dragController().draggableElement(&m_frame, targetElement.get(), result.roundedPointInInnerNodeFrame(), state);
}
void EventHandler::updateSelectionForMouseDrag()
{
if (!supportsSelectionUpdatesOnMouseDrag())
return;
FrameView* view = m_frame.view();
if (!view)
return;
auto* document = m_frame.document();
if (!document)
return;
constexpr OptionSet<HitTestRequest::Type> hitType { HitTestRequest::Type::ReadOnly, HitTestRequest::Type::Active, HitTestRequest::Type::Move, HitTestRequest::Type::DisallowUserAgentShadowContent };
HitTestResult result(view->windowToContents(valueOrDefault(m_lastKnownMousePosition)));
document->hitTest(hitType, result);
updateSelectionForMouseDrag(result);
}
void EventHandler::updateSelectionForMouseDrag(const HitTestResult& hitTestResult)
{
if (!supportsSelectionUpdatesOnMouseDrag())
return;
if (!mouseDownMayStartSelect())
return;
RefPtr target = hitTestResult.targetNode();
if (!target)
return;
if (!HTMLElement::shouldExtendSelectionToTargetNode(*target, m_frame.selection().selection()))
return;
VisiblePosition targetPosition = selectionExtentRespectingEditingBoundary(m_frame.selection().selection(), hitTestResult.localPoint(), target.get());
// Don't modify the selection if we're not on a node.
if (targetPosition.isNull())
return;
// Restart the selection if this is the first mouse move. This work is usually
// done in handleMousePressEvent, but not if the mouse press was on an existing selection.
VisibleSelection oldSelection = m_frame.selection().selection();
auto newSelection = oldSelection;
// Special case to limit selection to the containing block for SVG text.
// FIXME: Isn't there a better non-SVG-specific way to do this?
if (RefPtr selectionBaseNode = newSelection.base().deprecatedNode()) {
if (RenderObject* selectionBaseRenderer = selectionBaseNode->renderer()) {
if (selectionBaseRenderer->isSVGText()) {
if (target->renderer()->containingBlock() != selectionBaseRenderer->containingBlock())
return;
}
}
}