This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnsFrameSelection.cpp
2838 lines (2438 loc) · 98.9 KB
/
nsFrameSelection.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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* Implementation of nsFrameSelection
*/
#include "nsFrameSelection.h"
#include "mozilla/Attributes.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/EventStates.h"
#include "mozilla/HTMLEditor.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsISelectionListener.h"
#include "nsContentCID.h"
#include "nsDeviceContext.h"
#include "nsIContent.h"
#include "nsRange.h"
#include "nsITableCellLayout.h"
#include "nsTArray.h"
#include "nsTableWrapperFrame.h"
#include "nsTableCellFrame.h"
#include "nsIScrollableFrame.h"
#include "nsCCUncollectableMarker.h"
#include "nsIDocumentEncoder.h"
#include "nsTextFragment.h"
#include <algorithm>
#include "nsContentUtils.h"
#include "nsCSSFrameConstructor.h"
#include "nsGkAtoms.h"
#include "nsIFrameTraversal.h"
#include "nsLayoutUtils.h"
#include "nsLayoutCID.h"
#include "nsBidiPresUtils.h"
static NS_DEFINE_CID(kFrameTraversalCID, NS_FRAMETRAVERSAL_CID);
#include "nsTextFrame.h"
#include "nsThreadUtils.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "nsPresContext.h"
#include "nsCaret.h"
#include "mozilla/MouseEvents.h"
#include "mozilla/TextEvents.h"
#include "nsITimer.h"
// notifications
#include "mozilla/dom/Document.h"
#include "nsISelectionController.h" //for the enums
#include "nsCopySupport.h"
#include "nsIClipboard.h"
#include "nsIFrameInlines.h"
#include "nsIBidiKeyboard.h"
#include "nsError.h"
#include "mozilla/AutoCopyListener.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/Selection.h"
#include "mozilla/dom/ShadowRoot.h"
#include "mozilla/dom/Text.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/SelectionBinding.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/Telemetry.h"
#include "nsFocusManager.h"
#include "nsPIDOMWindow.h"
using namespace mozilla;
using namespace mozilla::dom;
//#define DEBUG_TABLE 1
static bool IsValidSelectionPoint(nsFrameSelection* aFrameSel, nsINode* aNode);
static nsAtom* GetTag(nsINode* aNode);
// returns the parent
static nsINode* ParentOffset(nsINode* aNode, int32_t* aChildOffset);
static nsINode* GetCellParent(nsINode* aDomNode);
#ifdef PRINT_RANGE
static void printRange(nsRange* aDomRange);
# define DEBUG_OUT_RANGE(x) printRange(x)
#else
# define DEBUG_OUT_RANGE(x)
#endif // PRINT_RANGE
/******************************************************************************
* nsPeekOffsetStruct
******************************************************************************/
//#define DEBUG_SELECTION // uncomment for printf describing every collapse and
// extend. #define DEBUG_NAVIGATION
//#define DEBUG_TABLE_SELECTION 1
nsPeekOffsetStruct::nsPeekOffsetStruct(
nsSelectionAmount aAmount, nsDirection aDirection, int32_t aStartOffset,
nsPoint aDesiredPos, bool aJumpLines, bool aScrollViewStop,
bool aIsKeyboardSelect, bool aVisual, bool aExtend,
ForceEditableRegion aForceEditableRegion,
EWordMovementType aWordMovementType, bool aTrimSpaces)
: mAmount(aAmount),
mDirection(aDirection),
mStartOffset(aStartOffset),
mDesiredPos(aDesiredPos),
mWordMovementType(aWordMovementType),
mJumpLines(aJumpLines),
mTrimSpaces(aTrimSpaces),
mScrollViewStop(aScrollViewStop),
mIsKeyboardSelect(aIsKeyboardSelect),
mVisual(aVisual),
mExtend(aExtend),
mForceEditableRegion(aForceEditableRegion == ForceEditableRegion::Yes),
mResultContent(),
mResultFrame(nullptr),
mContentOffset(0),
mAttach(CARET_ASSOCIATE_BEFORE) {}
// Array which contains index of each SelecionType in Selection::mDOMSelections.
// For avoiding using if nor switch to retrieve the index, this needs to have
// -1 for SelectionTypes which won't be created its Selection instance.
static const int8_t kIndexOfSelections[] = {
-1, // SelectionType::eInvalid
-1, // SelectionType::eNone
0, // SelectionType::eNormal
1, // SelectionType::eSpellCheck
2, // SelectionType::eIMERawClause
3, // SelectionType::eIMESelectedRawClause
4, // SelectionType::eIMEConvertedClause
5, // SelectionType::eIMESelectedClause
6, // SelectionType::eAccessibility
7, // SelectionType::eFind
8, // SelectionType::eURLSecondary
9, // SelectionType::eURLStrikeout
};
inline int8_t GetIndexFromSelectionType(SelectionType aSelectionType) {
// The enum value of eInvalid is -1 and the others are sequential value
// starting from 0. Therefore, |SelectionType + 1| is the index of
// kIndexOfSelections.
return kIndexOfSelections[static_cast<int8_t>(aSelectionType) + 1];
}
/*
The limiter is used specifically for the text areas and textfields
In that case it is the DIV tag that is anonymously created for the text
areas/fields. Text nodes and BR nodes fall beneath it. In the case of a
BR node the limiter will be the parent and the offset will point before or
after the BR node. In the case of the text node the parent content is
the text node itself and the offset will be the exact character position.
The offset is not important to check for validity. Simply look at the
passed in content. If it equals the limiter then the selection point is valid.
If its parent it the limiter then the point is also valid. In the case of
NO limiter all points are valid since you are in a topmost iframe. (browser
or composer)
*/
bool IsValidSelectionPoint(nsFrameSelection* aFrameSel, nsINode* aNode) {
if (!aFrameSel || !aNode) return false;
nsIContent* limiter = aFrameSel->GetLimiter();
if (limiter && limiter != aNode && limiter != aNode->GetParent()) {
// if newfocus == the limiter. that's ok. but if not there and not parent
// bad
return false; // not in the right content. tLimiter said so
}
limiter = aFrameSel->GetAncestorLimiter();
return !limiter || nsContentUtils::ContentIsDescendantOf(aNode, limiter);
}
namespace mozilla {
struct MOZ_RAII AutoPrepareFocusRange {
AutoPrepareFocusRange(Selection* aSelection, bool aContinueSelection,
bool aMultipleSelection
MOZ_GUARD_OBJECT_NOTIFIER_PARAM) {
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
if (aSelection->mRanges.Length() <= 1) {
return;
}
if (aSelection->mFrameSelection->IsUserSelectionReason()) {
mUserSelect.emplace(aSelection);
}
bool userSelection = aSelection->mUserInitiated;
nsTArray<RangeData>& ranges = aSelection->mRanges;
if (!userSelection || (!aContinueSelection && aMultipleSelection)) {
// Scripted command or the user is starting a new explicit multi-range
// selection.
for (RangeData& entry : ranges) {
entry.mRange->SetIsGenerated(false);
}
return;
}
int16_t reason = aSelection->mFrameSelection->mSelectionChangeReason;
bool isAnchorRelativeOp =
(reason & (nsISelectionListener::DRAG_REASON |
nsISelectionListener::MOUSEDOWN_REASON |
nsISelectionListener::MOUSEUP_REASON |
nsISelectionListener::COLLAPSETOSTART_REASON));
if (!isAnchorRelativeOp) {
return;
}
// This operation is against the anchor but our current mAnchorFocusRange
// represents the focus in a multi-range selection. The anchor from a user
// perspective is the most distant generated range on the opposite side.
// Find that range and make it the mAnchorFocusRange.
const size_t len = ranges.Length();
size_t newAnchorFocusIndex = size_t(-1);
if (aSelection->GetDirection() == eDirNext) {
for (size_t i = 0; i < len; ++i) {
if (ranges[i].mRange->IsGenerated()) {
newAnchorFocusIndex = i;
break;
}
}
} else {
size_t i = len;
while (i--) {
if (ranges[i].mRange->IsGenerated()) {
newAnchorFocusIndex = i;
break;
}
}
}
if (newAnchorFocusIndex == size_t(-1)) {
// There are no generated ranges - that's fine.
return;
}
// Setup the new mAnchorFocusRange and mark the old one as generated.
if (aSelection->mAnchorFocusRange) {
aSelection->mAnchorFocusRange->SetIsGenerated(true);
}
nsRange* range = ranges[newAnchorFocusIndex].mRange;
range->SetIsGenerated(false);
aSelection->mAnchorFocusRange = range;
// Remove all generated ranges (including the old mAnchorFocusRange).
RefPtr<nsPresContext> presContext = aSelection->GetPresContext();
size_t i = len;
while (i--) {
range = aSelection->mRanges[i].mRange;
if (range->IsGenerated()) {
range->SetSelection(nullptr);
aSelection->SelectFrames(presContext, range, false);
aSelection->mRanges.RemoveElementAt(i);
}
}
if (aSelection->mFrameSelection) {
aSelection->mFrameSelection->InvalidateDesiredPos();
}
}
Maybe<Selection::AutoUserInitiated> mUserSelect;
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};
} // namespace mozilla
////////////BEGIN nsFrameSelection methods
nsFrameSelection::nsFrameSelection() {
for (size_t i = 0; i < ArrayLength(mDomSelections); i++) {
mDomSelections[i] = new Selection(this);
mDomSelections[i]->SetType(kPresentSelectionTypes[i]);
}
#ifdef XP_MACOSX
// On macOS, cache the current selection to send to service menu of macOS.
bool enableAutoCopy = true;
AutoCopyListener::Init(nsIClipboard::kSelectionCache);
#else // #ifdef XP_MACOSX
// Check to see if the auto-copy pref is enabled and make the normal
// Selection notifies auto-copy listener of its changes.
bool enableAutoCopy = AutoCopyListener::IsPrefEnabled();
if (enableAutoCopy) {
AutoCopyListener::Init(nsIClipboard::kSelectionClipboard);
}
#endif // #ifdef XP_MACOSX #else
if (enableAutoCopy) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (mDomSelections[index]) {
mDomSelections[index]->NotifyAutoCopy();
}
}
}
nsFrameSelection::~nsFrameSelection() {}
NS_IMPL_CYCLE_COLLECTION_CLASS(nsFrameSelection)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsFrameSelection)
for (size_t i = 0; i < ArrayLength(tmp->mDomSelections); ++i) {
tmp->mDomSelections[i] = nullptr;
}
NS_IMPL_CYCLE_COLLECTION_UNLINK(mCellParent)
tmp->mSelectingTableCellMode = TableSelection::None;
tmp->mDragSelectingCells = false;
NS_IMPL_CYCLE_COLLECTION_UNLINK(mStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mEndSelectedCell)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mAppendStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mUnselectCellOnMouseUp)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mMaintainRange)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mLimiter)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mAncestorLimiter)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsFrameSelection)
if (tmp->mPresShell && tmp->mPresShell->GetDocument() &&
nsCCUncollectableMarker::InGeneration(
cb, tmp->mPresShell->GetDocument()->GetMarkedCCGeneration())) {
return NS_SUCCESS_INTERRUPTED_TRAVERSE;
}
for (size_t i = 0; i < ArrayLength(tmp->mDomSelections); ++i) {
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDomSelections[i])
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCellParent)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mEndSelectedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAppendStartSelectedCell)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mUnselectCellOnMouseUp)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mMaintainRange)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mLimiter)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAncestorLimiter)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(nsFrameSelection, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(nsFrameSelection, Release)
// Get the x (or y, in vertical writing mode) position requested
// by the Key Handling for line-up/down
nsresult nsFrameSelection::FetchDesiredPos(nsPoint& aDesiredPos) {
if (!mPresShell) {
NS_ERROR("fetch desired position failed");
return NS_ERROR_FAILURE;
}
if (mDesiredPosSet) {
aDesiredPos = mDesiredPos;
return NS_OK;
}
RefPtr<nsCaret> caret = mPresShell->GetCaret();
if (!caret) {
return NS_ERROR_NULL_POINTER;
}
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
caret->SetSelection(mDomSelections[index]);
nsRect coord;
nsIFrame* caretFrame = caret->GetGeometry(&coord);
if (!caretFrame) {
return NS_ERROR_FAILURE;
}
nsPoint viewOffset(0, 0);
nsView* view = nullptr;
caretFrame->GetOffsetFromView(viewOffset, &view);
if (view) {
coord += viewOffset;
}
aDesiredPos = coord.TopLeft();
return NS_OK;
}
void nsFrameSelection::InvalidateDesiredPos() // do not listen to mDesiredPos;
// you must get another.
{
mDesiredPosSet = false;
}
void nsFrameSelection::SetDesiredPos(nsPoint aPos) {
mDesiredPos = aPos;
mDesiredPosSet = true;
}
nsresult nsFrameSelection::ConstrainFrameAndPointToAnchorSubtree(
nsIFrame* aFrame, const nsPoint& aPoint, nsIFrame** aRetFrame,
nsPoint& aRetPoint) {
//
// The whole point of this method is to return a frame and point that
// that lie within the same valid subtree as the anchor node's frame,
// for use with the method GetContentAndOffsetsFromPoint().
//
// A valid subtree is defined to be one where all the content nodes in
// the tree have a valid parent-child relationship.
//
// If the anchor frame and aFrame are in the same subtree, aFrame will
// be returned in aRetFrame. If they are in different subtrees, we
// return the frame for the root of the subtree.
//
if (!aFrame || !aRetFrame) return NS_ERROR_NULL_POINTER;
*aRetFrame = aFrame;
aRetPoint = aPoint;
//
// Get the frame and content for the selection's anchor point!
//
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) return NS_ERROR_NULL_POINTER;
nsCOMPtr<nsIContent> anchorContent =
do_QueryInterface(mDomSelections[index]->GetAnchorNode());
if (!anchorContent) return NS_ERROR_FAILURE;
//
// Now find the root of the subtree containing the anchor's content.
//
NS_ENSURE_STATE(mPresShell);
nsIContent* anchorRoot = anchorContent->GetSelectionRootContent(mPresShell);
NS_ENSURE_TRUE(anchorRoot, NS_ERROR_UNEXPECTED);
//
// Now find the root of the subtree containing aFrame's content.
//
nsIContent* content = aFrame->GetContent();
if (content) {
nsIContent* contentRoot = content->GetSelectionRootContent(mPresShell);
NS_ENSURE_TRUE(contentRoot, NS_ERROR_UNEXPECTED);
if (anchorRoot == contentRoot) {
// If the aFrame's content isn't the capturing content, it should be
// a descendant. At this time, we can return simply.
nsIContent* capturedContent = PresShell::GetCapturingContent();
if (capturedContent != content) {
return NS_OK;
}
// Find the frame under the mouse cursor with the root frame.
// At this time, don't use the anchor's frame because it may not have
// fixed positioned frames.
nsIFrame* rootFrame = mPresShell->GetRootFrame();
nsPoint ptInRoot = aPoint + aFrame->GetOffsetTo(rootFrame);
nsIFrame* cursorFrame =
nsLayoutUtils::GetFrameForPoint(rootFrame, ptInRoot);
// If the mouse cursor in on a frame which is descendant of same
// selection root, we can expand the selection to the frame.
if (cursorFrame && cursorFrame->PresShell() == mPresShell) {
nsIContent* cursorContent = cursorFrame->GetContent();
NS_ENSURE_TRUE(cursorContent, NS_ERROR_FAILURE);
nsIContent* cursorContentRoot =
cursorContent->GetSelectionRootContent(mPresShell);
NS_ENSURE_TRUE(cursorContentRoot, NS_ERROR_UNEXPECTED);
if (cursorContentRoot == anchorRoot) {
*aRetFrame = cursorFrame;
aRetPoint = aPoint + aFrame->GetOffsetTo(cursorFrame);
return NS_OK;
}
}
// Otherwise, e.g., the cursor isn't on any frames (e.g., the mouse
// cursor is out of the window), we should use the frame of the anchor
// root.
}
}
//
// When we can't find a frame which is under the mouse cursor and has a same
// selection root as the anchor node's, we should return the selection root
// frame.
//
*aRetFrame = anchorRoot->GetPrimaryFrame();
if (!*aRetFrame) return NS_ERROR_FAILURE;
//
// Now make sure that aRetPoint is converted to the same coordinate
// system used by aRetFrame.
//
aRetPoint = aPoint + aFrame->GetOffsetTo(*aRetFrame);
return NS_OK;
}
void nsFrameSelection::SetCaretBidiLevel(nsBidiLevel aLevel) {
// If the current level is undefined, we have just inserted new text.
// In this case, we don't want to reset the keyboard language
mCaretBidiLevel = aLevel;
RefPtr<nsCaret> caret;
if (mPresShell && (caret = mPresShell->GetCaret())) {
caret->SchedulePaint();
}
}
nsBidiLevel nsFrameSelection::GetCaretBidiLevel() const {
return mCaretBidiLevel;
}
void nsFrameSelection::UndefineCaretBidiLevel() {
mCaretBidiLevel |= BIDI_LEVEL_UNDEFINED;
}
#ifdef PRINT_RANGE
void printRange(nsRange* aDomRange) {
if (!aDomRange) {
printf("NULL Range\n");
}
nsINode* startNode = aDomRange->GetStartContainer();
nsINode* endNode = aDomRange->GetEndContainer();
int32_t startOffset = aDomRange->StartOffset();
int32_t endOffset = aDomRange->EndOffset();
printf("range: 0x%lx\t start: 0x%lx %ld, \t end: 0x%lx,%ld\n",
(unsigned long)aDomRange, (unsigned long)startNode, (long)startOffset,
(unsigned long)endNode, (long)endOffset);
}
#endif /* PRINT_RANGE */
static nsAtom* GetTag(nsINode* aNode) {
nsCOMPtr<nsIContent> content = do_QueryInterface(aNode);
if (!content) {
MOZ_ASSERT_UNREACHABLE("bad node passed to GetTag()");
return nullptr;
}
return content->NodeInfo()->NameAtom();
}
// Returns the parent
nsINode* ParentOffset(nsINode* aNode, int32_t* aChildOffset) {
if (!aNode || !aChildOffset) return nullptr;
nsIContent* parent = aNode->GetParent();
if (parent) {
*aChildOffset = parent->ComputeIndexOf(aNode);
return parent;
}
return nullptr;
}
static nsINode* GetCellParent(nsINode* aDomNode) {
if (!aDomNode) return nullptr;
nsINode* current = aDomNode;
// Start with current node and look for a table cell
while (current) {
nsAtom* tag = GetTag(current);
if (tag == nsGkAtoms::td || tag == nsGkAtoms::th) return current;
current = current->GetParent();
}
return nullptr;
}
void nsFrameSelection::Init(mozilla::PresShell* aPresShell,
nsIContent* aLimiter,
bool aAccessibleCaretEnabled) {
mPresShell = aPresShell;
mDragState = false;
mDesiredPosSet = false;
mLimiter = aLimiter;
mCaretMovementStyle =
Preferences::GetInt("bidi.edit.caret_movement_style", 2);
// This should only ever be initialized on the main thread, so we are OK here.
static bool prefCachesInitialized = false;
if (!prefCachesInitialized) {
prefCachesInitialized = true;
Preferences::AddBoolVarCache(&sSelectionEventsOnTextControlsEnabled,
"dom.select_events.textcontrols.enabled",
false);
}
mAccessibleCaretEnabled = aAccessibleCaretEnabled;
if (mAccessibleCaretEnabled) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
mDomSelections[index]->MaybeNotifyAccessibleCaretEventHub(aPresShell);
}
bool plaintextControl = (aLimiter != nullptr);
bool initSelectEvents = plaintextControl
? sSelectionEventsOnTextControlsEnabled
: StaticPrefs::dom_select_events_enabled();
Document* doc = aPresShell->GetDocument();
if (initSelectEvents ||
(doc && nsContentUtils::IsSystemPrincipal(doc->NodePrincipal()))) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (mDomSelections[index]) {
mDomSelections[index]->EnableSelectionChangeEvent();
}
}
}
bool nsFrameSelection::sSelectionEventsOnTextControlsEnabled = false;
nsresult nsFrameSelection::MoveCaret(nsDirection aDirection,
bool aContinueSelection,
nsSelectionAmount aAmount,
CaretMovementStyle aMovementStyle) {
bool visualMovement = aMovementStyle == eVisual ||
(aMovementStyle == eUsePrefStyle &&
(mCaretMovementStyle == 1 ||
(mCaretMovementStyle == 2 && !aContinueSelection)));
NS_ENSURE_STATE(mPresShell);
// Flush out layout, since we need it to be up to date to do caret
// positioning.
OwningNonNull<PresShell> presShell(*mPresShell);
presShell->FlushPendingNotifications(FlushType::Layout);
if (!mPresShell) {
return NS_OK;
}
nsPresContext* context = mPresShell->GetPresContext();
if (!context) return NS_ERROR_FAILURE;
// we must keep this around and revalidate it when its just UP/DOWN
nsPoint desiredPos(0, 0);
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
RefPtr<Selection> sel = mDomSelections[index];
if (!sel) return NS_ERROR_NULL_POINTER;
int32_t scrollFlags = Selection::SCROLL_FOR_CARET_MOVE;
const bool isEditorSelection = sel->IsEditorSelection();
if (isEditorSelection) {
// If caret moves in editor, it should cause scrolling even if it's in
// overflow: hidden;.
scrollFlags |= Selection::SCROLL_OVERFLOW_HIDDEN;
}
int32_t caretStyle = Preferences::GetInt("layout.selection.caret_style", 0);
if (caretStyle == 0
#ifdef XP_WIN
&& aAmount != eSelectLine
#endif
) {
// Put caret at the selection edge in the |aDirection| direction.
caretStyle = 2;
}
bool doCollapse = !sel->IsCollapsed() && !aContinueSelection &&
caretStyle == 2 && aAmount <= eSelectLine;
if (doCollapse) {
if (aDirection == eDirPrevious) {
PostReason(nsISelectionListener::COLLAPSETOSTART_REASON);
mHint = CARET_ASSOCIATE_AFTER;
} else {
PostReason(nsISelectionListener::COLLAPSETOEND_REASON);
mHint = CARET_ASSOCIATE_BEFORE;
}
} else {
PostReason(nsISelectionListener::KEYPRESS_REASON);
}
AutoPrepareFocusRange prep(sel, aContinueSelection, false);
if (aAmount == eSelectLine) {
nsresult result = FetchDesiredPos(desiredPos);
if (NS_FAILED(result)) {
return result;
}
SetDesiredPos(desiredPos);
}
if (doCollapse) {
const nsRange* anchorFocusRange = sel->GetAnchorFocusRange();
if (anchorFocusRange) {
nsINode* node;
int32_t offset;
if (aDirection == eDirPrevious) {
node = anchorFocusRange->GetStartContainer();
offset = anchorFocusRange->StartOffset();
} else {
node = anchorFocusRange->GetEndContainer();
offset = anchorFocusRange->EndOffset();
}
sel->Collapse(node, offset);
}
sel->ScrollIntoView(nsISelectionController::SELECTION_FOCUS_REGION,
ScrollAxis(), ScrollAxis(), scrollFlags);
return NS_OK;
}
nsIFrame* frame;
int32_t offsetused = 0;
nsresult result =
sel->GetPrimaryFrameForFocusNode(&frame, &offsetused, visualMovement);
if (NS_FAILED(result) || !frame)
return NS_FAILED(result) ? result : NS_ERROR_FAILURE;
const auto forceEditableRegion =
isEditorSelection ? nsPeekOffsetStruct::ForceEditableRegion::Yes
: nsPeekOffsetStruct::ForceEditableRegion::No;
// set data using mLimiter to stop on scroll views. If we have a limiter then
// we stop peeking when we hit scrollable views. If no limiter then just let
// it go ahead
nsPeekOffsetStruct pos(aAmount, eDirPrevious, offsetused, desiredPos, true,
mLimiter != nullptr, true, visualMovement,
aContinueSelection, forceEditableRegion);
nsBidiDirection paraDir = nsBidiPresUtils::ParagraphDirection(frame);
CaretAssociateHint tHint(
mHint); // temporary variable so we dont set mHint until it is necessary
switch (aAmount) {
case eSelectCharacter:
case eSelectCluster:
case eSelectWord:
case eSelectWordNoSpace:
InvalidateDesiredPos();
pos.mAmount = aAmount;
pos.mDirection = (visualMovement && paraDir == NSBIDI_RTL)
? nsDirection(1 - aDirection)
: aDirection;
break;
case eSelectLine:
pos.mAmount = aAmount;
pos.mDirection = aDirection;
break;
case eSelectBeginLine:
case eSelectEndLine:
InvalidateDesiredPos();
pos.mAmount = aAmount;
pos.mDirection = (visualMovement && paraDir == NSBIDI_RTL)
? nsDirection(1 - aDirection)
: aDirection;
break;
default:
return NS_ERROR_FAILURE;
}
if (NS_SUCCEEDED(result = frame->PeekOffset(&pos)) && pos.mResultContent) {
nsIFrame* theFrame;
int32_t currentOffset, frameStart, frameEnd;
if (aAmount <= eSelectWordNoSpace) {
// For left/right, PeekOffset() sets pos.mResultFrame correctly, but does
// not set pos.mAttachForward, so determine the hint here based on the
// result frame and offset: If we're at the end of a text frame, set the
// hint to ASSOCIATE_BEFORE to indicate that we want the caret displayed
// at the end of this frame, not at the beginning of the next one.
theFrame = pos.mResultFrame;
theFrame->GetOffsets(frameStart, frameEnd);
currentOffset = pos.mContentOffset;
if (frameEnd == currentOffset && !(frameStart == 0 && frameEnd == 0))
tHint = CARET_ASSOCIATE_BEFORE;
else
tHint = CARET_ASSOCIATE_AFTER;
} else {
// For up/down and home/end, pos.mResultFrame might not be set correctly,
// or not at all. In these cases, get the frame based on the content and
// hint returned by PeekOffset().
tHint = pos.mAttach;
theFrame = GetFrameForNodeOffset(pos.mResultContent, pos.mContentOffset,
tHint, ¤tOffset);
if (!theFrame) return NS_ERROR_FAILURE;
theFrame->GetOffsets(frameStart, frameEnd);
}
if (context->BidiEnabled()) {
switch (aAmount) {
case eSelectBeginLine:
case eSelectEndLine: {
// In Bidi contexts, PeekOffset calculates pos.mContentOffset
// differently depending on whether the movement is visual or logical.
// For visual movement, pos.mContentOffset depends on the direction-
// ality of the first/last frame on the line (theFrame), and the caret
// directionality must correspond.
FrameBidiData bidiData = theFrame->GetBidiData();
SetCaretBidiLevel(visualMovement ? bidiData.embeddingLevel
: bidiData.baseLevel);
break;
}
default:
// If the current position is not a frame boundary, it's enough just
// to take the Bidi level of the current frame
if ((pos.mContentOffset != frameStart &&
pos.mContentOffset != frameEnd) ||
eSelectLine == aAmount) {
SetCaretBidiLevel(theFrame->GetEmbeddingLevel());
} else {
BidiLevelFromMove(mPresShell, pos.mResultContent,
pos.mContentOffset, aAmount, tHint);
}
}
}
// "pos" is on the stack, so pos.mResultContent has stack lifetime, so using
// MOZ_KnownLive is ok.
result = TakeFocus(MOZ_KnownLive(pos.mResultContent), pos.mContentOffset,
pos.mContentOffset, tHint, aContinueSelection, false);
} else if (aAmount <= eSelectWordNoSpace && aDirection == eDirNext &&
!aContinueSelection) {
// Collapse selection if PeekOffset failed, we either
// 1. bumped into the BRFrame, bug 207623
// 2. had select-all in a text input (DIV range), bug 352759.
bool isBRFrame = frame->IsBrFrame();
sel->Collapse(sel->GetFocusNode(), sel->FocusOffset());
// Note: 'frame' might be dead here.
if (!isBRFrame) {
mHint = CARET_ASSOCIATE_BEFORE; // We're now at the end of the frame to
// the left.
}
result = NS_OK;
}
if (NS_SUCCEEDED(result)) {
result = mDomSelections[index]->ScrollIntoView(
nsISelectionController::SELECTION_FOCUS_REGION, ScrollAxis(),
ScrollAxis(), scrollFlags);
}
return result;
}
nsPrevNextBidiLevels nsFrameSelection::GetPrevNextBidiLevels(
nsIContent* aNode, uint32_t aContentOffset, bool aJumpLines) const {
return GetPrevNextBidiLevels(aNode, aContentOffset, mHint, aJumpLines);
}
nsPrevNextBidiLevels nsFrameSelection::GetPrevNextBidiLevels(
nsIContent* aNode, uint32_t aContentOffset, CaretAssociateHint aHint,
bool aJumpLines) const {
// Get the level of the frames on each side
nsIFrame* currentFrame;
int32_t currentOffset;
int32_t frameStart, frameEnd;
nsDirection direction;
nsPrevNextBidiLevels levels;
levels.SetData(nullptr, nullptr, 0, 0);
currentFrame =
GetFrameForNodeOffset(aNode, aContentOffset, aHint, ¤tOffset);
if (!currentFrame) return levels;
currentFrame->GetOffsets(frameStart, frameEnd);
if (0 == frameStart && 0 == frameEnd)
direction = eDirPrevious;
else if (frameStart == currentOffset)
direction = eDirPrevious;
else if (frameEnd == currentOffset)
direction = eDirNext;
else {
// we are neither at the beginning nor at the end of the frame, so we have
// no worries
nsBidiLevel currentLevel = currentFrame->GetEmbeddingLevel();
levels.SetData(currentFrame, currentFrame, currentLevel, currentLevel);
return levels;
}
nsIFrame* newFrame;
int32_t offset;
bool jumpedLine, movedOverNonSelectableText;
nsresult rv = currentFrame->GetFrameFromDirection(
direction, false, aJumpLines, true, false, &newFrame, &offset,
&jumpedLine, &movedOverNonSelectableText);
if (NS_FAILED(rv)) newFrame = nullptr;
FrameBidiData currentBidi = currentFrame->GetBidiData();
nsBidiLevel currentLevel = currentBidi.embeddingLevel;
nsBidiLevel newLevel =
newFrame ? newFrame->GetEmbeddingLevel() : currentBidi.baseLevel;
// If not jumping lines, disregard br frames, since they might be positioned
// incorrectly.
// XXX This could be removed once bug 339786 is fixed.
if (!aJumpLines) {
if (currentFrame->IsBrFrame()) {
currentFrame = nullptr;
currentLevel = currentBidi.baseLevel;
}
if (newFrame && newFrame->IsBrFrame()) {
newFrame = nullptr;
newLevel = currentBidi.baseLevel;
}
}
if (direction == eDirNext)
levels.SetData(currentFrame, newFrame, currentLevel, newLevel);
else
levels.SetData(newFrame, currentFrame, newLevel, currentLevel);
return levels;
}
nsresult nsFrameSelection::GetFrameFromLevel(nsIFrame* aFrameIn,
nsDirection aDirection,
nsBidiLevel aBidiLevel,
nsIFrame** aFrameOut) const {
NS_ENSURE_STATE(mPresShell);
nsBidiLevel foundLevel = 0;
nsIFrame* foundFrame = aFrameIn;
nsCOMPtr<nsIFrameEnumerator> frameTraversal;
nsresult result;
nsCOMPtr<nsIFrameTraversal> trav(
do_CreateInstance(kFrameTraversalCID, &result));
if (NS_FAILED(result)) return result;
result =
trav->NewFrameTraversal(getter_AddRefs(frameTraversal),
mPresShell->GetPresContext(), aFrameIn, eLeaf,
false, // aVisual
false, // aLockInScrollView
false, // aFollowOOFs
false // aSkipPopupChecks
);
if (NS_FAILED(result)) return result;
do {
*aFrameOut = foundFrame;
if (aDirection == eDirNext)
frameTraversal->Next();
else
frameTraversal->Prev();
foundFrame = frameTraversal->CurrentItem();
if (!foundFrame) return NS_ERROR_FAILURE;
foundLevel = foundFrame->GetEmbeddingLevel();
} while (foundLevel > aBidiLevel);
return NS_OK;
}
nsresult nsFrameSelection::MaintainSelection(nsSelectionAmount aAmount) {
int8_t index = GetIndexFromSelectionType(SelectionType::eNormal);
if (!mDomSelections[index]) return NS_ERROR_NULL_POINTER;
mMaintainedAmount = aAmount;
const nsRange* anchorFocusRange =
mDomSelections[index]->GetAnchorFocusRange();
if (anchorFocusRange && aAmount != eSelectNoAmount) {
mMaintainRange = anchorFocusRange->CloneRange();
return NS_OK;
}
mMaintainRange = nullptr;
return NS_OK;
}
/**
* After moving the caret, its Bidi level is set according to the following
* rules:
*
* After moving over a character with left/right arrow, set to the Bidi level
* of the last moved over character. After Home and End, set to the paragraph
* embedding level. After up/down arrow, PageUp/Down, set to the lower level of
* the 2 surrounding characters. After mouse click, set to the level of the
* current frame.
*
* The following two methods use GetPrevNextBidiLevels to determine the new
* Bidi level. BidiLevelFromMove is called when the caret is moved in response
* to a keyboard event
*
* @param aPresShell is the presentation shell
* @param aNode is the content node
* @param aContentOffset is the new caret position, as an offset into aNode
* @param aAmount is the amount of the move that gave the caret its new position
* @param aHint is the hint indicating in what logical direction the caret moved
*/
void nsFrameSelection::BidiLevelFromMove(PresShell* aPresShell,
nsIContent* aNode,
uint32_t aContentOffset,
nsSelectionAmount aAmount,
CaretAssociateHint aHint) {
switch (aAmount) {
// Movement within the line: the new cursor Bidi level is the level of the
// last character moved over
case eSelectCharacter:
case eSelectCluster:
case eSelectWord:
case eSelectWordNoSpace:
case eSelectBeginLine: