forked from mozilla-firefox/firefox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnsTextFrame.cpp
10802 lines (9762 loc) · 412 KB
/
nsTextFrame.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/. */
/* rendering object for textual content of elements */
#include "nsTextFrame.h"
#include "gfx2DGlue.h"
#include "gfxUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/CaretAssociationHint.h"
#include "mozilla/ComputedStyle.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/Likely.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/StaticPresData.h"
#include "mozilla/SVGTextFrame.h"
#include "mozilla/TextEditor.h"
#include "mozilla/TextEvents.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/Unused.h"
#include "mozilla/PodOperations.h"
#include "mozilla/dom/PerformanceMainThread.h"
#include "nsCOMPtr.h"
#include "nsBlockFrame.h"
#include "nsFontMetrics.h"
#include "nsSplittableFrame.h"
#include "nsLineLayout.h"
#include "nsString.h"
#include "nsUnicharUtils.h"
#include "nsPresContext.h"
#include "nsIContent.h"
#include "nsStyleConsts.h"
#include "nsStyleStruct.h"
#include "nsStyleStructInlines.h"
#include "nsCoord.h"
#include "gfxContext.h"
#include "nsTArray.h"
#include "nsCSSPseudoElements.h"
#include "nsCSSFrameConstructor.h"
#include "nsCompatibility.h"
#include "nsCSSColorUtils.h"
#include "nsLayoutUtils.h"
#include "nsDisplayList.h"
#include "nsIFrame.h"
#include "nsIMathMLFrame.h"
#include "nsFirstLetterFrame.h"
#include "nsPlaceholderFrame.h"
#include "nsTextFrameUtils.h"
#include "nsTextPaintStyle.h"
#include "nsTextRunTransformations.h"
#include "MathMLTextRunFactory.h"
#include "nsUnicodeProperties.h"
#include "nsStyleUtil.h"
#include "nsRubyFrame.h"
#include "PresShellInlines.h"
#include "TextDrawTarget.h"
#include "nsTextFragment.h"
#include "nsGkAtoms.h"
#include "nsFrameSelection.h"
#include "nsRange.h"
#include "nsCSSRendering.h"
#include "nsContentUtils.h"
#include "nsLineBreaker.h"
#include "nsIFrameInlines.h"
#include "mozilla/intl/Bidi.h"
#include "mozilla/intl/Segmenter.h"
#include "mozilla/intl/UnicodeProperties.h"
#include "mozilla/ServoStyleSet.h"
#include <algorithm>
#include <limits>
#include <type_traits>
#ifdef ACCESSIBILITY
# include "nsAccessibilityService.h"
#endif
#include "nsPrintfCString.h"
#include "mozilla/gfx/DrawTargetRecording.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/dom/Element.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/ProfilerLabels.h"
#ifdef DEBUG
# undef NOISY_REFLOW
# undef NOISY_TRIM
#else
# undef NOISY_REFLOW
# undef NOISY_TRIM
#endif
#ifdef DrawText
# undef DrawText
#endif
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::gfx;
typedef mozilla::layout::TextDrawTarget TextDrawTarget;
static bool NeedsToMaskPassword(nsTextFrame* aFrame) {
MOZ_ASSERT(aFrame);
MOZ_ASSERT(aFrame->GetContent());
if (!aFrame->GetContent()->HasFlag(NS_MAYBE_MASKED)) {
return false;
}
nsIFrame* frame =
nsLayoutUtils::GetClosestFrameOfType(aFrame, LayoutFrameType::TextInput);
MOZ_ASSERT(frame, "How do we have a masked text node without a text input?");
return !frame || !frame->GetContent()->AsElement()->State().HasState(
ElementState::REVEALED);
}
struct TabWidth {
TabWidth(uint32_t aOffset, uint32_t aWidth)
: mOffset(aOffset), mWidth(float(aWidth)) {}
uint32_t mOffset; // DOM offset relative to the current frame's offset.
float mWidth; // extra space to be added at this position (in app units)
};
struct nsTextFrame::TabWidthStore {
explicit TabWidthStore(int32_t aValidForContentOffset)
: mLimit(0), mValidForContentOffset(aValidForContentOffset) {}
// Apply tab widths to the aSpacing array, which corresponds to characters
// beginning at aOffset and has length aLength. (Width records outside this
// range will be ignored.)
void ApplySpacing(gfxTextRun::PropertyProvider::Spacing* aSpacing,
uint32_t aOffset, uint32_t aLength);
// Offset up to which tabs have been measured; positions beyond this have not
// been calculated yet but may be appended if needed later. It's a DOM
// offset relative to the current frame's offset.
uint32_t mLimit;
// Need to recalc tab offsets if frame content offset differs from this.
int32_t mValidForContentOffset;
// A TabWidth record for each tab character measured so far.
nsTArray<TabWidth> mWidths;
};
namespace {
struct TabwidthAdaptor {
const nsTArray<TabWidth>& mWidths;
explicit TabwidthAdaptor(const nsTArray<TabWidth>& aWidths)
: mWidths(aWidths) {}
uint32_t operator[](size_t aIdx) const { return mWidths[aIdx].mOffset; }
};
} // namespace
void nsTextFrame::TabWidthStore::ApplySpacing(
gfxTextRun::PropertyProvider::Spacing* aSpacing, uint32_t aOffset,
uint32_t aLength) {
size_t i = 0;
const size_t len = mWidths.Length();
// If aOffset is non-zero, do a binary search to find where to start
// processing the tab widths, in case the list is really long. (See bug
// 953247.)
// We need to start from the first entry where mOffset >= aOffset.
if (aOffset > 0) {
mozilla::BinarySearch(TabwidthAdaptor(mWidths), 0, len, aOffset, &i);
}
uint32_t limit = aOffset + aLength;
while (i < len) {
const TabWidth& tw = mWidths[i];
if (tw.mOffset >= limit) {
break;
}
aSpacing[tw.mOffset - aOffset].mAfter += tw.mWidth;
i++;
}
}
NS_DECLARE_FRAME_PROPERTY_DELETABLE(TabWidthProperty,
nsTextFrame::TabWidthStore)
NS_DECLARE_FRAME_PROPERTY_WITHOUT_DTOR(OffsetToFrameProperty, nsTextFrame)
NS_DECLARE_FRAME_PROPERTY_RELEASABLE(UninflatedTextRunProperty, gfxTextRun)
NS_DECLARE_FRAME_PROPERTY_SMALL_VALUE(FontSizeInflationProperty, float)
NS_DECLARE_FRAME_PROPERTY_SMALL_VALUE(HangableWhitespaceProperty, nscoord)
NS_DECLARE_FRAME_PROPERTY_SMALL_VALUE(TrimmableWhitespaceProperty,
gfxTextRun::TrimmableWS)
struct nsTextFrame::PaintTextSelectionParams : nsTextFrame::PaintTextParams {
Point textBaselinePt;
PropertyProvider* provider = nullptr;
Range contentRange;
nsTextPaintStyle* textPaintStyle = nullptr;
Range glyphRange;
explicit PaintTextSelectionParams(const PaintTextParams& aParams)
: PaintTextParams(aParams) {}
};
struct nsTextFrame::DrawTextRunParams {
gfxContext* context;
mozilla::gfx::PaletteCache& paletteCache;
PropertyProvider* provider = nullptr;
gfxFloat* advanceWidth = nullptr;
mozilla::SVGContextPaint* contextPaint = nullptr;
DrawPathCallbacks* callbacks = nullptr;
nscolor textColor = NS_RGBA(0, 0, 0, 0);
nscolor textStrokeColor = NS_RGBA(0, 0, 0, 0);
nsAtom* fontPalette = nullptr;
float textStrokeWidth = 0.0f;
bool drawSoftHyphen = false;
bool hasTextShadow = false;
bool paintingShadows = false;
DrawTextRunParams(gfxContext* aContext,
mozilla::gfx::PaletteCache& aPaletteCache)
: context(aContext), paletteCache(aPaletteCache) {}
};
struct nsTextFrame::ClipEdges {
ClipEdges(const nsIFrame* aFrame, const nsPoint& aToReferenceFrame,
nscoord aVisIStartEdge, nscoord aVisIEndEdge) {
nsRect r = aFrame->ScrollableOverflowRect() + aToReferenceFrame;
if (aFrame->GetWritingMode().IsVertical()) {
mVisIStart = aVisIStartEdge > 0 ? r.y + aVisIStartEdge : nscoord_MIN;
mVisIEnd = aVisIEndEdge > 0
? std::max(r.YMost() - aVisIEndEdge, mVisIStart)
: nscoord_MAX;
} else {
mVisIStart = aVisIStartEdge > 0 ? r.x + aVisIStartEdge : nscoord_MIN;
mVisIEnd = aVisIEndEdge > 0
? std::max(r.XMost() - aVisIEndEdge, mVisIStart)
: nscoord_MAX;
}
}
void Intersect(nscoord* aVisIStart, nscoord* aVisISize) const {
nscoord end = *aVisIStart + *aVisISize;
*aVisIStart = std::max(*aVisIStart, mVisIStart);
*aVisISize = std::max(std::min(end, mVisIEnd) - *aVisIStart, 0);
}
nscoord mVisIStart;
nscoord mVisIEnd;
};
struct nsTextFrame::DrawTextParams : nsTextFrame::DrawTextRunParams {
Point framePt;
LayoutDeviceRect dirtyRect;
const nsTextPaintStyle* textStyle = nullptr;
const ClipEdges* clipEdges = nullptr;
const nscolor* decorationOverrideColor = nullptr;
Range glyphRange;
DrawTextParams(gfxContext* aContext,
mozilla::gfx::PaletteCache& aPaletteCache)
: DrawTextRunParams(aContext, aPaletteCache) {}
};
struct nsTextFrame::PaintShadowParams {
gfxTextRun::Range range;
LayoutDeviceRect dirtyRect;
Point framePt;
Point textBaselinePt;
gfxContext* context;
DrawPathCallbacks* callbacks = nullptr;
nscolor foregroundColor = NS_RGBA(0, 0, 0, 0);
const ClipEdges* clipEdges = nullptr;
PropertyProvider* provider = nullptr;
nscoord leftSideOffset = 0;
explicit PaintShadowParams(const PaintTextParams& aParams)
: dirtyRect(aParams.dirtyRect),
framePt(aParams.framePt),
context(aParams.context) {}
};
/**
* A glyph observer for the change of a font glyph in a text run.
*
* This is stored in {Simple, Complex}TextRunUserData.
*/
class GlyphObserver final : public gfxFont::GlyphChangeObserver {
public:
GlyphObserver(gfxFont* aFont, gfxTextRun* aTextRun)
: gfxFont::GlyphChangeObserver(aFont), mTextRun(aTextRun) {
MOZ_ASSERT(aTextRun->GetUserData());
}
void NotifyGlyphsChanged() override;
private:
gfxTextRun* mTextRun;
};
static const nsFrameState TEXT_REFLOW_FLAGS =
TEXT_FIRST_LETTER | TEXT_START_OF_LINE | TEXT_END_OF_LINE |
TEXT_HYPHEN_BREAK | TEXT_TRIMMED_TRAILING_WHITESPACE |
TEXT_JUSTIFICATION_ENABLED | TEXT_HAS_NONCOLLAPSED_CHARACTERS |
TEXT_SELECTION_UNDERLINE_OVERFLOWED | TEXT_NO_RENDERED_GLYPHS;
static const nsFrameState TEXT_WHITESPACE_FLAGS =
TEXT_IS_ONLY_WHITESPACE | TEXT_ISNOT_ONLY_WHITESPACE;
/*
* Some general notes
*
* Text frames delegate work to gfxTextRun objects. The gfxTextRun object
* transforms text to positioned glyphs. It can report the geometry of the
* glyphs and paint them. Text frames configure gfxTextRuns by providing text,
* spacing, language, and other information.
*
* A gfxTextRun can cover more than one DOM text node. This is necessary to
* get kerning, ligatures and shaping for text that spans multiple text nodes
* but is all the same font.
*
* The userdata for a gfxTextRun object can be:
*
* - A nsTextFrame* in the case a text run maps to only one flow. In this
* case, the textrun's user data pointer is a pointer to mStartFrame for that
* flow, mDOMOffsetToBeforeTransformOffset is zero, and mContentLength is the
* length of the text node.
*
* - A SimpleTextRunUserData in the case a text run maps to one flow, but we
* still have to keep a list of glyph observers.
*
* - A ComplexTextRunUserData in the case a text run maps to multiple flows,
* but we need to keep a list of glyph observers.
*
* - A TextRunUserData in the case a text run maps multiple flows, but it
* doesn't have any glyph observer for changes in SVG fonts.
*
* You can differentiate between the four different cases with the
* IsSimpleFlow and MightHaveGlyphChanges flags.
*
* We go to considerable effort to make sure things work even if in-flow
* siblings have different ComputedStyles (i.e., first-letter and first-line).
*
* Our convention is that unsigned integer character offsets are offsets into
* the transformed string. Signed integer character offsets are offsets into
* the DOM string.
*
* XXX currently we don't handle hyphenated breaks between text frames where the
* hyphen occurs at the end of the first text frame, e.g.
* <b>Kit­</b>ty
*/
/**
* This is our user data for the textrun, when textRun->GetFlags2() has
* IsSimpleFlow set, and also MightHaveGlyphChanges.
*
* This allows having an array of observers if there are fonts whose glyphs
* might change, but also avoid allocation in the simple case that there aren't.
*/
struct SimpleTextRunUserData {
nsTArray<UniquePtr<GlyphObserver>> mGlyphObservers;
nsTextFrame* mFrame;
explicit SimpleTextRunUserData(nsTextFrame* aFrame) : mFrame(aFrame) {}
};
/**
* We use an array of these objects to record which text frames
* are associated with the textrun. mStartFrame is the start of a list of
* text frames. Some sequence of its continuations are covered by the textrun.
* A content textnode can have at most one TextRunMappedFlow associated with it
* for a given textrun.
*
* mDOMOffsetToBeforeTransformOffset is added to DOM offsets for those frames to
* obtain the offset into the before-transformation text of the textrun. It can
* be positive (when a text node starts in the middle of a text run) or negative
* (when a text run starts in the middle of a text node). Of course it can also
* be zero.
*/
struct TextRunMappedFlow {
nsTextFrame* mStartFrame;
int32_t mDOMOffsetToBeforeTransformOffset;
// The text mapped starts at mStartFrame->GetContentOffset() and is this long
uint32_t mContentLength;
};
/**
* This is the type in the gfxTextRun's userdata field in the common case that
* the text run maps to multiple flows, but no fonts have been found with
* animatable glyphs.
*
* This way, we avoid allocating and constructing the extra nsTArray.
*/
struct TextRunUserData {
#ifdef DEBUG
TextRunMappedFlow* mMappedFlows;
#endif
uint32_t mMappedFlowCount;
uint32_t mLastFlowIndex;
};
/**
* This is our user data for the textrun, when textRun->GetFlags2() does not
* have IsSimpleFlow set and has the MightHaveGlyphChanges flag.
*/
struct ComplexTextRunUserData : public TextRunUserData {
nsTArray<UniquePtr<GlyphObserver>> mGlyphObservers;
};
static TextRunUserData* CreateUserData(uint32_t aMappedFlowCount) {
TextRunUserData* data = static_cast<TextRunUserData*>(moz_xmalloc(
sizeof(TextRunUserData) + aMappedFlowCount * sizeof(TextRunMappedFlow)));
#ifdef DEBUG
data->mMappedFlows = reinterpret_cast<TextRunMappedFlow*>(data + 1);
#endif
data->mMappedFlowCount = aMappedFlowCount;
data->mLastFlowIndex = 0;
return data;
}
static void DestroyUserData(TextRunUserData* aUserData) {
if (aUserData) {
free(aUserData);
}
}
static ComplexTextRunUserData* CreateComplexUserData(
uint32_t aMappedFlowCount) {
ComplexTextRunUserData* data = static_cast<ComplexTextRunUserData*>(
moz_xmalloc(sizeof(ComplexTextRunUserData) +
aMappedFlowCount * sizeof(TextRunMappedFlow)));
new (data) ComplexTextRunUserData();
#ifdef DEBUG
data->mMappedFlows = reinterpret_cast<TextRunMappedFlow*>(data + 1);
#endif
data->mMappedFlowCount = aMappedFlowCount;
data->mLastFlowIndex = 0;
return data;
}
static void DestroyComplexUserData(ComplexTextRunUserData* aUserData) {
if (aUserData) {
aUserData->~ComplexTextRunUserData();
free(aUserData);
}
}
static void DestroyTextRunUserData(gfxTextRun* aTextRun) {
MOZ_ASSERT(aTextRun->GetUserData());
if (aTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow) {
if (aTextRun->GetFlags2() &
nsTextFrameUtils::Flags::MightHaveGlyphChanges) {
delete static_cast<SimpleTextRunUserData*>(aTextRun->GetUserData());
}
} else {
if (aTextRun->GetFlags2() &
nsTextFrameUtils::Flags::MightHaveGlyphChanges) {
DestroyComplexUserData(
static_cast<ComplexTextRunUserData*>(aTextRun->GetUserData()));
} else {
DestroyUserData(static_cast<TextRunUserData*>(aTextRun->GetUserData()));
}
}
aTextRun->ClearFlagBits(nsTextFrameUtils::Flags::MightHaveGlyphChanges);
aTextRun->SetUserData(nullptr);
}
static TextRunMappedFlow* GetMappedFlows(const gfxTextRun* aTextRun) {
MOZ_ASSERT(aTextRun->GetUserData(), "UserData must exist.");
MOZ_ASSERT(!(aTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow),
"The method should not be called for simple flows.");
TextRunMappedFlow* flows;
if (aTextRun->GetFlags2() & nsTextFrameUtils::Flags::MightHaveGlyphChanges) {
flows = reinterpret_cast<TextRunMappedFlow*>(
static_cast<ComplexTextRunUserData*>(aTextRun->GetUserData()) + 1);
} else {
flows = reinterpret_cast<TextRunMappedFlow*>(
static_cast<TextRunUserData*>(aTextRun->GetUserData()) + 1);
}
MOZ_ASSERT(
static_cast<TextRunUserData*>(aTextRun->GetUserData())->mMappedFlows ==
flows,
"GetMappedFlows should return the same pointer as mMappedFlows.");
return flows;
}
/**
* These are utility functions just for helping with the complexity related with
* the text runs user data.
*/
static nsTextFrame* GetFrameForSimpleFlow(const gfxTextRun* aTextRun) {
MOZ_ASSERT(aTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow,
"Not so simple flow?");
if (aTextRun->GetFlags2() & nsTextFrameUtils::Flags::MightHaveGlyphChanges) {
return static_cast<SimpleTextRunUserData*>(aTextRun->GetUserData())->mFrame;
}
return static_cast<nsTextFrame*>(aTextRun->GetUserData());
}
/**
* Remove |aTextRun| from the frame continuation chain starting at
* |aStartContinuation| if non-null, otherwise starting at |aFrame|.
* Unmark |aFrame| as a text run owner if it's the frame we start at.
* Return true if |aStartContinuation| is non-null and was found
* in the next-continuation chain of |aFrame|.
*/
static bool ClearAllTextRunReferences(nsTextFrame* aFrame, gfxTextRun* aTextRun,
nsTextFrame* aStartContinuation,
nsFrameState aWhichTextRunState) {
MOZ_ASSERT(aFrame, "null frame");
MOZ_ASSERT(!aStartContinuation ||
(!aStartContinuation->GetTextRun(nsTextFrame::eInflated) ||
aStartContinuation->GetTextRun(nsTextFrame::eInflated) ==
aTextRun) ||
(!aStartContinuation->GetTextRun(nsTextFrame::eNotInflated) ||
aStartContinuation->GetTextRun(nsTextFrame::eNotInflated) ==
aTextRun),
"wrong aStartContinuation for this text run");
if (!aStartContinuation || aStartContinuation == aFrame) {
aFrame->RemoveStateBits(aWhichTextRunState);
} else {
do {
NS_ASSERTION(aFrame->IsTextFrame(), "Bad frame");
aFrame = aFrame->GetNextContinuation();
} while (aFrame && aFrame != aStartContinuation);
}
bool found = aStartContinuation == aFrame;
while (aFrame) {
NS_ASSERTION(aFrame->IsTextFrame(), "Bad frame");
if (!aFrame->RemoveTextRun(aTextRun)) {
break;
}
aFrame = aFrame->GetNextContinuation();
}
MOZ_ASSERT(!found || aStartContinuation, "how did we find null?");
return found;
}
/**
* Kill all references to |aTextRun| starting at |aStartContinuation|.
* It could be referenced by any of its owners, and all their in-flows.
* If |aStartContinuation| is null then process all userdata frames
* and their continuations.
* @note the caller is expected to take care of possibly destroying the
* text run if all userdata frames were reset (userdata is deallocated
* by this function though). The caller can detect this has occured by
* checking |aTextRun->GetUserData() == nullptr|.
*/
static void UnhookTextRunFromFrames(gfxTextRun* aTextRun,
nsTextFrame* aStartContinuation) {
if (!aTextRun->GetUserData()) {
return;
}
if (aTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow) {
nsTextFrame* userDataFrame = GetFrameForSimpleFlow(aTextRun);
nsFrameState whichTextRunState =
userDataFrame->GetTextRun(nsTextFrame::eInflated) == aTextRun
? TEXT_IN_TEXTRUN_USER_DATA
: TEXT_IN_UNINFLATED_TEXTRUN_USER_DATA;
DebugOnly<bool> found = ClearAllTextRunReferences(
userDataFrame, aTextRun, aStartContinuation, whichTextRunState);
NS_ASSERTION(!aStartContinuation || found,
"aStartContinuation wasn't found in simple flow text run");
if (!userDataFrame->HasAnyStateBits(whichTextRunState)) {
DestroyTextRunUserData(aTextRun);
}
} else {
auto userData = static_cast<TextRunUserData*>(aTextRun->GetUserData());
TextRunMappedFlow* userMappedFlows = GetMappedFlows(aTextRun);
int32_t destroyFromIndex = aStartContinuation ? -1 : 0;
for (uint32_t i = 0; i < userData->mMappedFlowCount; ++i) {
nsTextFrame* userDataFrame = userMappedFlows[i].mStartFrame;
nsFrameState whichTextRunState =
userDataFrame->GetTextRun(nsTextFrame::eInflated) == aTextRun
? TEXT_IN_TEXTRUN_USER_DATA
: TEXT_IN_UNINFLATED_TEXTRUN_USER_DATA;
bool found = ClearAllTextRunReferences(
userDataFrame, aTextRun, aStartContinuation, whichTextRunState);
if (found) {
if (userDataFrame->HasAnyStateBits(whichTextRunState)) {
destroyFromIndex = i + 1;
} else {
destroyFromIndex = i;
}
aStartContinuation = nullptr;
}
}
NS_ASSERTION(destroyFromIndex >= 0,
"aStartContinuation wasn't found in multi flow text run");
if (destroyFromIndex == 0) {
DestroyTextRunUserData(aTextRun);
} else {
userData->mMappedFlowCount = uint32_t(destroyFromIndex);
if (userData->mLastFlowIndex >= uint32_t(destroyFromIndex)) {
userData->mLastFlowIndex = uint32_t(destroyFromIndex) - 1;
}
}
}
}
static void InvalidateFrameDueToGlyphsChanged(nsIFrame* aFrame) {
MOZ_ASSERT(aFrame);
PresShell* presShell = aFrame->PresShell();
for (nsIFrame* f = aFrame; f;
f = nsLayoutUtils::GetNextContinuationOrIBSplitSibling(f)) {
f->InvalidateFrame();
// If this is a non-display text frame within SVG <text>, we need
// to reflow the SVGTextFrame. (This is similar to reflowing the
// SVGTextFrame in response to style changes, in
// SVGTextFrame::DidSetComputedStyle.)
if (f->IsInSVGTextSubtree() && f->HasAnyStateBits(NS_FRAME_IS_NONDISPLAY)) {
auto* svgTextFrame = static_cast<SVGTextFrame*>(
nsLayoutUtils::GetClosestFrameOfType(f, LayoutFrameType::SVGText));
svgTextFrame->ScheduleReflowSVGNonDisplayText(IntrinsicDirty::None);
} else {
// Theoretically we could just update overflow areas, perhaps using
// OverflowChangedTracker, but that would do a bunch of work eagerly that
// we should probably do lazily here since there could be a lot
// of text frames affected and we'd like to coalesce the work. So that's
// not easy to do well.
presShell->FrameNeedsReflow(f, IntrinsicDirty::None, NS_FRAME_IS_DIRTY);
}
}
}
void GlyphObserver::NotifyGlyphsChanged() {
if (mTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow) {
InvalidateFrameDueToGlyphsChanged(GetFrameForSimpleFlow(mTextRun));
return;
}
auto data = static_cast<TextRunUserData*>(mTextRun->GetUserData());
TextRunMappedFlow* userMappedFlows = GetMappedFlows(mTextRun);
for (uint32_t i = 0; i < data->mMappedFlowCount; ++i) {
InvalidateFrameDueToGlyphsChanged(userMappedFlows[i].mStartFrame);
}
}
int32_t nsTextFrame::GetContentEnd() const {
nsTextFrame* next = GetNextContinuation();
// In case of allocation failure when setting/modifying the textfragment,
// it's possible our text might be missing. So we check the fragment length,
// in addition to the offset of the next continuation (if any).
int32_t fragLen = TextFragment()->GetLength();
return next ? std::min(fragLen, next->GetContentOffset()) : fragLen;
}
struct FlowLengthProperty {
int32_t mStartOffset;
// The offset of the next fixed continuation after mStartOffset, or
// of the end of the text if there is none
int32_t mEndFlowOffset;
};
int32_t nsTextFrame::GetInFlowContentLength() {
if (!HasAnyStateBits(NS_FRAME_IS_BIDI)) {
return mContent->TextLength() - mContentOffset;
}
FlowLengthProperty* flowLength =
mContent->HasFlag(NS_HAS_FLOWLENGTH_PROPERTY)
? static_cast<FlowLengthProperty*>(
mContent->GetProperty(nsGkAtoms::flowlength))
: nullptr;
MOZ_ASSERT(mContent->HasFlag(NS_HAS_FLOWLENGTH_PROPERTY) == !!flowLength,
"incorrect NS_HAS_FLOWLENGTH_PROPERTY flag");
/**
* This frame must start inside the cached flow. If the flow starts at
* mContentOffset but this frame is empty, logically it might be before the
* start of the cached flow.
*/
if (flowLength &&
(flowLength->mStartOffset < mContentOffset ||
(flowLength->mStartOffset == mContentOffset &&
GetContentEnd() > mContentOffset)) &&
flowLength->mEndFlowOffset > mContentOffset) {
#ifdef DEBUG
NS_ASSERTION(flowLength->mEndFlowOffset >= GetContentEnd(),
"frame crosses fixed continuation boundary");
#endif
return flowLength->mEndFlowOffset - mContentOffset;
}
nsTextFrame* nextBidi = LastInFlow()->GetNextContinuation();
int32_t endFlow =
nextBidi ? nextBidi->GetContentOffset() : GetContent()->TextLength();
if (!flowLength) {
flowLength = new FlowLengthProperty;
if (NS_FAILED(mContent->SetProperty(
nsGkAtoms::flowlength, flowLength,
nsINode::DeleteProperty<FlowLengthProperty>))) {
delete flowLength;
flowLength = nullptr;
} else {
mContent->SetFlags(NS_HAS_FLOWLENGTH_PROPERTY);
}
}
if (flowLength) {
flowLength->mStartOffset = mContentOffset;
flowLength->mEndFlowOffset = endFlow;
}
return endFlow - mContentOffset;
}
// Smarter versions of dom::IsSpaceCharacter.
// Unicode is really annoying; sometimes a space character isn't whitespace ---
// when it combines with another character
// So we have several versions of IsSpace for use in different contexts.
static bool IsSpaceCombiningSequenceTail(const nsTextFragment* aFrag,
uint32_t aPos) {
NS_ASSERTION(aPos <= aFrag->GetLength(), "Bad offset");
if (!aFrag->Is2b()) {
return false;
}
return nsTextFrameUtils::IsSpaceCombiningSequenceTail(
aFrag->Get2b() + aPos, aFrag->GetLength() - aPos);
}
// Check whether aPos is a space for CSS 'word-spacing' purposes
static bool IsCSSWordSpacingSpace(const nsTextFragment* aFrag, uint32_t aPos,
const nsTextFrame* aFrame,
const nsStyleText* aStyleText) {
NS_ASSERTION(aPos < aFrag->GetLength(), "No text for IsSpace!");
char16_t ch = aFrag->CharAt(aPos);
switch (ch) {
case ' ':
case CH_NBSP:
return !IsSpaceCombiningSequenceTail(aFrag, aPos + 1);
case '\r':
case '\t':
return !aStyleText->WhiteSpaceIsSignificant();
case '\n':
return !aStyleText->NewlineIsSignificant(aFrame);
default:
return false;
}
}
constexpr char16_t kOghamSpaceMark = 0x1680;
// Check whether the string aChars/aLength starts with space that's
// trimmable according to CSS 'white-space:normal/nowrap'.
static bool IsTrimmableSpace(const char16_t* aChars, uint32_t aLength) {
NS_ASSERTION(aLength > 0, "No text for IsSpace!");
char16_t ch = *aChars;
if (ch == ' ' || ch == kOghamSpaceMark) {
return !nsTextFrameUtils::IsSpaceCombiningSequenceTail(aChars + 1,
aLength - 1);
}
return ch == '\t' || ch == '\f' || ch == '\n' || ch == '\r';
}
// Check whether the character aCh is trimmable according to CSS
// 'white-space:normal/nowrap'
static bool IsTrimmableSpace(char aCh) {
return aCh == ' ' || aCh == '\t' || aCh == '\f' || aCh == '\n' || aCh == '\r';
}
static bool IsTrimmableSpace(const nsTextFragment* aFrag, uint32_t aPos,
const nsStyleText* aStyleText,
bool aAllowHangingWS = false) {
NS_ASSERTION(aPos < aFrag->GetLength(), "No text for IsSpace!");
switch (aFrag->CharAt(aPos)) {
case ' ':
case kOghamSpaceMark:
return (!aStyleText->WhiteSpaceIsSignificant() || aAllowHangingWS) &&
!IsSpaceCombiningSequenceTail(aFrag, aPos + 1);
case '\n':
return !aStyleText->NewlineIsSignificantStyle() &&
aStyleText->mWhiteSpaceCollapse !=
StyleWhiteSpaceCollapse::PreserveSpaces;
case '\t':
case '\r':
case '\f':
return !aStyleText->WhiteSpaceIsSignificant() || aAllowHangingWS;
default:
return false;
}
}
static bool IsSelectionInlineWhitespace(const nsTextFragment* aFrag,
uint32_t aPos) {
NS_ASSERTION(aPos < aFrag->GetLength(),
"No text for IsSelectionInlineWhitespace!");
char16_t ch = aFrag->CharAt(aPos);
if (ch == ' ' || ch == CH_NBSP) {
return !IsSpaceCombiningSequenceTail(aFrag, aPos + 1);
}
return ch == '\t' || ch == '\f';
}
static bool IsSelectionNewline(const nsTextFragment* aFrag, uint32_t aPos) {
NS_ASSERTION(aPos < aFrag->GetLength(), "No text for IsSelectionNewline!");
char16_t ch = aFrag->CharAt(aPos);
return ch == '\n' || ch == '\r';
}
// Count the amount of trimmable whitespace (as per CSS
// 'white-space:normal/nowrap') in a text fragment. The first
// character is at offset aStartOffset; the maximum number of characters
// to check is aLength. aDirection is -1 or 1 depending on whether we should
// progress backwards or forwards.
static uint32_t GetTrimmableWhitespaceCount(const nsTextFragment* aFrag,
int32_t aStartOffset,
int32_t aLength,
int32_t aDirection) {
if (!aLength) {
return 0;
}
int32_t count = 0;
if (aFrag->Is2b()) {
const char16_t* str = aFrag->Get2b() + aStartOffset;
int32_t fragLen = aFrag->GetLength() - aStartOffset;
for (; count < aLength; ++count) {
if (!IsTrimmableSpace(str, fragLen)) {
break;
}
str += aDirection;
fragLen -= aDirection;
}
} else {
const char* str = aFrag->Get1b() + aStartOffset;
for (; count < aLength; ++count) {
if (!IsTrimmableSpace(*str)) {
break;
}
str += aDirection;
}
}
return count;
}
static bool IsAllWhitespace(const nsTextFragment* aFrag, bool aAllowNewline) {
if (aFrag->Is2b()) {
return false;
}
int32_t len = aFrag->GetLength();
const char* str = aFrag->Get1b();
for (int32_t i = 0; i < len; ++i) {
char ch = str[i];
if (ch == ' ' || ch == '\t' || ch == '\r' ||
(ch == '\n' && aAllowNewline)) {
continue;
}
return false;
}
return true;
}
static void ClearObserversFromTextRun(gfxTextRun* aTextRun) {
if (!(aTextRun->GetFlags2() &
nsTextFrameUtils::Flags::MightHaveGlyphChanges)) {
return;
}
if (aTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow) {
static_cast<SimpleTextRunUserData*>(aTextRun->GetUserData())
->mGlyphObservers.Clear();
} else {
static_cast<ComplexTextRunUserData*>(aTextRun->GetUserData())
->mGlyphObservers.Clear();
}
}
static void CreateObserversForAnimatedGlyphs(gfxTextRun* aTextRun) {
if (!aTextRun->GetUserData()) {
return;
}
ClearObserversFromTextRun(aTextRun);
nsTArray<gfxFont*> fontsWithAnimatedGlyphs;
uint32_t numGlyphRuns;
const gfxTextRun::GlyphRun* glyphRuns = aTextRun->GetGlyphRuns(&numGlyphRuns);
for (uint32_t i = 0; i < numGlyphRuns; ++i) {
gfxFont* font = glyphRuns[i].mFont;
if (font->GlyphsMayChange() && !fontsWithAnimatedGlyphs.Contains(font)) {
fontsWithAnimatedGlyphs.AppendElement(font);
}
}
if (fontsWithAnimatedGlyphs.IsEmpty()) {
// NB: Theoretically, we should clear the MightHaveGlyphChanges
// here. That would involve de-allocating the simple user data struct if
// present too, and resetting the pointer to the frame. In practice, I
// don't think worth doing that work here, given the flag's only purpose is
// to distinguish what kind of user data is there.
return;
}
nsTArray<UniquePtr<GlyphObserver>>* observers;
if (aTextRun->GetFlags2() & nsTextFrameUtils::Flags::IsSimpleFlow) {
// Swap the frame pointer for a just-allocated SimpleTextRunUserData if
// appropriate.
if (!(aTextRun->GetFlags2() &
nsTextFrameUtils::Flags::MightHaveGlyphChanges)) {
auto frame = static_cast<nsTextFrame*>(aTextRun->GetUserData());
aTextRun->SetUserData(new SimpleTextRunUserData(frame));
}
auto data = static_cast<SimpleTextRunUserData*>(aTextRun->GetUserData());
observers = &data->mGlyphObservers;
} else {
if (!(aTextRun->GetFlags2() &
nsTextFrameUtils::Flags::MightHaveGlyphChanges)) {
auto oldData = static_cast<TextRunUserData*>(aTextRun->GetUserData());
TextRunMappedFlow* oldMappedFlows = GetMappedFlows(aTextRun);
ComplexTextRunUserData* data =
CreateComplexUserData(oldData->mMappedFlowCount);
TextRunMappedFlow* dataMappedFlows =
reinterpret_cast<TextRunMappedFlow*>(data + 1);
data->mLastFlowIndex = oldData->mLastFlowIndex;
for (uint32_t i = 0; i < oldData->mMappedFlowCount; ++i) {
dataMappedFlows[i] = oldMappedFlows[i];
}
DestroyUserData(oldData);
aTextRun->SetUserData(data);
}
auto data = static_cast<ComplexTextRunUserData*>(aTextRun->GetUserData());
observers = &data->mGlyphObservers;
}
aTextRun->SetFlagBits(nsTextFrameUtils::Flags::MightHaveGlyphChanges);
observers->SetCapacity(observers->Length() +
fontsWithAnimatedGlyphs.Length());
for (auto font : fontsWithAnimatedGlyphs) {
observers->AppendElement(MakeUnique<GlyphObserver>(font, aTextRun));
}
}
/**
* This class accumulates state as we scan a paragraph of text. It detects
* textrun boundaries (changes from text to non-text, hard
* line breaks, and font changes) and builds a gfxTextRun at each boundary.
* It also detects linebreaker run boundaries (changes from text to non-text,
* and hard line breaks) and at each boundary runs the linebreaker to compute
* potential line breaks. It also records actual line breaks to store them in
* the textruns.
*/
class BuildTextRunsScanner {
public:
BuildTextRunsScanner(nsPresContext* aPresContext, DrawTarget* aDrawTarget,
nsIFrame* aLineContainer,
nsTextFrame::TextRunType aWhichTextRun,
bool aDoLineBreaking)
: mDrawTarget(aDrawTarget),
mLineContainer(aLineContainer),
mCommonAncestorWithLastFrame(nullptr),
mMissingFonts(aPresContext->MissingFontRecorder()),
mBidiEnabled(aPresContext->BidiEnabled()),
mStartOfLine(true),
mSkipIncompleteTextRuns(false),
mCanStopOnThisLine(false),
mDoLineBreaking(aDoLineBreaking),
mWhichTextRun(aWhichTextRun),
mNextRunContextInfo(nsTextFrameUtils::INCOMING_NONE),
mCurrentRunContextInfo(nsTextFrameUtils::INCOMING_NONE) {
ResetRunInfo();
}
~BuildTextRunsScanner() {
NS_ASSERTION(mBreakSinks.IsEmpty(), "Should have been cleared");
NS_ASSERTION(mLineBreakBeforeFrames.IsEmpty(), "Should have been cleared");
NS_ASSERTION(mMappedFlows.IsEmpty(), "Should have been cleared");
}
void SetAtStartOfLine() {
mStartOfLine = true;
mCanStopOnThisLine = false;
}
void SetSkipIncompleteTextRuns(bool aSkip) {
mSkipIncompleteTextRuns = aSkip;
}
void SetCommonAncestorWithLastFrame(nsIFrame* aFrame) {
mCommonAncestorWithLastFrame = aFrame;
}
bool CanStopOnThisLine() { return mCanStopOnThisLine; }
nsIFrame* GetCommonAncestorWithLastFrame() {
return mCommonAncestorWithLastFrame;
}