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/. */
7 #ifndef nsTextFrame_h__
8 #define nsTextFrame_h__
10 #include "mozilla/Attributes.h"
11 #include "mozilla/UniquePtr.h"
12 #include "mozilla/dom/Text.h"
13 #include "mozilla/gfx/2D.h"
16 #include "nsISelectionController.h"
17 #include "nsSplittableFrame.h"
18 #include "gfxSkipChars.h"
19 #include "gfxTextRun.h"
20 #include "JustificationUtils.h"
22 // Undo the windows.h damage
23 #if defined(XP_WIN) && defined(DrawText)
27 class nsTextPaintStyle
;
28 class nsLineList_iterator
;
29 struct SelectionDetails
;
33 class SVGContextPaint
;
35 class nsDisplayTextGeometry
;
37 } // namespace mozilla
39 class nsTextFrame
: public nsIFrame
{
40 typedef mozilla::LayoutDeviceRect LayoutDeviceRect
;
41 typedef mozilla::SelectionTypeMask SelectionTypeMask
;
42 typedef mozilla::SelectionType SelectionType
;
43 typedef mozilla::TextRangeStyle TextRangeStyle
;
44 typedef mozilla::gfx::DrawTarget DrawTarget
;
45 typedef mozilla::gfx::Point Point
;
46 typedef mozilla::gfx::Rect Rect
;
47 typedef mozilla::gfx::Size Size
;
48 typedef gfxTextRun::Range Range
;
51 enum TextRunType
: uint8_t;
55 * An implementation of gfxTextRun::PropertyProvider that computes spacing and
56 * hyphenation based on CSS properties for a text frame.
58 class MOZ_STACK_CLASS PropertyProvider final
59 : public gfxTextRun::PropertyProvider
{
60 typedef gfxTextRun::Range Range
;
61 typedef gfxTextRun::HyphenType HyphenType
;
62 typedef mozilla::gfx::DrawTarget DrawTarget
;
66 * Use this constructor for reflow, when we don't know what text is
67 * really mapped by the frame and we have a lot of other data around.
69 * @param aLength can be INT32_MAX to indicate we cover all the text
70 * associated with aFrame up to where its flow chain ends in the given
71 * textrun. If INT32_MAX is passed, justification and hyphen-related methods
72 * cannot be called, nor can GetOriginalLength().
74 PropertyProvider(gfxTextRun
* aTextRun
, const nsStyleText
* aTextStyle
,
75 const nsTextFragment
* aFrag
, nsTextFrame
* aFrame
,
76 const gfxSkipCharsIterator
& aStart
, int32_t aLength
,
77 nsIFrame
* aLineContainer
,
78 nscoord aOffsetFromBlockOriginForTabs
,
79 nsTextFrame::TextRunType aWhichTextRun
);
82 * Use this constructor after the frame has been reflowed and we don't
83 * have other data around. Gets everything from the frame. EnsureTextRun
84 * *must* be called before this!!!
86 PropertyProvider(nsTextFrame
* aFrame
, const gfxSkipCharsIterator
& aStart
,
87 nsTextFrame::TextRunType aWhichTextRun
,
88 nsFontMetrics
* aFontMetrics
);
91 * As above, but assuming we want the inflated text run and associated
94 PropertyProvider(nsTextFrame
* aFrame
, const gfxSkipCharsIterator
& aStart
)
95 : PropertyProvider(aFrame
, aStart
, nsTextFrame::eInflated
,
96 aFrame
->InflatedFontMetrics()) {}
98 // Call this after construction if you're not going to reflow the text
99 void InitializeForDisplay(bool aTrimAfter
);
101 void InitializeForMeasure();
103 void GetSpacing(Range aRange
, Spacing
* aSpacing
) const final
;
104 gfxFloat
GetHyphenWidth() const final
;
105 void GetHyphenationBreaks(Range aRange
,
106 HyphenType
* aBreakBefore
) const final
;
107 mozilla::StyleHyphens
GetHyphensOption() const final
{
108 return mTextStyle
->mHyphens
;
110 mozilla::gfx::ShapedTextFlags
GetShapedTextFlags() const final
;
112 already_AddRefed
<DrawTarget
> GetDrawTarget() const final
;
114 uint32_t GetAppUnitsPerDevUnit() const final
{
115 return mTextRun
->GetAppUnitsPerDevUnit();
118 void GetSpacingInternal(Range aRange
, Spacing
* aSpacing
,
119 bool aIgnoreTabs
) const;
122 * Compute the justification information in given DOM range, return
123 * justification info and assignments if requested.
125 mozilla::JustificationInfo
ComputeJustification(
127 nsTArray
<mozilla::JustificationAssignment
>* aAssignments
= nullptr);
129 const nsTextFrame
* GetFrame() const { return mFrame
; }
130 // This may not be equal to the frame offset/length in because we may have
131 // adjusted for whitespace trimming according to the state bits set in the
132 // frame (for the static provider)
133 const gfxSkipCharsIterator
& GetStart() const { return mStart
; }
134 // May return INT32_MAX if that was given to the constructor
135 uint32_t GetOriginalLength() const {
136 NS_ASSERTION(mLength
!= INT32_MAX
, "Length not known");
139 const nsTextFragment
* GetFragment() const { return mFrag
; }
141 gfxFontGroup
* GetFontGroup() const {
143 mFontGroup
= GetFontMetrics()->GetThebesFontGroup();
148 nsFontMetrics
* GetFontMetrics() const {
150 InitFontGroupAndFontMetrics();
155 void CalcTabWidths(Range aTransformedRange
, gfxFloat aTabWidth
) const;
157 gfxFloat
MinTabAdvance() const;
159 const gfxSkipCharsIterator
& GetEndHint() const { return mTempIterator
; }
162 void SetupJustificationSpacing(bool aPostReflow
);
164 void InitFontGroupAndFontMetrics() const;
166 const RefPtr
<gfxTextRun
> mTextRun
;
167 mutable gfxFontGroup
* mFontGroup
;
168 mutable RefPtr
<nsFontMetrics
> mFontMetrics
;
169 const nsStyleText
* mTextStyle
;
170 const nsTextFragment
* mFrag
;
171 const nsIFrame
* mLineContainer
;
173 gfxSkipCharsIterator mStart
; // Offset in original and transformed string
174 const gfxSkipCharsIterator mTempIterator
;
176 // Either null, or pointing to the frame's TabWidthProperty.
177 mutable nsTextFrame::TabWidthStore
* mTabWidths
;
178 // How far we've done tab-width calculation; this is ONLY valid when
179 // mTabWidths is nullptr (otherwise rely on mTabWidths->mLimit instead).
180 // It's a DOM offset relative to the current frame's offset.
181 mutable uint32_t mTabWidthsAnalyzedLimit
;
183 int32_t mLength
; // DOM string length, may be INT32_MAX
184 const gfxFloat mWordSpacing
; // space for each whitespace char
185 const gfxFloat mLetterSpacing
; // space for each letter
186 mutable gfxFloat mMinTabAdvance
; // min advance for <tab> char
187 mutable gfxFloat mHyphenWidth
;
188 mutable gfxFloat mOffsetFromBlockOriginForTabs
;
190 // The values in mJustificationSpacings corresponds to unskipped
191 // characters start from mJustificationArrayStart.
192 uint32_t mJustificationArrayStart
;
193 nsTArray
<Spacing
> mJustificationSpacings
;
195 const bool mReflowing
;
196 const nsTextFrame::TextRunType mWhichTextRun
;
199 explicit nsTextFrame(ComputedStyle
* aStyle
, nsPresContext
* aPresContext
,
200 ClassID aID
= kClassID
)
201 : nsIFrame(aStyle
, aPresContext
, aID
) {}
203 NS_DECL_FRAMEARENA_HELPERS(nsTextFrame
)
205 friend class nsContinuingTextFrame
;
210 NS_DECLARE_FRAME_PROPERTY_DELETABLE(ContinuationsProperty
,
211 nsTArray
<nsTextFrame
*>)
214 void BuildDisplayList(nsDisplayListBuilder
* aBuilder
,
215 const nsDisplayListSet
& aLists
) final
;
217 void Init(nsIContent
* aContent
, nsContainerFrame
* aParent
,
218 nsIFrame
* aPrevInFlow
) override
;
220 void Destroy(DestroyContext
&) override
;
222 mozilla::Maybe
<Cursor
> GetCursor(const nsPoint
&) final
;
224 nsresult
CharacterDataChanged(const CharacterDataChangeInfo
&) final
;
226 nsTextFrame
* FirstContinuation() const override
{
227 return const_cast<nsTextFrame
*>(this);
229 nsTextFrame
* GetPrevContinuation() const override
{ return nullptr; }
230 nsTextFrame
* GetNextContinuation() const final
{ return mNextContinuation
; }
231 void SetNextContinuation(nsIFrame
* aFrame
) final
;
232 nsTextFrame
* GetNextInFlow() const final
{
233 return mNextContinuation
&& mNextContinuation
->HasAnyStateBits(
234 NS_FRAME_IS_FLUID_CONTINUATION
)
238 void SetNextInFlow(nsIFrame
* aFrame
) final
;
239 nsTextFrame
* LastInFlow() const final
;
240 nsTextFrame
* LastContinuation() const final
;
242 bool ShouldSuppressLineBreak() const;
244 void InvalidateFrame(uint32_t aDisplayItemKey
= 0,
245 bool aRebuildDisplayItems
= true) final
;
246 void InvalidateFrameWithRect(const nsRect
& aRect
,
247 uint32_t aDisplayItemKey
= 0,
248 bool aRebuildDisplayItems
= true) final
;
250 #ifdef DEBUG_FRAME_DUMP
251 void List(FILE* out
= stderr
, const char* aPrefix
= "",
252 ListFlags aFlags
= ListFlags()) const final
;
253 nsresult
GetFrameName(nsAString
& aResult
) const final
;
254 void ToCString(nsCString
& aBuf
) const;
255 void ListTextRuns(FILE* out
, nsTHashSet
<const void*>& aSeen
) const final
;
258 // Returns this text frame's content's text fragment.
260 // Assertions in Init() ensure we only ever get a Text node as content.
261 const nsTextFragment
* TextFragment() const {
262 return &mContent
->AsText()->TextFragment();
266 * Check that the text in this frame is entirely whitespace. Importantly,
267 * this function considers non-breaking spaces (0xa0) to be whitespace,
268 * whereas nsTextFrame::IsEmpty does not. It also considers both one and
271 bool IsEntirelyWhitespace() const;
273 ContentOffsets
CalcContentOffsetsFromFramePoint(const nsPoint
& aPoint
) final
;
274 ContentOffsets
GetCharacterOffsetAtFramePoint(const nsPoint
& aPoint
);
277 * This is called only on the primary text frame. It indicates that
278 * the selection state of the given character range has changed.
279 * Frames corresponding to the character range are unconditionally invalidated
280 * (Selection::Repaint depends on this).
281 * @param aStart start of character range.
282 * @param aEnd end (exclusive) of character range.
283 * @param aSelected true iff the character range is now selected.
284 * @param aType the type of the changed selection.
286 void SelectionStateChanged(uint32_t aStart
, uint32_t aEnd
, bool aSelected
,
287 SelectionType aSelectionType
);
289 FrameSearchResult
PeekOffsetNoAmount(bool aForward
, int32_t* aOffset
) final
;
290 FrameSearchResult
PeekOffsetCharacter(
291 bool aForward
, int32_t* aOffset
,
292 PeekOffsetCharacterOptions aOptions
= PeekOffsetCharacterOptions()) final
;
293 FrameSearchResult
PeekOffsetWord(bool aForward
, bool aWordSelectEatSpace
,
294 bool aIsKeyboardSelect
, int32_t* aOffset
,
295 PeekWordState
* aState
,
296 bool aTrimSpaces
) final
;
298 // Helper method that editor code uses to test for visibility.
299 [[nodiscard
]] bool HasVisibleText();
301 // Flags for aSetLengthFlags
302 enum { ALLOW_FRAME_CREATION_AND_DESTRUCTION
= 0x01 };
304 // Update offsets to account for new length. This may clear mTextRun.
305 void SetLength(int32_t aLength
, nsLineLayout
* aLineLayout
,
306 uint32_t aSetLengthFlags
= 0);
308 std::pair
<int32_t, int32_t> GetOffsets() const final
;
310 void AdjustOffsetsForBidi(int32_t start
, int32_t end
) final
;
312 nsresult
GetPointFromOffset(int32_t inOffset
, nsPoint
* outPoint
) final
;
313 nsresult
GetCharacterRectsInRange(int32_t aInOffset
, int32_t aLength
,
314 nsTArray
<nsRect
>& aRects
) final
;
316 nsresult
GetChildFrameContainingOffset(int32_t inContentOffset
, bool inHint
,
317 int32_t* outFrameContentOffset
,
318 nsIFrame
** outChildFrame
) final
;
320 bool IsEmpty() final
;
321 bool IsSelfEmpty() final
{ return IsEmpty(); }
322 Maybe
<nscoord
> GetNaturalBaselineBOffset(
323 mozilla::WritingMode aWM
, BaselineSharingGroup aBaselineGroup
,
324 BaselineExportContext
) const override
;
326 bool HasSignificantTerminalNewline() const final
;
329 * Returns true if this text frame is logically adjacent to the end of the
332 bool IsAtEndOfLine() const;
335 * Call this only after reflow the frame. Returns true if non-collapsed
336 * characters are present.
338 bool HasNoncollapsedCharacters() const {
339 return HasAnyStateBits(TEXT_HAS_NONCOLLAPSED_CHARACTERS
);
343 mozilla::a11y::AccType
AccessibleType() final
;
346 float GetFontSizeInflation() const;
347 bool IsCurrentFontInflation(float aInflation
) const;
348 bool HasFontSizeInflation() const {
349 return HasAnyStateBits(TEXT_HAS_FONT_INFLATION
);
351 void SetFontSizeInflation(float aInflation
);
353 void MarkIntrinsicISizesDirty() final
;
354 nscoord
GetMinISize(gfxContext
* aRenderingContext
) final
;
355 nscoord
GetPrefISize(gfxContext
* aRenderingContext
) final
;
356 void AddInlineMinISize(gfxContext
* aRenderingContext
,
357 InlineMinISizeData
* aData
) override
;
358 void AddInlinePrefISize(gfxContext
* aRenderingContext
,
359 InlinePrefISizeData
* aData
) override
;
360 SizeComputationResult
ComputeSize(
361 gfxContext
* aRenderingContext
, mozilla::WritingMode aWM
,
362 const mozilla::LogicalSize
& aCBSize
, nscoord aAvailableISize
,
363 const mozilla::LogicalSize
& aMargin
,
364 const mozilla::LogicalSize
& aBorderPadding
,
365 const mozilla::StyleSizeOverrides
& aSizeOverrides
,
366 mozilla::ComputeSizeFlags aFlags
) final
;
367 nsRect
ComputeTightBounds(DrawTarget
* aDrawTarget
) const final
;
368 nsresult
GetPrefWidthTightBounds(gfxContext
* aContext
, nscoord
* aX
,
369 nscoord
* aXMost
) final
;
370 void Reflow(nsPresContext
* aPresContext
, ReflowOutput
& aMetrics
,
371 const ReflowInput
& aReflowInput
, nsReflowStatus
& aStatus
) final
;
372 bool CanContinueTextRun() const final
;
373 // Method that is called for a text frame that is logically
374 // adjacent to the end of the line (i.e. followed only by empty text frames,
375 // placeholders or inlines containing such).
377 // true if we trimmed some space or changed metrics in some other way.
378 // In this case, we should call RecomputeOverflow on this frame.
380 // an amount to *subtract* from the frame's width (zero if !mChanged)
383 TrimOutput
TrimTrailingWhiteSpace(DrawTarget
* aDrawTarget
);
384 RenderedText
GetRenderedText(
385 uint32_t aStartOffset
= 0, uint32_t aEndOffset
= UINT32_MAX
,
386 TextOffsetType aOffsetType
= TextOffsetType::OffsetsInContentText
,
387 TrailingWhitespace aTrimTrailingWhitespace
=
388 TrailingWhitespace::Trim
) final
;
390 mozilla::OverflowAreas
RecomputeOverflow(nsIFrame
* aBlockFrame
,
391 bool aIncludeShadows
= true);
393 enum TextRunType
: uint8_t {
394 // Anything in reflow (but not intrinsic width calculation) or
395 // painting should use the inflated text run (i.e., with font size
396 // inflation applied).
398 // Intrinsic width calculation should use the non-inflated text run.
399 // When there is font size inflation, it will be different.
403 void AddInlineMinISizeForFlow(gfxContext
* aRenderingContext
,
404 nsIFrame::InlineMinISizeData
* aData
,
405 TextRunType aTextRunType
);
406 void AddInlinePrefISizeForFlow(gfxContext
* aRenderingContext
,
407 InlinePrefISizeData
* aData
,
408 TextRunType aTextRunType
);
411 * Calculate the horizontal bounds of the grapheme clusters that fit entirely
412 * inside the given left[top]/right[bottom] edges (which are positive lengths
413 * from the respective frame edge). If an input value is zero it is ignored
414 * and the result for that edge is zero. All out parameter values are
415 * undefined when the method returns false.
416 * @return true if at least one whole grapheme cluster fit between the edges
418 bool MeasureCharClippedText(nscoord aVisIStartEdge
, nscoord aVisIEndEdge
,
419 nscoord
* aSnappedStartEdge
,
420 nscoord
* aSnappedEndEdge
);
422 * Same as above; this method also the returns the corresponding text run
423 * offset and number of characters that fit. All out parameter values are
424 * undefined when the method returns false.
425 * @return true if at least one whole grapheme cluster fit between the edges
427 bool MeasureCharClippedText(PropertyProvider
& aProvider
,
428 nscoord aVisIStartEdge
, nscoord aVisIEndEdge
,
429 uint32_t* aStartOffset
, uint32_t* aMaxLength
,
430 nscoord
* aSnappedStartEdge
,
431 nscoord
* aSnappedEndEdge
);
434 * Return true if this box has some text to display.
435 * It returns false if at least one of these conditions are met:
436 * a. the frame hasn't been reflowed yet
437 * b. GetContentLength() == 0
438 * c. it contains only non-significant white-space
440 bool HasNonSuppressedText() const;
443 * Object with various callbacks for PaintText() to invoke for different parts
444 * of the frame's text rendering, when we're generating paths rather than
447 * Callbacks are invoked in the following order:
449 * NotifySelectionBackgroundNeedsFill?
450 * PaintDecorationLine*
452 * NotifyGlyphPathEmitted*
454 * PaintDecorationLine*
455 * PaintSelectionDecorationLine*
457 * The color of each part of the frame's text rendering is passed as an
458 * argument to the NotifyBefore* callback for that part. The nscolor can take
459 * on one of the three selection special colors defined in LookAndFeel.h --
460 * NS_TRANSPARENT, NS_SAME_AS_FOREGROUND_COLOR and
461 * NS_40PERCENT_FOREGROUND_COLOR.
463 struct DrawPathCallbacks
: gfxTextRunDrawCallbacks
{
465 * @param aShouldPaintSVGGlyphs Whether SVG glyphs should be painted.
467 explicit DrawPathCallbacks(bool aShouldPaintSVGGlyphs
= false)
468 : gfxTextRunDrawCallbacks(aShouldPaintSVGGlyphs
) {}
471 * Called to have the selection highlight drawn before the text is drawn
474 virtual void NotifySelectionBackgroundNeedsFill(const Rect
& aBackgroundRect
,
476 DrawTarget
& aDrawTarget
) {}
479 * Called before (for under/over-line) or after (for line-through) the text
480 * is drawn to have a text decoration line drawn.
482 virtual void PaintDecorationLine(Rect aPath
, nscolor aColor
) {}
485 * Called after selected text is drawn to have a decoration line drawn over
486 * the text. (All types of text decoration are drawn after the text when
489 virtual void PaintSelectionDecorationLine(Rect aPath
, nscolor aColor
) {}
492 * Called just before any paths have been emitted to the gfxContext
493 * for the glyphs of the frame's text.
495 virtual void NotifyBeforeText(nscolor aColor
) {}
498 * Called just after all the paths have been emitted to the gfxContext
499 * for the glyphs of the frame's text.
501 virtual void NotifyAfterText() {}
504 * Called just before a path corresponding to a selection decoration line
505 * has been emitted to the gfxContext.
507 virtual void NotifyBeforeSelectionDecorationLine(nscolor aColor
) {}
510 * Called just after a path corresponding to a selection decoration line
511 * has been emitted to the gfxContext.
513 virtual void NotifySelectionDecorationLinePathEmitted() {}
516 struct MOZ_STACK_CLASS PaintTextParams
{
519 LayoutDeviceRect dirtyRect
;
520 mozilla::SVGContextPaint
* contextPaint
= nullptr;
521 DrawPathCallbacks
* callbacks
= nullptr;
523 PaintText
, // Normal text painting.
524 GenerateTextMask
// To generate a mask from a text frame. Should
525 // only paint text itself with opaque color.
526 // Text shadow, text selection color and text
527 // decoration are all discarded in this state.
529 uint8_t state
= PaintText
;
530 explicit PaintTextParams(gfxContext
* aContext
) : context(aContext
) {}
532 bool IsPaintText() const { return state
== PaintText
; }
533 bool IsGenerateTextMask() const { return state
== GenerateTextMask
; }
536 struct PaintTextSelectionParams
;
537 struct DrawTextRunParams
;
538 struct DrawTextParams
;
540 struct PaintShadowParams
;
541 struct PaintDecorationLineParams
;
543 struct PriorityOrderedSelectionsForRange
{
544 /// List of Selection Details active for the given range.
545 /// Ordered by priority, i.e. the last element has the highest priority.
546 nsTArray
<const SelectionDetails
*> mSelectionRanges
;
550 // Primary frame paint method called from nsDisplayText. Can also be used
551 // to generate paths rather than paint the frame's text by passing a callback
552 // object. The private DrawText() is what applies the text to a graphics
554 void PaintText(const PaintTextParams
& aParams
, const nscoord aVisIStartEdge
,
555 const nscoord aVisIEndEdge
, const nsPoint
& aToReferenceFrame
,
556 const bool aIsSelected
, float aOpacity
= 1.0f
);
557 // helper: paint text frame when we're impacted by at least one selection.
558 // Return false if the text was not painted and we should continue with
560 bool PaintTextWithSelection(const PaintTextSelectionParams
& aParams
,
561 const ClipEdges
& aClipEdges
);
562 // helper: paint text with foreground and background colors determined
563 // by selection(s). Also computes a mask of all selection types applying to
564 // our text, returned in aAllSelectionTypeMask.
565 // Return false if the text was not painted and we should continue with
567 bool PaintTextWithSelectionColors(
568 const PaintTextSelectionParams
& aParams
,
569 const mozilla::UniquePtr
<SelectionDetails
>& aDetails
,
570 SelectionTypeMask
* aAllSelectionTypeMask
, const ClipEdges
& aClipEdges
);
571 // helper: paint text decorations for text selected by aSelectionType
572 void PaintTextSelectionDecorations(
573 const PaintTextSelectionParams
& aParams
,
574 const mozilla::UniquePtr
<SelectionDetails
>& aDetails
,
575 SelectionType aSelectionType
);
577 SelectionTypeMask
ResolveSelections(
578 const PaintTextSelectionParams
& aParams
, const SelectionDetails
* aDetails
,
579 nsTArray
<PriorityOrderedSelectionsForRange
>& aResult
,
580 SelectionType aSelectionType
, bool* aAnyBackgrounds
= nullptr) const;
582 void DrawEmphasisMarks(gfxContext
* aContext
, mozilla::WritingMode aWM
,
583 const mozilla::gfx::Point
& aTextBaselinePt
,
584 const mozilla::gfx::Point
& aFramePt
, Range aRange
,
585 const nscolor
* aDecorationOverrideColor
,
586 PropertyProvider
* aProvider
);
588 nscolor
GetCaretColorAt(int32_t aOffset
) final
;
590 // @param aSelectionFlags may be multiple of nsISelectionDisplay::DISPLAY_*.
591 // @return nsISelectionController.idl's `getDisplaySelection`.
592 int16_t GetSelectionStatus(int16_t* aSelectionFlags
);
594 int32_t GetContentOffset() const { return mContentOffset
; }
595 int32_t GetContentLength() const {
596 NS_ASSERTION(GetContentEnd() - mContentOffset
>= 0, "negative length");
597 return GetContentEnd() - mContentOffset
;
599 int32_t GetContentEnd() const;
600 // This returns the length the frame thinks it *should* have after it was
601 // last reflowed (0 if it hasn't been reflowed yet). This should be used only
602 // when setting up the text offsets for a new continuation frame.
603 int32_t GetContentLengthHint() const { return mContentLengthHint
; }
605 // Compute the length of the content mapped by this frame
606 // and all its in-flow siblings. Basically this means starting at
607 // mContentOffset and going to the end of the text node or the next bidi
608 // continuation boundary.
609 int32_t GetInFlowContentLength();
612 * Acquires the text run for this content, if necessary.
613 * @param aWhichTextRun indicates whether to get an inflated or non-inflated
615 * @param aRefDrawTarget the DrawTarget to use as a reference for creating the
616 * textrun, if available (if not, we'll create one which will just be slower)
617 * @param aLineContainer the block ancestor for this frame, or nullptr if
619 * @param aFlowEndInTextRun if non-null, this returns the textrun offset of
620 * end of the text associated with this frame and its in-flow siblings
621 * @return a gfxSkipCharsIterator set up to map DOM offsets for this frame
622 * to offsets into the textrun; its initial offset is set to this frame's
625 gfxSkipCharsIterator
EnsureTextRun(TextRunType aWhichTextRun
,
626 DrawTarget
* aRefDrawTarget
= nullptr,
627 nsIFrame
* aLineContainer
= nullptr,
628 const nsLineList_iterator
* aLine
= nullptr,
629 uint32_t* aFlowEndInTextRun
= nullptr);
631 gfxTextRun
* GetTextRun(TextRunType aWhichTextRun
) const {
632 if (aWhichTextRun
== eInflated
|| !HasFontSizeInflation()) return mTextRun
;
633 return GetUninflatedTextRun();
635 gfxTextRun
* GetUninflatedTextRun() const;
636 void SetTextRun(gfxTextRun
* aTextRun
, TextRunType aWhichTextRun
,
638 bool IsInTextRunUserData() const {
639 return HasAnyStateBits(TEXT_IN_TEXTRUN_USER_DATA
|
640 TEXT_IN_UNINFLATED_TEXTRUN_USER_DATA
);
643 * Notify the frame that it should drop its pointer to a text run.
644 * Returns whether the text run was removed (i.e., whether it was
645 * associated with this frame, either as its inflated or non-inflated
648 bool RemoveTextRun(gfxTextRun
* aTextRun
);
650 * Clears out |mTextRun| (or the uninflated text run, when aInflated
651 * is nsTextFrame::eNotInflated and there is inflation) from all frames that
652 * hold a reference to it, starting at |aStartContinuation|, or if it's
653 * nullptr, starting at |this|. Deletes the text run if all references
654 * were cleared and it's not cached.
656 void ClearTextRun(nsTextFrame
* aStartContinuation
, TextRunType aWhichTextRun
);
658 void ClearTextRuns() {
659 ClearTextRun(nullptr, nsTextFrame::eInflated
);
660 if (HasFontSizeInflation()) {
661 ClearTextRun(nullptr, nsTextFrame::eNotInflated
);
666 * Wipe out references to textrun(s) without deleting the textruns.
668 void DisconnectTextRuns();
670 // Get the DOM content range mapped by this frame after excluding
671 // whitespace subject to start-of-line and end-of-line trimming.
672 // The textrun must have been created before calling this.
673 struct TrimmedOffsets
{
676 int32_t GetEnd() const { return mStart
+ mLength
; }
678 enum class TrimmedOffsetFlags
: uint8_t {
680 NotPostReflow
= 1 << 0,
681 NoTrimAfter
= 1 << 1,
682 NoTrimBefore
= 1 << 2
684 TrimmedOffsets
GetTrimmedOffsets(
685 const nsTextFragment
* aFrag
,
686 TrimmedOffsetFlags aFlags
= TrimmedOffsetFlags::Default
) const;
688 // Similar to Reflow(), but for use from nsLineLayout
689 void ReflowText(nsLineLayout
& aLineLayout
, nscoord aAvailableWidth
,
690 DrawTarget
* aDrawTarget
, ReflowOutput
& aMetrics
,
691 nsReflowStatus
& aStatus
);
693 nscoord
ComputeLineHeight() const;
695 bool IsFloatingFirstLetterChild() const;
697 bool IsInitialLetterChild() const;
699 bool ComputeCustomOverflow(mozilla::OverflowAreas
& aOverflowAreas
) final
;
700 bool ComputeCustomOverflowInternal(mozilla::OverflowAreas
& aOverflowAreas
,
701 bool aIncludeShadows
);
703 void AssignJustificationGaps(const mozilla::JustificationAssignment
& aAssign
);
704 mozilla::JustificationAssignment
GetJustificationAssignment() const;
706 uint32_t CountGraphemeClusters() const;
708 bool HasAnyNoncollapsedCharacters() final
;
711 * Call this after you have manually changed the text node contents without
712 * notifying that change. This behaves as if all the text contents changed.
713 * (You should only use this for native anonymous content.)
715 void NotifyNativeAnonymousTextnodeChange(uint32_t aOldLength
);
717 nsFontMetrics
* InflatedFontMetrics() const;
719 nsRect
WebRenderBounds();
721 // Find the continuation (which may be this frame itself) containing the
722 // given offset. Note that this may return null, if the offset is beyond the
723 // text covered by the continuation chain.
724 // (To be used only on the first textframe in the chain.)
725 nsTextFrame
* FindContinuationForOffset(int32_t aOffset
);
727 void SetHangableISize(nscoord aISize
);
728 nscoord
GetHangableISize() const;
729 void ClearHangableISize();
731 void SetTrimmableWS(gfxTextRun::TrimmableWS aTrimmableWS
);
732 gfxTextRun::TrimmableWS
GetTrimmableWS() const;
733 void ClearTrimmableWS();
736 virtual ~nsTextFrame();
738 friend class mozilla::nsDisplayTextGeometry
;
739 friend class mozilla::nsDisplayText
;
741 mutable RefPtr
<nsFontMetrics
> mFontMetrics
;
742 RefPtr
<gfxTextRun
> mTextRun
;
743 nsTextFrame
* mNextContinuation
= nullptr;
744 // The key invariant here is that mContentOffset never decreases along
745 // a next-continuation chain. And of course mContentOffset is always <= the
746 // the text node's content length, and the mContentOffset for the first frame
747 // is always 0. Furthermore the text mapped by a frame is determined by
748 // GetContentOffset() and GetContentLength()/GetContentEnd(), which get
749 // the length from the difference between this frame's offset and the next
750 // frame's offset, or the text length if there is no next frame. This means
751 // the frames always map the text node without overlapping or leaving any
753 int32_t mContentOffset
= 0;
754 // This does *not* indicate the length of text currently mapped by the frame;
755 // instead it's a hint saying that this frame *wants* to map this much text
756 // so if we create a new continuation, this is where that continuation should
758 int32_t mContentLengthHint
= 0;
761 // Cached selection state.
762 enum class SelectionState
: uint8_t {
767 mutable SelectionState mIsSelected
= SelectionState::Unknown
;
769 // Flags used to track whether certain properties are present.
770 // (Public to keep MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS happy.)
772 enum class PropertyFlags
: uint8_t {
773 // Whether a cached continuations array is present.
774 Continuations
= 1 << 0,
775 // Whether a HangableWhitespace property is present.
777 // Whether a TrimmableWhitespace property is present.
778 TrimmableWS
= 2 << 1,
782 PropertyFlags mPropertyFlags
= PropertyFlags(0);
785 * Return true if the frame is part of a Selection.
786 * Helper method to implement the public IsSelected() API.
788 bool IsFrameSelected() const final
;
790 void InvalidateSelectionState() { mIsSelected
= SelectionState::Unknown
; }
792 mozilla::UniquePtr
<SelectionDetails
> GetSelectionDetails();
794 void UnionAdditionalOverflow(nsPresContext
* aPresContext
, nsIFrame
* aBlock
,
795 PropertyProvider
& aProvider
,
796 nsRect
* aInkOverflowRect
,
797 bool aIncludeTextDecorations
,
798 bool aIncludeShadows
);
800 // Update information of emphasis marks, and return the visial
801 // overflow rect of the emphasis marks.
802 nsRect
UpdateTextEmphasis(mozilla::WritingMode aWM
,
803 PropertyProvider
& aProvider
);
805 void PaintOneShadow(const PaintShadowParams
& aParams
,
806 const mozilla::StyleSimpleShadow
& aShadowDetails
,
807 gfxRect
& aBoundingBox
, uint32_t aBlurFlags
);
809 void PaintShadows(mozilla::Span
<const mozilla::StyleSimpleShadow
>,
810 const PaintShadowParams
& aParams
);
812 struct LineDecoration
{
815 // This is represents the offset from our baseline to mFrame's baseline;
816 // positive offsets are *above* the baseline and negative offsets below
817 nscoord mBaselineOffset
;
819 // This represents the offset from the initial position of the underline
820 const mozilla::LengthPercentageOrAuto mTextUnderlineOffset
;
822 // for CSS property text-decoration-thickness, the width refers to the
823 // thickness of the decoration line
824 const mozilla::StyleTextDecorationLength mTextDecorationThickness
;
826 mozilla::StyleTextDecorationStyle mStyle
;
828 // The text-underline-position property; affects the underline offset only
829 // if mTextUnderlineOffset is auto.
830 const mozilla::StyleTextUnderlinePosition mTextUnderlinePosition
;
832 LineDecoration(nsIFrame
* const aFrame
, const nscoord aOff
,
833 mozilla::StyleTextUnderlinePosition aUnderlinePosition
,
834 const mozilla::LengthPercentageOrAuto
& aUnderlineOffset
,
835 const mozilla::StyleTextDecorationLength
& aDecThickness
,
836 const nscolor aColor
,
837 const mozilla::StyleTextDecorationStyle aStyle
)
839 mBaselineOffset(aOff
),
840 mTextUnderlineOffset(aUnderlineOffset
),
841 mTextDecorationThickness(aDecThickness
),
844 mTextUnderlinePosition(aUnderlinePosition
) {}
846 LineDecoration(const LineDecoration
& aOther
) = default;
848 bool operator==(const LineDecoration
& aOther
) const {
849 return mFrame
== aOther
.mFrame
&& mStyle
== aOther
.mStyle
&&
850 mColor
== aOther
.mColor
&&
851 mBaselineOffset
== aOther
.mBaselineOffset
&&
852 mTextUnderlinePosition
== aOther
.mTextUnderlinePosition
&&
853 mTextUnderlineOffset
== aOther
.mTextUnderlineOffset
&&
854 mTextDecorationThickness
== aOther
.mTextDecorationThickness
;
857 bool operator!=(const LineDecoration
& aOther
) const {
858 return !(*this == aOther
);
861 struct TextDecorations
{
862 AutoTArray
<LineDecoration
, 1> mOverlines
, mUnderlines
, mStrikes
;
864 TextDecorations() = default;
866 bool HasDecorationLines() const {
867 return HasUnderline() || HasOverline() || HasStrikeout();
869 bool HasUnderline() const { return !mUnderlines
.IsEmpty(); }
870 bool HasOverline() const { return !mOverlines
.IsEmpty(); }
871 bool HasStrikeout() const { return !mStrikes
.IsEmpty(); }
872 bool operator==(const TextDecorations
& aOther
) const {
873 return mOverlines
== aOther
.mOverlines
&&
874 mUnderlines
== aOther
.mUnderlines
&& mStrikes
== aOther
.mStrikes
;
876 bool operator!=(const TextDecorations
& aOther
) const {
877 return !(*this == aOther
);
880 enum TextDecorationColorResolution
{ eResolvedColors
, eUnresolvedColors
};
881 void GetTextDecorations(nsPresContext
* aPresContext
,
882 TextDecorationColorResolution aColorResolution
,
883 TextDecorations
& aDecorations
);
885 void DrawTextRun(Range aRange
, const mozilla::gfx::Point
& aTextBaselinePt
,
886 const DrawTextRunParams
& aParams
);
888 void DrawTextRunAndDecorations(Range aRange
,
889 const mozilla::gfx::Point
& aTextBaselinePt
,
890 const DrawTextParams
& aParams
,
891 const TextDecorations
& aDecorations
);
893 void DrawText(Range aRange
, const mozilla::gfx::Point
& aTextBaselinePt
,
894 const DrawTextParams
& aParams
);
896 // Set non empty rect to aRect, it should be overflow rect or frame rect.
897 // If the result rect is larger than the given rect, this returns true.
898 bool CombineSelectionUnderlineRect(nsPresContext
* aPresContext
,
901 // This sets *aShadows to the appropriate shadows, if any, for the given
902 // type of selection.
903 // If text-shadow was not specified, *aShadows is left untouched.
904 // Note that the returned shadow(s) will only be valid as long as the
905 // textPaintStyle remains in scope.
906 void GetSelectionTextShadow(
907 SelectionType aSelectionType
, nsTextPaintStyle
& aTextPaintStyle
,
908 mozilla::Span
<const mozilla::StyleSimpleShadow
>* aShadows
);
911 * Utility methods to paint selection.
913 void DrawSelectionDecorations(
914 gfxContext
* aContext
, const LayoutDeviceRect
& aDirtyRect
,
915 mozilla::SelectionType aSelectionType
, nsTextPaintStyle
& aTextPaintStyle
,
916 const TextRangeStyle
& aRangeStyle
, const Point
& aPt
,
917 gfxFloat aICoordInFrame
, gfxFloat aWidth
, gfxFloat aAscent
,
918 const gfxFont::Metrics
& aFontMetrics
, DrawPathCallbacks
* aCallbacks
,
919 bool aVertical
, mozilla::StyleTextDecorationLine aDecoration
);
921 void PaintDecorationLine(const PaintDecorationLineParams
& aParams
);
923 * ComputeDescentLimitForSelectionUnderline() computes the most far position
924 * where we can put selection underline.
926 * @return The maximum underline offset from the baseline (positive value
927 * means that the underline can put below the baseline).
929 gfxFloat
ComputeDescentLimitForSelectionUnderline(
930 nsPresContext
* aPresContext
, const gfxFont::Metrics
& aFontMetrics
);
932 * This function encapsulates all knowledge of how selections affect
933 * foreground and background colors.
934 * @param aForeground the foreground color to use
935 * @param aBackground the background color to use, or RGBA(0,0,0,0) if no
936 * background should be painted
937 * @return true if the selection affects colors, false otherwise
939 static bool GetSelectionTextColors(SelectionType aSelectionType
,
940 nsAtom
* aHighlightName
,
941 nsTextPaintStyle
& aTextPaintStyle
,
942 const TextRangeStyle
& aRangeStyle
,
943 nscolor
* aForeground
,
944 nscolor
* aBackground
);
946 * ComputeSelectionUnderlineHeight() computes selection underline height of
947 * the specified selection type from the font metrics.
949 static gfxFloat
ComputeSelectionUnderlineHeight(
950 nsPresContext
* aPresContext
, const gfxFont::Metrics
& aFontMetrics
,
951 SelectionType aSelectionType
);
954 * @brief Helper struct which contains selection data such as its details,
955 * range and priority.
957 struct SelectionRange
{
958 const SelectionDetails
* mDetails
{nullptr};
959 gfxTextRun::Range mRange
;
960 /// used to determine the order of overlapping selections of the same type.
961 uint32_t mPriority
{0};
964 * @brief Helper: Extracts a list of `SelectionRange` structs from given
965 * `SelectionDetails` and computes a priority for overlapping selection
968 static SelectionTypeMask
CreateSelectionRangeList(
969 const SelectionDetails
* aDetails
, SelectionType aSelectionType
,
970 const PaintTextSelectionParams
& aParams
,
971 nsTArray
<SelectionRange
>& aSelectionRanges
, bool* aAnyBackgrounds
);
974 * @brief Creates an array of `CombinedSelectionRange`s from given list
975 * of `SelectionRange`s.
976 * Each instance of `CombinedSelectionRange` represents a piece of text with
977 * constant Selections.
981 * Consider this text fragment, [] and () marking selection ranges:
983 * This results in the following array of combined ranges:
984 * - [0]: range: (2, 4), selections: "[]"
985 * - [1]: range: (4, 5), selections: "[]", "()"
986 * - [2]: range: (5, 6), selections: "()"
987 * Depending on the priorities of the ranges, [1] may have a different order
988 * of its ranges. The given example indicates that "()" has a higher priority
991 * @param aSelectionRanges Array of `SelectionRange` objects. Must be
992 * sorted by the start offset.
993 * @param aCombinedSelectionRanges Out parameter. Returns the constructed
994 * array of combined selection ranges.
996 static void CombineSelectionRanges(
997 const nsTArray
<SelectionRange
>& aSelectionRanges
,
998 nsTArray
<PriorityOrderedSelectionsForRange
>& aCombinedSelectionRanges
);
1000 ContentOffsets
GetCharacterOffsetAtFramePointInternal(
1001 const nsPoint
& aPoint
, bool aForInsertionPoint
);
1003 static float GetTextCombineScaleFactor(nsTextFrame
* aFrame
);
1005 void ClearFrameOffsetCache();
1007 void ClearMetrics(ReflowOutput
& aMetrics
);
1009 // Return pointer to an array of all frames in the continuation chain, or
1010 // null if we're too short of memory.
1011 nsTArray
<nsTextFrame
*>* GetContinuations();
1013 // Clear any cached continuations array; this should be called whenever the
1014 // chain is modified.
1015 inline void ClearCachedContinuations();
1018 * UpdateIteratorFromOffset() updates the iterator from a given offset.
1019 * Also, aInOffset may be updated to cluster start if aInOffset isn't
1020 * the offset of cluster start.
1022 void UpdateIteratorFromOffset(const PropertyProvider
& aProperties
,
1024 gfxSkipCharsIterator
& aIter
);
1026 nsPoint
GetPointFromIterator(const gfxSkipCharsIterator
& aIter
,
1027 PropertyProvider
& aProperties
);
1030 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(nsTextFrame::TrimmedOffsetFlags
)
1031 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(nsTextFrame::PropertyFlags
)
1033 inline void nsTextFrame::ClearCachedContinuations() {
1034 MOZ_ASSERT(NS_IsMainThread());
1035 if (mPropertyFlags
& PropertyFlags::Continuations
) {
1036 RemoveProperty(ContinuationsProperty());
1037 mPropertyFlags
&= ~PropertyFlags::Continuations
;