forked from qt/qtwebkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenderBoxModelObject.cpp
More file actions
2596 lines (2185 loc) · 123 KB
/
Copy pathRenderBoxModelObject.cpp
File metadata and controls
2596 lines (2185 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
* (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2013 Apple Inc. All rights reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "RenderBoxModelObject.h"
#include "BorderEdge.h"
#include "FloatRoundedRect.h"
#include "Frame.h"
#include "FrameView.h"
#include "GeometryUtilities.h"
#include "GraphicsContext.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLNames.h"
#include "ImageBuffer.h"
#include "ImageQualityController.h"
#include "Page.h"
#include "Path.h"
#include "RenderBlock.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderLayerBacking.h"
#include "RenderLayerCompositor.h"
#include "RenderMultiColumnFlowThread.h"
#include "RenderNamedFlowFragment.h"
#include "RenderNamedFlowThread.h"
#include "RenderRegion.h"
#include "RenderTable.h"
#include "RenderTableRow.h"
#include "RenderText.h"
#include "RenderTextFragment.h"
#include "RenderView.h"
#include "ScrollingConstraints.h"
#include "Settings.h"
#include "TransformState.h"
#include <wtf/NeverDestroyed.h>
namespace WebCore {
using namespace HTMLNames;
// The HashMap for storing continuation pointers.
// An inline can be split with blocks occuring in between the inline content.
// When this occurs we need a pointer to the next object. We can basically be
// split into a sequence of inlines and blocks. The continuation will either be
// an anonymous block (that houses other blocks) or it will be an inline flow.
// <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as
// its continuation but the <b> will just have an inline as its continuation.
typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
static ContinuationMap& continuationMap()
{
static NeverDestroyed<ContinuationMap> map;
return map;
}
// This HashMap is similar to the continuation map, but connects first-letter
// renderers to their remaining text fragments.
typedef HashMap<const RenderBoxModelObject*, RenderTextFragment*> FirstLetterRemainingTextMap;
static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = nullptr;
void RenderBoxModelObject::setSelectionState(SelectionState state)
{
if (state == SelectionInside && selectionState() != SelectionNone)
return;
if ((state == SelectionStart && selectionState() == SelectionEnd)
|| (state == SelectionEnd && selectionState() == SelectionStart))
RenderLayerModelObject::setSelectionState(SelectionBoth);
else
RenderLayerModelObject::setSelectionState(state);
// FIXME: We should consider whether it is OK propagating to ancestor RenderInlines.
// This is a workaround for http://webkit.org/b/32123
// The containing block can be null in case of an orphaned tree.
RenderBlock* containingBlock = this->containingBlock();
if (containingBlock && !containingBlock->isRenderView())
containingBlock->setSelectionState(state);
}
void RenderBoxModelObject::contentChanged(ContentChangeType changeType)
{
if (!hasLayer())
return;
layer()->contentChanged(changeType);
}
bool RenderBoxModelObject::hasAcceleratedCompositing() const
{
return view().compositor().hasAcceleratedCompositing();
}
bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
{
ASSERT(hasLayer());
ASSERT(isComposited());
return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
}
void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
{
ASSERT(hasLayer());
ASSERT(isComposited());
layer()->backing()->transitionPaused(timeOffset, propertyId);
}
void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
{
ASSERT(hasLayer());
ASSERT(isComposited());
layer()->backing()->transitionFinished(propertyId);
}
bool RenderBoxModelObject::startAnimation(double timeOffset, const Animation* animation, const KeyframeList& keyframes)
{
ASSERT(hasLayer());
ASSERT(isComposited());
return layer()->backing()->startAnimation(timeOffset, animation, keyframes);
}
void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
{
ASSERT(hasLayer());
ASSERT(isComposited());
layer()->backing()->animationPaused(timeOffset, name);
}
void RenderBoxModelObject::animationFinished(const String& name)
{
ASSERT(hasLayer());
ASSERT(isComposited());
layer()->backing()->animationFinished(name);
}
void RenderBoxModelObject::suspendAnimations(double time)
{
ASSERT(hasLayer());
ASSERT(isComposited());
layer()->backing()->suspendAnimations(time);
}
RenderBoxModelObject::RenderBoxModelObject(Element& element, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
: RenderLayerModelObject(element, WTFMove(style), baseTypeFlags | RenderBoxModelObjectFlag)
{
}
RenderBoxModelObject::RenderBoxModelObject(Document& document, Ref<RenderStyle>&& style, BaseTypeFlags baseTypeFlags)
: RenderLayerModelObject(document, WTFMove(style), baseTypeFlags | RenderBoxModelObjectFlag)
{
}
RenderBoxModelObject::~RenderBoxModelObject()
{
}
void RenderBoxModelObject::willBeDestroyed()
{
if (hasContinuation()) {
continuation()->destroy();
setContinuation(nullptr);
}
// If this is a first-letter object with a remaining text fragment then the
// entry needs to be cleared from the map.
if (firstLetterRemainingText())
setFirstLetterRemainingText(nullptr);
if (!documentBeingDestroyed())
view().imageQualityController().rendererWillBeDestroyed(*this);
RenderLayerModelObject::willBeDestroyed();
}
bool RenderBoxModelObject::hasBoxDecorationStyle() const
{
return hasBackground() || style().hasBorderDecoration() || style().hasAppearance() || style().boxShadow();
}
void RenderBoxModelObject::updateFromStyle()
{
RenderLayerModelObject::updateFromStyle();
// Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange,
// we only check for bits that could possibly be set to true.
const RenderStyle& styleToUse = style();
setHasBoxDecorations(hasBoxDecorationStyle());
setInline(styleToUse.isDisplayInlineType());
setPositionState(styleToUse.position());
setHorizontalWritingMode(styleToUse.isHorizontalWritingMode());
if (styleToUse.isFlippedBlocksWritingMode())
view().frameView().setHasFlippedBlockRenderers(true);
}
static LayoutSize accumulateInFlowPositionOffsets(const RenderObject* child)
{
if (!child->isAnonymousBlock() || !child->isInFlowPositioned())
return LayoutSize();
LayoutSize offset;
for (RenderElement* parent = downcast<RenderBlock>(*child).inlineElementContinuation(); is<RenderInline>(parent); parent = parent->parent()) {
if (parent->isInFlowPositioned())
offset += downcast<RenderInline>(*parent).offsetForInFlowPosition();
}
return offset;
}
bool RenderBoxModelObject::hasAutoHeightOrContainingBlockWithAutoHeight() const
{
Length logicalHeightLength = style().logicalHeight();
if (logicalHeightLength.isAuto())
return true;
// For percentage heights: The percentage is calculated with respect to the height of the generated box's
// containing block. If the height of the containing block is not specified explicitly (i.e., it depends
// on content height), and this element is not absolutely positioned, the value computes to 'auto'.
if (!logicalHeightLength.isPercentOrCalculated() || isOutOfFlowPositioned() || document().inQuirksMode())
return false;
// Anonymous block boxes are ignored when resolving percentage values that would refer to it:
// the closest non-anonymous ancestor box is used instead.
RenderBlock* cb = containingBlock();
while (cb && !is<RenderView>(*cb) && cb->isAnonymous())
cb = cb->containingBlock();
// Matching RenderBox::percentageLogicalHeightIsResolvableFromBlock() by
// ignoring table cell's attribute value, where it says that table cells violate
// what the CSS spec says to do with heights. Basically we
// don't care if the cell specified a height or not.
if (cb->isTableCell())
return false;
// Match RenderBox::availableLogicalHeightUsing by special casing
// the render view. The available height is taken from the frame.
if (cb->isRenderView())
return false;
if (cb->isOutOfFlowPositioned() && !cb->style().logicalTop().isAuto() && !cb->style().logicalBottom().isAuto())
return false;
// If the height of the containing block computes to 'auto', then it hasn't been 'specified explictly'.
return cb->hasAutoHeightOrContainingBlockWithAutoHeight();
}
LayoutSize RenderBoxModelObject::relativePositionOffset() const
{
// This function has been optimized to avoid calls to containingBlock() in the common case
// where all values are either auto or fixed.
LayoutSize offset = accumulateInFlowPositionOffsets(this);
// Objects that shrink to avoid floats normally use available line width when computing containing block width. However
// in the case of relative positioning using percentages, we can't do this. The offset should always be resolved using the
// available width of the containing block. Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
// call availableWidth on our containing block.
if (!style().left().isAuto()) {
if (!style().right().isAuto() && !containingBlock()->style().isLeftToRightDirection())
offset.setWidth(-valueForLength(style().right(), !style().right().isFixed() ? containingBlock()->availableWidth() : LayoutUnit()));
else
offset.expand(valueForLength(style().left(), !style().left().isFixed() ? containingBlock()->availableWidth() : LayoutUnit()), 0);
} else if (!style().right().isAuto()) {
offset.expand(-valueForLength(style().right(), !style().right().isFixed() ? containingBlock()->availableWidth() : LayoutUnit()), 0);
}
// If the containing block of a relatively positioned element does not
// specify a height, a percentage top or bottom offset should be resolved as
// auto. An exception to this is if the containing block has the WinIE quirk
// where <html> and <body> assume the size of the viewport. In this case,
// calculate the percent offset based on this height.
// See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
if (!style().top().isAuto()
&& (!style().top().isPercentOrCalculated()
|| !containingBlock()->hasAutoHeightOrContainingBlockWithAutoHeight()
|| containingBlock()->stretchesToViewport()))
offset.expand(0, valueForLength(style().top(), !style().top().isFixed() ? containingBlock()->availableHeight() : LayoutUnit()));
else if (!style().bottom().isAuto()
&& (!style().bottom().isPercentOrCalculated()
|| !containingBlock()->hasAutoHeightOrContainingBlockWithAutoHeight()
|| containingBlock()->stretchesToViewport()))
offset.expand(0, -valueForLength(style().bottom(), !style().bottom().isFixed() ? containingBlock()->availableHeight() : LayoutUnit()));
return offset;
}
LayoutPoint RenderBoxModelObject::adjustedPositionRelativeToOffsetParent(const LayoutPoint& startPoint) const
{
// If the element is the HTML body element or doesn't have a parent
// return 0 and stop this algorithm.
if (isBody() || !parent())
return LayoutPoint();
LayoutPoint referencePoint = startPoint;
// If the offsetParent of the element is null, or is the HTML body element,
// return the distance between the canvas origin and the left border edge
// of the element and stop this algorithm.
if (const RenderBoxModelObject* offsetParent = this->offsetParent()) {
if (is<RenderBox>(*offsetParent) && !offsetParent->isBody() && !is<RenderTable>(*offsetParent))
referencePoint.move(-downcast<RenderBox>(*offsetParent).borderLeft(), -downcast<RenderBox>(*offsetParent).borderTop());
if (!isOutOfFlowPositioned() || flowThreadContainingBlock()) {
if (isRelPositioned())
referencePoint.move(relativePositionOffset());
else if (isStickyPositioned())
referencePoint.move(stickyPositionOffset());
// CSS regions specification says that region flows should return the body element as their offsetParent.
// Since we will bypass the body’s renderer anyway, just end the loop if we encounter a region flow (named flow thread).
// See http://dev.w3.org/csswg/css-regions/#cssomview-offset-attributes
auto* ancestor = parent();
while (ancestor != offsetParent && !is<RenderNamedFlowThread>(*ancestor)) {
// FIXME: What are we supposed to do inside SVG content?
if (is<RenderMultiColumnFlowThread>(*ancestor)) {
// We need to apply a translation based off what region we are inside.
RenderRegion* region = downcast<RenderMultiColumnFlowThread>(*ancestor).physicalTranslationFromFlowToRegion(referencePoint);
if (region)
referencePoint.moveBy(region->topLeftLocation());
} else if (!isOutOfFlowPositioned()) {
if (is<RenderBox>(*ancestor) && !is<RenderTableRow>(*ancestor))
referencePoint.moveBy(downcast<RenderBox>(*ancestor).topLeftLocation());
}
ancestor = ancestor->parent();
}
// Compute the offset position for elements inside named flow threads for which the offsetParent was the body.
// See https://bugs.webkit.org/show_bug.cgi?id=115899
if (is<RenderNamedFlowThread>(*ancestor))
referencePoint = downcast<RenderNamedFlowThread>(*ancestor).adjustedPositionRelativeToOffsetParent(*this, referencePoint);
else if (is<RenderBox>(*offsetParent) && offsetParent->isBody() && !offsetParent->isPositioned())
referencePoint.moveBy(downcast<RenderBox>(*offsetParent).topLeftLocation());
}
}
return referencePoint;
}
void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& constrainingRect) const
{
constraints.setConstrainingRectAtLastLayout(constrainingRect);
RenderBlock* containingBlock = this->containingBlock();
RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf);
RenderBox& enclosingClippingBox = enclosingClippingLayer ? downcast<RenderBox>(enclosingClippingLayer->renderer()) : view();
LayoutRect containerContentRect;
if (!enclosingClippingLayer || (containingBlock != &enclosingClippingBox))
containerContentRect = containingBlock->contentBoxRect();
else {
containerContentRect = containingBlock->layoutOverflowRect();
LayoutPoint containerLocation = containerContentRect.location() + LayoutPoint(containingBlock->borderLeft() + containingBlock->paddingLeft(),
containingBlock->borderTop() + containingBlock->paddingTop());
containerContentRect.setLocation(containerLocation);
}
LayoutUnit maxWidth = containingBlock->availableLogicalWidth();
// Sticky positioned element ignore any override logical width on the containing block (as they don't call
// containingBlockLogicalWidthForContent). It's unclear whether this is totally fine.
LayoutBoxExtent minMargin(minimumValueForLength(style().marginTop(), maxWidth),
minimumValueForLength(style().marginRight(), maxWidth),
minimumValueForLength(style().marginBottom(), maxWidth),
minimumValueForLength(style().marginLeft(), maxWidth));
// Compute the container-relative area within which the sticky element is allowed to move.
containerContentRect.contract(minMargin);
// Finally compute container rect relative to the scrolling ancestor.
FloatRect containerRectRelativeToScrollingAncestor = containingBlock->localToContainerQuad(FloatRect(containerContentRect), &enclosingClippingBox).boundingBox();
if (enclosingClippingLayer) {
FloatPoint containerLocationRelativeToScrollingAncestor = containerRectRelativeToScrollingAncestor.location() -
FloatSize(enclosingClippingBox.borderLeft() + enclosingClippingBox.paddingLeft(),
enclosingClippingBox.borderTop() + enclosingClippingBox.paddingTop());
if (&enclosingClippingBox != containingBlock)
containerLocationRelativeToScrollingAncestor += enclosingClippingLayer->scrollOffset();
containerRectRelativeToScrollingAncestor.setLocation(containerLocationRelativeToScrollingAncestor);
}
constraints.setContainingBlockRect(containerRectRelativeToScrollingAncestor);
// Now compute the sticky box rect, also relative to the scrolling ancestor.
LayoutRect stickyBoxRect = frameRectForStickyPositioning();
LayoutRect flippedStickyBoxRect = stickyBoxRect;
containingBlock->flipForWritingMode(flippedStickyBoxRect);
FloatRect stickyBoxRelativeToScrollingAnecstor = flippedStickyBoxRect;
// FIXME: sucks to call localToContainerQuad again, but we can't just offset from the previously computed rect if there are transforms.
// Map to the view to avoid including page scale factor.
FloatPoint stickyLocationRelativeToScrollingAncestor = flippedStickyBoxRect.location() + containingBlock->localToContainerQuad(FloatRect(FloatPoint(), containingBlock->size()), &enclosingClippingBox).boundingBox().location();
if (enclosingClippingLayer) {
stickyLocationRelativeToScrollingAncestor -= FloatSize(enclosingClippingBox.borderLeft() + enclosingClippingBox.paddingLeft(),
enclosingClippingBox.borderTop() + enclosingClippingBox.paddingTop());
if (&enclosingClippingBox != containingBlock)
stickyLocationRelativeToScrollingAncestor += enclosingClippingLayer->scrollOffset();
}
// FIXME: For now, assume that |this| is not transformed.
stickyBoxRelativeToScrollingAnecstor.setLocation(stickyLocationRelativeToScrollingAncestor);
constraints.setStickyBoxRect(stickyBoxRelativeToScrollingAnecstor);
if (!style().left().isAuto()) {
constraints.setLeftOffset(valueForLength(style().left(), constrainingRect.width()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
}
if (!style().right().isAuto()) {
constraints.setRightOffset(valueForLength(style().right(), constrainingRect.width()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
}
if (!style().top().isAuto()) {
constraints.setTopOffset(valueForLength(style().top(), constrainingRect.height()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
}
if (!style().bottom().isAuto()) {
constraints.setBottomOffset(valueForLength(style().bottom(), constrainingRect.height()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
}
}
FloatRect RenderBoxModelObject::constrainingRectForStickyPosition() const
{
RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf);
if (enclosingClippingLayer) {
RenderBox& enclosingClippingBox = downcast<RenderBox>(enclosingClippingLayer->renderer());
LayoutRect clipRect = enclosingClippingBox.overflowClipRect(LayoutPoint(), 0); // FIXME: make this work in regions.
clipRect.contract(LayoutSize(enclosingClippingBox.paddingLeft() + enclosingClippingBox.paddingRight(),
enclosingClippingBox.paddingTop() + enclosingClippingBox.paddingBottom()));
FloatRect constrainingRect = enclosingClippingBox.localToContainerQuad(FloatRect(clipRect), &view()).boundingBox();
FloatPoint scrollOffset = FloatPoint() + enclosingClippingLayer->scrollOffset();
constrainingRect.setLocation(scrollOffset);
return constrainingRect;
}
return view().frameView().viewportConstrainedVisibleContentRect();
}
LayoutSize RenderBoxModelObject::stickyPositionOffset() const
{
ASSERT(hasLayer());
FloatRect constrainingRect = constrainingRectForStickyPosition();
StickyPositionViewportConstraints constraints;
computeStickyPositionConstraints(constraints, constrainingRect);
// The sticky offset is physical, so we can just return the delta computed in absolute coords (though it may be wrong with transforms).
return LayoutSize(constraints.computeStickyOffset(constrainingRect));
}
LayoutSize RenderBoxModelObject::offsetForInFlowPosition() const
{
if (isRelPositioned())
return relativePositionOffset();
if (isStickyPositioned())
return stickyPositionOffset();
return LayoutSize();
}
LayoutUnit RenderBoxModelObject::offsetLeft() const
{
// Note that RenderInline and RenderBox override this to pass a different
// startPoint to adjustedPositionRelativeToOffsetParent.
return adjustedPositionRelativeToOffsetParent(LayoutPoint()).x();
}
LayoutUnit RenderBoxModelObject::offsetTop() const
{
// Note that RenderInline and RenderBox override this to pass a different
// startPoint to adjustedPositionRelativeToOffsetParent.
return adjustedPositionRelativeToOffsetParent(LayoutPoint()).y();
}
LayoutUnit RenderBoxModelObject::computedCSSPadding(const Length& padding) const
{
LayoutUnit w = 0;
if (padding.isPercentOrCalculated())
w = containingBlockLogicalWidthForContent();
return minimumValueForLength(padding, w);
}
RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
{
RoundedRect border = style().getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
if (box && (box->nextLineBox() || box->prevLineBox())) {
RoundedRect segmentBorder = style().getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), includeLogicalLeftEdge, includeLogicalRightEdge);
border.setRadii(segmentBorder.radii());
}
return border;
}
void RenderBoxModelObject::clipRoundedInnerRect(GraphicsContext& context, const FloatRect& rect, const FloatRoundedRect& clipRect)
{
if (clipRect.isRenderable())
context.clipRoundedRect(clipRect);
else {
// We create a rounded rect for each of the corners and clip it, while making sure we clip opposing corners together.
if (!clipRect.radii().topLeft().isEmpty() || !clipRect.radii().bottomRight().isEmpty()) {
FloatRect topCorner(clipRect.rect().x(), clipRect.rect().y(), rect.maxX() - clipRect.rect().x(), rect.maxY() - clipRect.rect().y());
FloatRoundedRect::Radii topCornerRadii;
topCornerRadii.setTopLeft(clipRect.radii().topLeft());
context.clipRoundedRect(FloatRoundedRect(topCorner, topCornerRadii));
FloatRect bottomCorner(rect.x(), rect.y(), clipRect.rect().maxX() - rect.x(), clipRect.rect().maxY() - rect.y());
FloatRoundedRect::Radii bottomCornerRadii;
bottomCornerRadii.setBottomRight(clipRect.radii().bottomRight());
context.clipRoundedRect(FloatRoundedRect(bottomCorner, bottomCornerRadii));
}
if (!clipRect.radii().topRight().isEmpty() || !clipRect.radii().bottomLeft().isEmpty()) {
FloatRect topCorner(rect.x(), clipRect.rect().y(), clipRect.rect().maxX() - rect.x(), rect.maxY() - clipRect.rect().y());
FloatRoundedRect::Radii topCornerRadii;
topCornerRadii.setTopRight(clipRect.radii().topRight());
context.clipRoundedRect(FloatRoundedRect(topCorner, topCornerRadii));
FloatRect bottomCorner(clipRect.rect().x(), rect.y(), rect.maxX() - clipRect.rect().x(), clipRect.rect().maxY() - rect.y());
FloatRoundedRect::Radii bottomCornerRadii;
bottomCornerRadii.setBottomLeft(clipRect.radii().bottomLeft());
context.clipRoundedRect(FloatRoundedRect(bottomCorner, bottomCornerRadii));
}
}
}
static LayoutRect shrinkRectByOneDevicePixel(const GraphicsContext& context, const LayoutRect& rect, float devicePixelRatio)
{
LayoutRect shrunkRect = rect;
AffineTransform transform = context.getCTM();
shrunkRect.inflateX(-ceilToDevicePixel(LayoutUnit::fromPixel(1) / transform.xScale(), devicePixelRatio));
shrunkRect.inflateY(-ceilToDevicePixel(LayoutUnit::fromPixel(1) / transform.yScale(), devicePixelRatio));
return shrunkRect;
}
LayoutRect RenderBoxModelObject::borderInnerRectAdjustedForBleedAvoidance(const GraphicsContext& context, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance) const
{
if (bleedAvoidance != BackgroundBleedBackgroundOverBorder)
return rect;
// We shrink the rectangle by one device pixel on each side to make it fully overlap the anti-aliased background border
return shrinkRectByOneDevicePixel(context, rect, document().deviceScaleFactor());
}
RoundedRect RenderBoxModelObject::backgroundRoundedRectAdjustedForBleedAvoidance(const GraphicsContext& context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
{
if (bleedAvoidance == BackgroundBleedShrinkBackground) {
// We shrink the rectangle by one device pixel on each side because the bleed is one pixel maximum.
return getBackgroundRoundedRect(shrinkRectByOneDevicePixel(context, borderRect, document().deviceScaleFactor()), box, boxSize.width(), boxSize.height(),
includeLogicalLeftEdge, includeLogicalRightEdge);
}
if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
return style().getRoundedInnerBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
return getBackgroundRoundedRect(borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge);
}
static void applyBoxShadowForBackground(GraphicsContext& context, RenderStyle* style)
{
const ShadowData* boxShadow = style->boxShadow();
while (boxShadow->style() != Normal)
boxShadow = boxShadow->next();
FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
if (!boxShadow->isWebkitBoxShadow())
context.setShadow(shadowOffset, boxShadow->radius(), boxShadow->color());
else
context.setLegacyShadow(shadowOffset, boxShadow->radius(), boxShadow->color());
}
InterpolationQuality RenderBoxModelObject::chooseInterpolationQuality(GraphicsContext& context, Image& image, const void* layer, const LayoutSize& size)
{
return view().imageQualityController().chooseInterpolationQuality(context, this, image, layer, size);
}
void RenderBoxModelObject::paintMaskForTextFillBox(ImageBuffer* maskImage, const IntRect& maskRect, InlineFlowBox* box, const LayoutRect& scrolledPaintRect)
{
GraphicsContext& maskImageContext = maskImage->context();
maskImageContext.translate(-maskRect.x(), -maskRect.y());
// Now add the text to the clip. We do this by painting using a special paint phase that signals to
// InlineTextBoxes that they should just add their contents to the clip.
PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, PaintBehaviorForceBlackText);
if (box) {
const RootInlineBox& rootBox = box->root();
box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), rootBox.lineTop(), rootBox.lineBottom());
} else if (isRenderNamedFlowFragmentContainer()) {
RenderNamedFlowFragment& region = *downcast<RenderBlockFlow>(*this).renderNamedFlowFragment();
if (region.isValid())
region.flowThread()->layer()->paintNamedFlowThreadInsideRegion(maskImageContext, ®ion, maskRect, maskRect.location(), PaintBehaviorForceBlackText, RenderLayer::PaintLayerTemporaryClipRects);
} else {
LayoutSize localOffset = is<RenderBox>(*this) ? downcast<RenderBox>(*this).locationOffset() : LayoutSize();
paint(info, scrolledPaintRect.location() - localOffset);
}
}
void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage)
{
GraphicsContext& context = paintInfo.context();
if (context.paintingDisabled() || rect.isEmpty())
return;
bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
bool hasRoundedBorder = style().hasBorderRadius() && (includeLeftEdge || includeRightEdge);
bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
bool isBorderFill = bgLayer->clip() == BorderFillBox;
bool isRoot = this->isDocumentElementRenderer();
Color bgColor = color;
StyleImage* bgImage = bgLayer->image();
bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style().effectiveZoom());
bool forceBackgroundToWhite = false;
if (document().printing()) {
if (style().printColorAdjust() == PrintColorAdjustEconomy)
forceBackgroundToWhite = true;
if (frame().settings().shouldPrintBackgrounds())
forceBackgroundToWhite = false;
}
// When printing backgrounds is disabled or using economy mode,
// change existing background colors and images to a solid white background.
// If there's no bg color or image, leave it untouched to avoid affecting transparency.
// We don't try to avoid loading the background images, because this style flag is only set
// when printing, and at that point we've already loaded the background images anyway. (To avoid
// loading the background images we'd have to do this check when applying styles rather than
// while rendering.)
if (forceBackgroundToWhite) {
// Note that we can't reuse this variable below because the bgColor might be changed
bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha();
if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
bgColor = Color::white;
shouldPaintBackgroundImage = false;
}
}
bool baseBgColorOnly = (baseBgColorUsage == BaseBackgroundColorOnly);
if (baseBgColorOnly && (!isRoot || bgLayer->next() || (bgColor.isValid() && !bgColor.hasAlpha())))
return;
bool colorVisible = bgColor.isValid() && bgColor.alpha();
float deviceScaleFactor = document().deviceScaleFactor();
FloatRect pixelSnappedRect = snapRectToDevicePixels(rect, deviceScaleFactor);
// Fast path for drawing simple color backgrounds.
if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
if (!colorVisible)
return;
bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(rect.location(), bleedAvoidance, box);
GraphicsContextStateSaver shadowStateSaver(context, boxShadowShouldBeAppliedToBackground);
if (boxShadowShouldBeAppliedToBackground)
applyBoxShadowForBackground(context, &style());
if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
FloatRoundedRect pixelSnappedBorder = backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize,
includeLeftEdge, includeRightEdge).pixelSnappedRoundedRectForPainting(deviceScaleFactor);
if (pixelSnappedBorder.isRenderable())
context.fillRoundedRect(pixelSnappedBorder, bgColor);
else {
context.save();
clipRoundedInnerRect(context, pixelSnappedRect, pixelSnappedBorder);
context.fillRect(pixelSnappedBorder.rect(), bgColor);
context.restore();
}
} else
context.fillRect(pixelSnappedRect, bgColor);
return;
}
// BorderFillBox radius clipping is taken care of by BackgroundBleedUseTransparencyLayer
bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidance == BackgroundBleedUseTransparencyLayer);
GraphicsContextStateSaver clipToBorderStateSaver(context, clipToBorderRadius);
if (clipToBorderRadius) {
RoundedRect border = isBorderFill ? backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge) : getBackgroundRoundedRect(rect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
// Clip to the padding or content boxes as necessary.
if (bgLayer->clip() == ContentFillBox) {
border = style().getRoundedInnerBorderFor(border.rect(),
paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), includeLeftEdge, includeRightEdge);
} else if (bgLayer->clip() == PaddingFillBox)
border = style().getRoundedInnerBorderFor(border.rect(), includeLeftEdge, includeRightEdge);
clipRoundedInnerRect(context, pixelSnappedRect, border.pixelSnappedRoundedRectForPainting(deviceScaleFactor));
}
LayoutUnit bLeft = includeLeftEdge ? borderLeft() : LayoutUnit::fromPixel(0);
LayoutUnit bRight = includeRightEdge ? borderRight() : LayoutUnit::fromPixel(0);
LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : LayoutUnit();
LayoutUnit pRight = includeRightEdge ? paddingRight() : LayoutUnit();
GraphicsContextStateSaver clipWithScrollingStateSaver(context, clippedWithLocalScrolling);
LayoutRect scrolledPaintRect = rect;
if (clippedWithLocalScrolling) {
// Clip to the overflow area.
auto& thisBox = downcast<RenderBox>(*this);
context.clip(thisBox.overflowClipRect(rect.location(), currentRenderNamedFlowFragment()));
// Adjust the paint rect to reflect a scrolled content box with borders at the ends.
IntSize offset = thisBox.scrolledContentOffset();
scrolledPaintRect.move(-offset);
scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
}
GraphicsContextStateSaver backgroundClipStateSaver(context, false);
std::unique_ptr<ImageBuffer> maskImage;
IntRect maskRect;
if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
// Clip to the padding or content boxes as necessary.
if (!clipToBorderRadius) {
bool includePadding = bgLayer->clip() == ContentFillBox;
LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : LayoutUnit()),
scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : LayoutUnit()),
scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : LayoutUnit()),
scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : LayoutUnit()));
backgroundClipStateSaver.save();
context.clip(clipRect);
}
} else if (bgLayer->clip() == TextFillBox) {
// We have to draw our text into a mask that can then be used to clip background drawing.
// First figure out how big the mask has to be. It should be no bigger than what we need
// to actually render, so we should intersect the dirty rect with the border box of the background.
maskRect = snappedIntRect(rect);
maskRect.intersect(snappedIntRect(paintInfo.rect));
// Now create the mask.
maskImage = context.createCompatibleBuffer(maskRect.size());
if (!maskImage)
return;
paintMaskForTextFillBox(maskImage.get(), maskRect, box, scrolledPaintRect);
// The mask has been created. Now we just need to clip to it.
backgroundClipStateSaver.save();
context.clip(maskRect);
context.beginTransparencyLayer(1);
}
// Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
// no background in the child document should show the parent's background.
bool isOpaqueRoot = false;
if (isRoot) {
isOpaqueRoot = true;
if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255)) {
HTMLFrameOwnerElement* ownerElement = document().ownerElement();
if (ownerElement) {
if (!ownerElement->hasTagName(frameTag)) {
// Locate the <body> element using the DOM. This is easier than trying
// to crawl around a render tree with potential :before/:after content and
// anonymous blocks created by inline <body> tags etc. We can locate the <body>
// render object very easily via the DOM.
if (HTMLElement* body = document().bodyOrFrameset()) {
// Can't scroll a frameset document anyway.
isOpaqueRoot = is<HTMLFrameSetElement>(*body);
} else {
// SVG documents and XML documents with SVG root nodes are transparent.
isOpaqueRoot = !document().hasSVGRootNode();
}
}
} else
isOpaqueRoot = !view().frameView().isTransparent();
}
view().frameView().setContentIsOpaque(isOpaqueRoot);
}
// Paint the color first underneath all images, culled if background image occludes it.
// FIXME: In the bgLayer->hasFiniteBounds() case, we could improve the culling test
// by verifying whether the background image covers the entire layout rect.
if (!bgLayer->next()) {
LayoutRect backgroundRect(scrolledPaintRect);
bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(rect.location(), bleedAvoidance, box);
if (boxShadowShouldBeAppliedToBackground || !shouldPaintBackgroundImage || !bgLayer->hasOpaqueImage(*this) || !bgLayer->hasRepeatXY()) {
if (!boxShadowShouldBeAppliedToBackground)
backgroundRect.intersect(paintInfo.rect);
// If we have an alpha and we are painting the root element, blend with the base background color.
Color baseColor;
bool shouldClearBackground = false;
if ((baseBgColorUsage != BaseBackgroundColorSkip) && isOpaqueRoot) {
baseColor = view().frameView().baseBackgroundColor();
if (!baseColor.alpha())
shouldClearBackground = true;
}
GraphicsContextStateSaver shadowStateSaver(context, boxShadowShouldBeAppliedToBackground);
if (boxShadowShouldBeAppliedToBackground)
applyBoxShadowForBackground(context, &style());
FloatRect backgroundRectForPainting = snapRectToDevicePixels(backgroundRect, deviceScaleFactor);
if (baseColor.alpha()) {
if (!baseBgColorOnly && bgColor.alpha())
baseColor = baseColor.blend(bgColor);
context.fillRect(backgroundRectForPainting, baseColor, CompositeCopy);
} else if (!baseBgColorOnly && bgColor.alpha()) {
CompositeOperator operation = shouldClearBackground ? CompositeCopy : context.compositeOperation();
context.fillRect(backgroundRectForPainting, bgColor, operation);
} else if (shouldClearBackground)
context.clearRect(backgroundRectForPainting);
}
}
// no progressive loading of the background image
if (!baseBgColorOnly && shouldPaintBackgroundImage) {
BackgroundImageGeometry geometry = calculateBackgroundImageGeometry(paintInfo.paintContainer, *bgLayer, rect.location(), scrolledPaintRect, backgroundObject);
geometry.clip(LayoutRect(pixelSnappedRect));
RefPtr<Image> image;
if (!geometry.destRect().isEmpty() && (image = bgImage->image(backgroundObject ? backgroundObject : this, geometry.tileSize()))) {
CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
context.setDrawLuminanceMask(bgLayer->maskSourceType() == MaskLuminance);
InterpolationQuality interpolation = chooseInterpolationQuality(context, *image, bgLayer, geometry.tileSize());
context.drawTiledImage(*image, geometry.destRect(), toLayoutPoint(geometry.relativePhase()), geometry.tileSize(), geometry.spaceSize(), ImagePaintingOptions(compositeOp, bgLayer->blendMode(), ImageOrientationDescription(), interpolation));
}
}
if (maskImage && bgLayer->clip() == TextFillBox) {
context.drawConsumingImageBuffer(WTFMove(maskImage), maskRect, CompositeDestinationIn);
context.endTransparencyLayer();
}
}
static inline LayoutUnit resolveWidthForRatio(LayoutUnit height, const LayoutSize& intrinsicRatio)
{
return height * intrinsicRatio.width() / intrinsicRatio.height();
}
static inline LayoutUnit resolveHeightForRatio(LayoutUnit width, const LayoutSize& intrinsicRatio)
{
return width * intrinsicRatio.height() / intrinsicRatio.width();
}
static inline LayoutSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const LayoutSize& size, const LayoutSize& intrinsicRatio, LayoutUnit useWidth, LayoutUnit useHeight)
{
if (intrinsicRatio.isEmpty()) {
if (useWidth)
return LayoutSize(useWidth, size.height());
return LayoutSize(size.width(), useHeight);
}
if (useWidth)
return LayoutSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
return LayoutSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
}
static inline LayoutSize resolveAgainstIntrinsicRatio(const LayoutSize& size, const LayoutSize& intrinsicRatio)
{
// Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height())
// "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area.
LayoutUnit solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
LayoutUnit solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
if (solutionWidth <= size.width()) {
if (solutionHeight <= size.height()) {
// If both solutions fit, choose the one covering the larger area.
LayoutUnit areaOne = solutionWidth * size.height();
LayoutUnit areaTwo = size.width() * solutionHeight;
if (areaOne < areaTwo)
return LayoutSize(size.width(), solutionHeight);
return LayoutSize(solutionWidth, size.height());
}
// Only the first solution fits.
return LayoutSize(solutionWidth, size.height());
}
// Only the second solution fits, assert that.
ASSERT(solutionHeight <= size.height());
return LayoutSize(size.width(), solutionHeight);
}
LayoutSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const LayoutSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const
{
// A generated image without a fixed size, will always return the container size as intrinsic size.
if (image->isGeneratedImage() && image->usesImageContainerSize())
return LayoutSize(positioningAreaSize.width(), positioningAreaSize.height());
Length intrinsicWidth;
Length intrinsicHeight;
FloatSize intrinsicRatio;
image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
ASSERT(!intrinsicWidth.isPercentOrCalculated());
ASSERT(!intrinsicHeight.isPercentOrCalculated());
LayoutSize resolvedSize(intrinsicWidth.value(), intrinsicHeight.value());
LayoutSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0);
if (shouldScaleOrNot == ScaleByEffectiveZoom)
resolvedSize.scale(style().effectiveZoom());
resolvedSize.clampToMinimumSize(minimumSize);
if (!resolvedSize.isEmpty())
return resolvedSize;
// If the image has one of either an intrinsic width or an intrinsic height:
// * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio.
// * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that
// establishes the coordinate system for the 'background-position' property.
if (resolvedSize.width() > 0 || resolvedSize.height() > 0)
return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, LayoutSize(intrinsicRatio), resolvedSize.width(), resolvedSize.height());
// If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the
// largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that
// establishes the coordinate system for the 'background-position' property.
if (!intrinsicRatio.isEmpty())
return resolveAgainstIntrinsicRatio(positioningAreaSize, LayoutSize(intrinsicRatio));
// If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that
// establishes the coordinate system for the 'background-position' property.
return positioningAreaSize;
}
LayoutSize RenderBoxModelObject::calculateFillTileSize(const FillLayer& fillLayer, const LayoutSize& positioningAreaSize) const
{
StyleImage* image = fillLayer.image();
EFillSizeType type = fillLayer.size().type;
LayoutSize imageIntrinsicSize;
if (image) {
imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
} else
imageIntrinsicSize = positioningAreaSize;
switch (type) {
case SizeLength: {
LayoutSize tileSize = positioningAreaSize;
Length layerWidth = fillLayer.size().size.width();
Length layerHeight = fillLayer.size().size.height();
if (layerWidth.isFixed())
tileSize.setWidth(layerWidth.value());
else if (layerWidth.isPercentOrCalculated())
tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width()));
if (layerHeight.isFixed())
tileSize.setHeight(layerHeight.value());
else if (layerHeight.isPercentOrCalculated())
tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height()));
// If one of the values is auto we have to use the appropriate
// scale to maintain our aspect ratio.
if (layerWidth.isAuto() && !layerHeight.isAuto()) {
if (imageIntrinsicSize.height())
tileSize.setWidth(imageIntrinsicSize.width() * tileSize.height() / imageIntrinsicSize.height());
} else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
if (imageIntrinsicSize.width())
tileSize.setHeight(imageIntrinsicSize.height() * tileSize.width() / imageIntrinsicSize.width());
} else if (layerWidth.isAuto() && layerHeight.isAuto()) {
// If both width and height are auto, use the image's intrinsic size.
tileSize = imageIntrinsicSize;
}
tileSize.clampNegativeToZero();
return tileSize;
}
case SizeNone: {
// If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
if (!imageIntrinsicSize.isEmpty())
return imageIntrinsicSize;
// If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
type = Contain;
}
FALLTHROUGH;
case Contain:
case Cover: {
// Scale computation needs higher precision than what LayoutUnit can offer.
FloatSize localImageIntrinsicSize = imageIntrinsicSize;
FloatSize localPositioningAreaSize = positioningAreaSize;
float horizontalScaleFactor = localImageIntrinsicSize.width() ? (localPositioningAreaSize.width() / localImageIntrinsicSize.width()) : 1;