forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsFlexContainerFrame.cpp
2409 lines (2096 loc) · 92.8 KB
/
nsFlexContainerFrame.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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code is subject to the terms of the Mozilla Public License
* version 2.0 (the "License"). You can obtain a copy of the License at
* http://mozilla.org/MPL/2.0/. */
/* rendering object for CSS "display: flex" */
#include "nsFlexContainerFrame.h"
#include "nsContentUtils.h"
#include "nsDisplayList.h"
#include "nsLayoutUtils.h"
#include "nsPresContext.h"
#include "nsStyleContext.h"
#include "prlog.h"
using namespace mozilla::css;
#ifdef PR_LOGGING
static PRLogModuleInfo*
GetFlexContainerLog()
{
static PRLogModuleInfo *sLog;
if (!sLog)
sLog = PR_NewLogModule("nsFlexContainerFrame");
return sLog;
}
#endif /* PR_LOGGING */
// XXXdholbert Some of this helper-stuff should be separated out into a general
// "LogicalAxisUtils.h" helper. Should that be a class, or a namespace (under
// what super-namespace?), or what?
// Helper enums
// ============
// Represents a physical orientation for an axis.
// The directional suffix indicates the direction in which the axis *grows*.
// So e.g. eAxis_LR means a horizontal left-to-right axis, whereas eAxis_BT
// means a vertical bottom-to-top axis.
// NOTE: The order here is important -- these values are used as indices into
// the static array 'kAxisOrientationToSidesMap', defined below.
enum AxisOrientationType {
eAxis_LR,
eAxis_RL,
eAxis_TB,
eAxis_BT,
eNumAxisOrientationTypes // For sizing arrays that use these values as indices
};
// Represents one or the other extreme of an axis (e.g. for the main axis, the
// main-start vs. main-end edge.
// NOTE: The order here is important -- these values are used as indices into
// the sub-arrays in 'kAxisOrientationToSidesMap', defined below.
enum AxisEdgeType {
eAxisEdge_Start,
eAxisEdge_End,
eNumAxisEdges // For sizing arrays that use these values as indices
};
// This array maps each axis orientation to a pair of corresponding
// [start, end] physical mozilla::css::Side values.
static const Side
kAxisOrientationToSidesMap[eNumAxisOrientationTypes][eNumAxisEdges] = {
{ eSideLeft, eSideRight }, // eAxis_LR
{ eSideRight, eSideLeft }, // eAxis_RL
{ eSideTop, eSideBottom }, // eAxis_TB
{ eSideBottom, eSideTop } // eAxis_BT
};
// Helper structs / classes / methods
// ==================================
// Indicates whether advancing along the given axis is equivalent to
// increasing our X or Y position (as opposed to decreasing it).
static inline bool
AxisGrowsInPositiveDirection(AxisOrientationType aAxis)
{
return eAxis_LR == aAxis || eAxis_TB == aAxis;
}
// Indicates whether the given axis is horizontal.
static inline bool
IsAxisHorizontal(AxisOrientationType aAxis)
{
return eAxis_LR == aAxis || eAxis_RL == aAxis;
}
// Given an AxisOrientationType, returns the "reverse" AxisOrientationType
// (in the same dimension, but the opposite direction)
static inline AxisOrientationType
GetReverseAxis(AxisOrientationType aAxis)
{
AxisOrientationType reversedAxis;
if (aAxis % 2 == 0) {
// even enum value. Add 1 to reverse.
reversedAxis = AxisOrientationType(aAxis + 1);
} else {
// odd enum value. Subtract 1 to reverse.
reversedAxis = AxisOrientationType(aAxis - 1);
}
// Check that we're still in the enum's valid range
MOZ_ASSERT(reversedAxis >= eAxis_LR &&
reversedAxis <= eAxis_BT);
return reversedAxis;
}
// Returns aFrame's computed value for 'height' or 'width' -- whichever is in
// the same dimension as aAxis.
static inline const nsStyleCoord&
GetSizePropertyForAxis(const nsIFrame* aFrame, AxisOrientationType aAxis)
{
const nsStylePosition* stylePos = aFrame->GetStylePosition();
return IsAxisHorizontal(aAxis) ?
stylePos->mWidth :
stylePos->mHeight;
}
static nscoord
MarginComponentForSide(const nsMargin& aMargin, Side aSide)
{
switch (aSide) {
case eSideLeft:
return aMargin.left;
case eSideRight:
return aMargin.right;
case eSideTop:
return aMargin.top;
case eSideBottom:
return aMargin.bottom;
}
NS_NOTREACHED("unexpected Side enum");
return aMargin.left; // have to return something
// (but something's busted if we got here)
}
static nscoord&
MarginComponentForSide(nsMargin& aMargin, Side aSide)
{
switch (aSide) {
case eSideLeft:
return aMargin.left;
case eSideRight:
return aMargin.right;
case eSideTop:
return aMargin.top;
case eSideBottom:
return aMargin.bottom;
}
NS_NOTREACHED("unexpected Side enum");
return aMargin.left; // have to return something
// (but something's busted if we got here)
}
// Encapsulates our flex container's main & cross axes.
NS_STACK_CLASS class FlexboxAxisTracker {
public:
FlexboxAxisTracker(nsFlexContainerFrame* aFlexContainerFrame);
// Accessors:
AxisOrientationType GetMainAxis() const { return mMainAxis; }
AxisOrientationType GetCrossAxis() const { return mCrossAxis; }
nscoord GetMainComponent(const nsSize& aSize) const {
return IsAxisHorizontal(mMainAxis) ?
aSize.width : aSize.height;
}
int32_t GetMainComponent(const nsIntSize& aIntSize) const {
return IsAxisHorizontal(mMainAxis) ?
aIntSize.width : aIntSize.height;
}
nscoord GetMainComponent(const nsHTMLReflowMetrics& aMetrics) const {
return IsAxisHorizontal(mMainAxis) ?
aMetrics.width : aMetrics.height;
}
nscoord GetCrossComponent(const nsSize& aSize) const {
return IsAxisHorizontal(mCrossAxis) ?
aSize.width : aSize.height;
}
int32_t GetCrossComponent(const nsIntSize& aIntSize) const {
return IsAxisHorizontal(mCrossAxis) ?
aIntSize.width : aIntSize.height;
}
nscoord GetCrossComponent(const nsHTMLReflowMetrics& aMetrics) const {
return IsAxisHorizontal(mCrossAxis) ?
aMetrics.width : aMetrics.height;
}
nscoord GetMarginSizeInMainAxis(const nsMargin& aMargin) const {
return IsAxisHorizontal(mMainAxis) ?
aMargin.LeftRight() :
aMargin.TopBottom();
}
nscoord GetMarginSizeInCrossAxis(const nsMargin& aMargin) const {
return IsAxisHorizontal(mCrossAxis) ?
aMargin.LeftRight() :
aMargin.TopBottom();
}
nsPoint PhysicalPositionFromLogicalPosition(nscoord aMainPosn,
nscoord aCrossPosn) const {
return IsAxisHorizontal(mMainAxis) ?
nsPoint(aMainPosn, aCrossPosn) :
nsPoint(aCrossPosn, aMainPosn);
}
nsSize PhysicalSizeFromLogicalSizes(nscoord aMainSize,
nscoord aCrossSize) const {
return IsAxisHorizontal(mMainAxis) ?
nsSize(aMainSize, aCrossSize) :
nsSize(aCrossSize, aMainSize);
}
private:
AxisOrientationType mMainAxis;
AxisOrientationType mCrossAxis;
};
// Represents a flex item.
// Includes the various pieces of input that the Flexbox Layout Algorithm uses
// to resolve a flexible width.
class FlexItem {
public:
FlexItem(nsIFrame* aChildFrame,
float aFlexGrow, float aFlexShrink, nscoord aMainBaseSize,
nscoord aMainMinSize, nscoord aMainMaxSize,
nscoord aCrossMinSize, nscoord aCrossMaxSize,
nsMargin aMargin, nsMargin aBorderPadding,
const FlexboxAxisTracker& aAxisTracker);
// Accessors
nsIFrame* Frame() const { return mFrame; }
nscoord GetFlexBaseSize() const { return mFlexBaseSize; }
nscoord GetMainMinSize() const { return mMainMinSize; }
nscoord GetMainMaxSize() const { return mMainMaxSize; }
// Note: These return the main-axis position and size of our *content box*.
nscoord GetMainSize() const { return mMainSize; }
nscoord GetMainPosition() const { return mMainPosn; }
nscoord GetCrossMinSize() const { return mCrossMinSize; }
nscoord GetCrossMaxSize() const { return mCrossMaxSize; }
// Note: These return the cross-axis position and size of our *content box*.
nscoord GetCrossSize() const { return mCrossSize; }
nscoord GetCrossPosition() const { return mCrossPosn; }
nscoord GetAscent() const { return mAscent; }
float GetShareOfFlexWeightSoFar() const { return mShareOfFlexWeightSoFar; }
bool IsFrozen() const { return mIsFrozen; }
bool HadMinViolation() const { return mHadMinViolation; }
bool HadMaxViolation() const { return mHadMaxViolation; }
// Indicates whether this item received a preliminary "measuring" reflow
// before its actual reflow.
bool HadMeasuringReflow() const { return mHadMeasuringReflow; }
// Indicates whether this item's cross-size has been stretched (from having
// "align-self: stretch" with an auto cross-size and no auto margins in the
// cross axis).
bool IsStretched() const { return mIsStretched; }
uint8_t GetAlignSelf() const { return mAlignSelf; }
// Returns the flex weight that we should use in the "resolving flexible
// lengths" algorithm. If we've got a positive amount of free space, we use
// the flex-grow weight; otherwise, we use the "scaled flex shrink weight"
// (scaled by our flex base size)
float GetFlexWeightToUse(bool aHavePositiveFreeSpace)
{
if (IsFrozen()) {
return 0.0f;
}
return aHavePositiveFreeSpace ?
mFlexGrow :
mFlexShrink * mFlexBaseSize;
}
// Getters for margin:
// ===================
const nsMargin& GetMargin() const { return mMargin; }
// Returns the margin component for a given mozilla::css::Side
nscoord GetMarginComponentForSide(Side aSide) const
{ return MarginComponentForSide(mMargin, aSide); }
// Returns the total space occupied by this item's margins in the given axis
nscoord GetMarginSizeInAxis(AxisOrientationType aAxis) const
{
Side startSide = kAxisOrientationToSidesMap[aAxis][eAxisEdge_Start];
Side endSide = kAxisOrientationToSidesMap[aAxis][eAxisEdge_End];
return GetMarginComponentForSide(startSide) +
GetMarginComponentForSide(endSide);
}
// Getters for border/padding
// ==========================
// Returns the border+padding component for a given mozilla::css::Side
nscoord GetBorderPaddingComponentForSide(Side aSide) const
{ return MarginComponentForSide(mBorderPadding, aSide); }
// Returns the total space occupied by this item's borders and padding in
// the given axis
nscoord GetBorderPaddingSizeInAxis(AxisOrientationType aAxis) const
{
Side startSide = kAxisOrientationToSidesMap[aAxis][eAxisEdge_Start];
Side endSide = kAxisOrientationToSidesMap[aAxis][eAxisEdge_End];
return GetBorderPaddingComponentForSide(startSide) +
GetBorderPaddingComponentForSide(endSide);
}
// Getter for combined margin/border/padding
// =========================================
// Returns the total space occupied by this item's margins, borders and
// padding in the given axis
nscoord GetMarginBorderPaddingSizeInAxis(AxisOrientationType aAxis) const
{
return GetMarginSizeInAxis(aAxis) + GetBorderPaddingSizeInAxis(aAxis);
}
// Setters
// =======
// Setters used while we're resolving flexible lengths
// ---------------------------------------------------
// Sets the main-size of our flex item's content-box.
void SetMainSize(nscoord aNewMainSize)
{
MOZ_ASSERT(!mIsFrozen, "main size shouldn't change after we're frozen");
mMainSize = aNewMainSize;
}
void SetShareOfFlexWeightSoFar(float aNewShare)
{
MOZ_ASSERT(!mIsFrozen || aNewShare == 0.0f,
"shouldn't be giving this item any share of the weight "
"after it's frozen");
mShareOfFlexWeightSoFar = aNewShare;
}
void Freeze() { mIsFrozen = true; }
void SetHadMinViolation()
{
MOZ_ASSERT(!mIsFrozen,
"shouldn't be changing main size & having violations "
"after we're frozen");
mHadMinViolation = true;
}
void SetHadMaxViolation()
{
MOZ_ASSERT(!mIsFrozen,
"shouldn't be changing main size & having violations "
"after we're frozen");
mHadMaxViolation = true;
}
void ClearViolationFlags()
{ mHadMinViolation = mHadMaxViolation = false; }
// Setters for values that are determined after we've resolved our main size
// -------------------------------------------------------------------------
// Sets the main-axis position of our flex item's content-box.
// (This is the distance between the main-start edge of the flex container
// and the main-start edge of the flex item's content-box.)
void SetMainPosition(nscoord aPosn) {
MOZ_ASSERT(mIsFrozen, "main size should be resolved before this");
mMainPosn = aPosn;
}
// Sets the cross-size of our flex item's content-box.
void SetCrossSize(nscoord aCrossSize) {
MOZ_ASSERT(mIsFrozen, "main size should be resolved before this");
mCrossSize = aCrossSize;
}
// Sets the cross-axis position of our flex item's content-box.
// (This is the distance between the cross-start edge of the flex container
// and the cross-start edge of the flex item.)
void SetCrossPosition(nscoord aPosn) {
MOZ_ASSERT(mIsFrozen, "main size should be resolved before this");
mCrossPosn = aPosn;
}
void SetAscent(nscoord aAscent) {
mAscent = aAscent;
}
void SetHadMeasuringReflow() {
mHadMeasuringReflow = true;
}
void SetIsStretched() {
MOZ_ASSERT(mIsFrozen, "main size should be resolved before this");
mIsStretched = true;
}
// Setter for margin components (for resolving "auto" margins)
void SetMarginComponentForSide(Side aSide, nscoord aLength)
{
MOZ_ASSERT(mIsFrozen, "main size should be resolved before this");
MarginComponentForSide(mMargin, aSide) = aLength;
}
uint32_t GetNumAutoMarginsInAxis(AxisOrientationType aAxis) const;
protected:
// Our frame:
nsIFrame* const mFrame;
// Values that we already know in constructor: (and are hence mostly 'const')
const float mFlexGrow;
const float mFlexShrink;
const nsMargin mBorderPadding;
nsMargin mMargin; // non-const because we need to resolve auto margins
const nscoord mFlexBaseSize;
const nscoord mMainMinSize;
const nscoord mMainMaxSize;
const nscoord mCrossMinSize;
const nscoord mCrossMaxSize;
// Values that we compute after constructor:
nscoord mMainSize;
nscoord mMainPosn;
nscoord mCrossSize;
nscoord mCrossPosn;
nscoord mAscent;
// Temporary state, while we're resolving flexible widths (for our main size)
// XXXdholbert To save space, we could use a union to make these variables
// overlay the same memory as some other member vars that aren't touched
// until after main-size has been resolved. In particular, these could share
// memory with mMainPosn through mAscent, and mIsStretched.
float mShareOfFlexWeightSoFar;
bool mIsFrozen;
bool mHadMinViolation;
bool mHadMaxViolation;
// Misc:
bool mHadMeasuringReflow; // Did this item get a preliminary reflow,
// to measure its desired height?
bool mIsStretched; // See IsStretched() documentation
uint8_t mAlignSelf; // My "align-self" computed value (with "auto"
// swapped out for parent"s "align-items" value,
// in our constructor).
};
/**
* Helper-function to find the nsIContent* that we should use for comparing the
* DOM tree position of the given flex-item frame.
*
* In most cases, this will be aFrame->GetContent(), but if aFrame is an
* anonymous container, then its GetContent() won't be what we want. In such
* cases, we need to find aFrame's first non-anonymous-container descendant.
*/
static nsIContent*
GetContentForComparison(const nsIFrame* aFrame)
{
MOZ_ASSERT(aFrame, "null frame passed to GetContentForComparison()");
MOZ_ASSERT(aFrame->IsFlexItem(), "only intended for flex items");
while (true) {
nsIAtom* pseudoTag = aFrame->GetStyleContext()->GetPseudo();
// If aFrame isn't an anonymous container, then it'll do.
if (!pseudoTag || // No pseudotag.
!nsCSSAnonBoxes::IsAnonBox(pseudoTag) || // Pseudotag isn't anon.
pseudoTag == nsCSSAnonBoxes::mozNonElement) { // Text, not a container.
return aFrame->GetContent();
}
// Otherwise, descend to its first child and repeat.
aFrame = aFrame->GetFirstPrincipalChild();
MOZ_ASSERT(aFrame, "why do we have an anonymous box without any children?");
}
}
/**
* Sorting helper-function that compares two frames' "order" property-values,
* and if they're equal, compares the DOM positions of their corresponding
* content nodes. Returns true if aFrame1 is "less than or equal to" aFrame2
* according to this comparison.
*
* Note: This can't be a static function, because we need to pass it as a
* template argument. (Only functions with external linkage can be passed as
* template arguments.)
*
* @return true if the computed "order" property of aFrame1 is less than that
* of aFrame2, or if the computed "order" values are equal and aFrame1's
* corresponding DOM node is earlier than aFrame2's in the DOM tree.
* Otherwise, returns false.
*/
bool
IsOrderLEQWithDOMFallback(nsIFrame* aFrame1,
nsIFrame* aFrame2)
{
if (aFrame1 == aFrame2) {
// Anything is trivially LEQ itself, so we return "true" here... but it's
// probably bad if we end up actually needing this, so let's assert.
NS_ERROR("Why are we checking if a frame is LEQ itself?");
return true;
}
int32_t order1 = aFrame1->GetStylePosition()->mOrder;
int32_t order2 = aFrame2->GetStylePosition()->mOrder;
if (order1 != order2) {
return order1 < order2;
}
// Same "order" value --> use DOM position.
nsIContent* content1 = GetContentForComparison(aFrame1);
nsIContent* content2 = GetContentForComparison(aFrame2);
MOZ_ASSERT(content1 != content2,
"Two different flex items are using the same nsIContent node for "
"comparison, so we may be sorting them in an arbitrary order");
return nsContentUtils::PositionIsBefore(content1, content2);
}
/**
* Sorting helper-function that compares two frames' "order" property-values.
* Returns true if aFrame1 is "less than or equal to" aFrame2 according to this
* comparison.
*
* Note: This can't be a static function, because we need to pass it as a
* template argument. (Only functions with external linkage can be passed as
* template arguments.)
*
* @return true if the computed "order" property of aFrame1 is less than or
* equal to that of aFrame2. Otherwise, returns false.
*/
bool
IsOrderLEQ(nsIFrame* aFrame1,
nsIFrame* aFrame2)
{
int32_t order1 = aFrame1->GetStylePosition()->mOrder;
int32_t order2 = aFrame2->GetStylePosition()->mOrder;
return order1 <= order2;
}
bool
nsFlexContainerFrame::IsHorizontal()
{
const FlexboxAxisTracker axisTracker(this);
return IsAxisHorizontal(axisTracker.GetMainAxis());
}
nsresult
nsFlexContainerFrame::AppendFlexItemForChild(
nsPresContext* aPresContext,
nsIFrame* aChildFrame,
const nsHTMLReflowState& aParentReflowState,
const FlexboxAxisTracker& aAxisTracker,
nsTArray<FlexItem>& aFlexItems)
{
// Create temporary reflow state just for sizing -- to get hypothetical
// main-size and the computed values of min / max main-size property.
// (This reflow state will _not_ be used for reflow.)
nsHTMLReflowState childRS(aPresContext, aParentReflowState, aChildFrame,
nsSize(aParentReflowState.ComputedWidth(),
aParentReflowState.ComputedHeight()));
// FLEX GROW & SHRINK WEIGHTS
// --------------------------
const nsStylePosition* stylePos = aChildFrame->GetStylePosition();
float flexGrow = stylePos->mFlexGrow;
float flexShrink = stylePos->mFlexShrink;
// MAIN SIZES (flex base size, min/max size)
// -----------------------------------------
nscoord flexBaseSize =
aAxisTracker.GetMainComponent(nsSize(childRS.ComputedWidth(),
childRS.ComputedHeight()));
nscoord mainMinSize =
aAxisTracker.GetMainComponent(nsSize(childRS.mComputedMinWidth,
childRS.mComputedMinHeight));
nscoord mainMaxSize =
aAxisTracker.GetMainComponent(nsSize(childRS.mComputedMaxWidth,
childRS.mComputedMaxHeight));
// This is enforced by the nsHTMLReflowState where these values come from:
MOZ_ASSERT(mainMinSize <= mainMaxSize, "min size is larger than max size");
// SPECIAL MAIN-SIZING FOR VERTICAL FLEX CONTAINERS
// If we're vertical and our main size ended up being unconstrained
// (e.g. because we had height:auto), we need to instead use our
// "max-content" height, which is what we get from reflowing into our
// available width. This is the same as our "min-content" height --
// so if we have "min-height:auto", we need to use this value as our
// min-height.
bool needToMeasureMaxContentHeight = false;
if (!IsAxisHorizontal(aAxisTracker.GetMainAxis())) {
bool isMainSizeAuto = (NS_UNCONSTRAINEDSIZE == flexBaseSize);
bool isMainMinSizeAuto =
(eStyleUnit_Auto ==
aChildFrame->GetStylePosition()->mMinHeight.GetUnit());
needToMeasureMaxContentHeight = isMainSizeAuto || isMainMinSizeAuto;
if (needToMeasureMaxContentHeight) {
// Give the item a special reflow with "mIsFlexContainerMeasuringHeight"
// set. This tells it to behave as if it had "height: auto", regardless
// of what the "height" property is actually set to.
nsHTMLReflowState
childRSForMeasuringHeight(aPresContext, aParentReflowState,
aChildFrame,
nsSize(aParentReflowState.ComputedWidth(),
NS_UNCONSTRAINEDSIZE),
-1, -1, false);
childRSForMeasuringHeight.mFlags.mIsFlexContainerMeasuringHeight = true;
childRSForMeasuringHeight.Init(aPresContext);
// If this item is flexible (vertically), or if we're measuring the
// 'auto' min-height and our main-size is something else, then we assume
// that the computed-height we're reflowing with now could be different
// from the one we'll use for this flex item's "actual" reflow later on.
// In that case, we need to be sure the flex item treats this as a
// vertical resize, even though none of its ancestors are necessarily
// being vertically resized.
// (Note: We don't have to do this for width, because InitResizeFlags
// will always turn on mHResize on when it sees that the computed width
// is different from current width, and that's all we need.)
if (flexGrow != 0.0f || flexShrink != 0.0f || // Are we flexible?
!isMainSizeAuto) { // Are we *only* measuring this for min-height?
childRSForMeasuringHeight.mFlags.mVResize = true;
}
nsHTMLReflowMetrics childDesiredSize;
nsReflowStatus childReflowStatus;
nsresult rv = ReflowChild(aChildFrame, aPresContext,
childDesiredSize, childRSForMeasuringHeight,
0, 0, NS_FRAME_NO_MOVE_FRAME,
childReflowStatus);
NS_ENSURE_SUCCESS(rv, rv);
MOZ_ASSERT(NS_FRAME_IS_COMPLETE(childReflowStatus),
"We gave flex item unconstrained available height, so it "
"should be complete");
rv = FinishReflowChild(aChildFrame, aPresContext,
&childRSForMeasuringHeight, childDesiredSize,
0, 0, 0);
NS_ENSURE_SUCCESS(rv, rv);
// Subtract border/padding in vertical axis, to get _just_
// the effective computed value of the "height" property.
nscoord childDesiredHeight = childDesiredSize.height -
childRS.mComputedBorderPadding.TopBottom();
childDesiredHeight = NS_MAX(0, childDesiredHeight);
if (isMainSizeAuto) {
flexBaseSize = childDesiredHeight;
}
if (isMainMinSizeAuto) {
mainMinSize = childDesiredHeight;
mainMaxSize = NS_MAX(mainMaxSize, mainMinSize);
}
}
}
// CROSS MIN/MAX SIZE
// ------------------
nscoord crossMinSize =
aAxisTracker.GetCrossComponent(nsSize(childRS.mComputedMinWidth,
childRS.mComputedMinHeight));
nscoord crossMaxSize =
aAxisTracker.GetCrossComponent(nsSize(childRS.mComputedMaxWidth,
childRS.mComputedMaxHeight));
// SPECIAL-CASE FOR WIDGET-IMPOSED SIZES
// Check if we're a themed widget, in which case we might have a minimum
// main & cross size imposed by our widget (which we can't go below), or
// (more severe) our widget might have only a single valid size.
bool isFixedSizeWidget = false;
const nsStyleDisplay* disp = aChildFrame->GetStyleDisplay();
if (aChildFrame->IsThemed(disp)) {
nsIntSize widgetMinSize(0, 0);
bool canOverride = true;
aPresContext->GetTheme()->
GetMinimumWidgetSize(childRS.rendContext, aChildFrame,
disp->mAppearance,
&widgetMinSize, &canOverride);
nscoord widgetMainMinSize =
aPresContext->DevPixelsToAppUnits(
aAxisTracker.GetMainComponent(widgetMinSize));
nscoord widgetCrossMinSize =
aPresContext->DevPixelsToAppUnits(
aAxisTracker.GetCrossComponent(widgetMinSize));
// GMWS() returns border-box; we need content-box
widgetMainMinSize -=
aAxisTracker.GetMarginSizeInMainAxis(childRS.mComputedBorderPadding);
widgetCrossMinSize -=
aAxisTracker.GetMarginSizeInCrossAxis(childRS.mComputedBorderPadding);
if (!canOverride) {
// Fixed-size widget: freeze our main-size at the widget's mandated size.
// (Set min and max main-sizes to that size, too, to keep us from
// clamping to any other size later on.)
flexBaseSize = mainMinSize = mainMaxSize = widgetMainMinSize;
crossMinSize = crossMaxSize = widgetCrossMinSize;
isFixedSizeWidget = true;
} else {
// Variable-size widget: ensure our min/max sizes are at least as large
// as the widget's mandated minimum size, so we don't flex below that.
mainMinSize = NS_MAX(mainMinSize, widgetMainMinSize);
mainMaxSize = NS_MAX(mainMaxSize, widgetMainMinSize);
crossMinSize = NS_MAX(crossMinSize, widgetCrossMinSize);
crossMaxSize = NS_MAX(crossMaxSize, widgetCrossMinSize);
}
}
aFlexItems.AppendElement(FlexItem(aChildFrame,
flexGrow, flexShrink, flexBaseSize,
mainMinSize, mainMaxSize,
crossMinSize, crossMaxSize,
childRS.mComputedMargin,
childRS.mComputedBorderPadding,
aAxisTracker));
// If we're inflexible, we can just freeze to our hypothetical main-size
// up-front. Similarly, if we're a fixed-size widget, we only have one
// valid size, so we freeze to keep ourselves from flexing.
if (isFixedSizeWidget || (flexGrow == 0.0f && flexShrink == 0.0f)) {
aFlexItems.LastElement().Freeze();
}
// If we did a height-measuring reflow for this flex item, make a note of
// that, so our "actual" reflow can set resize flags accordingly.
if (needToMeasureMaxContentHeight) {
aFlexItems.LastElement().SetHadMeasuringReflow();
}
return NS_OK;
}
FlexItem::FlexItem(nsIFrame* aChildFrame,
float aFlexGrow, float aFlexShrink, nscoord aFlexBaseSize,
nscoord aMainMinSize, nscoord aMainMaxSize,
nscoord aCrossMinSize, nscoord aCrossMaxSize,
nsMargin aMargin, nsMargin aBorderPadding,
const FlexboxAxisTracker& aAxisTracker)
: mFrame(aChildFrame),
mFlexGrow(aFlexGrow),
mFlexShrink(aFlexShrink),
mBorderPadding(aBorderPadding),
mMargin(aMargin),
mFlexBaseSize(aFlexBaseSize),
mMainMinSize(aMainMinSize),
mMainMaxSize(aMainMaxSize),
mCrossMinSize(aCrossMinSize),
mCrossMaxSize(aCrossMaxSize),
// Init main-size to 'hypothetical main size', which is flex base size
// clamped to [min,max] range:
mMainSize(NS_CSS_MINMAX(aFlexBaseSize, aMainMinSize, aMainMaxSize)),
mMainPosn(0),
mCrossSize(0),
mCrossPosn(0),
mAscent(0),
mShareOfFlexWeightSoFar(0.0f),
mIsFrozen(false),
mHadMinViolation(false),
mHadMaxViolation(false),
mHadMeasuringReflow(false),
mIsStretched(false),
mAlignSelf(aChildFrame->GetStylePosition()->mAlignSelf)
{
MOZ_ASSERT(aChildFrame, "expecting a non-null child frame");
// Assert that any "auto" margin components are set to 0.
// (We'll resolve them later; until then, we want to treat them as 0-sized.)
#ifdef DEBUG
{
const nsStyleSides& styleMargin = mFrame->GetStyleMargin()->mMargin;
NS_FOR_CSS_SIDES(side) {
if (styleMargin.GetUnit(side) == eStyleUnit_Auto) {
MOZ_ASSERT(GetMarginComponentForSide(side) == 0,
"Someone else tried to resolve our auto margin");
}
}
}
#endif // DEBUG
// Resolve "align-self: auto" to parent's "align-items" value.
if (mAlignSelf == NS_STYLE_ALIGN_SELF_AUTO) {
mAlignSelf =
mFrame->GetStyleContext()->GetParent()->GetStylePosition()->mAlignItems;
}
// If the flex item's inline axis is the same as the cross axis, then
// 'align-self:baseline' is identical to 'flex-start'. If that's the case, we
// just directly convert our align-self value here, so that we don't have to
// handle this with special cases elsewhere.
// Moreover: for the time being (until we support writing-modes),
// all inline axes are horizontal -- so we can just check if the cross axis
// is horizontal.
// FIXME: Once we support writing-mode (vertical text), this IsAxisHorizontal
// check won't be sufficient anymore -- we'll actually need to compare our
// inline axis vs. the cross axis.
if (mAlignSelf == NS_STYLE_ALIGN_ITEMS_BASELINE &&
IsAxisHorizontal(aAxisTracker.GetCrossAxis())) {
mAlignSelf = NS_STYLE_ALIGN_ITEMS_FLEX_START;
}
}
uint32_t
FlexItem::GetNumAutoMarginsInAxis(AxisOrientationType aAxis) const
{
uint32_t numAutoMargins = 0;
const nsStyleSides& styleMargin = mFrame->GetStyleMargin()->mMargin;
for (uint32_t i = 0; i < eNumAxisEdges; i++) {
Side side = kAxisOrientationToSidesMap[aAxis][i];
if (styleMargin.GetUnit(side) == eStyleUnit_Auto) {
numAutoMargins++;
}
}
// Mostly for clarity:
MOZ_ASSERT(numAutoMargins <= 2,
"We're just looking at one item along one dimension, so we "
"should only have examined 2 margins");
return numAutoMargins;
}
// Keeps track of our position along a particular axis (where a '0' position
// corresponds to the 'start' edge of that axis).
// This class shouldn't be instantiated directly -- rather, it should only be
// instantiated via its subclasses defined below.
NS_STACK_CLASS
class PositionTracker {
public:
// Accessor for the current value of the position that we're tracking.
inline nscoord GetPosition() const { return mPosition; }
inline AxisOrientationType GetAxis() const { return mAxis; }
// Advances our position across the start edge of the given margin, in the
// axis we're tracking.
void EnterMargin(const nsMargin& aMargin)
{
Side side = kAxisOrientationToSidesMap[mAxis][eAxisEdge_Start];
mPosition += MarginComponentForSide(aMargin, side);
}
// Advances our position across the end edge of the given margin, in the axis
// we're tracking.
void ExitMargin(const nsMargin& aMargin)
{
Side side = kAxisOrientationToSidesMap[mAxis][eAxisEdge_End];
mPosition += MarginComponentForSide(aMargin, side);
}
// Advances our current position from the start side of a child frame's
// border-box to the frame's upper or left edge (depending on our axis).
// (Note that this is a no-op if our axis grows in positive direction.)
void EnterChildFrame(nscoord aChildFrameSize)
{
if (!AxisGrowsInPositiveDirection(mAxis))
mPosition += aChildFrameSize;
}
// Advances our current position from a frame's upper or left border-box edge
// (whichever is in the axis we're tracking) to the 'end' side of the frame
// in the axis that we're tracking. (Note that this is a no-op if our axis
// grows in the negative direction.)
void ExitChildFrame(nscoord aChildFrameSize)
{
if (AxisGrowsInPositiveDirection(mAxis))
mPosition += aChildFrameSize;
}
protected:
// Protected constructor, to be sure we're only instantiated via a subclass.
PositionTracker(AxisOrientationType aAxis)
: mPosition(0),
mAxis(aAxis)
{}
private:
// Private copy-constructor, since we don't want any instances of our
// subclasses to be accidentally copied.
PositionTracker(const PositionTracker& aOther)
: mPosition(aOther.mPosition),
mAxis(aOther.mAxis)
{}
protected:
// Member data:
nscoord mPosition; // The position we're tracking
const AxisOrientationType mAxis; // The axis along which we're moving
};
// Tracks our position in the main axis, when we're laying out flex items.
NS_STACK_CLASS
class MainAxisPositionTracker : public PositionTracker {
public:
MainAxisPositionTracker(nsFlexContainerFrame* aFlexContainerFrame,
const FlexboxAxisTracker& aAxisTracker,
const nsHTMLReflowState& aReflowState,
const nsTArray<FlexItem>& aItems);
~MainAxisPositionTracker() {
MOZ_ASSERT(mNumPackingSpacesRemaining == 0,
"miscounted the number of packing spaces");
MOZ_ASSERT(mNumAutoMarginsInMainAxis == 0,
"miscounted the number of auto margins");
}
// Advances past the packing space (if any) between two flex items
void TraversePackingSpace();
// If aItem has any 'auto' margins in the main axis, this method updates the
// corresponding values in its margin.
void ResolveAutoMarginsInMainAxis(FlexItem& aItem);
private:
nscoord mPackingSpaceRemaining;
uint32_t mNumAutoMarginsInMainAxis;
uint32_t mNumPackingSpacesRemaining;
uint8_t mJustifyContent;
};
// Utility class for managing our position along the cross axis along
// the whole flex container (at a higher level than a single line)
class SingleLineCrossAxisPositionTracker;
NS_STACK_CLASS
class CrossAxisPositionTracker : public PositionTracker {
public:
CrossAxisPositionTracker(nsFlexContainerFrame* aFlexContainerFrame,
const FlexboxAxisTracker& aAxisTracker,
const nsHTMLReflowState& aReflowState);
// XXXdholbert This probably needs a ResolveStretchedLines() method,
// (which takes an array of SingleLineCrossAxisPositionTracker objects
// and distributes an equal amount of space to each one).
// For now, we just have Reflow directly call
// SingleLineCrossAxisPositionTracker::SetLineCrossSize().
};
// Utility class for managing our position along the cross axis, *within* a
// single flex line.
NS_STACK_CLASS
class SingleLineCrossAxisPositionTracker : public PositionTracker {
public:
SingleLineCrossAxisPositionTracker(nsFlexContainerFrame* aFlexContainerFrame,
const FlexboxAxisTracker& aAxisTracker,
const nsTArray<FlexItem>& aItems);
void ComputeLineCrossSize(const nsTArray<FlexItem>& aItems);
inline nscoord GetLineCrossSize() const { return mLineCrossSize; }
// Used to override the flex line's size, for cases when the flex container is
// single-line and has a fixed size, and also in cases where
// "align-self: stretch" triggers some space-distribution between lines
// (when we support that property).
inline void SetLineCrossSize(nscoord aNewLineCrossSize) {
mLineCrossSize = aNewLineCrossSize;
}
void ResolveStretchedCrossSize(FlexItem& aItem);
void ResolveAutoMarginsInCrossAxis(FlexItem& aItem);
void EnterAlignPackingSpace(const FlexItem& aItem);
// Resets our position to the cross-start edge of this line.
inline void ResetPosition() { mPosition = 0; }
private:
// Returns the distance from the cross-start side of the given flex item's
// margin-box to its baseline. (Used in baseline alignment.)
nscoord GetBaselineOffsetFromCrossStart(const FlexItem& aItem) const;
nscoord mLineCrossSize;
// Largest distance from an item's cross-start margin-box edge to its
// baseline. Computed in ComputeLineCrossSize, and used for alignment of any
// "align-self: baseline" items in this line (and possibly used for computing
// the baseline of the flex container, as well).
nscoord mCrossStartToFurthestBaseline;
};