Bug 1839315: part 4) Link from `SheetLoadData::mWasAlternate` to spec. r=emilio DONTBUILD
[gecko.git] / layout / generic / TextOverflow.cpp
blob7d10e7fa5b757e96928d3b9c8e7548cc5050f30c
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 #include "TextOverflow.h"
8 #include <algorithm>
10 // Please maintain alphabetical order below
11 #include "gfxContext.h"
12 #include "nsBlockFrame.h"
13 #include "nsCaret.h"
14 #include "nsContentUtils.h"
15 #include "nsCSSAnonBoxes.h"
16 #include "nsFontMetrics.h"
17 #include "nsGfxScrollFrame.h"
18 #include "nsIScrollableFrame.h"
19 #include "nsLayoutUtils.h"
20 #include "nsPresContext.h"
21 #include "nsRect.h"
22 #include "nsTextFrame.h"
23 #include "nsIFrameInlines.h"
24 #include "mozilla/ArrayUtils.h"
25 #include "mozilla/Likely.h"
26 #include "mozilla/PresShell.h"
27 #include "mozilla/dom/Selection.h"
28 #include "TextDrawTarget.h"
30 using mozilla::layout::TextDrawTarget;
32 namespace mozilla {
33 namespace css {
35 class LazyReferenceRenderingDrawTargetGetterFromFrame final
36 : public gfxFontGroup::LazyReferenceDrawTargetGetter {
37 public:
38 typedef mozilla::gfx::DrawTarget DrawTarget;
40 explicit LazyReferenceRenderingDrawTargetGetterFromFrame(nsIFrame* aFrame)
41 : mFrame(aFrame) {}
42 virtual already_AddRefed<DrawTarget> GetRefDrawTarget() override {
43 UniquePtr<gfxContext> ctx =
44 mFrame->PresShell()->CreateReferenceRenderingContext();
45 RefPtr<DrawTarget> dt = ctx->GetDrawTarget();
46 return dt.forget();
49 private:
50 nsIFrame* mFrame;
53 static gfxTextRun* GetEllipsisTextRun(nsIFrame* aFrame) {
54 RefPtr<nsFontMetrics> fm =
55 nsLayoutUtils::GetInflatedFontMetricsForFrame(aFrame);
56 LazyReferenceRenderingDrawTargetGetterFromFrame lazyRefDrawTargetGetter(
57 aFrame);
58 return fm->GetThebesFontGroup()->GetEllipsisTextRun(
59 aFrame->PresContext()->AppUnitsPerDevPixel(),
60 nsLayoutUtils::GetTextRunOrientFlagsForStyle(aFrame->Style()),
61 lazyRefDrawTargetGetter);
64 static nsIFrame* GetSelfOrNearestBlock(nsIFrame* aFrame) {
65 MOZ_ASSERT(aFrame);
66 return aFrame->IsBlockFrameOrSubclass()
67 ? aFrame
68 : nsLayoutUtils::FindNearestBlockAncestor(aFrame);
71 // Return true if the frame is an atomic inline-level element.
72 // It's not supposed to be called for block frames since we never
73 // process block descendants for text-overflow.
74 static bool IsAtomicElement(nsIFrame* aFrame, LayoutFrameType aFrameType) {
75 MOZ_ASSERT(!aFrame->IsBlockFrameOrSubclass() || !aFrame->IsBlockOutside(),
76 "unexpected block frame");
77 MOZ_ASSERT(aFrameType != LayoutFrameType::Placeholder,
78 "unexpected placeholder frame");
79 return !aFrame->IsFrameOfType(nsIFrame::eLineParticipant);
82 static bool IsFullyClipped(nsTextFrame* aFrame, nscoord aLeft, nscoord aRight,
83 nscoord* aSnappedLeft, nscoord* aSnappedRight) {
84 *aSnappedLeft = aLeft;
85 *aSnappedRight = aRight;
86 if (aLeft <= 0 && aRight <= 0) {
87 return false;
89 return !aFrame->MeasureCharClippedText(aLeft, aRight, aSnappedLeft,
90 aSnappedRight);
93 static bool IsInlineAxisOverflowVisible(nsIFrame* aFrame) {
94 MOZ_ASSERT(aFrame && aFrame->IsBlockFrameOrSubclass(),
95 "expected a block frame");
97 nsIFrame* f = aFrame;
98 while (f && f->Style()->IsAnonBox() && !f->IsScrollFrame()) {
99 f = f->GetParent();
101 if (!f) {
102 return true;
104 auto overflow = aFrame->GetWritingMode().IsVertical()
105 ? f->StyleDisplay()->mOverflowY
106 : f->StyleDisplay()->mOverflowX;
107 return overflow == StyleOverflow::Visible;
110 static void ClipMarker(const nsRect& aContentArea, const nsRect& aMarkerRect,
111 DisplayListClipState::AutoSaveRestore& aClipState) {
112 nscoord rightOverflow = aMarkerRect.XMost() - aContentArea.XMost();
113 nsRect markerRect = aMarkerRect;
114 if (rightOverflow > 0) {
115 // Marker overflows on the right side (content width < marker width).
116 markerRect.width -= rightOverflow;
117 aClipState.ClipContentDescendants(markerRect);
118 } else {
119 nscoord leftOverflow = aContentArea.x - aMarkerRect.x;
120 if (leftOverflow > 0) {
121 // Marker overflows on the left side
122 markerRect.width -= leftOverflow;
123 markerRect.x += leftOverflow;
124 aClipState.ClipContentDescendants(markerRect);
129 static void InflateIStart(WritingMode aWM, LogicalRect* aRect, nscoord aDelta) {
130 nscoord iend = aRect->IEnd(aWM);
131 aRect->IStart(aWM) -= aDelta;
132 aRect->ISize(aWM) = std::max(iend - aRect->IStart(aWM), 0);
135 static void InflateIEnd(WritingMode aWM, LogicalRect* aRect, nscoord aDelta) {
136 aRect->ISize(aWM) = std::max(aRect->ISize(aWM) + aDelta, 0);
139 static bool IsFrameDescendantOfAny(
140 nsIFrame* aChild, const TextOverflow::FrameHashtable& aSetOfFrames,
141 nsIFrame* aCommonAncestor) {
142 for (nsIFrame* f = aChild; f && f != aCommonAncestor;
143 f = nsLayoutUtils::GetCrossDocParentFrameInProcess(f)) {
144 if (aSetOfFrames.Contains(f)) {
145 return true;
148 return false;
151 class nsDisplayTextOverflowMarker final : public nsPaintedDisplayItem {
152 public:
153 nsDisplayTextOverflowMarker(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
154 const nsRect& aRect, nscoord aAscent,
155 const StyleTextOverflowSide& aStyle)
156 : nsPaintedDisplayItem(aBuilder, aFrame),
157 mRect(aRect),
158 mStyle(aStyle),
159 mAscent(aAscent) {
160 MOZ_COUNT_CTOR(nsDisplayTextOverflowMarker);
163 MOZ_COUNTED_DTOR_OVERRIDE(nsDisplayTextOverflowMarker)
165 virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
166 bool* aSnap) const override {
167 *aSnap = false;
168 nsRect shadowRect = nsLayoutUtils::GetTextShadowRectsUnion(mRect, mFrame);
169 return mRect.Union(shadowRect);
172 virtual nsRect GetComponentAlphaBounds(
173 nsDisplayListBuilder* aBuilder) const override {
174 if (gfxPlatform::GetPlatform()->RespectsFontStyleSmoothing()) {
175 // On OS X, web authors can turn off subpixel text rendering using the
176 // CSS property -moz-osx-font-smoothing. If they do that, we don't need
177 // to use component alpha layers for the affected text.
178 if (mFrame->StyleFont()->mFont.smoothing == NS_FONT_SMOOTHING_GRAYSCALE) {
179 return nsRect();
182 bool snap;
183 return GetBounds(aBuilder, &snap);
186 virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
188 void PaintTextToContext(gfxContext* aCtx, nsPoint aOffsetFromRect);
190 virtual bool CreateWebRenderCommands(
191 mozilla::wr::DisplayListBuilder& aBuilder,
192 mozilla::wr::IpcResourceUpdateQueue& aResources,
193 const StackingContextHelper& aSc,
194 layers::RenderRootStateManager* aManager,
195 nsDisplayListBuilder* aDisplayListBuilder) override;
197 NS_DISPLAY_DECL_NAME("TextOverflow", TYPE_TEXT_OVERFLOW)
198 private:
199 nsRect mRect; // in reference frame coordinates
200 const StyleTextOverflowSide mStyle;
201 nscoord mAscent; // baseline for the marker text in mRect
204 static void PaintTextShadowCallback(gfxContext* aCtx, nsPoint aShadowOffset,
205 const nscolor& aShadowColor, void* aData) {
206 reinterpret_cast<nsDisplayTextOverflowMarker*>(aData)->PaintTextToContext(
207 aCtx, aShadowOffset);
210 void nsDisplayTextOverflowMarker::Paint(nsDisplayListBuilder* aBuilder,
211 gfxContext* aCtx) {
212 nscolor foregroundColor =
213 nsLayoutUtils::GetColor(mFrame, &nsStyleText::mWebkitTextFillColor);
215 // Paint the text-shadows for the overflow marker
216 nsLayoutUtils::PaintTextShadow(mFrame, aCtx, mRect,
217 GetPaintRect(aBuilder, aCtx), foregroundColor,
218 PaintTextShadowCallback, (void*)this);
219 aCtx->SetColor(gfx::sRGBColor::FromABGR(foregroundColor));
220 PaintTextToContext(aCtx, nsPoint(0, 0));
223 void nsDisplayTextOverflowMarker::PaintTextToContext(gfxContext* aCtx,
224 nsPoint aOffsetFromRect) {
225 WritingMode wm = mFrame->GetWritingMode();
226 nsPoint pt(mRect.x, mRect.y);
227 if (wm.IsVertical()) {
228 if (wm.IsVerticalLR()) {
229 pt.x = NSToCoordFloor(
230 nsLayoutUtils::GetSnappedBaselineX(mFrame, aCtx, pt.x, mAscent));
231 } else {
232 pt.x = NSToCoordFloor(nsLayoutUtils::GetSnappedBaselineX(
233 mFrame, aCtx, pt.x + mRect.width, -mAscent));
235 } else {
236 pt.y = NSToCoordFloor(
237 nsLayoutUtils::GetSnappedBaselineY(mFrame, aCtx, pt.y, mAscent));
239 pt += aOffsetFromRect;
241 if (mStyle.IsEllipsis()) {
242 gfxTextRun* textRun = GetEllipsisTextRun(mFrame);
243 if (textRun) {
244 NS_ASSERTION(!textRun->IsRightToLeft(),
245 "Ellipsis textruns should always be LTR!");
246 gfx::Point gfxPt(pt.x, pt.y);
247 textRun->Draw(gfxTextRun::Range(textRun), gfxPt,
248 gfxTextRun::DrawParams(aCtx));
250 } else {
251 RefPtr<nsFontMetrics> fm =
252 nsLayoutUtils::GetInflatedFontMetricsForFrame(mFrame);
253 NS_ConvertUTF8toUTF16 str16{mStyle.AsString().AsString()};
254 nsLayoutUtils::DrawString(mFrame, *fm, aCtx, str16.get(), str16.Length(),
255 pt);
259 bool nsDisplayTextOverflowMarker::CreateWebRenderCommands(
260 mozilla::wr::DisplayListBuilder& aBuilder,
261 mozilla::wr::IpcResourceUpdateQueue& aResources,
262 const StackingContextHelper& aSc, layers::RenderRootStateManager* aManager,
263 nsDisplayListBuilder* aDisplayListBuilder) {
264 bool snap;
265 nsRect bounds = GetBounds(aDisplayListBuilder, &snap);
266 if (bounds.IsEmpty()) {
267 return true;
270 // Run the rendering algorithm to capture the glyphs and shadows
271 RefPtr<TextDrawTarget> textDrawer =
272 new TextDrawTarget(aBuilder, aResources, aSc, aManager, this, bounds);
273 MOZ_ASSERT(textDrawer->IsValid());
274 if (!textDrawer->IsValid()) {
275 return false;
277 gfxContext captureCtx(textDrawer);
278 Paint(aDisplayListBuilder, &captureCtx);
279 textDrawer->TerminateShadows();
281 return textDrawer->Finish();
284 TextOverflow::TextOverflow(nsDisplayListBuilder* aBuilder,
285 nsBlockFrame* aBlockFrame)
286 : mContentArea(aBlockFrame->GetWritingMode(),
287 aBlockFrame->GetContentRectRelativeToSelf(),
288 aBlockFrame->GetSize()),
289 mBuilder(aBuilder),
290 mBlock(aBlockFrame),
291 mScrollableFrame(nsLayoutUtils::GetScrollableFrameFor(aBlockFrame)),
292 mMarkerList(aBuilder),
293 mBlockSize(aBlockFrame->GetSize()),
294 mBlockWM(aBlockFrame->GetWritingMode()),
295 mCanHaveInlineAxisScrollbar(false),
296 mInLineClampContext(aBlockFrame->IsInLineClampContext()),
297 mAdjustForPixelSnapping(false) {
298 if (mScrollableFrame) {
299 auto scrollbarStyle = mBlockWM.IsVertical()
300 ? mScrollableFrame->GetScrollStyles().mVertical
301 : mScrollableFrame->GetScrollStyles().mHorizontal;
302 mCanHaveInlineAxisScrollbar = scrollbarStyle != StyleOverflow::Hidden;
303 if (!mAdjustForPixelSnapping) {
304 // Scrolling to the end position can leave some text still overflowing due
305 // to pixel snapping behaviour in our scrolling code.
306 mAdjustForPixelSnapping = mCanHaveInlineAxisScrollbar;
308 // Use a null containerSize to convert a vector from logical to physical.
309 const nsSize nullContainerSize;
310 mContentArea.MoveBy(
311 mBlockWM, LogicalPoint(mBlockWM, mScrollableFrame->GetScrollPosition(),
312 nullContainerSize));
314 StyleDirection direction = aBlockFrame->StyleVisibility()->mDirection;
315 const nsStyleTextReset* style = aBlockFrame->StyleTextReset();
317 const auto& textOverflow = style->mTextOverflow;
318 bool shouldToggleDirection =
319 textOverflow.sides_are_logical && (direction == StyleDirection::Rtl);
320 const auto& leftSide =
321 shouldToggleDirection ? textOverflow.second : textOverflow.first;
322 const auto& rightSide =
323 shouldToggleDirection ? textOverflow.first : textOverflow.second;
325 if (mBlockWM.IsBidiLTR()) {
326 mIStart.Init(leftSide);
327 mIEnd.Init(rightSide);
328 } else {
329 mIStart.Init(rightSide);
330 mIEnd.Init(leftSide);
332 // The left/right marker string is setup in ExamineLineFrames when a line
333 // has overflow on that side.
336 /* static */
337 Maybe<TextOverflow> TextOverflow::WillProcessLines(
338 nsDisplayListBuilder* aBuilder, nsBlockFrame* aBlockFrame) {
339 // Ignore text-overflow and -webkit-line-clamp for event and frame visibility
340 // processing.
341 if (aBuilder->IsForEventDelivery() || aBuilder->IsForFrameVisibility() ||
342 !CanHaveOverflowMarkers(aBlockFrame)) {
343 return Nothing();
345 nsIScrollableFrame* scrollableFrame =
346 nsLayoutUtils::GetScrollableFrameFor(aBlockFrame);
347 if (scrollableFrame && scrollableFrame->IsTransformingByAPZ()) {
348 // If the APZ is actively scrolling this, don't bother with markers.
349 return Nothing();
351 return Some(TextOverflow(aBuilder, aBlockFrame));
354 void TextOverflow::ExamineFrameSubtree(nsIFrame* aFrame,
355 const LogicalRect& aContentArea,
356 const LogicalRect& aInsideMarkersArea,
357 FrameHashtable* aFramesToHide,
358 AlignmentEdges* aAlignmentEdges,
359 bool* aFoundVisibleTextOrAtomic,
360 InnerClipEdges* aClippedMarkerEdges) {
361 const LayoutFrameType frameType = aFrame->Type();
362 if (frameType == LayoutFrameType::Br ||
363 frameType == LayoutFrameType::Placeholder) {
364 return;
366 const bool isAtomic = IsAtomicElement(aFrame, frameType);
367 if (aFrame->StyleVisibility()->IsVisible()) {
368 LogicalRect childRect =
369 GetLogicalScrollableOverflowRectRelativeToBlock(aFrame);
370 bool overflowIStart =
371 childRect.IStart(mBlockWM) < aContentArea.IStart(mBlockWM);
372 bool overflowIEnd = childRect.IEnd(mBlockWM) > aContentArea.IEnd(mBlockWM);
373 if (overflowIStart) {
374 mIStart.mHasOverflow = true;
376 if (overflowIEnd) {
377 mIEnd.mHasOverflow = true;
379 if (isAtomic && ((mIStart.mActive && overflowIStart) ||
380 (mIEnd.mActive && overflowIEnd))) {
381 aFramesToHide->Insert(aFrame);
382 } else if (isAtomic || frameType == LayoutFrameType::Text) {
383 AnalyzeMarkerEdges(aFrame, frameType, aInsideMarkersArea, aFramesToHide,
384 aAlignmentEdges, aFoundVisibleTextOrAtomic,
385 aClippedMarkerEdges);
388 if (isAtomic) {
389 return;
392 for (nsIFrame* child : aFrame->PrincipalChildList()) {
393 ExamineFrameSubtree(child, aContentArea, aInsideMarkersArea, aFramesToHide,
394 aAlignmentEdges, aFoundVisibleTextOrAtomic,
395 aClippedMarkerEdges);
399 void TextOverflow::AnalyzeMarkerEdges(nsIFrame* aFrame,
400 LayoutFrameType aFrameType,
401 const LogicalRect& aInsideMarkersArea,
402 FrameHashtable* aFramesToHide,
403 AlignmentEdges* aAlignmentEdges,
404 bool* aFoundVisibleTextOrAtomic,
405 InnerClipEdges* aClippedMarkerEdges) {
406 MOZ_ASSERT(aFrameType == LayoutFrameType::Text ||
407 IsAtomicElement(aFrame, aFrameType));
408 LogicalRect borderRect(mBlockWM,
409 nsRect(aFrame->GetOffsetTo(mBlock), aFrame->GetSize()),
410 mBlockSize);
411 nscoord istartOverlap = std::max(
412 aInsideMarkersArea.IStart(mBlockWM) - borderRect.IStart(mBlockWM), 0);
413 nscoord iendOverlap = std::max(
414 borderRect.IEnd(mBlockWM) - aInsideMarkersArea.IEnd(mBlockWM), 0);
415 bool insideIStartEdge =
416 aInsideMarkersArea.IStart(mBlockWM) <= borderRect.IEnd(mBlockWM);
417 bool insideIEndEdge =
418 borderRect.IStart(mBlockWM) <= aInsideMarkersArea.IEnd(mBlockWM);
420 if (istartOverlap > 0) {
421 aClippedMarkerEdges->AccumulateIStart(mBlockWM, borderRect);
422 if (!mIStart.mActive) {
423 istartOverlap = 0;
426 if (iendOverlap > 0) {
427 aClippedMarkerEdges->AccumulateIEnd(mBlockWM, borderRect);
428 if (!mIEnd.mActive) {
429 iendOverlap = 0;
433 if ((istartOverlap > 0 && insideIStartEdge) ||
434 (iendOverlap > 0 && insideIEndEdge)) {
435 if (aFrameType == LayoutFrameType::Text) {
436 auto textFrame = static_cast<nsTextFrame*>(aFrame);
437 if ((aInsideMarkersArea.IStart(mBlockWM) <
438 aInsideMarkersArea.IEnd(mBlockWM)) &&
439 textFrame->HasNonSuppressedText()) {
440 // a clipped text frame and there is some room between the markers
441 nscoord snappedIStart, snappedIEnd;
442 bool isFullyClipped =
443 mBlockWM.IsBidiLTR()
444 ? IsFullyClipped(textFrame, istartOverlap, iendOverlap,
445 &snappedIStart, &snappedIEnd)
446 : IsFullyClipped(textFrame, iendOverlap, istartOverlap,
447 &snappedIEnd, &snappedIStart);
448 if (!isFullyClipped) {
449 LogicalRect snappedRect = borderRect;
450 if (istartOverlap > 0) {
451 snappedRect.IStart(mBlockWM) += snappedIStart;
452 snappedRect.ISize(mBlockWM) -= snappedIStart;
454 if (iendOverlap > 0) {
455 snappedRect.ISize(mBlockWM) -= snappedIEnd;
457 aAlignmentEdges->AccumulateInner(mBlockWM, snappedRect);
458 *aFoundVisibleTextOrAtomic = true;
461 } else {
462 aFramesToHide->Insert(aFrame);
464 } else if (!insideIStartEdge || !insideIEndEdge) {
465 // frame is outside
466 if (!insideIStartEdge) {
467 aAlignmentEdges->AccumulateOuter(mBlockWM, borderRect);
469 if (IsAtomicElement(aFrame, aFrameType)) {
470 aFramesToHide->Insert(aFrame);
472 } else {
473 // frame is inside
474 aAlignmentEdges->AccumulateInner(mBlockWM, borderRect);
475 if (aFrameType == LayoutFrameType::Text) {
476 auto textFrame = static_cast<nsTextFrame*>(aFrame);
477 if (textFrame->HasNonSuppressedText()) {
478 *aFoundVisibleTextOrAtomic = true;
480 } else {
481 *aFoundVisibleTextOrAtomic = true;
486 LogicalRect TextOverflow::ExamineLineFrames(nsLineBox* aLine,
487 FrameHashtable* aFramesToHide,
488 AlignmentEdges* aAlignmentEdges) {
489 // No ellipsing for 'clip' style.
490 bool suppressIStart = mIStart.IsSuppressed(mInLineClampContext);
491 bool suppressIEnd = mIEnd.IsSuppressed(mInLineClampContext);
492 if (mCanHaveInlineAxisScrollbar) {
493 LogicalPoint pos(mBlockWM, mScrollableFrame->GetScrollPosition(),
494 mBlockSize);
495 LogicalRect scrollRange(mBlockWM, mScrollableFrame->GetScrollRange(),
496 mBlockSize);
497 // No ellipsing when nothing to scroll to on that side (this includes
498 // overflow:auto that doesn't trigger a horizontal scrollbar).
499 if (pos.I(mBlockWM) <= scrollRange.IStart(mBlockWM)) {
500 suppressIStart = true;
502 if (pos.I(mBlockWM) >= scrollRange.IEnd(mBlockWM)) {
503 // Except that we always want to display a -webkit-line-clamp ellipsis.
504 if (!mIEnd.mHasBlockEllipsis) {
505 suppressIEnd = true;
510 LogicalRect contentArea = mContentArea;
511 bool snapStart = true, snapEnd = true;
512 nscoord startEdge, endEdge;
513 if (aLine->GetFloatEdges(&startEdge, &endEdge)) {
514 // Narrow the |contentArea| to account for any floats on this line, and
515 // don't bother with the snapping quirk on whichever side(s) we narrow.
516 nscoord delta = endEdge - contentArea.IEnd(mBlockWM);
517 if (delta < 0) {
518 nscoord newSize = contentArea.ISize(mBlockWM) + delta;
519 contentArea.ISize(mBlockWM) = std::max(nscoord(0), newSize);
520 snapEnd = false;
522 delta = startEdge - contentArea.IStart(mBlockWM);
523 if (delta > 0) {
524 contentArea.IStart(mBlockWM) = startEdge;
525 nscoord newSize = contentArea.ISize(mBlockWM) - delta;
526 contentArea.ISize(mBlockWM) = std::max(nscoord(0), newSize);
527 snapStart = false;
530 // Save the non-snapped area since that's what we want to use when placing
531 // the markers (our return value). The snapped area is only for analysis.
532 LogicalRect nonSnappedContentArea = contentArea;
533 if (mAdjustForPixelSnapping) {
534 const nscoord scrollAdjust = mBlock->PresContext()->AppUnitsPerDevPixel();
535 if (snapStart) {
536 InflateIStart(mBlockWM, &contentArea, scrollAdjust);
538 if (snapEnd) {
539 InflateIEnd(mBlockWM, &contentArea, scrollAdjust);
543 LogicalRect lineRect(mBlockWM, aLine->ScrollableOverflowRect(), mBlockSize);
544 const bool istartWantsMarker =
545 !suppressIStart &&
546 lineRect.IStart(mBlockWM) < contentArea.IStart(mBlockWM);
547 const bool iendWantsTextOverflowMarker =
548 !suppressIEnd && lineRect.IEnd(mBlockWM) > contentArea.IEnd(mBlockWM);
549 const bool iendWantsBlockEllipsisMarker =
550 !suppressIEnd && mIEnd.mHasBlockEllipsis;
551 const bool iendWantsMarker =
552 iendWantsTextOverflowMarker || iendWantsBlockEllipsisMarker;
553 if (!istartWantsMarker && !iendWantsMarker) {
554 // We don't need any markers on this line.
555 return nonSnappedContentArea;
558 int pass = 0;
559 bool retryEmptyLine = true;
560 bool guessIStart = istartWantsMarker;
561 bool guessIEnd = iendWantsMarker;
562 mIStart.mActive = istartWantsMarker;
563 mIEnd.mActive = iendWantsMarker;
564 mIStart.mEdgeAligned = mCanHaveInlineAxisScrollbar && istartWantsMarker;
565 mIEnd.mEdgeAligned =
566 mCanHaveInlineAxisScrollbar && iendWantsTextOverflowMarker;
567 bool clippedIStartMarker = false;
568 bool clippedIEndMarker = false;
569 do {
570 // Setup marker strings as needed.
571 if (guessIStart) {
572 mIStart.SetupString(mBlock);
574 if (guessIEnd) {
575 mIEnd.SetupString(mBlock);
578 // If there is insufficient space for both markers then keep the one on the
579 // end side per the block's 'direction'.
580 nscoord istartMarkerISize = mIStart.mActive ? mIStart.mISize : 0;
581 nscoord iendMarkerISize = mIEnd.mActive ? mIEnd.mISize : 0;
582 if (istartMarkerISize && iendMarkerISize &&
583 istartMarkerISize + iendMarkerISize > contentArea.ISize(mBlockWM)) {
584 istartMarkerISize = 0;
587 // Calculate the area between the potential markers aligned at the
588 // block's edge.
589 LogicalRect insideMarkersArea = nonSnappedContentArea;
590 if (guessIStart) {
591 InflateIStart(mBlockWM, &insideMarkersArea, -istartMarkerISize);
593 if (guessIEnd) {
594 InflateIEnd(mBlockWM, &insideMarkersArea, -iendMarkerISize);
597 // Analyze the frames on aLine for the overflow situation at the content
598 // edges and at the edges of the area between the markers.
599 bool foundVisibleTextOrAtomic = false;
600 int32_t n = aLine->GetChildCount();
601 nsIFrame* child = aLine->mFirstChild;
602 InnerClipEdges clippedMarkerEdges;
603 for (; n-- > 0; child = child->GetNextSibling()) {
604 ExamineFrameSubtree(child, contentArea, insideMarkersArea, aFramesToHide,
605 aAlignmentEdges, &foundVisibleTextOrAtomic,
606 &clippedMarkerEdges);
608 if (!foundVisibleTextOrAtomic && retryEmptyLine) {
609 aAlignmentEdges->mAssignedInner = false;
610 aAlignmentEdges->mIEndOuter = 0;
611 aFramesToHide->Clear();
612 pass = -1;
613 if (mIStart.IsNeeded() && mIStart.mActive && !clippedIStartMarker) {
614 if (clippedMarkerEdges.mAssignedIStart &&
615 clippedMarkerEdges.mIStart >
616 nonSnappedContentArea.IStart(mBlockWM)) {
617 mIStart.mISize = clippedMarkerEdges.mIStart -
618 nonSnappedContentArea.IStart(mBlockWM);
619 NS_ASSERTION(mIStart.mISize < mIStart.mIntrinsicISize,
620 "clipping a marker should make it strictly smaller");
621 clippedIStartMarker = true;
622 } else {
623 mIStart.mActive = guessIStart = false;
625 continue;
627 if (mIEnd.IsNeeded() && mIEnd.mActive && !clippedIEndMarker) {
628 if (clippedMarkerEdges.mAssignedIEnd &&
629 nonSnappedContentArea.IEnd(mBlockWM) > clippedMarkerEdges.mIEnd) {
630 mIEnd.mISize =
631 nonSnappedContentArea.IEnd(mBlockWM) - clippedMarkerEdges.mIEnd;
632 NS_ASSERTION(mIEnd.mISize < mIEnd.mIntrinsicISize,
633 "clipping a marker should make it strictly smaller");
634 clippedIEndMarker = true;
635 } else {
636 mIEnd.mActive = guessIEnd = false;
638 continue;
640 // The line simply has no visible content even without markers,
641 // so examine the line again without suppressing markers.
642 retryEmptyLine = false;
643 mIStart.mISize = mIStart.mIntrinsicISize;
644 mIStart.mActive = guessIStart = istartWantsMarker;
645 mIEnd.mISize = mIEnd.mIntrinsicISize;
646 mIEnd.mActive = guessIEnd = iendWantsMarker;
647 // If we wanted to place a block ellipsis but didn't, due to not having
648 // any visible content to align to or the line's content being scrolled
649 // out of view, then clip the ellipsis so that it looks like it is aligned
650 // with the out of view content.
651 if (mIEnd.IsNeeded() && mIEnd.mActive && mIEnd.mHasBlockEllipsis) {
652 NS_ASSERTION(nonSnappedContentArea.IStart(mBlockWM) >
653 aAlignmentEdges->mIEndOuter,
654 "Expected the alignment edge for the out of view content "
655 "to be before the start of the content area");
656 mIEnd.mISize = std::max(
657 mIEnd.mIntrinsicISize - (nonSnappedContentArea.IStart(mBlockWM) -
658 aAlignmentEdges->mIEndOuter),
661 continue;
663 if (guessIStart == (mIStart.mActive && mIStart.IsNeeded()) &&
664 guessIEnd == (mIEnd.mActive && mIEnd.IsNeeded())) {
665 break;
666 } else {
667 guessIStart = mIStart.mActive && mIStart.IsNeeded();
668 guessIEnd = mIEnd.mActive && mIEnd.IsNeeded();
669 mIStart.Reset();
670 mIEnd.Reset();
671 aFramesToHide->Clear();
673 NS_ASSERTION(pass == 0, "2nd pass should never guess wrong");
674 } while (++pass != 2);
675 if (!istartWantsMarker || !mIStart.mActive) {
676 mIStart.Reset();
678 if (!iendWantsMarker || !mIEnd.mActive) {
679 mIEnd.Reset();
681 return nonSnappedContentArea;
684 void TextOverflow::ProcessLine(const nsDisplayListSet& aLists, nsLineBox* aLine,
685 uint32_t aLineNumber) {
686 if (mIStart.mStyle->IsClip() && mIEnd.mStyle->IsClip() &&
687 !aLine->HasLineClampEllipsis()) {
688 return;
691 mIStart.Reset();
692 mIStart.mActive = !mIStart.mStyle->IsClip();
693 mIEnd.Reset();
694 mIEnd.mHasBlockEllipsis = aLine->HasLineClampEllipsis();
695 mIEnd.mActive = !mIEnd.IsSuppressed(mInLineClampContext);
697 FrameHashtable framesToHide(64);
698 AlignmentEdges alignmentEdges;
699 const LogicalRect contentArea =
700 ExamineLineFrames(aLine, &framesToHide, &alignmentEdges);
701 bool needIStart = mIStart.IsNeeded();
702 bool needIEnd = mIEnd.IsNeeded();
703 if (!needIStart && !needIEnd) {
704 return;
706 NS_ASSERTION(!mIStart.IsSuppressed(mInLineClampContext) || !needIStart,
707 "left marker when not needed");
708 NS_ASSERTION(!mIEnd.IsSuppressed(mInLineClampContext) || !needIEnd,
709 "right marker when not needed");
711 // If there is insufficient space for both markers then keep the one on the
712 // end side per the block's 'direction'.
713 if (needIStart && needIEnd &&
714 mIStart.mISize + mIEnd.mISize > contentArea.ISize(mBlockWM)) {
715 needIStart = false;
717 LogicalRect insideMarkersArea = contentArea;
718 if (needIStart) {
719 InflateIStart(mBlockWM, &insideMarkersArea, -mIStart.mISize);
721 if (needIEnd) {
722 InflateIEnd(mBlockWM, &insideMarkersArea, -mIEnd.mISize);
725 if (alignmentEdges.mAssignedInner) {
726 if (mIStart.mEdgeAligned) {
727 alignmentEdges.mIStart = insideMarkersArea.IStart(mBlockWM);
729 if (mIEnd.mEdgeAligned) {
730 alignmentEdges.mIEnd = insideMarkersArea.IEnd(mBlockWM);
732 LogicalRect alignmentRect(mBlockWM, alignmentEdges.mIStart,
733 insideMarkersArea.BStart(mBlockWM),
734 alignmentEdges.ISize(), 1);
735 insideMarkersArea.IntersectRect(insideMarkersArea, alignmentRect);
736 } else {
737 // There was no content on the line that was visible at the current scolled
738 // position. If we wanted to place a block ellipsis but failed due to
739 // having no visible content to align it to, we still need to ensure it
740 // is displayed. It goes at the start of the line, even though it's an
741 // IEnd marker, since that is the side of the line that the content has
742 // been scrolled past. We set the insideMarkersArea to a zero-sized
743 // rectangle placed next to the scrolled-out-of-view content.
744 if (mIEnd.mHasBlockEllipsis) {
745 insideMarkersArea = LogicalRect(mBlockWM, alignmentEdges.mIEndOuter,
746 insideMarkersArea.BStart(mBlockWM), 0, 1);
750 // Clip and remove display items as needed at the final marker edges.
751 nsDisplayList* lists[] = {aLists.Content(), aLists.PositionedDescendants()};
752 for (uint32_t i = 0; i < ArrayLength(lists); ++i) {
753 PruneDisplayListContents(lists[i], framesToHide, insideMarkersArea);
755 CreateMarkers(aLine, needIStart, needIEnd, insideMarkersArea, contentArea,
756 aLineNumber);
759 void TextOverflow::PruneDisplayListContents(
760 nsDisplayList* aList, const FrameHashtable& aFramesToHide,
761 const LogicalRect& aInsideMarkersArea) {
762 for (nsDisplayItem* item : aList->TakeItems()) {
763 nsIFrame* itemFrame = item->Frame();
764 if (IsFrameDescendantOfAny(itemFrame, aFramesToHide, mBlock)) {
765 item->Destroy(mBuilder);
766 continue;
769 nsDisplayList* wrapper = item->GetSameCoordinateSystemChildren();
770 if (wrapper) {
771 if (!itemFrame || GetSelfOrNearestBlock(itemFrame) == mBlock) {
772 PruneDisplayListContents(wrapper, aFramesToHide, aInsideMarkersArea);
776 nsDisplayText* textItem =
777 itemFrame ? nsDisplayText::CheckCast(item) : nullptr;
778 if (textItem && GetSelfOrNearestBlock(itemFrame) == mBlock) {
779 LogicalRect rect =
780 GetLogicalScrollableOverflowRectRelativeToBlock(itemFrame);
781 if (mIStart.IsNeeded()) {
782 nscoord istart =
783 aInsideMarkersArea.IStart(mBlockWM) - rect.IStart(mBlockWM);
784 if (istart > 0) {
785 (mBlockWM.IsBidiLTR() ? textItem->VisIStartEdge()
786 : textItem->VisIEndEdge()) = istart;
789 if (mIEnd.IsNeeded()) {
790 nscoord iend = rect.IEnd(mBlockWM) - aInsideMarkersArea.IEnd(mBlockWM);
791 if (iend > 0) {
792 (mBlockWM.IsBidiLTR() ? textItem->VisIEndEdge()
793 : textItem->VisIStartEdge()) = iend;
798 aList->AppendToTop(item);
802 /* static */
803 bool TextOverflow::HasClippedTextOverflow(nsIFrame* aBlockFrame) {
804 const nsStyleTextReset* style = aBlockFrame->StyleTextReset();
805 return style->mTextOverflow.first.IsClip() &&
806 style->mTextOverflow.second.IsClip();
809 /* static */
810 bool TextOverflow::HasBlockEllipsis(nsIFrame* aBlockFrame) {
811 nsBlockFrame* f = do_QueryFrame(aBlockFrame);
812 return f && f->HasAnyStateBits(NS_BLOCK_HAS_LINE_CLAMP_ELLIPSIS);
815 static bool BlockCanHaveLineClampEllipsis(nsBlockFrame* aBlockFrame,
816 bool aBeforeReflow) {
817 if (aBeforeReflow) {
818 return aBlockFrame->IsInLineClampContext();
820 return aBlockFrame->HasAnyStateBits(NS_BLOCK_HAS_LINE_CLAMP_ELLIPSIS);
823 /* static */
824 bool TextOverflow::CanHaveOverflowMarkers(nsBlockFrame* aBlockFrame,
825 BeforeReflow aBeforeReflow) {
826 if (BlockCanHaveLineClampEllipsis(aBlockFrame,
827 aBeforeReflow == BeforeReflow::Yes)) {
828 return true;
831 // Nothing to do for text-overflow:clip or if 'overflow-x/y:visible'.
832 if (HasClippedTextOverflow(aBlockFrame) ||
833 IsInlineAxisOverflowVisible(aBlockFrame)) {
834 return false;
837 // Skip ComboboxControlFrame because it would clip the drop-down arrow.
838 // Its anon block inherits 'text-overflow' and does what is expected.
839 if (aBlockFrame->IsComboboxControlFrame()) {
840 return false;
843 // Inhibit the markers if a descendant content owns the caret.
844 RefPtr<nsCaret> caret = aBlockFrame->PresShell()->GetCaret();
845 if (caret && caret->IsVisible()) {
846 RefPtr<dom::Selection> domSelection = caret->GetSelection();
847 if (domSelection) {
848 nsCOMPtr<nsIContent> content =
849 nsIContent::FromNodeOrNull(domSelection->GetFocusNode());
850 if (content &&
851 content->IsInclusiveDescendantOf(aBlockFrame->GetContent())) {
852 return false;
856 return true;
859 void TextOverflow::CreateMarkers(const nsLineBox* aLine, bool aCreateIStart,
860 bool aCreateIEnd,
861 const LogicalRect& aInsideMarkersArea,
862 const LogicalRect& aContentArea,
863 uint32_t aLineNumber) {
864 if (!mBlock->IsVisibleForPainting()) {
865 return;
868 if (aCreateIStart) {
869 DisplayListClipState::AutoSaveRestore clipState(mBuilder);
871 LogicalRect markerLogicalRect(
872 mBlockWM, aInsideMarkersArea.IStart(mBlockWM) - mIStart.mIntrinsicISize,
873 aLine->BStart(), mIStart.mIntrinsicISize, aLine->BSize());
874 nsPoint offset = mBuilder->ToReferenceFrame(mBlock);
875 nsRect markerRect =
876 markerLogicalRect.GetPhysicalRect(mBlockWM, mBlockSize) + offset;
877 ClipMarker(aContentArea.GetPhysicalRect(mBlockWM, mBlockSize) + offset,
878 markerRect, clipState);
880 mMarkerList.AppendNewToTopWithIndex<nsDisplayTextOverflowMarker>(
881 mBuilder, mBlock, /* aIndex = */ (aLineNumber << 1) + 0, markerRect,
882 aLine->GetLogicalAscent(), *mIStart.mStyle);
885 if (aCreateIEnd) {
886 DisplayListClipState::AutoSaveRestore clipState(mBuilder);
888 LogicalRect markerLogicalRect(mBlockWM, aInsideMarkersArea.IEnd(mBlockWM),
889 aLine->BStart(), mIEnd.mIntrinsicISize,
890 aLine->BSize());
891 nsPoint offset = mBuilder->ToReferenceFrame(mBlock);
892 nsRect markerRect =
893 markerLogicalRect.GetPhysicalRect(mBlockWM, mBlockSize) + offset;
894 ClipMarker(aContentArea.GetPhysicalRect(mBlockWM, mBlockSize) + offset,
895 markerRect, clipState);
897 mMarkerList.AppendNewToTopWithIndex<nsDisplayTextOverflowMarker>(
898 mBuilder, mBlock, /* aIndex = */ (aLineNumber << 1) + 1, markerRect,
899 aLine->GetLogicalAscent(),
900 mIEnd.mHasBlockEllipsis ? StyleTextOverflowSide::Ellipsis()
901 : *mIEnd.mStyle);
905 void TextOverflow::Marker::SetupString(nsIFrame* aFrame) {
906 if (mInitialized) {
907 return;
910 // A limitation here is that at the IEnd of a line, we only ever render one of
911 // a text-overflow marker and a -webkit-line-clamp block ellipsis. Since we
912 // don't track the block ellipsis string and the text-overflow marker string
913 // separately, if both apply to the element, we will always use "…" as the
914 // string for text-overflow.
915 if (HasBlockEllipsis(aFrame) || mStyle->IsEllipsis()) {
916 gfxTextRun* textRun = GetEllipsisTextRun(aFrame);
917 if (textRun) {
918 mISize = textRun->GetAdvanceWidth();
919 } else {
920 mISize = 0;
922 } else {
923 UniquePtr<gfxContext> rc =
924 aFrame->PresShell()->CreateReferenceRenderingContext();
925 RefPtr<nsFontMetrics> fm =
926 nsLayoutUtils::GetInflatedFontMetricsForFrame(aFrame);
927 mISize = nsLayoutUtils::AppUnitWidthOfStringBidi(
928 NS_ConvertUTF8toUTF16(mStyle->AsString().AsString()), aFrame, *fm, *rc);
930 mIntrinsicISize = mISize;
931 mInitialized = true;
934 } // namespace css
935 } // namespace mozilla