1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "nsBidiPresUtils.h"
8 
9 #include "mozilla/IntegerRange.h"
10 #include "mozilla/Maybe.h"
11 #include "mozilla/PresShell.h"
12 #include "mozilla/dom/Text.h"
13 
14 #include "gfxContext.h"
15 #include "nsFontMetrics.h"
16 #include "nsGkAtoms.h"
17 #include "nsPresContext.h"
18 #include "nsBidiUtils.h"
19 #include "nsCSSFrameConstructor.h"
20 #include "nsContainerFrame.h"
21 #include "nsInlineFrame.h"
22 #include "nsPlaceholderFrame.h"
23 #include "nsPointerHashKeys.h"
24 #include "nsFirstLetterFrame.h"
25 #include "nsUnicodeProperties.h"
26 #include "nsTextFrame.h"
27 #include "nsBlockFrame.h"
28 #include "nsIFrameInlines.h"
29 #include "nsStyleStructInlines.h"
30 #include "RubyUtils.h"
31 #include "nsRubyFrame.h"
32 #include "nsRubyBaseFrame.h"
33 #include "nsRubyTextFrame.h"
34 #include "nsRubyBaseContainerFrame.h"
35 #include "nsRubyTextContainerFrame.h"
36 #include <algorithm>
37 
38 #undef NOISY_BIDI
39 #undef REALLY_NOISY_BIDI
40 
41 using namespace mozilla;
42 
43 static const char16_t kSpace = 0x0020;
44 static const char16_t kZWSP = 0x200B;
45 static const char16_t kLineSeparator = 0x2028;
46 static const char16_t kObjectSubstitute = 0xFFFC;
47 static const char16_t kLRE = 0x202A;
48 static const char16_t kRLE = 0x202B;
49 static const char16_t kLRO = 0x202D;
50 static const char16_t kRLO = 0x202E;
51 static const char16_t kPDF = 0x202C;
52 static const char16_t kLRI = 0x2066;
53 static const char16_t kRLI = 0x2067;
54 static const char16_t kFSI = 0x2068;
55 static const char16_t kPDI = 0x2069;
56 // All characters with Bidi type Segment Separator or Block Separator
57 static const char16_t kSeparators[] = {
58     char16_t('\t'), char16_t('\r'),   char16_t('\n'), char16_t(0xb),
59     char16_t(0x1c), char16_t(0x1d),   char16_t(0x1e), char16_t(0x1f),
60     char16_t(0x85), char16_t(0x2029), char16_t(0)};
61 
62 #define NS_BIDI_CONTROL_FRAME ((nsIFrame*)0xfffb1d1)
63 
64 // This exists just to be a type; the value doesn't matter.
65 enum class BidiControlFrameType { Value };
66 
IsIsolateControl(char16_t aChar)67 static bool IsIsolateControl(char16_t aChar) {
68   return aChar == kLRI || aChar == kRLI || aChar == kFSI;
69 }
70 
71 // Given a ComputedStyle, return any bidi control character necessary to
72 // implement style properties that override directionality (i.e. if it has
73 // unicode-bidi:bidi-override, or text-orientation:upright in vertical
74 // writing mode) when applying the bidi algorithm.
75 //
76 // Returns 0 if no override control character is implied by this style.
GetBidiOverride(ComputedStyle * aComputedStyle)77 static char16_t GetBidiOverride(ComputedStyle* aComputedStyle) {
78   const nsStyleVisibility* vis = aComputedStyle->StyleVisibility();
79   if ((vis->mWritingMode == StyleWritingModeProperty::VerticalRl ||
80        vis->mWritingMode == StyleWritingModeProperty::VerticalLr) &&
81       vis->mTextOrientation == StyleTextOrientation::Upright) {
82     return kLRO;
83   }
84   const nsStyleTextReset* text = aComputedStyle->StyleTextReset();
85   if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_BIDI_OVERRIDE) {
86     return StyleDirection::Rtl == vis->mDirection ? kRLO : kLRO;
87   }
88   return 0;
89 }
90 
91 // Given a ComputedStyle, return any bidi control character necessary to
92 // implement style properties that affect bidi resolution (i.e. if it
93 // has unicode-bidiembed, isolate, or plaintext) when applying the bidi
94 // algorithm.
95 //
96 // Returns 0 if no control character is implied by the style.
97 //
98 // Note that GetBidiOverride and GetBidiControl need to be separate
99 // because in the case of unicode-bidi:isolate-override we need both
100 // FSI and LRO/RLO.
GetBidiControl(ComputedStyle * aComputedStyle)101 static char16_t GetBidiControl(ComputedStyle* aComputedStyle) {
102   const nsStyleVisibility* vis = aComputedStyle->StyleVisibility();
103   const nsStyleTextReset* text = aComputedStyle->StyleTextReset();
104   if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_EMBED) {
105     return StyleDirection::Rtl == vis->mDirection ? kRLE : kLRE;
106   }
107   if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_ISOLATE) {
108     if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_BIDI_OVERRIDE) {
109       // isolate-override
110       return kFSI;
111     }
112     // <bdi> element already has its directionality set from content so
113     // we never need to return kFSI.
114     return StyleDirection::Rtl == vis->mDirection ? kRLI : kLRI;
115   }
116   if (text->mUnicodeBidi & NS_STYLE_UNICODE_BIDI_PLAINTEXT) {
117     return kFSI;
118   }
119   return 0;
120 }
121 
122 #ifdef DEBUG
AreContinuationsInOrder(nsIFrame * aFrame1,nsIFrame * aFrame2)123 static inline bool AreContinuationsInOrder(nsIFrame* aFrame1,
124                                            nsIFrame* aFrame2) {
125   nsIFrame* f = aFrame1;
126   do {
127     f = f->GetNextContinuation();
128   } while (f && f != aFrame2);
129   return !!f;
130 }
131 #endif
132 
133 struct MOZ_STACK_CLASS BidiParagraphData {
134   struct FrameInfo {
FrameInfoBidiParagraphData::FrameInfo135     FrameInfo(nsIFrame* aFrame, nsBlockInFlowLineIterator& aLineIter)
136         : mFrame(aFrame),
137           mBlockContainer(aLineIter.GetContainer()),
138           mInOverflow(aLineIter.GetInOverflow()) {}
139 
FrameInfoBidiParagraphData::FrameInfo140     explicit FrameInfo(BidiControlFrameType aValue)
141         : mFrame(NS_BIDI_CONTROL_FRAME),
142           mBlockContainer(nullptr),
143           mInOverflow(false) {}
144 
FrameInfoBidiParagraphData::FrameInfo145     FrameInfo()
146         : mFrame(nullptr), mBlockContainer(nullptr), mInOverflow(false) {}
147 
148     nsIFrame* mFrame;
149 
150     // The block containing mFrame (i.e., which continuation).
151     nsBlockFrame* mBlockContainer;
152 
153     // true if mFrame is in mBlockContainer's overflow lines, false if
154     // in primary lines
155     bool mInOverflow;
156   };
157 
158   nsAutoString mBuffer;
159   AutoTArray<char16_t, 16> mEmbeddingStack;
160   AutoTArray<FrameInfo, 16> mLogicalFrames;
161   nsTHashMap<nsPtrHashKey<const nsIContent>, int32_t> mContentToFrameIndex;
162   // Cached presentation context for the frames we're processing.
163   nsPresContext* mPresContext;
164   bool mIsVisual;
165   bool mRequiresBidi;
166   nsBidiLevel mParaLevel;
167   nsIContent* mPrevContent;
168 
169   /**
170    * This class is designed to manage the process of mapping a frame to
171    * the line that it's in, when we know that (a) the frames we ask it
172    * about are always in the block's lines and (b) each successive frame
173    * we ask it about is the same as or after (in depth-first search
174    * order) the previous.
175    *
176    * Since we move through the lines at a different pace in Traverse and
177    * ResolveParagraph, we use one of these for each.
178    *
179    * The state of the mapping is also different between TraverseFrames
180    * and ResolveParagraph since since resolving can call functions
181    * (EnsureBidiContinuation or SplitInlineAncestors) that can create
182    * new frames and thus break lines.
183    *
184    * The TraverseFrames iterator is only used in some edge cases.
185    */
186   struct FastLineIterator {
FastLineIteratorBidiParagraphData::FastLineIterator187     FastLineIterator() : mPrevFrame(nullptr), mNextLineStart(nullptr) {}
188 
189     // These iterators *and* mPrevFrame track the line list that we're
190     // iterating over.
191     //
192     // mPrevFrame, if non-null, should be either the frame we're currently
193     // handling (in ResolveParagraph or TraverseFrames, depending on the
194     // iterator) or a frame before it, and is also guaranteed to either be in
195     // mCurrentLine or have been in mCurrentLine until recently.
196     //
197     // In case the splitting causes block frames to break lines, however, we
198     // also track the first frame of the next line.  If that changes, it means
199     // we've broken lines and we have to invalidate mPrevFrame.
200     nsBlockInFlowLineIterator mLineIterator;
201     nsIFrame* mPrevFrame;
202     nsIFrame* mNextLineStart;
203 
GetLineBidiParagraphData::FastLineIterator204     nsLineList::iterator GetLine() { return mLineIterator.GetLine(); }
205 
IsFrameInCurrentLineBidiParagraphData::FastLineIterator206     static bool IsFrameInCurrentLine(nsBlockInFlowLineIterator* aLineIter,
207                                      nsIFrame* aPrevFrame, nsIFrame* aFrame) {
208       MOZ_ASSERT(!aPrevFrame || aLineIter->GetLine()->Contains(aPrevFrame),
209                  "aPrevFrame must be in aLineIter's current line");
210       nsIFrame* endFrame = aLineIter->IsLastLineInList()
211                                ? nullptr
212                                : aLineIter->GetLine().next()->mFirstChild;
213       nsIFrame* startFrame =
214           aPrevFrame ? aPrevFrame : aLineIter->GetLine()->mFirstChild;
215       for (nsIFrame* frame = startFrame; frame && frame != endFrame;
216            frame = frame->GetNextSibling()) {
217         if (frame == aFrame) return true;
218       }
219       return false;
220     }
221 
FirstChildOfNextLineBidiParagraphData::FastLineIterator222     static nsIFrame* FirstChildOfNextLine(
223         nsBlockInFlowLineIterator& aIterator) {
224       const nsLineList::iterator line = aIterator.GetLine();
225       const nsLineList::iterator lineEnd = aIterator.End();
226       MOZ_ASSERT(line != lineEnd, "iterator should start off valid");
227       const nsLineList::iterator nextLine = line.next();
228 
229       return nextLine != lineEnd ? nextLine->mFirstChild : nullptr;
230     }
231 
232     // Advance line iterator to the line containing aFrame, assuming
233     // that aFrame is already in the line list our iterator is iterating
234     // over.
AdvanceToFrameBidiParagraphData::FastLineIterator235     void AdvanceToFrame(nsIFrame* aFrame) {
236       if (mPrevFrame && FirstChildOfNextLine(mLineIterator) != mNextLineStart) {
237         // Something has caused a line to split.  We need to invalidate
238         // mPrevFrame since it may now be in a *later* line, though it may
239         // still be in this line, so we need to start searching for it from
240         // the start of this line.
241         mPrevFrame = nullptr;
242       }
243       nsIFrame* child = aFrame;
244       nsIFrame* parent = nsLayoutUtils::GetParentOrPlaceholderFor(child);
245       while (parent && !parent->IsBlockFrameOrSubclass()) {
246         child = parent;
247         parent = nsLayoutUtils::GetParentOrPlaceholderFor(child);
248       }
249       MOZ_ASSERT(parent, "aFrame is not a descendent of a block frame");
250       while (!IsFrameInCurrentLine(&mLineIterator, mPrevFrame, child)) {
251 #ifdef DEBUG
252         bool hasNext =
253 #endif
254             mLineIterator.Next();
255         MOZ_ASSERT(hasNext, "Can't find frame in lines!");
256         mPrevFrame = nullptr;
257       }
258       mPrevFrame = child;
259       mNextLineStart = FirstChildOfNextLine(mLineIterator);
260     }
261 
262     // Advance line iterator to the line containing aFrame, which may
263     // require moving forward into overflow lines or into a later
264     // continuation (or both).
AdvanceToLinesAndFrameBidiParagraphData::FastLineIterator265     void AdvanceToLinesAndFrame(const FrameInfo& aFrameInfo) {
266       if (mLineIterator.GetContainer() != aFrameInfo.mBlockContainer ||
267           mLineIterator.GetInOverflow() != aFrameInfo.mInOverflow) {
268         MOZ_ASSERT(
269             mLineIterator.GetContainer() == aFrameInfo.mBlockContainer
270                 ? (!mLineIterator.GetInOverflow() && aFrameInfo.mInOverflow)
271                 : (!mLineIterator.GetContainer() ||
272                    AreContinuationsInOrder(mLineIterator.GetContainer(),
273                                            aFrameInfo.mBlockContainer)),
274             "must move forwards");
275         nsBlockFrame* block = aFrameInfo.mBlockContainer;
276         nsLineList::iterator lines =
277             aFrameInfo.mInOverflow ? block->GetOverflowLines()->mLines.begin()
278                                    : block->LinesBegin();
279         mLineIterator =
280             nsBlockInFlowLineIterator(block, lines, aFrameInfo.mInOverflow);
281         mPrevFrame = nullptr;
282       }
283       AdvanceToFrame(aFrameInfo.mFrame);
284     }
285   };
286 
287   FastLineIterator mCurrentTraverseLine, mCurrentResolveLine;
288 
289 #ifdef DEBUG
290   // Only used for NOISY debug output.
291   // Matches the current TraverseFrames state, not the ResolveParagraph
292   // state.
293   nsBlockFrame* mCurrentBlock;
294 #endif
295 
BidiParagraphDataBidiParagraphData296   explicit BidiParagraphData(nsBlockFrame* aBlockFrame)
297       : mPresContext(aBlockFrame->PresContext()),
298         mIsVisual(mPresContext->IsVisualMode()),
299         mRequiresBidi(false),
300         mParaLevel(nsBidiPresUtils::BidiLevelFromStyle(aBlockFrame->Style())),
301         mPrevContent(nullptr)
302 #ifdef DEBUG
303         ,
304         mCurrentBlock(aBlockFrame)
305 #endif
306   {
307     if (mParaLevel > 0) {
308       mRequiresBidi = true;
309     }
310 
311     if (mIsVisual) {
312       /**
313        * Drill up in content to detect whether this is an element that needs to
314        * be rendered with logical order even on visual pages.
315        *
316        * We always use logical order on form controls, firstly so that text
317        * entry will be in logical order, but also because visual pages were
318        * written with the assumption that even if the browser had no support
319        * for right-to-left text rendering, it would use native widgets with
320        * bidi support to display form controls.
321        *
322        * We also use logical order in XUL elements, since we expect that if a
323        * XUL element appears in a visual page, it will be generated by an XBL
324        * binding and contain localized text which will be in logical order.
325        */
326       for (nsIContent* content = aBlockFrame->GetContent(); content;
327            content = content->GetParent()) {
328         if (content->IsNodeOfType(nsINode::eHTML_FORM_CONTROL) ||
329             content->IsXULElement()) {
330           mIsVisual = false;
331           break;
332         }
333       }
334     }
335   }
336 
SetParaBidiParagraphData337   nsresult SetPara() {
338     return mPresContext->GetBidiEngine().SetPara(mBuffer.get(), BufferLength(),
339                                                  mParaLevel);
340   }
341 
342   /**
343    * mParaLevel can be NSBIDI_DEFAULT_LTR as well as NSBIDI_LTR or NSBIDI_RTL.
344    * GetParaLevel() returns the actual (resolved) paragraph level which is
345    * always either NSBIDI_LTR or NSBIDI_RTL
346    */
GetParaLevelBidiParagraphData347   nsBidiLevel GetParaLevel() {
348     nsBidiLevel paraLevel = mParaLevel;
349     if (paraLevel == NSBIDI_DEFAULT_LTR || paraLevel == NSBIDI_DEFAULT_RTL) {
350       paraLevel = mPresContext->GetBidiEngine().GetParaLevel();
351     }
352     return paraLevel;
353   }
354 
GetDirectionBidiParagraphData355   nsBidiDirection GetDirection() {
356     return mPresContext->GetBidiEngine().GetDirection();
357   }
358 
CountRunsBidiParagraphData359   nsresult CountRuns(int32_t* runCount) {
360     return mPresContext->GetBidiEngine().CountRuns(runCount);
361   }
362 
GetLogicalRunBidiParagraphData363   void GetLogicalRun(int32_t aLogicalStart, int32_t* aLogicalLimit,
364                      nsBidiLevel* aLevel) {
365     mPresContext->GetBidiEngine().GetLogicalRun(aLogicalStart, aLogicalLimit,
366                                                 aLevel);
367     if (mIsVisual) {
368       *aLevel = GetParaLevel();
369     }
370   }
371 
ResetDataBidiParagraphData372   void ResetData() {
373     mLogicalFrames.Clear();
374     mContentToFrameIndex.Clear();
375     mBuffer.SetLength(0);
376     mPrevContent = nullptr;
377     for (uint32_t i = 0; i < mEmbeddingStack.Length(); ++i) {
378       mBuffer.Append(mEmbeddingStack[i]);
379       mLogicalFrames.AppendElement(FrameInfo(BidiControlFrameType::Value));
380     }
381   }
382 
AppendFrameBidiParagraphData383   void AppendFrame(nsIFrame* aFrame, FastLineIterator& aLineIter,
384                    nsIContent* aContent = nullptr) {
385     if (aContent) {
386       mContentToFrameIndex.InsertOrUpdate(aContent, FrameCount());
387     }
388 
389     // We don't actually need to advance aLineIter to aFrame, since all we use
390     // from it is the block and is-overflow state, which are correct already.
391     mLogicalFrames.AppendElement(FrameInfo(aFrame, aLineIter.mLineIterator));
392   }
393 
AdvanceAndAppendFrameBidiParagraphData394   void AdvanceAndAppendFrame(nsIFrame** aFrame, FastLineIterator& aLineIter,
395                              nsIFrame** aNextSibling) {
396     nsIFrame* frame = *aFrame;
397     nsIFrame* nextSibling = *aNextSibling;
398 
399     frame = frame->GetNextContinuation();
400     if (frame) {
401       AppendFrame(frame, aLineIter, nullptr);
402 
403       /*
404        * If we have already overshot the saved next-sibling while
405        * scanning the frame's continuations, advance it.
406        */
407       if (frame == nextSibling) {
408         nextSibling = frame->GetNextSibling();
409       }
410     }
411 
412     *aFrame = frame;
413     *aNextSibling = nextSibling;
414   }
415 
GetLastFrameForContentBidiParagraphData416   int32_t GetLastFrameForContent(nsIContent* aContent) {
417     return mContentToFrameIndex.Get(aContent);
418   }
419 
FrameCountBidiParagraphData420   int32_t FrameCount() { return mLogicalFrames.Length(); }
421 
BufferLengthBidiParagraphData422   int32_t BufferLength() { return mBuffer.Length(); }
423 
FrameAtBidiParagraphData424   nsIFrame* FrameAt(int32_t aIndex) { return mLogicalFrames[aIndex].mFrame; }
425 
FrameInfoAtBidiParagraphData426   const FrameInfo& FrameInfoAt(int32_t aIndex) {
427     return mLogicalFrames[aIndex];
428   }
429 
AppendUnicharBidiParagraphData430   void AppendUnichar(char16_t aCh) { mBuffer.Append(aCh); }
431 
AppendStringBidiParagraphData432   void AppendString(const nsDependentSubstring& aString) {
433     mBuffer.Append(aString);
434   }
435 
AppendControlCharBidiParagraphData436   void AppendControlChar(char16_t aCh) {
437     mLogicalFrames.AppendElement(FrameInfo(BidiControlFrameType::Value));
438     AppendUnichar(aCh);
439   }
440 
PushBidiControlBidiParagraphData441   void PushBidiControl(char16_t aCh) {
442     AppendControlChar(aCh);
443     mEmbeddingStack.AppendElement(aCh);
444   }
445 
AppendPopCharBidiParagraphData446   void AppendPopChar(char16_t aCh) {
447     AppendControlChar(IsIsolateControl(aCh) ? kPDI : kPDF);
448   }
449 
PopBidiControlBidiParagraphData450   void PopBidiControl(char16_t aCh) {
451     MOZ_ASSERT(mEmbeddingStack.Length(), "embedding/override underflow");
452     MOZ_ASSERT(aCh == mEmbeddingStack.LastElement());
453     AppendPopChar(aCh);
454     mEmbeddingStack.RemoveLastElement();
455   }
456 
ClearBidiControlsBidiParagraphData457   void ClearBidiControls() {
458     for (char16_t c : Reversed(mEmbeddingStack)) {
459       AppendPopChar(c);
460     }
461   }
462 };
463 
464 struct MOZ_STACK_CLASS BidiLineData {
465   AutoTArray<nsIFrame*, 16> mLogicalFrames;
466   AutoTArray<nsIFrame*, 16> mVisualFrames;
467   AutoTArray<int32_t, 16> mIndexMap;
468   AutoTArray<uint8_t, 16> mLevels;
469   bool mIsReordered;
470 
BidiLineDataBidiLineData471   BidiLineData(nsIFrame* aFirstFrameOnLine, int32_t aNumFramesOnLine) {
472     /**
473      * Initialize the logically-ordered array of frames using the top-level
474      * frames of a single line
475      */
476     bool isReordered = false;
477     bool hasRTLFrames = false;
478     bool hasVirtualControls = false;
479 
480     auto appendFrame = [&](nsIFrame* frame, nsBidiLevel level) {
481       mLogicalFrames.AppendElement(frame);
482       mLevels.AppendElement(level);
483       mIndexMap.AppendElement(0);
484       if (IS_LEVEL_RTL(level)) {
485         hasRTLFrames = true;
486       }
487     };
488 
489     bool firstFrame = true;
490     for (nsIFrame* frame = aFirstFrameOnLine; frame && aNumFramesOnLine--;
491          frame = frame->GetNextSibling()) {
492       FrameBidiData bidiData = nsBidiPresUtils::GetFrameBidiData(frame);
493       // Ignore virtual control before the first frame. Doing so should
494       // not affect the visual result, but could avoid running into the
495       // stripping code below for many cases.
496       if (!firstFrame && bidiData.precedingControl != kBidiLevelNone) {
497         appendFrame(NS_BIDI_CONTROL_FRAME, bidiData.precedingControl);
498         hasVirtualControls = true;
499       }
500       appendFrame(frame, bidiData.embeddingLevel);
501       firstFrame = false;
502     }
503 
504     // Reorder the line
505     nsBidi::ReorderVisual(mLevels.Elements(), FrameCount(),
506                           mIndexMap.Elements());
507 
508     // Strip virtual frames
509     if (hasVirtualControls) {
510       auto originalCount = mLogicalFrames.Length();
511       AutoTArray<int32_t, 16> realFrameMap;
512       realFrameMap.SetCapacity(originalCount);
513       size_t count = 0;
514       for (auto i : IntegerRange(originalCount)) {
515         if (mLogicalFrames[i] == NS_BIDI_CONTROL_FRAME) {
516           realFrameMap.AppendElement(-1);
517         } else {
518           mLogicalFrames[count] = mLogicalFrames[i];
519           mLevels[count] = mLevels[i];
520           realFrameMap.AppendElement(count);
521           count++;
522         }
523       }
524       // Only keep index map for real frames.
525       for (size_t i = 0, j = 0; i < originalCount; ++i) {
526         auto newIndex = realFrameMap[mIndexMap[i]];
527         if (newIndex != -1) {
528           mIndexMap[j] = newIndex;
529           j++;
530         }
531       }
532       mLogicalFrames.TruncateLength(count);
533       mLevels.TruncateLength(count);
534       mIndexMap.TruncateLength(count);
535     }
536 
537     for (int32_t i = 0; i < FrameCount(); i++) {
538       mVisualFrames.AppendElement(LogicalFrameAt(mIndexMap[i]));
539       if (i != mIndexMap[i]) {
540         isReordered = true;
541       }
542     }
543 
544     // If there's an RTL frame, assume the line is reordered
545     mIsReordered = isReordered || hasRTLFrames;
546   }
547 
FrameCountBidiLineData548   int32_t FrameCount() const { return mLogicalFrames.Length(); }
549 
LogicalFrameAtBidiLineData550   nsIFrame* LogicalFrameAt(int32_t aIndex) const {
551     return mLogicalFrames[aIndex];
552   }
553 
VisualFrameAtBidiLineData554   nsIFrame* VisualFrameAt(int32_t aIndex) const {
555     return mVisualFrames[aIndex];
556   }
557 };
558 
559 #ifdef DEBUG
560 extern "C" {
DumpFrameArray(const nsTArray<nsIFrame * > & aFrames)561 void MOZ_EXPORT DumpFrameArray(const nsTArray<nsIFrame*>& aFrames) {
562   for (nsIFrame* frame : aFrames) {
563     if (frame == NS_BIDI_CONTROL_FRAME) {
564       fprintf_stderr(stderr, "(Bidi control frame)\n");
565     } else {
566       frame->List();
567     }
568   }
569 }
570 
DumpBidiLine(BidiLineData * aData,bool aVisualOrder)571 void MOZ_EXPORT DumpBidiLine(BidiLineData* aData, bool aVisualOrder) {
572   DumpFrameArray(aVisualOrder ? aData->mVisualFrames : aData->mLogicalFrames);
573 }
574 }
575 #endif
576 
577 /* Some helper methods for Resolve() */
578 
579 // Should this frame be split between text runs?
IsBidiSplittable(nsIFrame * aFrame)580 static bool IsBidiSplittable(nsIFrame* aFrame) {
581   MOZ_ASSERT(aFrame);
582   // Bidi inline containers should be split, unless they're line frames.
583   LayoutFrameType frameType = aFrame->Type();
584   return (aFrame->IsFrameOfType(nsIFrame::eBidiInlineContainer) &&
585           frameType != LayoutFrameType::Line) ||
586          frameType == LayoutFrameType::Text;
587 }
588 
589 // Should this frame be treated as a leaf (e.g. when building mLogicalFrames)?
IsBidiLeaf(const nsIFrame * aFrame)590 static bool IsBidiLeaf(const nsIFrame* aFrame) {
591   nsIFrame* kid = aFrame->PrincipalChildList().FirstChild();
592   if (kid) {
593     if (aFrame->IsFrameOfType(nsIFrame::eBidiInlineContainer) ||
594         RubyUtils::IsRubyBox(aFrame->Type())) {
595       return false;
596     }
597   }
598   return true;
599 }
600 
601 /**
602  * Create non-fluid continuations for the ancestors of a given frame all the way
603  * up the frame tree until we hit a non-splittable frame (a line or a block).
604  *
605  * @param aParent the first parent frame to be split
606  * @param aFrame the child frames after this frame are reparented to the
607  *        newly-created continuation of aParent.
608  *        If aFrame is null, all the children of aParent are reparented.
609  */
SplitInlineAncestors(nsContainerFrame * aParent,nsLineList::iterator aLine,nsIFrame * aFrame)610 static void SplitInlineAncestors(nsContainerFrame* aParent,
611                                  nsLineList::iterator aLine, nsIFrame* aFrame) {
612   PresShell* presShell = aParent->PresShell();
613   nsIFrame* frame = aFrame;
614   nsContainerFrame* parent = aParent;
615   nsContainerFrame* newParent;
616 
617   while (IsBidiSplittable(parent)) {
618     nsContainerFrame* grandparent = parent->GetParent();
619     NS_ASSERTION(grandparent,
620                  "Couldn't get parent's parent in "
621                  "nsBidiPresUtils::SplitInlineAncestors");
622 
623     // Split the child list after |frame|, unless it is the last child.
624     if (!frame || frame->GetNextSibling()) {
625       newParent = static_cast<nsContainerFrame*>(
626           presShell->FrameConstructor()->CreateContinuingFrame(
627               parent, grandparent, false));
628 
629       nsFrameList tail = parent->StealFramesAfter(frame);
630 
631       // Reparent views as necessary
632       nsContainerFrame::ReparentFrameViewList(tail, parent, newParent);
633 
634       // The parent's continuation adopts the siblings after the split.
635       MOZ_ASSERT(!newParent->IsBlockFrameOrSubclass(),
636                  "blocks should not be IsBidiSplittable");
637       newParent->InsertFrames(nsIFrame::kNoReflowPrincipalList, nullptr,
638                               nullptr, tail);
639 
640       // While passing &aLine to InsertFrames for a non-block isn't harmful
641       // because it's a no-op, it doesn't really make sense.  However, the
642       // MOZ_ASSERT() we need to guarantee that it's safe only works if the
643       // parent is actually the block.
644       const nsLineList::iterator* parentLine;
645       if (grandparent->IsBlockFrameOrSubclass()) {
646         MOZ_ASSERT(aLine->Contains(parent));
647         parentLine = &aLine;
648       } else {
649         parentLine = nullptr;
650       }
651 
652       // The list name kNoReflowPrincipalList would indicate we don't want
653       // reflow
654       nsFrameList temp(newParent, newParent);
655       grandparent->InsertFrames(nsIFrame::kNoReflowPrincipalList, parent,
656                                 parentLine, temp);
657     }
658 
659     frame = parent;
660     parent = grandparent;
661   }
662 }
663 
MakeContinuationFluid(nsIFrame * aFrame,nsIFrame * aNext)664 static void MakeContinuationFluid(nsIFrame* aFrame, nsIFrame* aNext) {
665   NS_ASSERTION(!aFrame->GetNextInFlow() || aFrame->GetNextInFlow() == aNext,
666                "next-in-flow is not next continuation!");
667   aFrame->SetNextInFlow(aNext);
668 
669   NS_ASSERTION(!aNext->GetPrevInFlow() || aNext->GetPrevInFlow() == aFrame,
670                "prev-in-flow is not prev continuation!");
671   aNext->SetPrevInFlow(aFrame);
672 }
673 
MakeContinuationsNonFluidUpParentChain(nsIFrame * aFrame,nsIFrame * aNext)674 static void MakeContinuationsNonFluidUpParentChain(nsIFrame* aFrame,
675                                                    nsIFrame* aNext) {
676   nsIFrame* frame;
677   nsIFrame* next;
678 
679   for (frame = aFrame, next = aNext;
680        frame && next && next != frame && next == frame->GetNextInFlow() &&
681        IsBidiSplittable(frame);
682        frame = frame->GetParent(), next = next->GetParent()) {
683     frame->SetNextContinuation(next);
684     next->SetPrevContinuation(frame);
685   }
686 }
687 
688 // If aFrame is the last child of its parent, convert bidi continuations to
689 // fluid continuations for all of its inline ancestors.
690 // If it isn't the last child, make sure that its continuation is fluid.
JoinInlineAncestors(nsIFrame * aFrame)691 static void JoinInlineAncestors(nsIFrame* aFrame) {
692   nsIFrame* frame = aFrame;
693   while (frame && IsBidiSplittable(frame)) {
694     nsIFrame* next = frame->GetNextContinuation();
695     if (next) {
696       MakeContinuationFluid(frame, next);
697     }
698     // Join the parent only as long as we're its last child.
699     if (frame->GetNextSibling()) break;
700     frame = frame->GetParent();
701   }
702 }
703 
CreateContinuation(nsIFrame * aFrame,const nsLineList::iterator aLine,nsIFrame ** aNewFrame,bool aIsFluid)704 static void CreateContinuation(nsIFrame* aFrame,
705                                const nsLineList::iterator aLine,
706                                nsIFrame** aNewFrame, bool aIsFluid) {
707   MOZ_ASSERT(aNewFrame, "null OUT ptr");
708   MOZ_ASSERT(aFrame, "null ptr");
709 
710   *aNewFrame = nullptr;
711 
712   nsPresContext* presContext = aFrame->PresContext();
713   PresShell* presShell = presContext->PresShell();
714   NS_ASSERTION(presShell,
715                "PresShell must be set on PresContext before calling "
716                "nsBidiPresUtils::CreateContinuation");
717 
718   nsContainerFrame* parent = aFrame->GetParent();
719   NS_ASSERTION(
720       parent,
721       "Couldn't get frame parent in nsBidiPresUtils::CreateContinuation");
722 
723   // While passing &aLine to InsertFrames for a non-block isn't harmful
724   // because it's a no-op, it doesn't really make sense.  However, the
725   // MOZ_ASSERT() we need to guarantee that it's safe only works if the
726   // parent is actually the block.
727   const nsLineList::iterator* parentLine;
728   if (parent->IsBlockFrameOrSubclass()) {
729     MOZ_ASSERT(aLine->Contains(aFrame));
730     parentLine = &aLine;
731   } else {
732     parentLine = nullptr;
733   }
734 
735   // Have to special case floating first letter frames because the continuation
736   // doesn't go in the first letter frame. The continuation goes with the rest
737   // of the text that the first letter frame was made out of.
738   if (parent->IsLetterFrame() && parent->IsFloating()) {
739     nsFirstLetterFrame* letterFrame = do_QueryFrame(parent);
740     letterFrame->CreateContinuationForFloatingParent(aFrame, aNewFrame,
741                                                      aIsFluid);
742     return;
743   }
744 
745   *aNewFrame = presShell->FrameConstructor()->CreateContinuingFrame(
746       aFrame, parent, aIsFluid);
747 
748   // The list name kNoReflowPrincipalList would indicate we don't want reflow
749   // XXXbz this needs higher-level framelist love
750   nsFrameList temp(*aNewFrame, *aNewFrame);
751   parent->InsertFrames(nsIFrame::kNoReflowPrincipalList, aFrame, parentLine,
752                        temp);
753 
754   if (!aIsFluid) {
755     // Split inline ancestor frames
756     SplitInlineAncestors(parent, aLine, aFrame);
757   }
758 }
759 
760 /*
761  * Overview of the implementation of Resolve():
762  *
763  *  Walk through the descendants of aBlockFrame and build:
764  *   * mLogicalFrames: an nsTArray of nsIFrame* pointers in logical order
765  *   * mBuffer: an nsString containing a representation of
766  *     the content of the frames.
767  *     In the case of text frames, this is the actual text context of the
768  *     frames, but some other elements are represented in a symbolic form which
769  *     will make the Unicode Bidi Algorithm give the correct results.
770  *     Bidi isolates, embeddings, and overrides set by CSS, <bdi>, or <bdo>
771  *     elements are represented by the corresponding Unicode control characters.
772  *     <br> elements are represented by U+2028 LINE SEPARATOR
773  *     Other inline elements are represented by U+FFFC OBJECT REPLACEMENT
774  *     CHARACTER
775  *
776  *  Then pass mBuffer to the Bidi engine for resolving of embedding levels
777  *  by nsBidi::SetPara() and division into directional runs by
778  *  nsBidi::CountRuns().
779  *
780  *  Finally, walk these runs in logical order using nsBidi::GetLogicalRun() and
781  *  correlate them with the frames indexed in mLogicalFrames, setting the
782  *  baseLevel and embeddingLevel properties according to the results returned
783  *  by the Bidi engine.
784  *
785  *  The rendering layer requires each text frame to contain text in only one
786  *  direction, so we may need to call EnsureBidiContinuation() to split frames.
787  *  We may also need to call RemoveBidiContinuation() to convert frames created
788  *  by EnsureBidiContinuation() in previous reflows into fluid continuations.
789  */
Resolve(nsBlockFrame * aBlockFrame)790 nsresult nsBidiPresUtils::Resolve(nsBlockFrame* aBlockFrame) {
791   BidiParagraphData bpd(aBlockFrame);
792 
793   // Handle bidi-override being set on the block itself before calling
794   // TraverseFrames.
795   // No need to call GetBidiControl as well, because isolate and embed
796   // values of unicode-bidi property are redundant on block elements.
797   // unicode-bidi:plaintext on a block element is handled by block frame
798   // via using nsIFrame::GetWritingMode(nsIFrame*).
799   char16_t ch = GetBidiOverride(aBlockFrame->Style());
800   if (ch != 0) {
801     bpd.PushBidiControl(ch);
802     bpd.mRequiresBidi = true;
803   } else {
804     // If there are no unicode-bidi properties and no RTL characters in the
805     // block's content, then it is pure LTR and we can skip the rest of bidi
806     // resolution.
807     nsIContent* currContent = nullptr;
808     for (nsBlockFrame* block = aBlockFrame; block;
809          block = static_cast<nsBlockFrame*>(block->GetNextContinuation())) {
810       block->RemoveStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION);
811       if (!bpd.mRequiresBidi &&
812           ChildListMayRequireBidi(block->PrincipalChildList().FirstChild(),
813                                   &currContent)) {
814         bpd.mRequiresBidi = true;
815       }
816       if (!bpd.mRequiresBidi) {
817         nsBlockFrame::FrameLines* overflowLines = block->GetOverflowLines();
818         if (overflowLines) {
819           if (ChildListMayRequireBidi(overflowLines->mFrames.FirstChild(),
820                                       &currContent)) {
821             bpd.mRequiresBidi = true;
822           }
823         }
824       }
825     }
826     if (!bpd.mRequiresBidi) {
827       return NS_OK;
828     }
829   }
830 
831   for (nsBlockFrame* block = aBlockFrame; block;
832        block = static_cast<nsBlockFrame*>(block->GetNextContinuation())) {
833 #ifdef DEBUG
834     bpd.mCurrentBlock = block;
835 #endif
836     block->RemoveStateBits(NS_BLOCK_NEEDS_BIDI_RESOLUTION);
837     bpd.mCurrentTraverseLine.mLineIterator =
838         nsBlockInFlowLineIterator(block, block->LinesBegin());
839     bpd.mCurrentTraverseLine.mPrevFrame = nullptr;
840     TraverseFrames(block->PrincipalChildList().FirstChild(), &bpd);
841     nsBlockFrame::FrameLines* overflowLines = block->GetOverflowLines();
842     if (overflowLines) {
843       bpd.mCurrentTraverseLine.mLineIterator =
844           nsBlockInFlowLineIterator(block, overflowLines->mLines.begin(), true);
845       bpd.mCurrentTraverseLine.mPrevFrame = nullptr;
846       TraverseFrames(overflowLines->mFrames.FirstChild(), &bpd);
847     }
848   }
849 
850   if (ch != 0) {
851     bpd.PopBidiControl(ch);
852   }
853 
854   return ResolveParagraph(&bpd);
855 }
856 
ResolveParagraph(BidiParagraphData * aBpd)857 nsresult nsBidiPresUtils::ResolveParagraph(BidiParagraphData* aBpd) {
858   if (aBpd->BufferLength() < 1) {
859     return NS_OK;
860   }
861   aBpd->mBuffer.ReplaceChar(kSeparators, kSpace);
862 
863   int32_t runCount;
864 
865   nsresult rv = aBpd->SetPara();
866   NS_ENSURE_SUCCESS(rv, rv);
867 
868   nsBidiLevel embeddingLevel = aBpd->GetParaLevel();
869 
870   rv = aBpd->CountRuns(&runCount);
871   NS_ENSURE_SUCCESS(rv, rv);
872 
873   int32_t runLength = 0;     // the length of the current run of text
874   int32_t logicalLimit = 0;  // the end of the current run + 1
875   int32_t numRun = -1;
876   int32_t fragmentLength = 0;  // the length of the current text frame
877   int32_t frameIndex = -1;     // index to the frames in mLogicalFrames
878   int32_t frameCount = aBpd->FrameCount();
879   int32_t contentOffset = 0;  // offset of current frame in its content node
880   bool isTextFrame = false;
881   nsIFrame* frame = nullptr;
882   BidiParagraphData::FrameInfo frameInfo;
883   nsIContent* content = nullptr;
884   int32_t contentTextLength = 0;
885 
886 #ifdef DEBUG
887 #  ifdef NOISY_BIDI
888   printf(
889       "Before Resolve(), mCurrentBlock=%p, mBuffer='%s', frameCount=%d, "
890       "runCount=%d\n",
891       (void*)aBpd->mCurrentBlock, NS_ConvertUTF16toUTF8(aBpd->mBuffer).get(),
892       frameCount, runCount);
893 #    ifdef REALLY_NOISY_BIDI
894   printf(" block frame tree=:\n");
895   aBpd->mCurrentBlock->List(stdout);
896 #    endif
897 #  endif
898 #endif
899 
900   if (runCount == 1 && frameCount == 1 && aBpd->GetDirection() == NSBIDI_LTR &&
901       aBpd->GetParaLevel() == 0) {
902     // We have a single left-to-right frame in a left-to-right paragraph,
903     // without bidi isolation from the surrounding text.
904     // Make sure that the embedding level and base level frame properties aren't
905     // set (because if they are this frame used to have some other direction,
906     // so we can't do this optimization), and we're done.
907     nsIFrame* frame = aBpd->FrameAt(0);
908     if (frame != NS_BIDI_CONTROL_FRAME) {
909       FrameBidiData bidiData = frame->GetBidiData();
910       if (!bidiData.embeddingLevel && !bidiData.baseLevel) {
911 #ifdef DEBUG
912 #  ifdef NOISY_BIDI
913         printf("early return for single direction frame %p\n", (void*)frame);
914 #  endif
915 #endif
916         frame->AddStateBits(NS_FRAME_IS_BIDI);
917         return NS_OK;
918       }
919     }
920   }
921 
922   BidiParagraphData::FrameInfo lastRealFrame;
923   nsBidiLevel lastEmbeddingLevel = kBidiLevelNone;
924   nsBidiLevel precedingControl = kBidiLevelNone;
925 
926   auto storeBidiDataToFrame = [&]() {
927     FrameBidiData bidiData;
928     bidiData.embeddingLevel = embeddingLevel;
929     bidiData.baseLevel = aBpd->GetParaLevel();
930     // If a control character doesn't have a lower embedding level than
931     // both the preceding and the following frame, it isn't something
932     // needed for getting the correct result. This optimization should
933     // remove almost all of embeds and overrides, and some of isolates.
934     if (precedingControl >= embeddingLevel ||
935         precedingControl >= lastEmbeddingLevel) {
936       bidiData.precedingControl = kBidiLevelNone;
937     } else {
938       bidiData.precedingControl = precedingControl;
939     }
940     precedingControl = kBidiLevelNone;
941     lastEmbeddingLevel = embeddingLevel;
942     frame->SetProperty(nsIFrame::BidiDataProperty(), bidiData);
943   };
944 
945   for (;;) {
946     if (fragmentLength <= 0) {
947       // Get the next frame from mLogicalFrames
948       if (++frameIndex >= frameCount) {
949         break;
950       }
951       frameInfo = aBpd->FrameInfoAt(frameIndex);
952       frame = frameInfo.mFrame;
953       if (frame == NS_BIDI_CONTROL_FRAME || !frame->IsTextFrame()) {
954         /*
955          * Any non-text frame corresponds to a single character in the text
956          * buffer (a bidi control character, LINE SEPARATOR, or OBJECT
957          * SUBSTITUTE)
958          */
959         isTextFrame = false;
960         fragmentLength = 1;
961       } else {
962         aBpd->mCurrentResolveLine.AdvanceToLinesAndFrame(frameInfo);
963         content = frame->GetContent();
964         if (!content) {
965           rv = NS_OK;
966           break;
967         }
968         contentTextLength = content->TextLength();
969         auto [start, end] = frame->GetOffsets();
970         NS_ASSERTION(!(contentTextLength < end - start),
971                      "Frame offsets don't fit in content");
972         fragmentLength = std::min(contentTextLength, end - start);
973         contentOffset = start;
974         isTextFrame = true;
975       }
976     }  // if (fragmentLength <= 0)
977 
978     if (runLength <= 0) {
979       // Get the next run of text from the Bidi engine
980       if (++numRun >= runCount) {
981         // We've run out of runs of text; but don't forget to store bidi data
982         // to the frame before breaking out of the loop (bug 1426042).
983         storeBidiDataToFrame();
984         if (isTextFrame) {
985           frame->AdjustOffsetsForBidi(contentOffset,
986                                       contentOffset + fragmentLength);
987         }
988         break;
989       }
990       int32_t lineOffset = logicalLimit;
991       aBpd->GetLogicalRun(lineOffset, &logicalLimit, &embeddingLevel);
992       runLength = logicalLimit - lineOffset;
993     }  // if (runLength <= 0)
994 
995     if (frame == NS_BIDI_CONTROL_FRAME) {
996       // In theory, we only need to do this for isolates. However, it is
997       // easier to do this for all here because we do not maintain the
998       // index to get corresponding character from buffer. Since we do
999       // have proper embedding level for all those characters, including
1000       // them wouldn't affect the final result.
1001       precedingControl = std::min(precedingControl, embeddingLevel);
1002     } else {
1003       storeBidiDataToFrame();
1004       if (isTextFrame) {
1005         if (contentTextLength == 0) {
1006           // Set the base level and embedding level of the current run even
1007           // on an empty frame. Otherwise frame reordering will not be correct.
1008           frame->AdjustOffsetsForBidi(0, 0);
1009           // Nothing more to do for an empty frame, except update
1010           // lastRealFrame like we do below.
1011           lastRealFrame = frameInfo;
1012           continue;
1013         }
1014         nsLineList::iterator currentLine = aBpd->mCurrentResolveLine.GetLine();
1015         if ((runLength > 0) && (runLength < fragmentLength)) {
1016           /*
1017            * The text in this frame continues beyond the end of this directional
1018            * run. Create a non-fluid continuation frame for the next directional
1019            * run.
1020            */
1021           currentLine->MarkDirty();
1022           nsIFrame* nextBidi;
1023           int32_t runEnd = contentOffset + runLength;
1024           EnsureBidiContinuation(frame, currentLine, &nextBidi, contentOffset,
1025                                  runEnd);
1026           nextBidi->AdjustOffsetsForBidi(runEnd,
1027                                          contentOffset + fragmentLength);
1028           frame = nextBidi;
1029           frameInfo.mFrame = frame;
1030           contentOffset = runEnd;
1031 
1032           aBpd->mCurrentResolveLine.AdvanceToFrame(frame);
1033         }  // if (runLength < fragmentLength)
1034         else {
1035           if (contentOffset + fragmentLength == contentTextLength) {
1036             /*
1037              * We have finished all the text in this content node. Convert any
1038              * further non-fluid continuations to fluid continuations and
1039              * advance frameIndex to the last frame in the content node
1040              */
1041             int32_t newIndex = aBpd->GetLastFrameForContent(content);
1042             if (newIndex > frameIndex) {
1043               currentLine->MarkDirty();
1044               RemoveBidiContinuation(aBpd, frame, frameIndex, newIndex);
1045               frameIndex = newIndex;
1046               frameInfo = aBpd->FrameInfoAt(frameIndex);
1047               frame = frameInfo.mFrame;
1048             }
1049           } else if (fragmentLength > 0 && runLength > fragmentLength) {
1050             /*
1051              * There is more text that belongs to this directional run in the
1052              * next text frame: make sure it is a fluid continuation of the
1053              * current frame. Do not advance frameIndex, because the next frame
1054              * may contain multi-directional text and need to be split
1055              */
1056             int32_t newIndex = frameIndex;
1057             do {
1058             } while (++newIndex < frameCount &&
1059                      aBpd->FrameAt(newIndex) == NS_BIDI_CONTROL_FRAME);
1060             if (newIndex < frameCount) {
1061               currentLine->MarkDirty();
1062               RemoveBidiContinuation(aBpd, frame, frameIndex, newIndex);
1063             }
1064           } else if (runLength == fragmentLength) {
1065             /*
1066              * If the directional run ends at the end of the frame, make sure
1067              * that any continuation is non-fluid, and do the same up the
1068              * parent chain
1069              */
1070             nsIFrame* next = frame->GetNextInFlow();
1071             if (next) {
1072               currentLine->MarkDirty();
1073               MakeContinuationsNonFluidUpParentChain(frame, next);
1074             }
1075           }
1076           frame->AdjustOffsetsForBidi(contentOffset,
1077                                       contentOffset + fragmentLength);
1078         }
1079       }  // isTextFrame
1080     }    // not bidi control frame
1081     int32_t temp = runLength;
1082     runLength -= fragmentLength;
1083     fragmentLength -= temp;
1084 
1085     // Record last real frame so that we can do splitting properly even
1086     // if a run ends after a virtual bidi control frame.
1087     if (frame != NS_BIDI_CONTROL_FRAME) {
1088       lastRealFrame = frameInfo;
1089     }
1090     if (lastRealFrame.mFrame && fragmentLength <= 0) {
1091       // If the frame is at the end of a run, and this is not the end of our
1092       // paragraph, split all ancestor inlines that need splitting.
1093       // To determine whether we're at the end of the run, we check that we've
1094       // finished processing the current run, and that the current frame
1095       // doesn't have a fluid continuation (it could have a fluid continuation
1096       // of zero length, so testing runLength alone is not sufficient).
1097       if (runLength <= 0 && !lastRealFrame.mFrame->GetNextInFlow()) {
1098         if (numRun + 1 < runCount) {
1099           nsIFrame* child = lastRealFrame.mFrame;
1100           nsContainerFrame* parent = child->GetParent();
1101           // As long as we're on the last sibling, the parent doesn't have to
1102           // be split.
1103           // However, if the parent has a fluid continuation, we do have to make
1104           // it non-fluid. This can happen e.g. when we have a first-letter
1105           // frame and the end of the first-letter coincides with the end of a
1106           // directional run.
1107           while (parent && IsBidiSplittable(parent) &&
1108                  !child->GetNextSibling()) {
1109             nsIFrame* next = parent->GetNextInFlow();
1110             if (next) {
1111               parent->SetNextContinuation(next);
1112               next->SetPrevContinuation(parent);
1113             }
1114             child = parent;
1115             parent = child->GetParent();
1116           }
1117           if (parent && IsBidiSplittable(parent)) {
1118             aBpd->mCurrentResolveLine.AdvanceToLinesAndFrame(lastRealFrame);
1119             SplitInlineAncestors(parent, aBpd->mCurrentResolveLine.GetLine(),
1120                                  child);
1121 
1122             aBpd->mCurrentResolveLine.AdvanceToLinesAndFrame(lastRealFrame);
1123           }
1124         }
1125       } else if (frame != NS_BIDI_CONTROL_FRAME) {
1126         // We're not at an end of a run. If |frame| is the last child of its
1127         // parent, and its ancestors happen to have bidi continuations, convert
1128         // them into fluid continuations.
1129         JoinInlineAncestors(frame);
1130       }
1131     }
1132   }  // for
1133 
1134 #ifdef DEBUG
1135 #  ifdef REALLY_NOISY_BIDI
1136   printf("---\nAfter Resolve(), frameTree =:\n");
1137   aBpd->mCurrentBlock->List(stdout);
1138   printf("===\n");
1139 #  endif
1140 #endif
1141 
1142   return rv;
1143 }
1144 
TraverseFrames(nsIFrame * aCurrentFrame,BidiParagraphData * aBpd)1145 void nsBidiPresUtils::TraverseFrames(nsIFrame* aCurrentFrame,
1146                                      BidiParagraphData* aBpd) {
1147   if (!aCurrentFrame) return;
1148 
1149 #ifdef DEBUG
1150   nsBlockFrame* initialLineContainer =
1151       aBpd->mCurrentTraverseLine.mLineIterator.GetContainer();
1152 #endif
1153 
1154   nsIFrame* childFrame = aCurrentFrame;
1155   do {
1156     /*
1157      * It's important to get the next sibling and next continuation *before*
1158      * handling the frame: If we encounter a forced paragraph break and call
1159      * ResolveParagraph within this loop, doing GetNextSibling and
1160      * GetNextContinuation after that could return a bidi continuation that had
1161      * just been split from the original childFrame and we would process it
1162      * twice.
1163      */
1164     nsIFrame* nextSibling = childFrame->GetNextSibling();
1165 
1166     // If the real frame for a placeholder is a first letter frame, we need to
1167     // drill down into it and include its contents in Bidi resolution.
1168     // If not, we just use the placeholder.
1169     nsIFrame* frame = childFrame;
1170     if (childFrame->IsPlaceholderFrame()) {
1171       nsIFrame* realFrame =
1172           nsPlaceholderFrame::GetRealFrameForPlaceholder(childFrame);
1173       if (realFrame->IsLetterFrame()) {
1174         frame = realFrame;
1175       }
1176     }
1177 
1178     auto DifferentBidiValues = [](ComputedStyle* aSC1, nsIFrame* aFrame2) {
1179       ComputedStyle* sc2 = aFrame2->Style();
1180       return GetBidiControl(aSC1) != GetBidiControl(sc2) ||
1181              GetBidiOverride(aSC1) != GetBidiOverride(sc2);
1182     };
1183 
1184     ComputedStyle* sc = frame->Style();
1185     nsIFrame* nextContinuation = frame->GetNextContinuation();
1186     nsIFrame* prevContinuation = frame->GetPrevContinuation();
1187     bool isLastFrame =
1188         !nextContinuation || DifferentBidiValues(sc, nextContinuation);
1189     bool isFirstFrame =
1190         !prevContinuation || DifferentBidiValues(sc, prevContinuation);
1191 
1192     char16_t controlChar = 0;
1193     char16_t overrideChar = 0;
1194     LayoutFrameType frameType = frame->Type();
1195     if (frame->IsFrameOfType(nsIFrame::eBidiInlineContainer) ||
1196         frameType == LayoutFrameType::Ruby) {
1197       if (!frame->HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
1198         nsContainerFrame* c = static_cast<nsContainerFrame*>(frame);
1199         MOZ_ASSERT(c == do_QueryFrame(frame),
1200                    "eBidiInlineContainer and ruby frame must be"
1201                    " a nsContainerFrame subclass");
1202         c->DrainSelfOverflowList();
1203       }
1204 
1205       controlChar = GetBidiControl(sc);
1206       overrideChar = GetBidiOverride(sc);
1207 
1208       // Add dummy frame pointers representing bidi control codes before
1209       // the first frames of elements specifying override, isolation, or
1210       // plaintext.
1211       if (isFirstFrame) {
1212         if (controlChar != 0) {
1213           aBpd->PushBidiControl(controlChar);
1214         }
1215         if (overrideChar != 0) {
1216           aBpd->PushBidiControl(overrideChar);
1217         }
1218       }
1219     }
1220 
1221     if (IsBidiLeaf(frame)) {
1222       /* Bidi leaf frame: add the frame to the mLogicalFrames array,
1223        * and add its index to the mContentToFrameIndex hashtable. This
1224        * will be used in RemoveBidiContinuation() to identify the last
1225        * frame in the array with a given content.
1226        */
1227       nsIContent* content = frame->GetContent();
1228       aBpd->AppendFrame(frame, aBpd->mCurrentTraverseLine, content);
1229 
1230       // Append the content of the frame to the paragraph buffer
1231       if (LayoutFrameType::Text == frameType) {
1232         if (content != aBpd->mPrevContent) {
1233           aBpd->mPrevContent = content;
1234           if (!frame->StyleText()->NewlineIsSignificant(
1235                   static_cast<nsTextFrame*>(frame))) {
1236             content->GetAsText()->AppendTextTo(aBpd->mBuffer);
1237           } else {
1238             /*
1239              * For preformatted text we have to do bidi resolution on each line
1240              * separately.
1241              */
1242             nsAutoString text;
1243             content->GetAsText()->AppendTextTo(text);
1244             nsIFrame* next;
1245             do {
1246               next = nullptr;
1247 
1248               auto [start, end] = frame->GetOffsets();
1249               int32_t endLine = text.FindChar('\n', start);
1250               if (endLine == -1) {
1251                 /*
1252                  * If there is no newline in the text content, just save the
1253                  * text from this frame and its continuations, and do bidi
1254                  * resolution later
1255                  */
1256                 aBpd->AppendString(Substring(text, start));
1257                 while (frame && nextSibling) {
1258                   aBpd->AdvanceAndAppendFrame(
1259                       &frame, aBpd->mCurrentTraverseLine, &nextSibling);
1260                 }
1261                 break;
1262               }
1263 
1264               /*
1265                * If there is a newline in the frame, break the frame after the
1266                * newline, do bidi resolution and repeat until the last sibling
1267                */
1268               ++endLine;
1269 
1270               /*
1271                * If the frame ends before the new line, save the text and move
1272                * into the next continuation
1273                */
1274               aBpd->AppendString(
1275                   Substring(text, start, std::min(end, endLine) - start));
1276               while (end < endLine && nextSibling) {
1277                 aBpd->AdvanceAndAppendFrame(&frame, aBpd->mCurrentTraverseLine,
1278                                             &nextSibling);
1279                 NS_ASSERTION(frame, "Premature end of continuation chain");
1280                 std::tie(start, end) = frame->GetOffsets();
1281                 aBpd->AppendString(
1282                     Substring(text, start, std::min(end, endLine) - start));
1283               }
1284 
1285               if (end < endLine) {
1286                 aBpd->mPrevContent = nullptr;
1287                 break;
1288               }
1289 
1290               bool createdContinuation = false;
1291               if (uint32_t(endLine) < text.Length()) {
1292                 /*
1293                  * Timing is everything here: if the frame already has a bidi
1294                  * continuation, we need to make the continuation fluid *before*
1295                  * resetting the length of the current frame. Otherwise
1296                  * nsTextFrame::SetLength won't set the continuation frame's
1297                  * text offsets correctly.
1298                  *
1299                  * On the other hand, if the frame doesn't have a continuation,
1300                  * we need to create one *after* resetting the length, or
1301                  * CreateContinuingFrame will complain that there is no more
1302                  * content for the continuation.
1303                  */
1304                 next = frame->GetNextInFlow();
1305                 if (!next) {
1306                   // If the frame already has a bidi continuation, make it fluid
1307                   next = frame->GetNextContinuation();
1308                   if (next) {
1309                     MakeContinuationFluid(frame, next);
1310                     JoinInlineAncestors(frame);
1311                   }
1312                 }
1313 
1314                 nsTextFrame* textFrame = static_cast<nsTextFrame*>(frame);
1315                 textFrame->SetLength(endLine - start, nullptr);
1316 
1317                 // If it weren't for CreateContinuation needing this to
1318                 // be current, we could restructure the marking dirty
1319                 // below to use mCurrentResolveLine and eliminate
1320                 // mCurrentTraverseLine entirely.
1321                 aBpd->mCurrentTraverseLine.AdvanceToFrame(frame);
1322 
1323                 if (!next) {
1324                   // If the frame has no next in flow, create one.
1325                   CreateContinuation(
1326                       frame, aBpd->mCurrentTraverseLine.GetLine(), &next, true);
1327                   createdContinuation = true;
1328                 }
1329                 // Mark the line before the newline as dirty.
1330                 aBpd->mCurrentTraverseLine.GetLine()->MarkDirty();
1331               }
1332               ResolveParagraphWithinBlock(aBpd);
1333 
1334               if (!nextSibling && !createdContinuation) {
1335                 break;
1336               }
1337               if (next) {
1338                 frame = next;
1339                 aBpd->AppendFrame(frame, aBpd->mCurrentTraverseLine);
1340                 // Mark the line after the newline as dirty.
1341                 aBpd->mCurrentTraverseLine.AdvanceToFrame(frame);
1342                 aBpd->mCurrentTraverseLine.GetLine()->MarkDirty();
1343               }
1344 
1345               /*
1346                * If we have already overshot the saved next-sibling while
1347                * scanning the frame's continuations, advance it.
1348                */
1349               if (frame && frame == nextSibling) {
1350                 nextSibling = frame->GetNextSibling();
1351               }
1352 
1353             } while (next);
1354           }
1355         }
1356       } else if (LayoutFrameType::Br == frameType) {
1357         // break frame -- append line separator
1358         aBpd->AppendUnichar(kLineSeparator);
1359         ResolveParagraphWithinBlock(aBpd);
1360       } else {
1361         // other frame type -- see the Unicode Bidi Algorithm:
1362         // "...inline objects (such as graphics) are treated as if they are ...
1363         // U+FFFC"
1364         // <wbr>, however, is treated as U+200B ZERO WIDTH SPACE. See
1365         // http://dev.w3.org/html5/spec/Overview.html#phrasing-content-1
1366         aBpd->AppendUnichar(
1367             content->IsHTMLElement(nsGkAtoms::wbr) ? kZWSP : kObjectSubstitute);
1368         if (!frame->IsInlineOutside()) {
1369           // if it is not inline, end the paragraph
1370           ResolveParagraphWithinBlock(aBpd);
1371         }
1372       }
1373     } else {
1374       // For a non-leaf frame, recurse into TraverseFrames
1375       nsIFrame* kid = frame->PrincipalChildList().FirstChild();
1376       MOZ_ASSERT(!frame->GetChildList(nsIFrame::kOverflowList).FirstChild(),
1377                  "should have drained the overflow list above");
1378       if (kid) {
1379         TraverseFrames(kid, aBpd);
1380       }
1381     }
1382 
1383     // If the element is attributed by dir, indicate direction pop (add PDF
1384     // frame)
1385     if (isLastFrame) {
1386       // Add a dummy frame pointer representing a bidi control code after the
1387       // last frame of an element specifying embedding or override
1388       if (overrideChar != 0) {
1389         aBpd->PopBidiControl(overrideChar);
1390       }
1391       if (controlChar != 0) {
1392         aBpd->PopBidiControl(controlChar);
1393       }
1394     }
1395     childFrame = nextSibling;
1396   } while (childFrame);
1397 
1398   MOZ_ASSERT(initialLineContainer ==
1399              aBpd->mCurrentTraverseLine.mLineIterator.GetContainer());
1400 }
1401 
ChildListMayRequireBidi(nsIFrame * aFirstChild,nsIContent ** aCurrContent)1402 bool nsBidiPresUtils::ChildListMayRequireBidi(nsIFrame* aFirstChild,
1403                                               nsIContent** aCurrContent) {
1404   MOZ_ASSERT(!aFirstChild || !aFirstChild->GetPrevSibling(),
1405              "Expecting to traverse from the start of a child list");
1406 
1407   for (nsIFrame* childFrame = aFirstChild; childFrame;
1408        childFrame = childFrame->GetNextSibling()) {
1409     nsIFrame* frame = childFrame;
1410 
1411     // If the real frame for a placeholder is a first-letter frame, we need to
1412     // consider its contents for potential Bidi resolution.
1413     if (childFrame->IsPlaceholderFrame()) {
1414       nsIFrame* realFrame =
1415           nsPlaceholderFrame::GetRealFrameForPlaceholder(childFrame);
1416       if (realFrame->IsLetterFrame()) {
1417         frame = realFrame;
1418       }
1419     }
1420 
1421     // If unicode-bidi properties are present, we should do bidi resolution.
1422     ComputedStyle* sc = frame->Style();
1423     if (GetBidiControl(sc) || GetBidiOverride(sc)) {
1424       return true;
1425     }
1426 
1427     if (IsBidiLeaf(frame)) {
1428       if (frame->IsTextFrame()) {
1429         // If the frame already has a BidiDataProperty, we know we need to
1430         // perform bidi resolution (even if no bidi content is NOW present --
1431         // we might need to remove the property set by a previous reflow, if
1432         // content has changed; see bug 1366623).
1433         if (frame->HasProperty(nsIFrame::BidiDataProperty())) {
1434           return true;
1435         }
1436 
1437         // Check whether the text frame has any RTL characters; if so, bidi
1438         // resolution will be needed.
1439         dom::Text* content = frame->GetContent()->AsText();
1440         if (content != *aCurrContent) {
1441           *aCurrContent = content;
1442           const nsTextFragment* txt = &content->TextFragment();
1443           if (txt->Is2b() &&
1444               HasRTLChars(Span(txt->Get2b(), txt->GetLength()))) {
1445             return true;
1446           }
1447         }
1448       }
1449     } else if (ChildListMayRequireBidi(frame->PrincipalChildList().FirstChild(),
1450                                        aCurrContent)) {
1451       return true;
1452     }
1453   }
1454 
1455   return false;
1456 }
1457 
ResolveParagraphWithinBlock(BidiParagraphData * aBpd)1458 void nsBidiPresUtils::ResolveParagraphWithinBlock(BidiParagraphData* aBpd) {
1459   aBpd->ClearBidiControls();
1460   ResolveParagraph(aBpd);
1461   aBpd->ResetData();
1462 }
1463 
1464 /* static */
ReorderFrames(nsIFrame * aFirstFrameOnLine,int32_t aNumFramesOnLine,WritingMode aLineWM,const nsSize & aContainerSize,nscoord aStart)1465 nscoord nsBidiPresUtils::ReorderFrames(nsIFrame* aFirstFrameOnLine,
1466                                        int32_t aNumFramesOnLine,
1467                                        WritingMode aLineWM,
1468                                        const nsSize& aContainerSize,
1469                                        nscoord aStart) {
1470   nsSize containerSize(aContainerSize);
1471 
1472   // If this line consists of a line frame, reorder the line frame's children.
1473   if (aFirstFrameOnLine->IsLineFrame()) {
1474     // The line frame is positioned at the start-edge, so use its size
1475     // as the container size.
1476     containerSize = aFirstFrameOnLine->GetSize();
1477 
1478     aFirstFrameOnLine = aFirstFrameOnLine->PrincipalChildList().FirstChild();
1479     if (!aFirstFrameOnLine) {
1480       return 0;
1481     }
1482     // All children of the line frame are on the first line. Setting
1483     // aNumFramesOnLine to -1 makes InitLogicalArrayFromLine look at all of
1484     // them.
1485     aNumFramesOnLine = -1;
1486     // As the line frame itself has been adjusted at its inline-start position
1487     // by the caller, we do not want to apply this to its children.
1488     aStart = 0;
1489   }
1490 
1491   BidiLineData bld(aFirstFrameOnLine, aNumFramesOnLine);
1492   return RepositionInlineFrames(&bld, aLineWM, containerSize, aStart);
1493 }
1494 
GetFirstLeaf(nsIFrame * aFrame)1495 nsIFrame* nsBidiPresUtils::GetFirstLeaf(nsIFrame* aFrame) {
1496   nsIFrame* firstLeaf = aFrame;
1497   while (!IsBidiLeaf(firstLeaf)) {
1498     nsIFrame* firstChild = firstLeaf->PrincipalChildList().FirstChild();
1499     nsIFrame* realFrame = nsPlaceholderFrame::GetRealFrameFor(firstChild);
1500     firstLeaf = (realFrame->IsLetterFrame()) ? realFrame : firstChild;
1501   }
1502   return firstLeaf;
1503 }
1504 
GetFrameBidiData(nsIFrame * aFrame)1505 FrameBidiData nsBidiPresUtils::GetFrameBidiData(nsIFrame* aFrame) {
1506   return GetFirstLeaf(aFrame)->GetBidiData();
1507 }
1508 
GetFrameEmbeddingLevel(nsIFrame * aFrame)1509 nsBidiLevel nsBidiPresUtils::GetFrameEmbeddingLevel(nsIFrame* aFrame) {
1510   return GetFirstLeaf(aFrame)->GetEmbeddingLevel();
1511 }
1512 
GetFrameBaseLevel(const nsIFrame * aFrame)1513 nsBidiLevel nsBidiPresUtils::GetFrameBaseLevel(const nsIFrame* aFrame) {
1514   const nsIFrame* firstLeaf = aFrame;
1515   while (!IsBidiLeaf(firstLeaf)) {
1516     firstLeaf = firstLeaf->PrincipalChildList().FirstChild();
1517   }
1518   return firstLeaf->GetBaseLevel();
1519 }
1520 
IsFirstOrLast(nsIFrame * aFrame,nsContinuationStates * aContinuationStates,bool aSpanDirMatchesLineDir,bool & aIsFirst,bool & aIsLast)1521 void nsBidiPresUtils::IsFirstOrLast(nsIFrame* aFrame,
1522                                     nsContinuationStates* aContinuationStates,
1523                                     bool aSpanDirMatchesLineDir,
1524                                     bool& aIsFirst /* out */,
1525                                     bool& aIsLast /* out */) {
1526   /*
1527    * Since we lay out frames in the line's direction, visiting a frame with
1528    * 'mFirstVisualFrame == nullptr', means it's the first appearance of one
1529    * of its continuation chain frames on the line.
1530    * To determine if it's the last visual frame of its continuation chain on
1531    * the line or not, we count the number of frames of the chain on the line,
1532    * and then reduce it when we lay out a frame of the chain. If this value
1533    * becomes 1 it means that it's the last visual frame of its continuation
1534    * chain on this line.
1535    */
1536 
1537   bool firstInLineOrder, lastInLineOrder;
1538   nsFrameContinuationState* frameState = aContinuationStates->Get(aFrame);
1539   nsFrameContinuationState* firstFrameState;
1540 
1541   if (!frameState->mFirstVisualFrame) {
1542     // aFrame is the first visual frame of its continuation chain
1543     nsFrameContinuationState* contState;
1544     nsIFrame* frame;
1545 
1546     frameState->mFrameCount = 1;
1547     frameState->mFirstVisualFrame = aFrame;
1548 
1549     /**
1550      * Traverse continuation chain of aFrame in both backward and forward
1551      * directions while the frames are on this line. Count the frames and
1552      * set their mFirstVisualFrame to aFrame.
1553      */
1554     // Traverse continuation chain backward
1555     for (frame = aFrame->GetPrevContinuation();
1556          frame && (contState = aContinuationStates->Get(frame));
1557          frame = frame->GetPrevContinuation()) {
1558       frameState->mFrameCount++;
1559       contState->mFirstVisualFrame = aFrame;
1560     }
1561     frameState->mHasContOnPrevLines = (frame != nullptr);
1562 
1563     // Traverse continuation chain forward
1564     for (frame = aFrame->GetNextContinuation();
1565          frame && (contState = aContinuationStates->Get(frame));
1566          frame = frame->GetNextContinuation()) {
1567       frameState->mFrameCount++;
1568       contState->mFirstVisualFrame = aFrame;
1569     }
1570     frameState->mHasContOnNextLines = (frame != nullptr);
1571 
1572     firstInLineOrder = true;
1573     firstFrameState = frameState;
1574   } else {
1575     // aFrame is not the first visual frame of its continuation chain
1576     firstInLineOrder = false;
1577     firstFrameState = aContinuationStates->Get(frameState->mFirstVisualFrame);
1578   }
1579 
1580   lastInLineOrder = (firstFrameState->mFrameCount == 1);
1581 
1582   if (aSpanDirMatchesLineDir) {
1583     aIsFirst = firstInLineOrder;
1584     aIsLast = lastInLineOrder;
1585   } else {
1586     aIsFirst = lastInLineOrder;
1587     aIsLast = firstInLineOrder;
1588   }
1589 
1590   if (frameState->mHasContOnPrevLines) {
1591     aIsFirst = false;
1592   }
1593   if (firstFrameState->mHasContOnNextLines) {
1594     aIsLast = false;
1595   }
1596 
1597   if ((aIsFirst || aIsLast) &&
1598       aFrame->HasAnyStateBits(NS_FRAME_PART_OF_IBSPLIT)) {
1599     // For ib splits, don't treat anything except the last part as
1600     // endmost or anything except the first part as startmost.
1601     // As an optimization, only get the first continuation once.
1602     nsIFrame* firstContinuation = aFrame->FirstContinuation();
1603     if (firstContinuation->FrameIsNonLastInIBSplit()) {
1604       // We are not endmost
1605       aIsLast = false;
1606     }
1607     if (firstContinuation->FrameIsNonFirstInIBSplit()) {
1608       // We are not startmost
1609       aIsFirst = false;
1610     }
1611   }
1612 
1613   // Reduce number of remaining frames of the continuation chain on the line.
1614   firstFrameState->mFrameCount--;
1615 
1616   nsInlineFrame* testFrame = do_QueryFrame(aFrame);
1617 
1618   if (testFrame) {
1619     aFrame->AddStateBits(NS_INLINE_FRAME_BIDI_VISUAL_STATE_IS_SET);
1620 
1621     if (aIsFirst) {
1622       aFrame->AddStateBits(NS_INLINE_FRAME_BIDI_VISUAL_IS_FIRST);
1623     } else {
1624       aFrame->RemoveStateBits(NS_INLINE_FRAME_BIDI_VISUAL_IS_FIRST);
1625     }
1626 
1627     if (aIsLast) {
1628       aFrame->AddStateBits(NS_INLINE_FRAME_BIDI_VISUAL_IS_LAST);
1629     } else {
1630       aFrame->RemoveStateBits(NS_INLINE_FRAME_BIDI_VISUAL_IS_LAST);
1631     }
1632   }
1633 }
1634 
1635 /* static */
RepositionRubyContentFrame(nsIFrame * aFrame,WritingMode aFrameWM,const LogicalMargin & aBorderPadding)1636 void nsBidiPresUtils::RepositionRubyContentFrame(
1637     nsIFrame* aFrame, WritingMode aFrameWM,
1638     const LogicalMargin& aBorderPadding) {
1639   const nsFrameList& childList = aFrame->PrincipalChildList();
1640   if (childList.IsEmpty()) {
1641     return;
1642   }
1643 
1644   // Reorder the children.
1645   nscoord isize =
1646       ReorderFrames(childList.FirstChild(), childList.GetLength(), aFrameWM,
1647                     aFrame->GetSize(), aBorderPadding.IStart(aFrameWM));
1648   isize += aBorderPadding.IEnd(aFrameWM);
1649 
1650   if (aFrame->StyleText()->mRubyAlign == StyleRubyAlign::Start) {
1651     return;
1652   }
1653   nscoord residualISize = aFrame->ISize(aFrameWM) - isize;
1654   if (residualISize <= 0) {
1655     return;
1656   }
1657 
1658   // When ruby-align is not "start", if the content does not fill this
1659   // frame, we need to center the children.
1660   const nsSize dummyContainerSize;
1661   for (nsIFrame* child : childList) {
1662     LogicalRect rect = child->GetLogicalRect(aFrameWM, dummyContainerSize);
1663     rect.IStart(aFrameWM) += residualISize / 2;
1664     child->SetRect(aFrameWM, rect, dummyContainerSize);
1665   }
1666 }
1667 
1668 /* static */
RepositionRubyFrame(nsIFrame * aFrame,nsContinuationStates * aContinuationStates,const WritingMode aContainerWM,const LogicalMargin & aBorderPadding)1669 nscoord nsBidiPresUtils::RepositionRubyFrame(
1670     nsIFrame* aFrame, nsContinuationStates* aContinuationStates,
1671     const WritingMode aContainerWM, const LogicalMargin& aBorderPadding) {
1672   LayoutFrameType frameType = aFrame->Type();
1673   MOZ_ASSERT(RubyUtils::IsRubyBox(frameType));
1674 
1675   nscoord icoord = 0;
1676   WritingMode frameWM = aFrame->GetWritingMode();
1677   bool isLTR = frameWM.IsBidiLTR();
1678   nsSize frameSize = aFrame->GetSize();
1679   if (frameType == LayoutFrameType::Ruby) {
1680     icoord += aBorderPadding.IStart(frameWM);
1681     // Reposition ruby segments in a ruby container
1682     for (RubySegmentEnumerator e(static_cast<nsRubyFrame*>(aFrame)); !e.AtEnd();
1683          e.Next()) {
1684       nsRubyBaseContainerFrame* rbc = e.GetBaseContainer();
1685       AutoRubyTextContainerArray textContainers(rbc);
1686 
1687       nscoord segmentISize = RepositionFrame(
1688           rbc, isLTR, icoord, aContinuationStates, frameWM, false, frameSize);
1689       for (nsRubyTextContainerFrame* rtc : textContainers) {
1690         nscoord isize = RepositionFrame(rtc, isLTR, icoord, aContinuationStates,
1691                                         frameWM, false, frameSize);
1692         segmentISize = std::max(segmentISize, isize);
1693       }
1694       icoord += segmentISize;
1695     }
1696     icoord += aBorderPadding.IEnd(frameWM);
1697   } else if (frameType == LayoutFrameType::RubyBaseContainer) {
1698     // Reposition ruby columns in a ruby segment
1699     auto rbc = static_cast<nsRubyBaseContainerFrame*>(aFrame);
1700     AutoRubyTextContainerArray textContainers(rbc);
1701 
1702     for (RubyColumnEnumerator e(rbc, textContainers); !e.AtEnd(); e.Next()) {
1703       RubyColumn column;
1704       e.GetColumn(column);
1705 
1706       nscoord columnISize =
1707           RepositionFrame(column.mBaseFrame, isLTR, icoord, aContinuationStates,
1708                           frameWM, false, frameSize);
1709       for (nsRubyTextFrame* rt : column.mTextFrames) {
1710         nscoord isize = RepositionFrame(rt, isLTR, icoord, aContinuationStates,
1711                                         frameWM, false, frameSize);
1712         columnISize = std::max(columnISize, isize);
1713       }
1714       icoord += columnISize;
1715     }
1716   } else {
1717     if (frameType == LayoutFrameType::RubyBase ||
1718         frameType == LayoutFrameType::RubyText) {
1719       RepositionRubyContentFrame(aFrame, frameWM, aBorderPadding);
1720     }
1721     // Note that, ruby text container is not present in all conditions
1722     // above. It is intended, because the children of rtc are reordered
1723     // with the children of ruby base container simultaneously. We only
1724     // need to return its isize here, as it should not be changed.
1725     icoord += aFrame->ISize(aContainerWM);
1726   }
1727   return icoord;
1728 }
1729 
1730 /* static */
RepositionFrame(nsIFrame * aFrame,bool aIsEvenLevel,nscoord aStartOrEnd,nsContinuationStates * aContinuationStates,WritingMode aContainerWM,bool aContainerReverseDir,const nsSize & aContainerSize)1731 nscoord nsBidiPresUtils::RepositionFrame(
1732     nsIFrame* aFrame, bool aIsEvenLevel, nscoord aStartOrEnd,
1733     nsContinuationStates* aContinuationStates, WritingMode aContainerWM,
1734     bool aContainerReverseDir, const nsSize& aContainerSize) {
1735   nscoord lineSize =
1736       aContainerWM.IsVertical() ? aContainerSize.height : aContainerSize.width;
1737   NS_ASSERTION(lineSize != NS_UNCONSTRAINEDSIZE,
1738                "Unconstrained inline line size in bidi frame reordering");
1739   if (!aFrame) return 0;
1740 
1741   bool isFirst, isLast;
1742   WritingMode frameWM = aFrame->GetWritingMode();
1743   IsFirstOrLast(aFrame, aContinuationStates,
1744                 aContainerWM.IsBidiLTR() == frameWM.IsBidiLTR(),
1745                 isFirst /* out */, isLast /* out */);
1746 
1747   // We only need the margin if the frame is first or last in its own
1748   // writing mode, but we're traversing the frames in the order of the
1749   // container's writing mode. To get the right values, we set start and
1750   // end margins on a logical margin in the frame's writing mode, and
1751   // then convert the margin to the container's writing mode to set the
1752   // coordinates.
1753 
1754   // This method is called from nsBlockFrame::PlaceLine via the call to
1755   // bidiUtils->ReorderFrames, so this is guaranteed to be after the inlines
1756   // have been reflowed, which is required for GetUsedMargin/Border/Padding
1757   nscoord frameISize = aFrame->ISize();
1758   LogicalMargin frameMargin = aFrame->GetLogicalUsedMargin(frameWM);
1759   LogicalMargin borderPadding = aFrame->GetLogicalUsedBorderAndPadding(frameWM);
1760   // Since the visual order of frame could be different from the continuation
1761   // order, we need to remove any inline border/padding [that is already applied
1762   // based on continuation order] and then add it back based on the visual order
1763   // (i.e. isFirst/isLast) to get the correct isize for the current frame.
1764   // We don't need to do that for 'box-decoration-break:clone' because then all
1765   // continuations have border/padding/margin applied.
1766   if (aFrame->StyleBorder()->mBoxDecorationBreak ==
1767       StyleBoxDecorationBreak::Slice) {
1768     // First remove the border/padding that was applied based on logical order.
1769     if (!aFrame->GetPrevContinuation()) {
1770       frameISize -= borderPadding.IStart(frameWM);
1771     }
1772     if (!aFrame->GetNextContinuation()) {
1773       frameISize -= borderPadding.IEnd(frameWM);
1774     }
1775     // Set margin/border/padding based on visual order.
1776     if (!isFirst) {
1777       frameMargin.IStart(frameWM) = 0;
1778       borderPadding.IStart(frameWM) = 0;
1779     }
1780     if (!isLast) {
1781       frameMargin.IEnd(frameWM) = 0;
1782       borderPadding.IEnd(frameWM) = 0;
1783     }
1784     // Add the border/padding which is now based on visual order.
1785     frameISize += borderPadding.IStartEnd(frameWM);
1786   }
1787 
1788   nscoord icoord = 0;
1789   if (IsBidiLeaf(aFrame)) {
1790     icoord +=
1791         frameWM.IsOrthogonalTo(aContainerWM) ? aFrame->BSize() : frameISize;
1792   } else if (RubyUtils::IsRubyBox(aFrame->Type())) {
1793     icoord += RepositionRubyFrame(aFrame, aContinuationStates, aContainerWM,
1794                                   borderPadding);
1795   } else {
1796     bool reverseDir = aIsEvenLevel != frameWM.IsBidiLTR();
1797     icoord += reverseDir ? borderPadding.IEnd(frameWM)
1798                          : borderPadding.IStart(frameWM);
1799     LogicalSize logicalSize(frameWM, frameISize, aFrame->BSize());
1800     nsSize frameSize = logicalSize.GetPhysicalSize(frameWM);
1801     // Reposition the child frames
1802     for (nsFrameList::Enumerator e(aFrame->PrincipalChildList()); !e.AtEnd();
1803          e.Next()) {
1804       icoord +=
1805           RepositionFrame(e.get(), aIsEvenLevel, icoord, aContinuationStates,
1806                           frameWM, reverseDir, frameSize);
1807     }
1808     icoord += reverseDir ? borderPadding.IStart(frameWM)
1809                          : borderPadding.IEnd(frameWM);
1810   }
1811 
1812   // In the following variables, if aContainerReverseDir is true, i.e.
1813   // the container is positioning its children in reverse of its logical
1814   // direction, the "StartOrEnd" refers to the distance from the frame
1815   // to the inline end edge of the container, elsewise, it refers to the
1816   // distance to the inline start edge.
1817   const LogicalMargin margin = frameMargin.ConvertTo(aContainerWM, frameWM);
1818   nscoord marginStartOrEnd = aContainerReverseDir ? margin.IEnd(aContainerWM)
1819                                                   : margin.IStart(aContainerWM);
1820   nscoord frameStartOrEnd = aStartOrEnd + marginStartOrEnd;
1821 
1822   LogicalRect rect = aFrame->GetLogicalRect(aContainerWM, aContainerSize);
1823   rect.ISize(aContainerWM) = icoord;
1824   rect.IStart(aContainerWM) = aContainerReverseDir
1825                                   ? lineSize - frameStartOrEnd - icoord
1826                                   : frameStartOrEnd;
1827   aFrame->SetRect(aContainerWM, rect, aContainerSize);
1828 
1829   return icoord + margin.IStartEnd(aContainerWM);
1830 }
1831 
InitContinuationStates(nsIFrame * aFrame,nsContinuationStates * aContinuationStates)1832 void nsBidiPresUtils::InitContinuationStates(
1833     nsIFrame* aFrame, nsContinuationStates* aContinuationStates) {
1834   aContinuationStates->Insert(aFrame);
1835   if (!IsBidiLeaf(aFrame)) {
1836     // Continue for child frames
1837     for (nsIFrame* frame : aFrame->PrincipalChildList()) {
1838       InitContinuationStates(frame, aContinuationStates);
1839     }
1840   }
1841 }
1842 
1843 /* static */
RepositionInlineFrames(BidiLineData * aBld,WritingMode aLineWM,const nsSize & aContainerSize,nscoord aStart)1844 nscoord nsBidiPresUtils::RepositionInlineFrames(BidiLineData* aBld,
1845                                                 WritingMode aLineWM,
1846                                                 const nsSize& aContainerSize,
1847                                                 nscoord aStart) {
1848   nscoord start = aStart;
1849   nsIFrame* frame;
1850   int32_t count = aBld->mVisualFrames.Length();
1851   int32_t index;
1852   nsContinuationStates continuationStates;
1853 
1854   // Initialize continuation states to (nullptr, 0) for
1855   // each frame on the line.
1856   for (index = 0; index < count; index++) {
1857     InitContinuationStates(aBld->VisualFrameAt(index), &continuationStates);
1858   }
1859 
1860   // Reposition frames in visual order
1861   int32_t step, limit;
1862   if (aLineWM.IsBidiLTR()) {
1863     index = 0;
1864     step = 1;
1865     limit = count;
1866   } else {
1867     index = count - 1;
1868     step = -1;
1869     limit = -1;
1870   }
1871   for (; index != limit; index += step) {
1872     frame = aBld->VisualFrameAt(index);
1873     start += RepositionFrame(
1874         frame, !(IS_LEVEL_RTL(aBld->mLevels[aBld->mIndexMap[index]])), start,
1875         &continuationStates, aLineWM, false, aContainerSize);
1876   }
1877   return start;
1878 }
1879 
CheckLineOrder(nsIFrame * aFirstFrameOnLine,int32_t aNumFramesOnLine,nsIFrame ** aFirstVisual,nsIFrame ** aLastVisual)1880 bool nsBidiPresUtils::CheckLineOrder(nsIFrame* aFirstFrameOnLine,
1881                                      int32_t aNumFramesOnLine,
1882                                      nsIFrame** aFirstVisual,
1883                                      nsIFrame** aLastVisual) {
1884   BidiLineData bld(aFirstFrameOnLine, aNumFramesOnLine);
1885   int32_t count = bld.FrameCount();
1886 
1887   if (aFirstVisual) {
1888     *aFirstVisual = bld.VisualFrameAt(0);
1889   }
1890   if (aLastVisual) {
1891     *aLastVisual = bld.VisualFrameAt(count - 1);
1892   }
1893 
1894   return bld.mIsReordered;
1895 }
1896 
GetFrameToRightOf(const nsIFrame * aFrame,nsIFrame * aFirstFrameOnLine,int32_t aNumFramesOnLine)1897 nsIFrame* nsBidiPresUtils::GetFrameToRightOf(const nsIFrame* aFrame,
1898                                              nsIFrame* aFirstFrameOnLine,
1899                                              int32_t aNumFramesOnLine) {
1900   BidiLineData bld(aFirstFrameOnLine, aNumFramesOnLine);
1901 
1902   int32_t count = bld.mVisualFrames.Length();
1903 
1904   if (aFrame == nullptr && count) return bld.VisualFrameAt(0);
1905 
1906   for (int32_t i = 0; i < count - 1; i++) {
1907     if (bld.VisualFrameAt(i) == aFrame) {
1908       return bld.VisualFrameAt(i + 1);
1909     }
1910   }
1911 
1912   return nullptr;
1913 }
1914 
GetFrameToLeftOf(const nsIFrame * aFrame,nsIFrame * aFirstFrameOnLine,int32_t aNumFramesOnLine)1915 nsIFrame* nsBidiPresUtils::GetFrameToLeftOf(const nsIFrame* aFrame,
1916                                             nsIFrame* aFirstFrameOnLine,
1917                                             int32_t aNumFramesOnLine) {
1918   BidiLineData bld(aFirstFrameOnLine, aNumFramesOnLine);
1919 
1920   int32_t count = bld.mVisualFrames.Length();
1921 
1922   if (aFrame == nullptr && count) return bld.VisualFrameAt(count - 1);
1923 
1924   for (int32_t i = 1; i < count; i++) {
1925     if (bld.VisualFrameAt(i) == aFrame) {
1926       return bld.VisualFrameAt(i - 1);
1927     }
1928   }
1929 
1930   return nullptr;
1931 }
1932 
EnsureBidiContinuation(nsIFrame * aFrame,const nsLineList::iterator aLine,nsIFrame ** aNewFrame,int32_t aStart,int32_t aEnd)1933 inline void nsBidiPresUtils::EnsureBidiContinuation(
1934     nsIFrame* aFrame, const nsLineList::iterator aLine, nsIFrame** aNewFrame,
1935     int32_t aStart, int32_t aEnd) {
1936   MOZ_ASSERT(aNewFrame, "null OUT ptr");
1937   MOZ_ASSERT(aFrame, "aFrame is null");
1938 
1939   aFrame->AdjustOffsetsForBidi(aStart, aEnd);
1940   CreateContinuation(aFrame, aLine, aNewFrame, false);
1941 }
1942 
RemoveBidiContinuation(BidiParagraphData * aBpd,nsIFrame * aFrame,int32_t aFirstIndex,int32_t aLastIndex)1943 void nsBidiPresUtils::RemoveBidiContinuation(BidiParagraphData* aBpd,
1944                                              nsIFrame* aFrame,
1945                                              int32_t aFirstIndex,
1946                                              int32_t aLastIndex) {
1947   FrameBidiData bidiData = aFrame->GetBidiData();
1948   bidiData.precedingControl = kBidiLevelNone;
1949   for (int32_t index = aFirstIndex + 1; index <= aLastIndex; index++) {
1950     nsIFrame* frame = aBpd->FrameAt(index);
1951     if (frame != NS_BIDI_CONTROL_FRAME) {
1952       // Make the frame and its continuation ancestors fluid,
1953       // so they can be reused or deleted by normal reflow code
1954       frame->SetProperty(nsIFrame::BidiDataProperty(), bidiData);
1955       frame->AddStateBits(NS_FRAME_IS_BIDI);
1956       while (frame && IsBidiSplittable(frame)) {
1957         nsIFrame* prev = frame->GetPrevContinuation();
1958         if (prev) {
1959           MakeContinuationFluid(prev, frame);
1960           frame = frame->GetParent();
1961         } else {
1962           break;
1963         }
1964       }
1965     }
1966   }
1967 
1968   // Make sure that the last continuation we made fluid does not itself have a
1969   // fluid continuation (this can happen when re-resolving after dynamic changes
1970   // to content)
1971   nsIFrame* lastFrame = aBpd->FrameAt(aLastIndex);
1972   MakeContinuationsNonFluidUpParentChain(lastFrame, lastFrame->GetNextInFlow());
1973 }
1974 
FormatUnicodeText(nsPresContext * aPresContext,char16_t * aText,int32_t & aTextLength,nsCharType aCharType)1975 nsresult nsBidiPresUtils::FormatUnicodeText(nsPresContext* aPresContext,
1976                                             char16_t* aText,
1977                                             int32_t& aTextLength,
1978                                             nsCharType aCharType) {
1979   nsresult rv = NS_OK;
1980   // ahmed
1981   // adjusted for correct numeral shaping
1982   uint32_t bidiOptions = aPresContext->GetBidi();
1983   switch (GET_BIDI_OPTION_NUMERAL(bidiOptions)) {
1984     case IBMBIDI_NUMERAL_HINDI:
1985       HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_HINDI);
1986       break;
1987 
1988     case IBMBIDI_NUMERAL_ARABIC:
1989       HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_ARABIC);
1990       break;
1991 
1992     case IBMBIDI_NUMERAL_PERSIAN:
1993       HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_PERSIAN);
1994       break;
1995 
1996     case IBMBIDI_NUMERAL_REGULAR:
1997 
1998       switch (aCharType) {
1999         case eCharType_EuropeanNumber:
2000           HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_ARABIC);
2001           break;
2002 
2003         case eCharType_ArabicNumber:
2004           HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_HINDI);
2005           break;
2006 
2007         default:
2008           break;
2009       }
2010       break;
2011 
2012     case IBMBIDI_NUMERAL_HINDICONTEXT:
2013       if (((GET_BIDI_OPTION_DIRECTION(bidiOptions) ==
2014             IBMBIDI_TEXTDIRECTION_RTL) &&
2015            (IS_ARABIC_DIGIT(aText[0]))) ||
2016           (eCharType_ArabicNumber == aCharType))
2017         HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_HINDI);
2018       else if (eCharType_EuropeanNumber == aCharType)
2019         HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_ARABIC);
2020       break;
2021 
2022     case IBMBIDI_NUMERAL_PERSIANCONTEXT:
2023       if (((GET_BIDI_OPTION_DIRECTION(bidiOptions) ==
2024             IBMBIDI_TEXTDIRECTION_RTL) &&
2025            (IS_ARABIC_DIGIT(aText[0]))) ||
2026           (eCharType_ArabicNumber == aCharType))
2027         HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_PERSIAN);
2028       else if (eCharType_EuropeanNumber == aCharType)
2029         HandleNumbers(aText, aTextLength, IBMBIDI_NUMERAL_ARABIC);
2030       break;
2031 
2032     case IBMBIDI_NUMERAL_NOMINAL:
2033     default:
2034       break;
2035   }
2036 
2037   StripBidiControlCharacters(aText, aTextLength);
2038   return rv;
2039 }
2040 
StripBidiControlCharacters(char16_t * aText,int32_t & aTextLength)2041 void nsBidiPresUtils::StripBidiControlCharacters(char16_t* aText,
2042                                                  int32_t& aTextLength) {
2043   if ((nullptr == aText) || (aTextLength < 1)) {
2044     return;
2045   }
2046 
2047   int32_t stripLen = 0;
2048 
2049   for (int32_t i = 0; i < aTextLength; i++) {
2050     // XXX: This silently ignores surrogate characters.
2051     //      As of Unicode 4.0, all Bidi control characters are within the BMP.
2052     if (IsBidiControl((uint32_t)aText[i])) {
2053       ++stripLen;
2054     } else {
2055       aText[i - stripLen] = aText[i];
2056     }
2057   }
2058   aTextLength -= stripLen;
2059 }
2060 
2061 #if 0  // XXX: for the future use ???
2062 void
2063 RemoveDiacritics(char16_t* aText,
2064                  int32_t&   aTextLength)
2065 {
2066   if (aText && (aTextLength > 0) ) {
2067     int32_t offset = 0;
2068 
2069     for (int32_t i = 0; i < aTextLength && aText[i]; i++) {
2070       if (IS_BIDI_DIACRITIC(aText[i]) ) {
2071         ++offset;
2072         continue;
2073       }
2074       aText[i - offset] = aText[i];
2075     }
2076     aTextLength = i - offset;
2077     aText[aTextLength] = 0;
2078   }
2079 }
2080 #endif
2081 
CalculateCharType(nsBidi * aBidiEngine,const char16_t * aText,int32_t & aOffset,int32_t aCharTypeLimit,int32_t & aRunLimit,int32_t & aRunLength,int32_t & aRunCount,uint8_t & aCharType,uint8_t & aPrevCharType)2082 void nsBidiPresUtils::CalculateCharType(nsBidi* aBidiEngine,
2083                                         const char16_t* aText, int32_t& aOffset,
2084                                         int32_t aCharTypeLimit,
2085                                         int32_t& aRunLimit, int32_t& aRunLength,
2086                                         int32_t& aRunCount, uint8_t& aCharType,
2087                                         uint8_t& aPrevCharType)
2088 
2089 {
2090   bool strongTypeFound = false;
2091   int32_t offset;
2092   nsCharType charType;
2093 
2094   aCharType = eCharType_OtherNeutral;
2095 
2096   int32_t charLen;
2097   for (offset = aOffset; offset < aCharTypeLimit; offset += charLen) {
2098     // Make sure we give RTL chartype to all characters that would be classified
2099     // as Right-To-Left by a bidi platform.
2100     // (May differ from the UnicodeData, eg we set RTL chartype to some NSMs.)
2101     charLen = 1;
2102     uint32_t ch = aText[offset];
2103     if (IS_HEBREW_CHAR(ch)) {
2104       charType = eCharType_RightToLeft;
2105     } else if (IS_ARABIC_ALPHABETIC(ch)) {
2106       charType = eCharType_RightToLeftArabic;
2107     } else {
2108       if (offset + 1 < aCharTypeLimit &&
2109           NS_IS_SURROGATE_PAIR(ch, aText[offset + 1])) {
2110         ch = SURROGATE_TO_UCS4(ch, aText[offset + 1]);
2111         charLen = 2;
2112       }
2113       charType = unicode::GetBidiCat(ch);
2114     }
2115 
2116     if (!CHARTYPE_IS_WEAK(charType)) {
2117       if (strongTypeFound && (charType != aPrevCharType) &&
2118           (CHARTYPE_IS_RTL(charType) || CHARTYPE_IS_RTL(aPrevCharType))) {
2119         // Stop at this point to ensure uni-directionality of the text
2120         // (from platform's point of view).
2121         // Also, don't mix Arabic and Hebrew content (since platform may
2122         // provide BIDI support to one of them only).
2123         aRunLength = offset - aOffset;
2124         aRunLimit = offset;
2125         ++aRunCount;
2126         break;
2127       }
2128 
2129       if ((eCharType_RightToLeftArabic == aPrevCharType ||
2130            eCharType_ArabicNumber == aPrevCharType) &&
2131           eCharType_EuropeanNumber == charType) {
2132         charType = eCharType_ArabicNumber;
2133       }
2134 
2135       // Set PrevCharType to the last strong type in this frame
2136       // (for correct numeric shaping)
2137       aPrevCharType = charType;
2138 
2139       strongTypeFound = true;
2140       aCharType = charType;
2141     }
2142   }
2143   aOffset = offset;
2144 }
2145 
ProcessText(const char16_t * aText,int32_t aLength,nsBidiLevel aBaseLevel,nsPresContext * aPresContext,BidiProcessor & aprocessor,Mode aMode,nsBidiPositionResolve * aPosResolve,int32_t aPosResolveCount,nscoord * aWidth,nsBidi * aBidiEngine)2146 nsresult nsBidiPresUtils::ProcessText(const char16_t* aText, int32_t aLength,
2147                                       nsBidiLevel aBaseLevel,
2148                                       nsPresContext* aPresContext,
2149                                       BidiProcessor& aprocessor, Mode aMode,
2150                                       nsBidiPositionResolve* aPosResolve,
2151                                       int32_t aPosResolveCount, nscoord* aWidth,
2152                                       nsBidi* aBidiEngine) {
2153   NS_ASSERTION((aPosResolve == nullptr) != (aPosResolveCount > 0),
2154                "Incorrect aPosResolve / aPosResolveCount arguments");
2155 
2156   int32_t runCount;
2157 
2158   nsAutoString textBuffer(aText, aLength);
2159   textBuffer.ReplaceChar(kSeparators, kSpace);
2160   const char16_t* text = textBuffer.get();
2161 
2162   nsresult rv = aBidiEngine->SetPara(text, aLength, aBaseLevel);
2163   if (NS_FAILED(rv)) return rv;
2164 
2165   rv = aBidiEngine->CountRuns(&runCount);
2166   if (NS_FAILED(rv)) return rv;
2167 
2168   nscoord xOffset = 0;
2169   nscoord width, xEndRun = 0;
2170   nscoord totalWidth = 0;
2171   int32_t i, start, limit, length;
2172   uint32_t visualStart = 0;
2173   uint8_t charType;
2174   uint8_t prevType = eCharType_LeftToRight;
2175 
2176   for (int nPosResolve = 0; nPosResolve < aPosResolveCount; ++nPosResolve) {
2177     aPosResolve[nPosResolve].visualIndex = kNotFound;
2178     aPosResolve[nPosResolve].visualLeftTwips = kNotFound;
2179     aPosResolve[nPosResolve].visualWidth = kNotFound;
2180   }
2181 
2182   for (i = 0; i < runCount; i++) {
2183     nsBidiDirection dir = aBidiEngine->GetVisualRun(i, &start, &length);
2184 
2185     nsBidiLevel level;
2186     aBidiEngine->GetLogicalRun(start, &limit, &level);
2187 
2188     dir = DIRECTION_FROM_LEVEL(level);
2189     int32_t subRunLength = limit - start;
2190     int32_t lineOffset = start;
2191     int32_t typeLimit = std::min(limit, aLength);
2192     int32_t subRunCount = 1;
2193     int32_t subRunLimit = typeLimit;
2194 
2195     /*
2196      * If |level| is even, i.e. the direction of the run is left-to-right, we
2197      * render the subruns from left to right and increment the x-coordinate
2198      * |xOffset| by the width of each subrun after rendering.
2199      *
2200      * If |level| is odd, i.e. the direction of the run is right-to-left, we
2201      * render the subruns from right to left. We begin by incrementing |xOffset|
2202      * by the width of the whole run, and then decrement it by the width of each
2203      * subrun before rendering. After rendering all the subruns, we restore the
2204      * x-coordinate of the end of the run for the start of the next run.
2205      */
2206 
2207     if (dir == NSBIDI_RTL) {
2208       aprocessor.SetText(text + start, subRunLength, dir);
2209       width = aprocessor.GetWidth();
2210       xOffset += width;
2211       xEndRun = xOffset;
2212     }
2213 
2214     while (subRunCount > 0) {
2215       // CalculateCharType can increment subRunCount if the run
2216       // contains mixed character types
2217       CalculateCharType(aBidiEngine, text, lineOffset, typeLimit, subRunLimit,
2218                         subRunLength, subRunCount, charType, prevType);
2219 
2220       nsAutoString runVisualText;
2221       runVisualText.Assign(text + start, subRunLength);
2222       if (int32_t(runVisualText.Length()) < subRunLength)
2223         return NS_ERROR_OUT_OF_MEMORY;
2224       FormatUnicodeText(aPresContext, runVisualText.BeginWriting(),
2225                         subRunLength, (nsCharType)charType);
2226 
2227       aprocessor.SetText(runVisualText.get(), subRunLength, dir);
2228       width = aprocessor.GetWidth();
2229       totalWidth += width;
2230       if (dir == NSBIDI_RTL) {
2231         xOffset -= width;
2232       }
2233       if (aMode == MODE_DRAW) {
2234         aprocessor.DrawText(xOffset, width);
2235       }
2236 
2237       /*
2238        * The caller may request to calculate the visual position of one
2239        * or more characters.
2240        */
2241       for (int nPosResolve = 0; nPosResolve < aPosResolveCount; ++nPosResolve) {
2242         nsBidiPositionResolve* posResolve = &aPosResolve[nPosResolve];
2243         /*
2244          * Did we already resolve this position's visual metric? If so, skip.
2245          */
2246         if (posResolve->visualLeftTwips != kNotFound) continue;
2247 
2248         /*
2249          * First find out if the logical position is within this run.
2250          */
2251         if (start <= posResolve->logicalIndex &&
2252             start + subRunLength > posResolve->logicalIndex) {
2253           /*
2254            * If this run is only one character long, we have an easy case:
2255            * the visual position is the x-coord of the start of the run
2256            * less the x-coord of the start of the whole text.
2257            */
2258           if (subRunLength == 1) {
2259             posResolve->visualIndex = visualStart;
2260             posResolve->visualLeftTwips = xOffset;
2261             posResolve->visualWidth = width;
2262           }
2263           /*
2264            * Otherwise, we need to measure the width of the run's part
2265            * which is to the visual left of the index.
2266            * In other words, the run is broken in two, around the logical index,
2267            * and we measure the part which is visually left.
2268            * If the run is right-to-left, this part will span from after the
2269            * index up to the end of the run; if it is left-to-right, this part
2270            * will span from the start of the run up to (and inclduing) the
2271            * character before the index.
2272            */
2273           else {
2274             /*
2275              * Here is a description of how the width of the current character
2276              * (posResolve->visualWidth) is calculated:
2277              *
2278              * LTR (current char: "P"):
2279              *    S A M P L E          (logical index: 3, visual index: 3)
2280              *    ^ (visualLeftPart)
2281              *    ^ (visualRightSide)
2282              *    visualLeftLength == 3
2283              *    ^^^^^^ (subWidth)
2284              *    ^^^^^^^^ (aprocessor.GetWidth() -- with visualRightSide)
2285              *          ^^ (posResolve->visualWidth)
2286              *
2287              * RTL (current char: "M"):
2288              *    E L P M A S          (logical index: 2, visual index: 3)
2289              *        ^ (visualLeftPart)
2290              *          ^ (visualRightSide)
2291              *    visualLeftLength == 3
2292              *    ^^^^^^ (subWidth)
2293              *    ^^^^^^^^ (aprocessor.GetWidth() -- with visualRightSide)
2294              *          ^^ (posResolve->visualWidth)
2295              */
2296             nscoord subWidth;
2297             // The position in the text where this run's "left part" begins.
2298             const char16_t* visualLeftPart;
2299             const char16_t* visualRightSide;
2300             if (dir == NSBIDI_RTL) {
2301               // One day, son, this could all be replaced with
2302               // mPresContext->GetBidiEngine().GetVisualIndex() ...
2303               posResolve->visualIndex =
2304                   visualStart +
2305                   (subRunLength - (posResolve->logicalIndex + 1 - start));
2306               // Skipping to the "left part".
2307               visualLeftPart = text + posResolve->logicalIndex + 1;
2308               // Skipping to the right side of the current character
2309               visualRightSide = visualLeftPart - 1;
2310             } else {
2311               posResolve->visualIndex =
2312                   visualStart + (posResolve->logicalIndex - start);
2313               // Skipping to the "left part".
2314               visualLeftPart = text + start;
2315               // In LTR mode this is the same as visualLeftPart
2316               visualRightSide = visualLeftPart;
2317             }
2318             // The delta between the start of the run and the left part's end.
2319             int32_t visualLeftLength = posResolve->visualIndex - visualStart;
2320             aprocessor.SetText(visualLeftPart, visualLeftLength, dir);
2321             subWidth = aprocessor.GetWidth();
2322             aprocessor.SetText(visualRightSide, visualLeftLength + 1, dir);
2323             posResolve->visualLeftTwips = xOffset + subWidth;
2324             posResolve->visualWidth = aprocessor.GetWidth() - subWidth;
2325           }
2326         }
2327       }
2328 
2329       if (dir == NSBIDI_LTR) {
2330         xOffset += width;
2331       }
2332 
2333       --subRunCount;
2334       start = lineOffset;
2335       subRunLimit = typeLimit;
2336       subRunLength = typeLimit - lineOffset;
2337     }  // while
2338     if (dir == NSBIDI_RTL) {
2339       xOffset = xEndRun;
2340     }
2341 
2342     visualStart += length;
2343   }  // for
2344 
2345   if (aWidth) {
2346     *aWidth = totalWidth;
2347   }
2348   return NS_OK;
2349 }
2350 
2351 class MOZ_STACK_CLASS nsIRenderingContextBidiProcessor final
2352     : public nsBidiPresUtils::BidiProcessor {
2353  public:
2354   typedef mozilla::gfx::DrawTarget DrawTarget;
2355 
nsIRenderingContextBidiProcessor(gfxContext * aCtx,DrawTarget * aTextRunConstructionDrawTarget,nsFontMetrics * aFontMetrics,const nsPoint & aPt)2356   nsIRenderingContextBidiProcessor(gfxContext* aCtx,
2357                                    DrawTarget* aTextRunConstructionDrawTarget,
2358                                    nsFontMetrics* aFontMetrics,
2359                                    const nsPoint& aPt)
2360       : mCtx(aCtx),
2361         mTextRunConstructionDrawTarget(aTextRunConstructionDrawTarget),
2362         mFontMetrics(aFontMetrics),
2363         mPt(aPt),
2364         mText(nullptr),
2365         mLength(0) {}
2366 
~nsIRenderingContextBidiProcessor()2367   ~nsIRenderingContextBidiProcessor() { mFontMetrics->SetTextRunRTL(false); }
2368 
SetText(const char16_t * aText,int32_t aLength,nsBidiDirection aDirection)2369   virtual void SetText(const char16_t* aText, int32_t aLength,
2370                        nsBidiDirection aDirection) override {
2371     mFontMetrics->SetTextRunRTL(aDirection == NSBIDI_RTL);
2372     mText = aText;
2373     mLength = aLength;
2374   }
2375 
GetWidth()2376   virtual nscoord GetWidth() override {
2377     return nsLayoutUtils::AppUnitWidthOfString(mText, mLength, *mFontMetrics,
2378                                                mTextRunConstructionDrawTarget);
2379   }
2380 
DrawText(nscoord aIOffset,nscoord)2381   virtual void DrawText(nscoord aIOffset, nscoord) override {
2382     nsPoint pt(mPt);
2383     if (mFontMetrics->GetVertical()) {
2384       pt.y += aIOffset;
2385     } else {
2386       pt.x += aIOffset;
2387     }
2388     mFontMetrics->DrawString(mText, mLength, pt.x, pt.y, mCtx,
2389                              mTextRunConstructionDrawTarget);
2390   }
2391 
2392  private:
2393   gfxContext* mCtx;
2394   DrawTarget* mTextRunConstructionDrawTarget;
2395   nsFontMetrics* mFontMetrics;
2396   nsPoint mPt;
2397   const char16_t* mText;
2398   int32_t mLength;
2399 };
2400 
ProcessTextForRenderingContext(const char16_t * aText,int32_t aLength,nsBidiLevel aBaseLevel,nsPresContext * aPresContext,gfxContext & aRenderingContext,DrawTarget * aTextRunConstructionDrawTarget,nsFontMetrics & aFontMetrics,Mode aMode,nscoord aX,nscoord aY,nsBidiPositionResolve * aPosResolve,int32_t aPosResolveCount,nscoord * aWidth)2401 nsresult nsBidiPresUtils::ProcessTextForRenderingContext(
2402     const char16_t* aText, int32_t aLength, nsBidiLevel aBaseLevel,
2403     nsPresContext* aPresContext, gfxContext& aRenderingContext,
2404     DrawTarget* aTextRunConstructionDrawTarget, nsFontMetrics& aFontMetrics,
2405     Mode aMode, nscoord aX, nscoord aY, nsBidiPositionResolve* aPosResolve,
2406     int32_t aPosResolveCount, nscoord* aWidth) {
2407   nsIRenderingContextBidiProcessor processor(&aRenderingContext,
2408                                              aTextRunConstructionDrawTarget,
2409                                              &aFontMetrics, nsPoint(aX, aY));
2410   return ProcessText(aText, aLength, aBaseLevel, aPresContext, processor, aMode,
2411                      aPosResolve, aPosResolveCount, aWidth,
2412                      &aPresContext->GetBidiEngine());
2413 }
2414 
2415 /* static */
BidiLevelFromStyle(ComputedStyle * aComputedStyle)2416 nsBidiLevel nsBidiPresUtils::BidiLevelFromStyle(ComputedStyle* aComputedStyle) {
2417   if (aComputedStyle->StyleTextReset()->mUnicodeBidi &
2418       NS_STYLE_UNICODE_BIDI_PLAINTEXT) {
2419     return NSBIDI_DEFAULT_LTR;
2420   }
2421 
2422   if (aComputedStyle->StyleVisibility()->mDirection == StyleDirection::Rtl) {
2423     return NSBIDI_RTL;
2424   }
2425 
2426   return NSBIDI_LTR;
2427 }
2428