forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnsBidiPresUtils.cpp
2439 lines (2169 loc) · 89.2 KB
/
nsBidiPresUtils.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/. */
#include "nsBidiPresUtils.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/Maybe.h"
#include "mozilla/PresShell.h"
#include "mozilla/dom/Text.h"
#include "gfxContext.h"
#include "nsFontMetrics.h"
#include "nsGkAtoms.h"
#include "nsPresContext.h"
#include "nsBidiUtils.h"
#include "nsCSSFrameConstructor.h"
#include "nsContainerFrame.h"
#include "nsInlineFrame.h"
#include "nsPlaceholderFrame.h"
#include "nsPointerHashKeys.h"
#include "nsFirstLetterFrame.h"
#include "nsUnicodeProperties.h"
#include "nsTextFrame.h"
#include "nsBlockFrame.h"
#include "nsIFrameInlines.h"
#include "nsStyleStructInlines.h"
#include "RubyUtils.h"
#include "nsRubyFrame.h"
#include "nsRubyBaseFrame.h"
#include "nsRubyTextFrame.h"
#include "nsRubyBaseContainerFrame.h"
#include "nsRubyTextContainerFrame.h"
#include <algorithm>
#undef NOISY_BIDI
#undef REALLY_NOISY_BIDI
using namespace mozilla;
static const char16_t kSpace = 0x0020;
static const char16_t kZWSP = 0x200B;
static const char16_t kLineSeparator = 0x2028;
static const char16_t kObjectSubstitute = 0xFFFC;
static const char16_t kLRE = 0x202A;
static const char16_t kRLE = 0x202B;
static const char16_t kLRO = 0x202D;
static const char16_t kRLO = 0x202E;
static const char16_t kPDF = 0x202C;
static const char16_t kLRI = 0x2066;
static const char16_t kRLI = 0x2067;
static const char16_t kFSI = 0x2068;
static const char16_t kPDI = 0x2069;
// All characters with Bidi type Segment Separator or Block Separator
static const char16_t kSeparators[] = {
char16_t('\t'), char16_t('\r'), char16_t('\n'), char16_t(0xb),
char16_t(0x1c), char16_t(0x1d), char16_t(0x1e), char16_t(0x1f),
char16_t(0x85), char16_t(0x2029), char16_t(0)};
#define NS_BIDI_CONTROL_FRAME ((nsIFrame*)0xfffb1d1)
// This exists just to be a type; the value doesn't matter.
enum class BidiControlFrameType { Value };
static bool IsIsolateControl(char16_t aChar) {
return aChar == kLRI || aChar == kRLI || aChar == kFSI;
}
// Given a ComputedStyle, return any bidi control character necessary to
// implement style properties that override directionality (i.e. if it has
// unicode-bidi:bidi-override, or text-orientation:upright in vertical
// writing mode) when applying the bidi algorithm.
//
// Returns 0 if no override control character is implied by this style.
static char16_t GetBidiOverride(ComputedStyle* aComputedStyle) {
const nsStyleVisibility* vis = aComputedStyle->StyleVisibility();
if ((vis->mWritingMode == NS_STYLE_WRITING_MODE_VERTICAL_RL ||
vis->mWritingMode == NS_STYLE_WRITING_MODE_VERTICAL_LR) &&
vis->mTextOrientation == StyleTextOrientation::Upright) {
return kLRO;
}
const nsStyleTextReset* text = aComputedStyle->StyleTextReset();
if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_BIDI_OVERRIDE) {
return NS_STYLE_DIRECTION_RTL == vis->mDirection ? kRLO : kLRO;
}
return 0;
}
// Given a ComputedStyle, return any bidi control character necessary to
// implement style properties that affect bidi resolution (i.e. if it
// has unicode-bidiembed, isolate, or plaintext) when applying the bidi
// algorithm.
//
// Returns 0 if no control character is implied by the style.
//
// Note that GetBidiOverride and GetBidiControl need to be separate
// because in the case of unicode-bidi:isolate-override we need both
// FSI and LRO/RLO.
static char16_t GetBidiControl(ComputedStyle* aComputedStyle) {
const nsStyleVisibility* vis = aComputedStyle->StyleVisibility();
const nsStyleTextReset* text = aComputedStyle->StyleTextReset();
if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_EMBED) {
return NS_STYLE_DIRECTION_RTL == vis->mDirection ? kRLE : kLRE;
}
if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_ISOLATE) {
if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_BIDI_OVERRIDE) {
// isolate-override
return kFSI;
}
// <bdi> element already has its directionality set from content so
// we never need to return kFSI.
return NS_STYLE_DIRECTION_RTL == vis->mDirection ? kRLI : kLRI;
}
if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_PLAINTEXT) {
return kFSI;
}
return 0;
}
#ifdef DEBUG
static inline bool AreContinuationsInOrder(nsIFrame* aFrame1,
nsIFrame* aFrame2) {
nsIFrame* f = aFrame1;
do {
f = f->GetNextContinuation();
} while (f && f != aFrame2);
return !!f;
}
#endif
struct MOZ_STACK_CLASS BidiParagraphData {
struct FrameInfo {
FrameInfo(nsIFrame* aFrame, nsBlockInFlowLineIterator& aLineIter)
: mFrame(aFrame),
mBlockContainer(aLineIter.GetContainer()),
mInOverflow(aLineIter.GetInOverflow()) {}
explicit FrameInfo(BidiControlFrameType aValue)
: mFrame(NS_BIDI_CONTROL_FRAME),
mBlockContainer(nullptr),
mInOverflow(false) {}
FrameInfo()
: mFrame(nullptr), mBlockContainer(nullptr), mInOverflow(false) {}
nsIFrame* mFrame;
// The block containing mFrame (i.e., which continuation).
nsBlockFrame* mBlockContainer;
// true if mFrame is in mBlockContainer's overflow lines, false if
// in primary lines
bool mInOverflow;
};
nsAutoString mBuffer;
AutoTArray<char16_t, 16> mEmbeddingStack;
AutoTArray<FrameInfo, 16> mLogicalFrames;
nsDataHashtable<nsPtrHashKey<const nsIContent>, int32_t> mContentToFrameIndex;
// Cached presentation context for the frames we're processing.
nsPresContext* mPresContext;
bool mIsVisual;
bool mRequiresBidi;
nsBidiLevel mParaLevel;
nsIContent* mPrevContent;
/**
* This class is designed to manage the process of mapping a frame to
* the line that it's in, when we know that (a) the frames we ask it
* about are always in the block's lines and (b) each successive frame
* we ask it about is the same as or after (in depth-first search
* order) the previous.
*
* Since we move through the lines at a different pace in Traverse and
* ResolveParagraph, we use one of these for each.
*
* The state of the mapping is also different between TraverseFrames
* and ResolveParagraph since since resolving can call functions
* (EnsureBidiContinuation or SplitInlineAncestors) that can create
* new frames and thus break lines.
*
* The TraverseFrames iterator is only used in some edge cases.
*/
struct FastLineIterator {
FastLineIterator() : mPrevFrame(nullptr), mNextLineStart(nullptr) {}
// These iterators *and* mPrevFrame track the line list that we're
// iterating over.
//
// mPrevFrame, if non-null, should be either the frame we're currently
// handling (in ResolveParagraph or TraverseFrames, depending on the
// iterator) or a frame before it, and is also guaranteed to either be in
// mCurrentLine or have been in mCurrentLine until recently.
//
// In case the splitting causes block frames to break lines, however, we
// also track the first frame of the next line. If that changes, it means
// we've broken lines and we have to invalidate mPrevFrame.
nsBlockInFlowLineIterator mLineIterator;
nsIFrame* mPrevFrame;
nsIFrame* mNextLineStart;
nsLineList::iterator GetLine() { return mLineIterator.GetLine(); }
static bool IsFrameInCurrentLine(nsBlockInFlowLineIterator* aLineIter,
nsIFrame* aPrevFrame, nsIFrame* aFrame) {
MOZ_ASSERT(!aPrevFrame || aLineIter->GetLine()->Contains(aPrevFrame),
"aPrevFrame must be in aLineIter's current line");
nsIFrame* endFrame = aLineIter->IsLastLineInList()
? nullptr
: aLineIter->GetLine().next()->mFirstChild;
nsIFrame* startFrame =
aPrevFrame ? aPrevFrame : aLineIter->GetLine()->mFirstChild;
for (nsIFrame* frame = startFrame; frame && frame != endFrame;
frame = frame->GetNextSibling()) {
if (frame == aFrame) return true;
}
return false;
}
static nsIFrame* FirstChildOfNextLine(
nsBlockInFlowLineIterator& aIterator) {
const nsLineList::iterator line = aIterator.GetLine();
const nsLineList::iterator lineEnd = aIterator.End();
MOZ_ASSERT(line != lineEnd, "iterator should start off valid");
const nsLineList::iterator nextLine = line.next();
return nextLine != lineEnd ? nextLine->mFirstChild : nullptr;
}
// Advance line iterator to the line containing aFrame, assuming
// that aFrame is already in the line list our iterator is iterating
// over.
void AdvanceToFrame(nsIFrame* aFrame) {
if (mPrevFrame && FirstChildOfNextLine(mLineIterator) != mNextLineStart) {
// Something has caused a line to split. We need to invalidate
// mPrevFrame since it may now be in a *later* line, though it may
// still be in this line, so we need to start searching for it from
// the start of this line.
mPrevFrame = nullptr;
}
nsIFrame* child = aFrame;
nsIFrame* parent = nsLayoutUtils::GetParentOrPlaceholderFor(child);
while (parent && !parent->IsBlockFrameOrSubclass()) {
child = parent;
parent = nsLayoutUtils::GetParentOrPlaceholderFor(child);
}
MOZ_ASSERT(parent, "aFrame is not a descendent of a block frame");
while (!IsFrameInCurrentLine(&mLineIterator, mPrevFrame, child)) {
#ifdef DEBUG
bool hasNext =
#endif
mLineIterator.Next();
MOZ_ASSERT(hasNext, "Can't find frame in lines!");
mPrevFrame = nullptr;
}
mPrevFrame = child;
mNextLineStart = FirstChildOfNextLine(mLineIterator);
}
// Advance line iterator to the line containing aFrame, which may
// require moving forward into overflow lines or into a later
// continuation (or both).
void AdvanceToLinesAndFrame(const FrameInfo& aFrameInfo) {
if (mLineIterator.GetContainer() != aFrameInfo.mBlockContainer ||
mLineIterator.GetInOverflow() != aFrameInfo.mInOverflow) {
MOZ_ASSERT(
mLineIterator.GetContainer() == aFrameInfo.mBlockContainer
? (!mLineIterator.GetInOverflow() && aFrameInfo.mInOverflow)
: (!mLineIterator.GetContainer() ||
AreContinuationsInOrder(mLineIterator.GetContainer(),
aFrameInfo.mBlockContainer)),
"must move forwards");
nsBlockFrame* block = aFrameInfo.mBlockContainer;
nsLineList::iterator lines =
aFrameInfo.mInOverflow ? block->GetOverflowLines()->mLines.begin()
: block->LinesBegin();
mLineIterator =
nsBlockInFlowLineIterator(block, lines, aFrameInfo.mInOverflow);
mPrevFrame = nullptr;
}
AdvanceToFrame(aFrameInfo.mFrame);
}
};
FastLineIterator mCurrentTraverseLine, mCurrentResolveLine;
#ifdef DEBUG
// Only used for NOISY debug output.
// Matches the current TraverseFrames state, not the ResolveParagraph
// state.
nsBlockFrame* mCurrentBlock;
#endif
explicit BidiParagraphData(nsBlockFrame* aBlockFrame)
: mPresContext(aBlockFrame->PresContext()),
mIsVisual(mPresContext->IsVisualMode()),
mRequiresBidi(false),
mParaLevel(nsBidiPresUtils::BidiLevelFromStyle(aBlockFrame->Style())),
mPrevContent(nullptr)
#ifdef DEBUG
,
mCurrentBlock(aBlockFrame)
#endif
{
if (mParaLevel > 0) {
mRequiresBidi = true;
}
if (mIsVisual) {
/**
* Drill up in content to detect whether this is an element that needs to
* be rendered with logical order even on visual pages.
*
* We always use logical order on form controls, firstly so that text
* entry will be in logical order, but also because visual pages were
* written with the assumption that even if the browser had no support
* for right-to-left text rendering, it would use native widgets with
* bidi support to display form controls.
*
* We also use logical order in XUL elements, since we expect that if a
* XUL element appears in a visual page, it will be generated by an XBL
* binding and contain localized text which will be in logical order.
*/
for (nsIContent* content = aBlockFrame->GetContent(); content;
content = content->GetParent()) {
if (content->IsNodeOfType(nsINode::eHTML_FORM_CONTROL) ||
content->IsXULElement()) {
mIsVisual = false;
break;
}
}
}
}
nsresult SetPara() {
return mPresContext->GetBidiEngine().SetPara(mBuffer.get(), BufferLength(),
mParaLevel);
}
/**
* mParaLevel can be NSBIDI_DEFAULT_LTR as well as NSBIDI_LTR or NSBIDI_RTL.
* GetParaLevel() returns the actual (resolved) paragraph level which is
* always either NSBIDI_LTR or NSBIDI_RTL
*/
nsBidiLevel GetParaLevel() {
nsBidiLevel paraLevel = mParaLevel;
if (paraLevel == NSBIDI_DEFAULT_LTR || paraLevel == NSBIDI_DEFAULT_RTL) {
paraLevel = mPresContext->GetBidiEngine().GetParaLevel();
}
return paraLevel;
}
nsBidiDirection GetDirection() {
return mPresContext->GetBidiEngine().GetDirection();
}
nsresult CountRuns(int32_t* runCount) {
return mPresContext->GetBidiEngine().CountRuns(runCount);
}
void GetLogicalRun(int32_t aLogicalStart, int32_t* aLogicalLimit,
nsBidiLevel* aLevel) {
mPresContext->GetBidiEngine().GetLogicalRun(aLogicalStart, aLogicalLimit,
aLevel);
if (mIsVisual) {
*aLevel = GetParaLevel();
}
}
void ResetData() {
mLogicalFrames.Clear();
mContentToFrameIndex.Clear();
mBuffer.SetLength(0);
mPrevContent = nullptr;
for (uint32_t i = 0; i < mEmbeddingStack.Length(); ++i) {
mBuffer.Append(mEmbeddingStack[i]);
mLogicalFrames.AppendElement(FrameInfo(BidiControlFrameType::Value));
}
}
void AppendFrame(nsIFrame* aFrame, FastLineIterator& aLineIter,
nsIContent* aContent = nullptr) {
if (aContent) {
mContentToFrameIndex.Put(aContent, FrameCount());
}
// We don't actually need to advance aLineIter to aFrame, since all we use
// from it is the block and is-overflow state, which are correct already.
mLogicalFrames.AppendElement(FrameInfo(aFrame, aLineIter.mLineIterator));
}
void AdvanceAndAppendFrame(nsIFrame** aFrame, FastLineIterator& aLineIter,
nsIFrame** aNextSibling) {
nsIFrame* frame = *aFrame;
nsIFrame* nextSibling = *aNextSibling;
frame = frame->GetNextContinuation();
if (frame) {
AppendFrame(frame, aLineIter, nullptr);
/*
* If we have already overshot the saved next-sibling while
* scanning the frame's continuations, advance it.
*/
if (frame == nextSibling) {
nextSibling = frame->GetNextSibling();
}
}
*aFrame = frame;
*aNextSibling = nextSibling;
}
int32_t GetLastFrameForContent(nsIContent* aContent) {
int32_t index = 0;
mContentToFrameIndex.Get(aContent, &index);
return index;
}
int32_t FrameCount() { return mLogicalFrames.Length(); }
int32_t BufferLength() { return mBuffer.Length(); }
nsIFrame* FrameAt(int32_t aIndex) { return mLogicalFrames[aIndex].mFrame; }
const FrameInfo& FrameInfoAt(int32_t aIndex) {
return mLogicalFrames[aIndex];
}
void AppendUnichar(char16_t aCh) { mBuffer.Append(aCh); }
void AppendString(const nsDependentSubstring& aString) {
mBuffer.Append(aString);
}
void AppendControlChar(char16_t aCh) {
mLogicalFrames.AppendElement(FrameInfo(BidiControlFrameType::Value));
AppendUnichar(aCh);
}
void PushBidiControl(char16_t aCh) {
AppendControlChar(aCh);
mEmbeddingStack.AppendElement(aCh);
}
void AppendPopChar(char16_t aCh) {
AppendControlChar(IsIsolateControl(aCh) ? kPDI : kPDF);
}
void PopBidiControl(char16_t aCh) {
MOZ_ASSERT(mEmbeddingStack.Length(), "embedding/override underflow");
MOZ_ASSERT(aCh == mEmbeddingStack.LastElement());
AppendPopChar(aCh);
mEmbeddingStack.TruncateLength(mEmbeddingStack.Length() - 1);
}
void ClearBidiControls() {
for (char16_t c : Reversed(mEmbeddingStack)) {
AppendPopChar(c);
}
}
};
struct MOZ_STACK_CLASS BidiLineData {
AutoTArray<nsIFrame*, 16> mLogicalFrames;
AutoTArray<nsIFrame*, 16> mVisualFrames;
AutoTArray<int32_t, 16> mIndexMap;
AutoTArray<uint8_t, 16> mLevels;
bool mIsReordered;
BidiLineData(nsIFrame* aFirstFrameOnLine, int32_t aNumFramesOnLine) {
/**
* Initialize the logically-ordered array of frames using the top-level
* frames of a single line
*/
bool isReordered = false;
bool hasRTLFrames = false;
bool hasVirtualControls = false;
auto appendFrame = [&](nsIFrame* frame, nsBidiLevel level) {
mLogicalFrames.AppendElement(frame);
mLevels.AppendElement(level);
mIndexMap.AppendElement(0);
if (IS_LEVEL_RTL(level)) {
hasRTLFrames = true;
}
};
bool firstFrame = true;
for (nsIFrame* frame = aFirstFrameOnLine; frame && aNumFramesOnLine--;
frame = frame->GetNextSibling()) {
FrameBidiData bidiData = nsBidiPresUtils::GetFrameBidiData(frame);
// Ignore virtual control before the first frame. Doing so should
// not affect the visual result, but could avoid running into the
// stripping code below for many cases.
if (!firstFrame && bidiData.precedingControl != kBidiLevelNone) {
appendFrame(NS_BIDI_CONTROL_FRAME, bidiData.precedingControl);
hasVirtualControls = true;
}
appendFrame(frame, bidiData.embeddingLevel);
firstFrame = false;
}
// Reorder the line
nsBidi::ReorderVisual(mLevels.Elements(), FrameCount(),
mIndexMap.Elements());
// Strip virtual frames
if (hasVirtualControls) {
auto originalCount = mLogicalFrames.Length();
AutoTArray<int32_t, 16> realFrameMap;
realFrameMap.SetCapacity(originalCount);
size_t count = 0;
for (auto i : IntegerRange(originalCount)) {
if (mLogicalFrames[i] == NS_BIDI_CONTROL_FRAME) {
realFrameMap.AppendElement(-1);
} else {
mLogicalFrames[count] = mLogicalFrames[i];
mLevels[count] = mLevels[i];
realFrameMap.AppendElement(count);
count++;
}
}
// Only keep index map for real frames.
for (size_t i = 0, j = 0; i < originalCount; ++i) {
auto newIndex = realFrameMap[mIndexMap[i]];
if (newIndex != -1) {
mIndexMap[j] = newIndex;
j++;
}
}
mLogicalFrames.TruncateLength(count);
mLevels.TruncateLength(count);
mIndexMap.TruncateLength(count);
}
for (int32_t i = 0; i < FrameCount(); i++) {
mVisualFrames.AppendElement(LogicalFrameAt(mIndexMap[i]));
if (i != mIndexMap[i]) {
isReordered = true;
}
}
// If there's an RTL frame, assume the line is reordered
mIsReordered = isReordered || hasRTLFrames;
}
int32_t FrameCount() const { return mLogicalFrames.Length(); }
nsIFrame* LogicalFrameAt(int32_t aIndex) const {
return mLogicalFrames[aIndex];
}
nsIFrame* VisualFrameAt(int32_t aIndex) const {
return mVisualFrames[aIndex];
}
};
#ifdef DEBUG
extern "C" {
void MOZ_EXPORT DumpFrameArray(const nsTArray<nsIFrame*>& aFrames) {
for (nsIFrame* frame : aFrames) {
if (frame == NS_BIDI_CONTROL_FRAME) {
fprintf_stderr(stderr, "(Bidi control frame)\n");
} else {
frame->List();
}
}
}
void MOZ_EXPORT DumpBidiLine(BidiLineData* aData, bool aVisualOrder) {
DumpFrameArray(aVisualOrder ? aData->mVisualFrames : aData->mLogicalFrames);
}
}
#endif
/* Some helper methods for Resolve() */
// Should this frame be split between text runs?
static bool IsBidiSplittable(nsIFrame* aFrame) {
MOZ_ASSERT(aFrame);
// Bidi inline containers should be split, unless they're line frames.
LayoutFrameType frameType = aFrame->Type();
return (aFrame->IsFrameOfType(nsIFrame::eBidiInlineContainer) &&
frameType != LayoutFrameType::Line) ||
frameType == LayoutFrameType::Text;
}
// Should this frame be treated as a leaf (e.g. when building mLogicalFrames)?
static bool IsBidiLeaf(nsIFrame* aFrame) {
nsIFrame* kid = aFrame->PrincipalChildList().FirstChild();
return !kid || !aFrame->IsFrameOfType(nsIFrame::eBidiInlineContainer);
}
/**
* Create non-fluid continuations for the ancestors of a given frame all the way
* up the frame tree until we hit a non-splittable frame (a line or a block).
*
* @param aParent the first parent frame to be split
* @param aFrame the child frames after this frame are reparented to the
* newly-created continuation of aParent.
* If aFrame is null, all the children of aParent are reparented.
*/
static nsresult SplitInlineAncestors(nsContainerFrame* aParent,
nsLineList::iterator aLine,
nsIFrame* aFrame) {
nsPresContext* presContext = aParent->PresContext();
PresShell* presShell = presContext->PresShell();
nsIFrame* frame = aFrame;
nsContainerFrame* parent = aParent;
nsContainerFrame* newParent;
while (IsBidiSplittable(parent)) {
nsContainerFrame* grandparent = parent->GetParent();
NS_ASSERTION(grandparent,
"Couldn't get parent's parent in "
"nsBidiPresUtils::SplitInlineAncestors");
// Split the child list after |frame|, unless it is the last child.
if (!frame || frame->GetNextSibling()) {
newParent = static_cast<nsContainerFrame*>(
presShell->FrameConstructor()->CreateContinuingFrame(
presContext, parent, grandparent, false));
nsFrameList tail = parent->StealFramesAfter(frame);
// Reparent views as necessary
nsresult rv;
rv = nsContainerFrame::ReparentFrameViewList(tail, parent, newParent);
if (NS_FAILED(rv)) {
return rv;
}
// The parent's continuation adopts the siblings after the split.
MOZ_ASSERT(!newParent->IsBlockFrameOrSubclass(),
"blocks should not be IsBidiSplittable");
newParent->InsertFrames(nsIFrame::kNoReflowPrincipalList, nullptr,
nullptr, tail);
// While passing &aLine to InsertFrames for a non-block isn't harmful
// because it's a no-op, it doesn't really make sense. However, the
// MOZ_ASSERT() we need to guarantee that it's safe only works if the
// parent is actually the block.
const nsLineList::iterator* parentLine;
if (grandparent->IsBlockFrameOrSubclass()) {
MOZ_ASSERT(aLine->Contains(parent));
parentLine = &aLine;
} else {
parentLine = nullptr;
}
// The list name kNoReflowPrincipalList would indicate we don't want
// reflow
nsFrameList temp(newParent, newParent);
grandparent->InsertFrames(nsIFrame::kNoReflowPrincipalList, parent,
parentLine, temp);
}
frame = parent;
parent = grandparent;
}
return NS_OK;
}
static void MakeContinuationFluid(nsIFrame* aFrame, nsIFrame* aNext) {
NS_ASSERTION(!aFrame->GetNextInFlow() || aFrame->GetNextInFlow() == aNext,
"next-in-flow is not next continuation!");
aFrame->SetNextInFlow(aNext);
NS_ASSERTION(!aNext->GetPrevInFlow() || aNext->GetPrevInFlow() == aFrame,
"prev-in-flow is not prev continuation!");
aNext->SetPrevInFlow(aFrame);
}
static void MakeContinuationsNonFluidUpParentChain(nsIFrame* aFrame,
nsIFrame* aNext) {
nsIFrame* frame;
nsIFrame* next;
for (frame = aFrame, next = aNext;
frame && next && next != frame && next == frame->GetNextInFlow() &&
IsBidiSplittable(frame);
frame = frame->GetParent(), next = next->GetParent()) {
frame->SetNextContinuation(next);
next->SetPrevContinuation(frame);
}
}
// If aFrame is the last child of its parent, convert bidi continuations to
// fluid continuations for all of its inline ancestors.
// If it isn't the last child, make sure that its continuation is fluid.
static void JoinInlineAncestors(nsIFrame* aFrame) {
nsIFrame* frame = aFrame;
while (frame && IsBidiSplittable(frame)) {
nsIFrame* next = frame->GetNextContinuation();
if (next) {
MakeContinuationFluid(frame, next);
}
// Join the parent only as long as we're its last child.
if (frame->GetNextSibling()) break;
frame = frame->GetParent();
}
}
static nsresult CreateContinuation(nsIFrame* aFrame,
const nsLineList::iterator aLine,
nsIFrame** aNewFrame, bool aIsFluid) {
MOZ_ASSERT(aNewFrame, "null OUT ptr");
MOZ_ASSERT(aFrame, "null ptr");
*aNewFrame = nullptr;
nsPresContext* presContext = aFrame->PresContext();
PresShell* presShell = presContext->PresShell();
NS_ASSERTION(presShell,
"PresShell must be set on PresContext before calling "
"nsBidiPresUtils::CreateContinuation");
nsContainerFrame* parent = aFrame->GetParent();
NS_ASSERTION(
parent,
"Couldn't get frame parent in nsBidiPresUtils::CreateContinuation");
// While passing &aLine to InsertFrames for a non-block isn't harmful
// because it's a no-op, it doesn't really make sense. However, the
// MOZ_ASSERT() we need to guarantee that it's safe only works if the
// parent is actually the block.
const nsLineList::iterator* parentLine;
if (parent->IsBlockFrameOrSubclass()) {
MOZ_ASSERT(aLine->Contains(aFrame));
parentLine = &aLine;
} else {
parentLine = nullptr;
}
nsresult rv = NS_OK;
// Have to special case floating first letter frames because the continuation
// doesn't go in the first letter frame. The continuation goes with the rest
// of the text that the first letter frame was made out of.
if (parent->IsLetterFrame() && parent->IsFloating()) {
nsFirstLetterFrame* letterFrame = do_QueryFrame(parent);
rv = letterFrame->CreateContinuationForFloatingParent(presContext, aFrame,
aNewFrame, aIsFluid);
return rv;
}
*aNewFrame = presShell->FrameConstructor()->CreateContinuingFrame(
presContext, aFrame, parent, aIsFluid);
// The list name kNoReflowPrincipalList would indicate we don't want reflow
// XXXbz this needs higher-level framelist love
nsFrameList temp(*aNewFrame, *aNewFrame);
parent->InsertFrames(nsIFrame::kNoReflowPrincipalList, aFrame, parentLine,
temp);
if (!aIsFluid) {
// Split inline ancestor frames
rv = SplitInlineAncestors(parent, aLine, aFrame);
if (NS_FAILED(rv)) {
return rv;
}
}
return NS_OK;
}
/*
* Overview of the implementation of Resolve():
*
* Walk through the descendants of aBlockFrame and build:
* * mLogicalFrames: an nsTArray of nsIFrame* pointers in logical order
* * mBuffer: an nsString containing a representation of
* the content of the frames.
* In the case of text frames, this is the actual text context of the
* frames, but some other elements are represented in a symbolic form which
* will make the Unicode Bidi Algorithm give the correct results.
* Bidi isolates, embeddings, and overrides set by CSS, <bdi>, or <bdo>
* elements are represented by the corresponding Unicode control characters.
* <br> elements are represented by U+2028 LINE SEPARATOR
* Other inline elements are represented by U+FFFC OBJECT REPLACEMENT
* CHARACTER
*
* Then pass mBuffer to the Bidi engine for resolving of embedding levels
* by nsBidi::SetPara() and division into directional runs by
* nsBidi::CountRuns().
*
* Finally, walk these runs in logical order using nsBidi::GetLogicalRun() and
* correlate them with the frames indexed in mLogicalFrames, setting the
* baseLevel and embeddingLevel properties according to the results returned
* by the Bidi engine.
*
* The rendering layer requires each text frame to contain text in only one
* direction, so we may need to call EnsureBidiContinuation() to split frames.
* We may also need to call RemoveBidiContinuation() to convert frames created
* by EnsureBidiContinuation() in previous reflows into fluid continuations.
*/
nsresult nsBidiPresUtils::Resolve(nsBlockFrame* aBlockFrame) {
BidiParagraphData bpd(aBlockFrame);
// Handle bidi-override being set on the block itself before calling
// TraverseFrames.
// No need to call GetBidiControl as well, because isolate and embed
// values of unicode-bidi property are redundant on block elements.
// unicode-bidi:plaintext on a block element is handled by block frame
// via using nsIFrame::GetWritingMode(nsIFrame*).
char16_t ch = GetBidiOverride(aBlockFrame->Style());
if (ch != 0) {
bpd.PushBidiControl(ch);
bpd.mRequiresBidi = true;
} else {
// If there are no unicode-bidi properties and no RTL characters in the
// block's content, then it is pure LTR and we can skip the rest of bidi
// resolution.
nsIContent* currContent = nullptr;
for (nsBlockFrame* block = aBlockFrame; block;
block = static_cast<nsBlockFrame*>(block->GetNextContinuation())) {
block->RemoveStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION);
if (!bpd.mRequiresBidi &&
ChildListMayRequireBidi(block->PrincipalChildList().FirstChild(),
&currContent)) {
bpd.mRequiresBidi = true;
}
if (!bpd.mRequiresBidi) {
nsBlockFrame::FrameLines* overflowLines = block->GetOverflowLines();
if (overflowLines) {
if (ChildListMayRequireBidi(overflowLines->mFrames.FirstChild(),
&currContent)) {
bpd.mRequiresBidi = true;
}
}
}
}
if (!bpd.mRequiresBidi) {
return NS_OK;
}
}
for (nsBlockFrame* block = aBlockFrame; block;
block = static_cast<nsBlockFrame*>(block->GetNextContinuation())) {
#ifdef DEBUG
bpd.mCurrentBlock = block;
#endif
block->RemoveStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION);
bpd.mCurrentTraverseLine.mLineIterator =
nsBlockInFlowLineIterator(block, block->LinesBegin());
bpd.mCurrentTraverseLine.mPrevFrame = nullptr;
TraverseFrames(block->PrincipalChildList().FirstChild(), &bpd);
nsBlockFrame::FrameLines* overflowLines = block->GetOverflowLines();
if (overflowLines) {
bpd.mCurrentTraverseLine.mLineIterator =
nsBlockInFlowLineIterator(block, overflowLines->mLines.begin(), true);
bpd.mCurrentTraverseLine.mPrevFrame = nullptr;
TraverseFrames(overflowLines->mFrames.FirstChild(), &bpd);
}
}
if (ch != 0) {
bpd.PopBidiControl(ch);
}
return ResolveParagraph(&bpd);
}
nsresult nsBidiPresUtils::ResolveParagraph(BidiParagraphData* aBpd) {
if (aBpd->BufferLength() < 1) {
return NS_OK;
}
aBpd->mBuffer.ReplaceChar(kSeparators, kSpace);
int32_t runCount;
nsresult rv = aBpd->SetPara();
NS_ENSURE_SUCCESS(rv, rv);
nsBidiLevel embeddingLevel = aBpd->GetParaLevel();
rv = aBpd->CountRuns(&runCount);
NS_ENSURE_SUCCESS(rv, rv);
int32_t runLength = 0; // the length of the current run of text
int32_t logicalLimit = 0; // the end of the current run + 1
int32_t numRun = -1;
int32_t fragmentLength = 0; // the length of the current text frame
int32_t frameIndex = -1; // index to the frames in mLogicalFrames
int32_t frameCount = aBpd->FrameCount();
int32_t contentOffset = 0; // offset of current frame in its content node
bool isTextFrame = false;
nsIFrame* frame = nullptr;
BidiParagraphData::FrameInfo frameInfo;
nsIContent* content = nullptr;
int32_t contentTextLength = 0;
#ifdef DEBUG
# ifdef NOISY_BIDI
printf(
"Before Resolve(), mCurrentBlock=%p, mBuffer='%s', frameCount=%d, "
"runCount=%d\n",
(void*)aBpd->mCurrentBlock, NS_ConvertUTF16toUTF8(aBpd->mBuffer).get(),
frameCount, runCount);
# ifdef REALLY_NOISY_BIDI
printf(" block frame tree=:\n");
aBpd->mCurrentBlock->List(stdout);
# endif
# endif
#endif
if (runCount == 1 && frameCount == 1 && aBpd->GetDirection() == NSBIDI_LTR &&
aBpd->GetParaLevel() == 0) {
// We have a single left-to-right frame in a left-to-right paragraph,
// without bidi isolation from the surrounding text.
// Make sure that the embedding level and base level frame properties aren't
// set (because if they are this frame used to have some other direction,
// so we can't do this optimization), and we're done.
nsIFrame* frame = aBpd->FrameAt(0);
if (frame != NS_BIDI_CONTROL_FRAME) {
FrameBidiData bidiData = frame->GetBidiData();
if (!bidiData.embeddingLevel && !bidiData.baseLevel) {
#ifdef DEBUG
# ifdef NOISY_BIDI
printf("early return for single direction frame %p\n", (void*)frame);
# endif
#endif
frame->AddStateBits(NS_FRAME_IS_BIDI);
return NS_OK;
}
}
}
BidiParagraphData::FrameInfo lastRealFrame;
nsBidiLevel lastEmbeddingLevel = kBidiLevelNone;
nsBidiLevel precedingControl = kBidiLevelNone;
auto storeBidiDataToFrame = [&]() {
FrameBidiData bidiData;
bidiData.embeddingLevel = embeddingLevel;
bidiData.baseLevel = aBpd->GetParaLevel();
// If a control character doesn't have a lower embedding level than
// both the preceding and the following frame, it isn't something
// needed for getting the correct result. This optimization should
// remove almost all of embeds and overrides, and some of isolates.
if (precedingControl >= embeddingLevel ||
precedingControl >= lastEmbeddingLevel) {
bidiData.precedingControl = kBidiLevelNone;
} else {
bidiData.precedingControl = precedingControl;
}
precedingControl = kBidiLevelNone;
lastEmbeddingLevel = embeddingLevel;
frame->SetProperty(nsIFrame::BidiDataProperty(), bidiData);
};
for (;;) {
if (fragmentLength <= 0) {
// Get the next frame from mLogicalFrames
if (++frameIndex >= frameCount) {
break;
}
frameInfo = aBpd->FrameInfoAt(frameIndex);
frame = frameInfo.mFrame;
if (frame == NS_BIDI_CONTROL_FRAME || !frame->IsTextFrame()) {
/*
* Any non-text frame corresponds to a single character in the text
* buffer (a bidi control character, LINE SEPARATOR, or OBJECT
* SUBSTITUTE)
*/
isTextFrame = false;
fragmentLength = 1;
} else {
aBpd->mCurrentResolveLine.AdvanceToLinesAndFrame(frameInfo);
content = frame->GetContent();
if (!content) {
rv = NS_OK;
break;
}
contentTextLength = content->TextLength();
int32_t start, end;
frame->GetOffsets(start, end);
NS_ASSERTION(!(contentTextLength < end - start),
"Frame offsets don't fit in content");
fragmentLength = std::min(contentTextLength, end - start);
contentOffset = start;
isTextFrame = true;
}
} // if (fragmentLength <= 0)
if (runLength <= 0) {
// Get the next run of text from the Bidi engine
if (++numRun >= runCount) {
// We've run out of runs of text; but don't forget to store bidi data
// to the frame before breaking out of the loop (bug 1426042).
storeBidiDataToFrame();
if (isTextFrame) {
frame->AdjustOffsetsForBidi(contentOffset,
contentOffset + fragmentLength);
}
break;