-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRenderBoxModelObject.cpp
2801 lines (2361 loc) · 122 KB
/
RenderBoxModelObject.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 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 "FilterOperations.h"
#include "GraphicsContext.h"
#include "HTMLFrameOwnerElement.h"
#include "HTMLNames.h"
#include "ImageBuffer.h"
#include "Page.h"
#include "Path.h"
#include "RenderBlock.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderView.h"
#include "ScrollingConstraints.h"
#include "Settings.h"
#include "TransformState.h"
#include <wtf/CurrentTime.h>
#if USE(ACCELERATED_COMPOSITING)
#include "RenderLayerBacking.h"
#include "RenderLayerCompositor.h"
#endif
using namespace std;
namespace WebCore {
using namespace HTMLNames;
static const double cInterpolationCutoff = 800. * 800.;
static const double cLowQualityTimeThreshold = 0.500; // 500 ms
typedef HashMap<const void*, LayoutSize> LayerSizeMap;
typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
// 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 = 0;
// This HashMap is similar to the continuation map, but connects first-letter
// renderers to their remaining text fragments.
typedef HashMap<const RenderBoxModelObject*, RenderObject*> FirstLetterRemainingTextMap;
static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
class ImageQualityController {
WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
public:
ImageQualityController();
bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const LayoutSize&);
void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
void objectDestroyed(RenderBoxModelObject*);
bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
private:
void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
void restartTimer();
ObjectLayerSizeMap m_objectLayerSizeMap;
Timer<ImageQualityController> m_timer;
bool m_animatedResizeIsActive;
};
ImageQualityController::ImageQualityController()
: m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
, m_animatedResizeIsActive(false)
{
}
void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
{
if (innerMap) {
innerMap->remove(layer);
if (innerMap->isEmpty())
objectDestroyed(object);
}
}
void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const LayoutSize& size)
{
if (innerMap)
innerMap->set(layer, size);
else {
LayerSizeMap newInnerMap;
newInnerMap.set(layer, size);
m_objectLayerSizeMap.set(object, newInnerMap);
}
}
void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
{
m_objectLayerSizeMap.remove(object);
if (m_objectLayerSizeMap.isEmpty()) {
m_animatedResizeIsActive = false;
m_timer.stop();
}
}
void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
{
if (m_animatedResizeIsActive) {
m_animatedResizeIsActive = false;
for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it)
it->key->repaint();
}
}
void ImageQualityController::restartTimer()
{
m_timer.startOneShot(cLowQualityTimeThreshold);
}
bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const LayoutSize& size)
{
// If the image is not a bitmap image, then none of this is relevant and we just paint at high
// quality.
if (!image || !image->isBitmapImage() || context->paintingDisabled())
return false;
if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
return true;
// Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
// is actually being scaled.
IntSize imageSize(image->width(), image->height());
// Look ourselves up in the hashtables.
ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->value : 0;
LayoutSize oldSize;
bool isFirstResize = true;
if (innerMap) {
LayerSizeMap::iterator j = innerMap->find(layer);
if (j != innerMap->end()) {
isFirstResize = false;
oldSize = j->value;
}
}
const AffineTransform& currentTransform = context->getCTM();
bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
if (!contextIsScaled && size == imageSize) {
// There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
removeLayer(object, innerMap, layer);
return false;
}
// There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
if (object->document()->page()->inLowQualityImageInterpolationMode()) {
double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
if (totalPixels > cInterpolationCutoff)
return true;
}
// If an animated resize is active, paint in low quality and kick the timer ahead.
if (m_animatedResizeIsActive) {
set(object, innerMap, layer, size);
restartTimer();
return true;
}
// If this is the first time resizing this image, or its size is the
// same as the last resize, draw at high res, but record the paint
// size and set the timer.
if (isFirstResize || oldSize == size) {
restartTimer();
set(object, innerMap, layer, size);
return false;
}
// If the timer is no longer active, draw at high quality and don't
// set the timer.
if (!m_timer.isActive()) {
removeLayer(object, innerMap, layer);
return false;
}
// This object has been resized to two different sizes while the timer
// is active, so draw at low quality, set the flag for animated resizes and
// the object to the list for high quality redraw.
set(object, innerMap, layer, size);
m_animatedResizeIsActive = true;
restartTimer();
return true;
}
static ImageQualityController* gImageQualityController = 0;
static ImageQualityController* imageQualityController()
{
if (!gImageQualityController)
gImageQualityController = new ImageQualityController;
return gImageQualityController;
}
void RenderBoxModelObject::setSelectionState(SelectionState state)
{
if (state == SelectionInside && selectionState() != SelectionNone)
return;
if ((state == SelectionStart && selectionState() == SelectionEnd)
|| (state == SelectionEnd && selectionState() == SelectionStart))
RenderObject::setSelectionState(SelectionBoth);
else
RenderObject::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);
}
#if USE(ACCELERATED_COMPOSITING)
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);
}
#endif
bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
{
return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
}
RenderBoxModelObject::RenderBoxModelObject(Node* node)
: RenderLayerModelObject(node)
{
}
RenderBoxModelObject::~RenderBoxModelObject()
{
if (gImageQualityController) {
gImageQualityController->objectDestroyed(this);
if (gImageQualityController->isEmpty()) {
delete gImageQualityController;
gImageQualityController = 0;
}
}
}
void RenderBoxModelObject::willBeDestroyed()
{
// A continuation of this RenderObject should be destroyed at subclasses.
ASSERT(!continuation());
if (isPositioned()) {
if (RenderView* view = this->view()) {
if (FrameView* frameView = view->frameView()) {
if (style()->hasViewportConstrainedPosition())
frameView->removeViewportConstrainedObject(this);
}
}
}
// 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(0);
RenderLayerModelObject::willBeDestroyed();
}
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.
RenderStyle* styleToUse = style();
setHasBoxDecorations(hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow());
setInline(styleToUse->isDisplayInlineType());
setRelPositioned(styleToUse->position() == RelativePosition);
setStickyPositioned(styleToUse->position() == StickyPosition);
setHorizontalWritingMode(styleToUse->isHorizontalWritingMode());
}
static LayoutSize accumulateInFlowPositionOffsets(const RenderObject* child)
{
if (!child->isAnonymousBlock() || !child->isInFlowPositioned())
return LayoutSize();
LayoutSize offset;
RenderObject* p = toRenderBlock(child)->inlineElementContinuation();
while (p && p->isRenderInline()) {
if (p->isInFlowPositioned()) {
RenderInline* renderInline = toRenderInline(p);
offset += renderInline->offsetForInFlowPosition();
}
p = p->parent();
}
return offset;
}
LayoutSize RenderBoxModelObject::relativePositionOffset() const
{
LayoutSize offset = accumulateInFlowPositionOffsets(this);
RenderBlock* containingBlock = this->containingBlock();
// 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(), containingBlock->availableWidth(), view()));
else
offset.expand(valueForLength(style()->left(), containingBlock->availableWidth(), view()), 0);
} else if (!style()->right().isAuto()) {
offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth(), view()), 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()
&& (!containingBlock->style()->height().isAuto()
|| !style()->top().isPercent()
|| containingBlock->stretchesToViewport()))
offset.expand(0, valueForLength(style()->top(), containingBlock->availableHeight(), view()));
else if (!style()->bottom().isAuto()
&& (!containingBlock->style()->height().isAuto()
|| !style()->bottom().isPercent()
|| containingBlock->stretchesToViewport()))
offset.expand(0, -valueForLength(style()->bottom(), containingBlock->availableHeight(), view()));
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;
referencePoint.move(parent()->offsetForColumns(referencePoint));
// 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 (offsetParent->isBox() && !offsetParent->isBody())
referencePoint.move(-toRenderBox(offsetParent)->borderLeft(), -toRenderBox(offsetParent)->borderTop());
if (!isOutOfFlowPositioned()) {
if (isRelPositioned())
referencePoint.move(relativePositionOffset());
else if (isStickyPositioned())
referencePoint.move(stickyPositionOffset());
const RenderObject* curr = parent();
while (curr != offsetParent) {
// FIXME: What are we supposed to do inside SVG content?
if (curr->isBox() && !curr->isTableRow())
referencePoint.moveBy(toRenderBox(curr)->topLeftLocation());
referencePoint.move(curr->parent()->offsetForColumns(referencePoint));
curr = curr->parent();
}
if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned())
referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
}
}
return referencePoint;
}
void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& viewportRect) const
{
RenderBlock* containingBlock = this->containingBlock();
LayoutRect containerContentRect = containingBlock->contentBoxRect();
LayoutUnit minLeftMargin = minimumValueForLength(style()->marginLeft(), containingBlock->availableLogicalWidth(), view());
LayoutUnit minTopMargin = minimumValueForLength(style()->marginTop(), containingBlock->availableLogicalWidth(), view());
LayoutUnit minRightMargin = minimumValueForLength(style()->marginRight(), containingBlock->availableLogicalWidth(), view());
LayoutUnit minBottomMargin = minimumValueForLength(style()->marginBottom(), containingBlock->availableLogicalWidth(), view());
// Compute the container-relative area within which the sticky element is allowed to move.
containerContentRect.move(minLeftMargin, minTopMargin);
containerContentRect.contract(minLeftMargin + minRightMargin, minTopMargin + minBottomMargin);
constraints.setAbsoluteContainingBlockRect(containingBlock->localToAbsoluteQuad(FloatRect(containerContentRect), SnapOffsetForTransforms).boundingBox());
LayoutRect stickyBoxRect = frameRectForStickyPositioning();
LayoutRect flippedStickyBoxRect = stickyBoxRect;
containingBlock->flipForWritingMode(flippedStickyBoxRect);
LayoutPoint stickyLocation = flippedStickyBoxRect.location();
// FIXME: sucks to call localToAbsolute again, but we can't just offset from the previously computed rect if there are transforms.
FloatRect absContainerFrame = containingBlock->localToAbsoluteQuad(FloatRect(FloatPoint(), containingBlock->size()), SnapOffsetForTransforms).boundingBox();
// We can't call localToAbsolute on |this| because that will recur. FIXME: For now, assume that |this| is not transformed.
FloatRect absoluteStickyBoxRect(absContainerFrame.location() + stickyLocation, flippedStickyBoxRect.size());
constraints.setAbsoluteStickyBoxRect(absoluteStickyBoxRect);
if (!style()->left().isAuto()) {
constraints.setLeftOffset(valueForLength(style()->left(), viewportRect.width(), view()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
}
if (!style()->right().isAuto()) {
constraints.setRightOffset(valueForLength(style()->right(), viewportRect.width(), view()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
}
if (!style()->top().isAuto()) {
constraints.setTopOffset(valueForLength(style()->top(), viewportRect.height(), view()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
}
if (!style()->bottom().isAuto()) {
constraints.setBottomOffset(valueForLength(style()->bottom(), viewportRect.height(), view()));
constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
}
}
LayoutSize RenderBoxModelObject::stickyPositionOffset() const
{
LayoutRect viewportRect = view()->frameView()->visibleContentRect();
StickyPositionViewportConstraints constraints;
computeStickyPositionConstraints(constraints, viewportRect);
// 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(viewportRect));
}
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();
}
int RenderBoxModelObject::pixelSnappedOffsetWidth() const
{
return snapSizeToPixel(offsetWidth(), offsetLeft());
}
int RenderBoxModelObject::pixelSnappedOffsetHeight() const
{
return snapSizeToPixel(offsetHeight(), offsetTop());
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingTop() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingTop();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingBottom() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingBottom();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingLeft() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingLeft();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingRight() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingRight();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingBefore() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingBefore();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingAfter() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingAfter();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingStart() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingStart();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
LayoutUnit RenderBoxModelObject::computedCSSPaddingEnd() const
{
LayoutUnit w = ZERO_LAYOUT_UNIT;
RenderView* renderView = 0;
Length padding = style()->paddingEnd();
if (padding.isPercent())
w = containingBlock()->availableLogicalWidth();
else if (padding.isViewportPercentage())
renderView = view();
return minimumValueForLength(padding, w, renderView);
}
RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
{
RenderView* renderView = view();
RoundedRect border = style()->getRoundedBorderFor(borderRect, renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
if (box && (box->nextLineBox() || box->prevLineBox())) {
RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
border.setRadii(segmentBorder.radii());
}
return border;
}
void RenderBoxModelObject::clipRoundedInnerRect(GraphicsContext * context, const LayoutRect& rect, const RoundedRect& clipRect)
{
if (clipRect.isRenderable())
context->addRoundedRectClip(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()) {
IntRect topCorner(clipRect.rect().x(), clipRect.rect().y(), rect.maxX() - clipRect.rect().x(), rect.maxY() - clipRect.rect().y());
RoundedRect::Radii topCornerRadii;
topCornerRadii.setTopLeft(clipRect.radii().topLeft());
context->addRoundedRectClip(RoundedRect(topCorner, topCornerRadii));
IntRect bottomCorner(rect.x(), rect.y(), clipRect.rect().maxX() - rect.x(), clipRect.rect().maxY() - rect.y());
RoundedRect::Radii bottomCornerRadii;
bottomCornerRadii.setBottomRight(clipRect.radii().bottomRight());
context->addRoundedRectClip(RoundedRect(bottomCorner, bottomCornerRadii));
}
if (!clipRect.radii().topRight().isEmpty() || !clipRect.radii().bottomLeft().isEmpty()) {
IntRect topCorner(rect.x(), clipRect.rect().y(), clipRect.rect().maxX() - rect.x(), rect.maxY() - clipRect.rect().y());
RoundedRect::Radii topCornerRadii;
topCornerRadii.setTopRight(clipRect.radii().topRight());
context->addRoundedRectClip(RoundedRect(topCorner, topCornerRadii));
IntRect bottomCorner(clipRect.rect().x(), rect.y(), rect.maxX() - clipRect.rect().x(), clipRect.rect().maxY() - rect.y());
RoundedRect::Radii bottomCornerRadii;
bottomCornerRadii.setBottomLeft(clipRect.radii().bottomLeft());
context->addRoundedRectClip(RoundedRect(bottomCorner, bottomCornerRadii));
}
}
}
static LayoutRect backgroundRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance)
{
if (bleedAvoidance != BackgroundBleedShrinkBackground)
return borderRect;
// We shrink the rectangle by one pixel on each side because the bleed is one pixel maximum.
AffineTransform transform = context->getCTM();
LayoutRect adjustedRect = borderRect;
adjustedRect.inflateX(-static_cast<LayoutUnit>(ceil(1 / transform.xScale())));
adjustedRect.inflateY(-static_cast<LayoutUnit>(ceil(1 / transform.yScale())));
return adjustedRect;
}
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->blur(), boxShadow->color(), style->colorSpace());
else
context->setLegacyShadow(shadowOffset, boxShadow->blur(), boxShadow->color(), style->colorSpace());
}
void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
{
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->isRoot();
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 (document()->settings() && document()->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 colorVisible = bgColor.isValid() && bgColor.alpha();
// Fast path for drawing simple color backgrounds.
if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
if (!colorVisible)
return;
bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
if (boxShadowShouldBeAppliedToBackground)
applyBoxShadowForBackground(context, style());
if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
context->fillRoundedRect(border, bgColor, style()->colorSpace());
} else
context->fillRect(pixelSnappedIntRect(rect), bgColor, style()->colorSpace());
return;
}
// BorderFillBox radius clipping is taken care of by BackgroundBleedUseTransparencyLayer
bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidance == BackgroundBleedUseTransparencyLayer);
GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
if (clipToBorderRadius) {
LayoutRect adjustedRect = isBorderFill ? backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance) : rect;
RoundedRect border = getBackgroundRoundedRect(adjustedRect, 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, rect, border);
}
int bLeft = includeLeftEdge ? borderLeft() : 0;
int bRight = includeRightEdge ? borderRight() : 0;
LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : ZERO_LAYOUT_UNIT;
LayoutUnit pRight = includeRightEdge ? paddingRight() : ZERO_LAYOUT_UNIT;
GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
LayoutRect scrolledPaintRect = rect;
if (clippedWithLocalScrolling) {
// Clip to the overflow area.
RenderBox* thisBox = toRenderBox(this);
context->clip(thisBox->overflowClipRect(rect.location(), paintInfo.renderRegion));
// 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);
OwnPtr<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 : ZERO_LAYOUT_UNIT),
scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : ZERO_LAYOUT_UNIT),
scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : ZERO_LAYOUT_UNIT),
scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : ZERO_LAYOUT_UNIT));
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 = pixelSnappedIntRect(rect);
maskRect.intersect(paintInfo.rect);
// Now create the mask.
maskImage = context->createCompatibleBuffer(maskRect.size());
if (!maskImage)
return;
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, true, 0, paintInfo.renderRegion, 0);
if (box) {
RootInlineBox* root = box->root();
box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
} else {
LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
paint(info, scrolledPaintRect.location() - localOffset);
}
// 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) && view()->frameView()) {
Element* 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.
HTMLElement* body = document()->body();
if (body) {
// Can't scroll a frameset document anyway.
isOpaqueRoot = body->hasLocalName(framesetTag);
}
#if ENABLE(SVG)
else {
// SVG documents and XML documents with SVG root nodes are transparent.
isOpaqueRoot = !document()->hasSVGRootNode();
}
#endif
}
} else
isOpaqueRoot = !view()->frameView()->isTransparent();
}
view()->frameView()->setContentIsOpaque(isOpaqueRoot);
}
// Paint the color first underneath all images.
if (!bgLayer->next()) {
IntRect backgroundRect(pixelSnappedIntRect(scrolledPaintRect));
bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
if (!boxShadowShouldBeAppliedToBackground)
backgroundRect.intersect(paintInfo.rect);
// If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
Color baseColor;
bool shouldClearBackground = false;
if (isOpaqueRoot) {
baseColor = view()->frameView()->baseBackgroundColor();
if (!baseColor.alpha())
shouldClearBackground = true;
}
GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
if (boxShadowShouldBeAppliedToBackground)
applyBoxShadowForBackground(context, style());
if (baseColor.alpha()) {
if (bgColor.alpha())
baseColor = baseColor.blend(bgColor);
context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
} else if (bgColor.alpha()) {
CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
} else if (shouldClearBackground)
context->clearRect(backgroundRect);
}
// no progressive loading of the background image
if (shouldPaintBackgroundImage) {
BackgroundImageGeometry geometry;
calculateBackgroundImageGeometry(bgLayer, scrolledPaintRect, geometry);
geometry.clip(paintInfo.rect);
if (!geometry.destRect().isEmpty()) {
CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
compositeOp, useLowQualityScaling);
}
}
if (bgLayer->clip() == TextFillBox) {
context->drawImageBuffer(maskImage.get(), ColorSpaceDeviceRGB, maskRect, CompositeDestinationIn);
context->endTransparencyLayer();
}
}
static inline int resolveWidthForRatio(int height, const FloatSize& intrinsicRatio)
{
return ceilf(height * intrinsicRatio.width() / intrinsicRatio.height());
}
static inline int resolveHeightForRatio(int width, const FloatSize& intrinsicRatio)
{
return ceilf(width * intrinsicRatio.height() / intrinsicRatio.width());
}
static inline IntSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const IntSize& size, const FloatSize& intrinsicRatio, int useWidth, int useHeight)
{
if (intrinsicRatio.isEmpty()) {
if (useWidth)
return IntSize(useWidth, size.height());
return IntSize(size.width(), useHeight);
}
if (useWidth)
return IntSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
return IntSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
}
static inline IntSize resolveAgainstIntrinsicRatio(const IntSize& size, const FloatSize& 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.
int solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
int solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
if (solutionWidth <= size.width()) {
if (solutionHeight <= size.height()) {
// If both solutions fit, choose the one covering the larger area.
int areaOne = solutionWidth * size.height();
int areaTwo = size.width() * solutionHeight;
if (areaOne < areaTwo)
return IntSize(size.width(), solutionHeight);
return IntSize(solutionWidth, size.height());
}
// Only the first solution fits.
return IntSize(solutionWidth, size.height());
}
// Only the second solution fits, assert that.
ASSERT(solutionHeight <= size.height());
return IntSize(size.width(), solutionHeight);
}
IntSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const IntSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const