-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbox.dart
More file actions
2535 lines (2409 loc) · 108 KB
/
box.dart
File metadata and controls
2535 lines (2409 loc) · 108 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 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'dart:ui' as ui show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:vector_math/vector_math_64.dart';
import 'debug.dart';
import 'object.dart';
// This class should only be used in debug builds.
class _DebugSize extends Size {
_DebugSize(Size source, this._owner, this._canBeUsedByParent) : super.copy(source);
final RenderBox _owner;
final bool _canBeUsedByParent;
}
/// Immutable layout constraints for [RenderBox] layout.
///
/// A [Size] respects a [BoxConstraints] if, and only if, all of the following
/// relations hold:
///
/// * [minWidth] <= [Size.width] <= [maxWidth]
/// * [minHeight] <= [Size.height] <= [maxHeight]
///
/// The constraints themselves must satisfy these relations:
///
/// * 0.0 <= [minWidth] <= [maxWidth] <= [double.infinity]
/// * 0.0 <= [minHeight] <= [maxHeight] <= [double.infinity]
///
/// [double.infinity] is a legal value for each constraint.
///
/// ## The box layout model
///
/// Render objects in the Flutter framework are laid out by a one-pass layout
/// model which walks down the render tree passing constraints, then walks back
/// up the render tree passing concrete geometry.
///
/// For boxes, the constraints are [BoxConstraints], which, as described herein,
/// consist of four numbers: a minimum width [minWidth], a maximum width
/// [maxWidth], a minimum height [minHeight], and a maximum height [maxHeight].
///
/// The geometry for boxes consists of a [Size], which must satisfy the
/// constraints described above.
///
/// Each [RenderBox] (the objects that provide the layout models for box
/// widgets) receives [BoxConstraints] from its parent, then lays out each of
/// its children, then picks a [Size] that satisfies the [BoxConstraints].
///
/// Render objects position their children independently of laying them out.
/// Frequently, the parent will use the children's sizes to determine their
/// position. A child does not know its position and will not necessarily be
/// laid out again, or repainted, if its position changes.
///
/// ## Terminology
///
/// When the minimum constraints and the maximum constraint in an axis are the
/// same, that axis is _tightly_ constrained. See: [new
/// BoxConstraints.tightFor], [new BoxConstraints.tightForFinite], [tighten],
/// [hasTightWidth], [hasTightHeight], [isTight].
///
/// An axis with a minimum constraint of 0.0 is _loose_ (regardless of the
/// maximum constraint; if it is also 0.0, then the axis is simultaneously tight
/// and loose!). See: [new BoxConstraints.loose], [loosen].
///
/// An axis whose maximum constraint is not infinite is _bounded_. See:
/// [hasBoundedWidth], [hasBoundedHeight].
///
/// An axis whose maximum constraint is infinite is _unbounded_. An axis is
/// _expanding_ if it is tightly infinite (its minimum and maximum constraints
/// are both infinite). See: [new BoxConstraints.expand].
///
/// An axis whose _minimum_ constraint is infinite is just said to be _infinite_
/// (since by definition the maximum constraint must also be infinite in that
/// case). See: [hasInfiniteWidth], [hasInfiniteHeight].
///
/// A size is _constrained_ when it satisfies a [BoxConstraints] description.
/// See: [constrain], [constrainWidth], [constrainHeight],
/// [constrainDimensions], [constrainSizeAndAttemptToPreserveAspectRatio],
/// [isSatisfiedBy].
class BoxConstraints extends Constraints {
/// Creates box constraints with the given constraints.
const BoxConstraints({
this.minWidth = 0.0,
this.maxWidth = double.infinity,
this.minHeight = 0.0,
this.maxHeight = double.infinity,
}) : assert (minWidth != null),
assert (maxWidth != null),
assert (minHeight != null),
assert (maxHeight != null);
/// Creates box constraints that is respected only by the given size.
BoxConstraints.tight(Size size)
: minWidth = size.width,
maxWidth = size.width,
minHeight = size.height,
maxHeight = size.height;
/// Creates box constraints that require the given width or height.
///
/// See also:
///
/// * [new BoxConstraints.tightForFinite], which is similar but instead of
/// being tight if the value is non-null, is tight if the value is not
/// infinite.
const BoxConstraints.tightFor({
double width,
double height,
}) : minWidth = width ?? 0.0,
maxWidth = width ?? double.infinity,
minHeight = height ?? 0.0,
maxHeight = height ?? double.infinity;
/// Creates box constraints that require the given width or height, except if
/// they are infinite.
///
/// See also:
///
/// * [new BoxConstraints.tightFor], which is similar but instead of being
/// tight if the value is not infinite, is tight if the value is non-null.
const BoxConstraints.tightForFinite({
double width = double.infinity,
double height = double.infinity,
}) : minWidth = width != double.infinity ? width : 0.0,
maxWidth = width != double.infinity ? width : double.infinity,
minHeight = height != double.infinity ? height : 0.0,
maxHeight = height != double.infinity ? height : double.infinity;
/// Creates box constraints that forbid sizes larger than the given size.
BoxConstraints.loose(Size size)
: minWidth = 0.0,
maxWidth = size.width,
minHeight = 0.0,
maxHeight = size.height;
/// Creates box constraints that expand to fill another box constraints.
///
/// If width or height is given, the constraints will require exactly the
/// given value in the given dimension.
const BoxConstraints.expand({
double width,
double height,
}) : minWidth = width ?? double.infinity,
maxWidth = width ?? double.infinity,
minHeight = height ?? double.infinity,
maxHeight = height ?? double.infinity;
/// The minimum width that satisfies the constraints.
final double minWidth;
/// The maximum width that satisfies the constraints.
///
/// Might be [double.infinity].
final double maxWidth;
/// The minimum height that satisfies the constraints.
final double minHeight;
/// The maximum height that satisfies the constraints.
///
/// Might be [double.infinity].
final double maxHeight;
/// Creates a copy of this box constraints but with the given fields replaced with the new values.
BoxConstraints copyWith({
double minWidth,
double maxWidth,
double minHeight,
double maxHeight,
}) {
return BoxConstraints(
minWidth: minWidth ?? this.minWidth,
maxWidth: maxWidth ?? this.maxWidth,
minHeight: minHeight ?? this.minHeight,
maxHeight: maxHeight ?? this.maxHeight,
);
}
/// Returns new box constraints that are smaller by the given edge dimensions.
BoxConstraints deflate(EdgeInsets edges) {
assert(edges != null);
assert(debugAssertIsValid());
final double horizontal = edges.horizontal;
final double vertical = edges.vertical;
final double deflatedMinWidth = math.max(0.0, minWidth - horizontal);
final double deflatedMinHeight = math.max(0.0, minHeight - vertical);
return BoxConstraints(
minWidth: deflatedMinWidth,
maxWidth: math.max(deflatedMinWidth, maxWidth - horizontal),
minHeight: deflatedMinHeight,
maxHeight: math.max(deflatedMinHeight, maxHeight - vertical),
);
}
/// Returns new box constraints that remove the minimum width and height requirements.
BoxConstraints loosen() {
assert(debugAssertIsValid());
return BoxConstraints(
minWidth: 0.0,
maxWidth: maxWidth,
minHeight: 0.0,
maxHeight: maxHeight,
);
}
/// Returns new box constraints that respect the given constraints while being
/// as close as possible to the original constraints.
BoxConstraints enforce(BoxConstraints constraints) {
return BoxConstraints(
minWidth: minWidth.clamp(constraints.minWidth, constraints.maxWidth) as double,
maxWidth: maxWidth.clamp(constraints.minWidth, constraints.maxWidth) as double,
minHeight: minHeight.clamp(constraints.minHeight, constraints.maxHeight) as double,
maxHeight: maxHeight.clamp(constraints.minHeight, constraints.maxHeight) as double,
);
}
/// Returns new box constraints with a tight width and/or height as close to
/// the given width and height as possible while still respecting the original
/// box constraints.
BoxConstraints tighten({ double width, double height }) {
return BoxConstraints(
minWidth: width == null ? minWidth : width.clamp(minWidth, maxWidth) as double,
maxWidth: width == null ? maxWidth : width.clamp(minWidth, maxWidth) as double,
minHeight: height == null ? minHeight : height.clamp(minHeight, maxHeight) as double,
maxHeight: height == null ? maxHeight : height.clamp(minHeight, maxHeight) as double,
);
}
/// A box constraints with the width and height constraints flipped.
BoxConstraints get flipped {
return BoxConstraints(
minWidth: minHeight,
maxWidth: maxHeight,
minHeight: minWidth,
maxHeight: maxWidth,
);
}
/// Returns box constraints with the same width constraints but with
/// unconstrained height.
BoxConstraints widthConstraints() => BoxConstraints(minWidth: minWidth, maxWidth: maxWidth);
/// Returns box constraints with the same height constraints but with
/// unconstrained width
BoxConstraints heightConstraints() => BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);
/// Returns the width that both satisfies the constraints and is as close as
/// possible to the given width.
double constrainWidth([ double width = double.infinity ]) {
assert(debugAssertIsValid());
return width.clamp(minWidth, maxWidth) as double;
}
/// Returns the height that both satisfies the constraints and is as close as
/// possible to the given height.
double constrainHeight([ double height = double.infinity ]) {
assert(debugAssertIsValid());
return height.clamp(minHeight, maxHeight) as double;
}
Size _debugPropagateDebugSize(Size size, Size result) {
assert(() {
if (size is _DebugSize)
result = _DebugSize(result, size._owner, size._canBeUsedByParent);
return true;
}());
return result;
}
/// Returns the size that both satisfies the constraints and is as close as
/// possible to the given size.
///
/// See also:
///
/// * [constrainDimensions], which applies the same algorithm to
/// separately provided widths and heights.
Size constrain(Size size) {
Size result = Size(constrainWidth(size.width), constrainHeight(size.height));
assert(() {
result = _debugPropagateDebugSize(size, result);
return true;
}());
return result;
}
/// Returns the size that both satisfies the constraints and is as close as
/// possible to the given width and height.
///
/// When you already have a [Size], prefer [constrain], which applies the same
/// algorithm to a [Size] directly.
Size constrainDimensions(double width, double height) {
return Size(constrainWidth(width), constrainHeight(height));
}
/// Returns a size that attempts to meet the following conditions, in order:
///
/// * The size must satisfy these constraints.
/// * The aspect ratio of the returned size matches the aspect ratio of the
/// given size.
/// * The returned size as big as possible while still being equal to or
/// smaller than the given size.
Size constrainSizeAndAttemptToPreserveAspectRatio(Size size) {
if (isTight) {
Size result = smallest;
assert(() {
result = _debugPropagateDebugSize(size, result);
return true;
}());
return result;
}
double width = size.width;
double height = size.height;
assert(width > 0.0);
assert(height > 0.0);
final double aspectRatio = width / height;
if (width > maxWidth) {
width = maxWidth;
height = width / aspectRatio;
}
if (height > maxHeight) {
height = maxHeight;
width = height * aspectRatio;
}
if (width < minWidth) {
width = minWidth;
height = width / aspectRatio;
}
if (height < minHeight) {
height = minHeight;
width = height * aspectRatio;
}
Size result = Size(constrainWidth(width), constrainHeight(height));
assert(() {
result = _debugPropagateDebugSize(size, result);
return true;
}());
return result;
}
/// The biggest size that satisfies the constraints.
Size get biggest => Size(constrainWidth(), constrainHeight());
/// The smallest size that satisfies the constraints.
Size get smallest => Size(constrainWidth(0.0), constrainHeight(0.0));
/// Whether there is exactly one width value that satisfies the constraints.
bool get hasTightWidth => minWidth >= maxWidth;
/// Whether there is exactly one height value that satisfies the constraints.
bool get hasTightHeight => minHeight >= maxHeight;
/// Whether there is exactly one size that satisfies the constraints.
@override
bool get isTight => hasTightWidth && hasTightHeight;
/// Whether there is an upper bound on the maximum width.
///
/// See also:
///
/// * [hasBoundedHeight], the equivalent for the vertical axis.
/// * [hasInfiniteWidth], which describes whether the minimum width
/// constraint is infinite.
bool get hasBoundedWidth => maxWidth < double.infinity;
/// Whether there is an upper bound on the maximum height.
///
/// See also:
///
/// * [hasBoundedWidth], the equivalent for the horizontal axis.
/// * [hasInfiniteHeight], which describes whether the minimum height
/// constraint is infinite.
bool get hasBoundedHeight => maxHeight < double.infinity;
/// Whether the width constraint is infinite.
///
/// Such a constraint is used to indicate that a box should grow as large as
/// some other constraint (in this case, horizontally). If constraints are
/// infinite, then they must have other (non-infinite) constraints [enforce]d
/// upon them, or must be [tighten]ed, before they can be used to derive a
/// [Size] for a [RenderBox.size].
///
/// See also:
///
/// * [hasInfiniteHeight], the equivalent for the vertical axis.
/// * [hasBoundedWidth], which describes whether the maximum width
/// constraint is finite.
bool get hasInfiniteWidth => minWidth >= double.infinity;
/// Whether the height constraint is infinite.
///
/// Such a constraint is used to indicate that a box should grow as large as
/// some other constraint (in this case, vertically). If constraints are
/// infinite, then they must have other (non-infinite) constraints [enforce]d
/// upon them, or must be [tighten]ed, before they can be used to derive a
/// [Size] for a [RenderBox.size].
///
/// See also:
///
/// * [hasInfiniteWidth], the equivalent for the horizontal axis.
/// * [hasBoundedHeight], which describes whether the maximum height
/// constraint is finite.
bool get hasInfiniteHeight => minHeight >= double.infinity;
/// Whether the given size satisfies the constraints.
bool isSatisfiedBy(Size size) {
assert(debugAssertIsValid());
return (minWidth <= size.width) && (size.width <= maxWidth) &&
(minHeight <= size.height) && (size.height <= maxHeight);
}
/// Scales each constraint parameter by the given factor.
BoxConstraints operator*(double factor) {
return BoxConstraints(
minWidth: minWidth * factor,
maxWidth: maxWidth * factor,
minHeight: minHeight * factor,
maxHeight: maxHeight * factor,
);
}
/// Scales each constraint parameter by the inverse of the given factor.
BoxConstraints operator/(double factor) {
return BoxConstraints(
minWidth: minWidth / factor,
maxWidth: maxWidth / factor,
minHeight: minHeight / factor,
maxHeight: maxHeight / factor,
);
}
/// Scales each constraint parameter by the inverse of the given factor, rounded to the nearest integer.
BoxConstraints operator~/(double factor) {
return BoxConstraints(
minWidth: (minWidth ~/ factor).toDouble(),
maxWidth: (maxWidth ~/ factor).toDouble(),
minHeight: (minHeight ~/ factor).toDouble(),
maxHeight: (maxHeight ~/ factor).toDouble(),
);
}
/// Computes the remainder of each constraint parameter by the given value.
BoxConstraints operator%(double value) {
return BoxConstraints(
minWidth: minWidth % value,
maxWidth: maxWidth % value,
minHeight: minHeight % value,
maxHeight: maxHeight % value,
);
}
/// Linearly interpolate between two BoxConstraints.
///
/// If either is null, this function interpolates from a [BoxConstraints]
/// object whose fields are all set to 0.0.
///
/// {@macro dart.ui.shadow.lerp}
static BoxConstraints lerp(BoxConstraints a, BoxConstraints b, double t) {
assert(t != null);
if (a == null && b == null)
return null;
if (a == null)
return b * t;
if (b == null)
return a * (1.0 - t);
assert(a.debugAssertIsValid());
assert(b.debugAssertIsValid());
assert((a.minWidth.isFinite && b.minWidth.isFinite) || (a.minWidth == double.infinity && b.minWidth == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.');
assert((a.maxWidth.isFinite && b.maxWidth.isFinite) || (a.maxWidth == double.infinity && b.maxWidth == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.');
assert((a.minHeight.isFinite && b.minHeight.isFinite) || (a.minHeight == double.infinity && b.minHeight == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.');
assert((a.maxHeight.isFinite && b.maxHeight.isFinite) || (a.maxHeight == double.infinity && b.maxHeight == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.');
return BoxConstraints(
minWidth: a.minWidth.isFinite ? ui.lerpDouble(a.minWidth, b.minWidth, t) : double.infinity,
maxWidth: a.maxWidth.isFinite ? ui.lerpDouble(a.maxWidth, b.maxWidth, t) : double.infinity,
minHeight: a.minHeight.isFinite ? ui.lerpDouble(a.minHeight, b.minHeight, t) : double.infinity,
maxHeight: a.maxHeight.isFinite ? ui.lerpDouble(a.maxHeight, b.maxHeight, t) : double.infinity,
);
}
/// Returns whether the object's constraints are normalized.
/// Constraints are normalized if the minimums are less than or
/// equal to the corresponding maximums.
///
/// For example, a BoxConstraints object with a minWidth of 100.0
/// and a maxWidth of 90.0 is not normalized.
///
/// Most of the APIs on BoxConstraints expect the constraints to be
/// normalized and have undefined behavior when they are not. In
/// checked mode, many of these APIs will assert if the constraints
/// are not normalized.
@override
bool get isNormalized {
return minWidth >= 0.0 &&
minWidth <= maxWidth &&
minHeight >= 0.0 &&
minHeight <= maxHeight;
}
@override
bool debugAssertIsValid({
bool isAppliedConstraint = false,
InformationCollector informationCollector,
}) {
assert(() {
void throwError(DiagnosticsNode message) {
throw FlutterError.fromParts(<DiagnosticsNode>[
message,
if (informationCollector != null) ...informationCollector(),
DiagnosticsProperty<BoxConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty),
]);
}
if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) {
final List<String> affectedFieldsList = <String>[
if (minWidth.isNaN) 'minWidth',
if (maxWidth.isNaN) 'maxWidth',
if (minHeight.isNaN) 'minHeight',
if (maxHeight.isNaN) 'maxHeight',
];
assert(affectedFieldsList.isNotEmpty);
if (affectedFieldsList.length > 1)
affectedFieldsList.add('and ${affectedFieldsList.removeLast()}');
String whichFields = '';
if (affectedFieldsList.length > 2) {
whichFields = affectedFieldsList.join(', ');
} else if (affectedFieldsList.length == 2) {
whichFields = affectedFieldsList.join(' ');
} else {
whichFields = affectedFieldsList.single;
}
throwError(ErrorSummary('BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values' } in $whichFields.'));
}
if (minWidth < 0.0 && minHeight < 0.0)
throwError(ErrorSummary('BoxConstraints has both a negative minimum width and a negative minimum height.'));
if (minWidth < 0.0)
throwError(ErrorSummary('BoxConstraints has a negative minimum width.'));
if (minHeight < 0.0)
throwError(ErrorSummary('BoxConstraints has a negative minimum height.'));
if (maxWidth < minWidth && maxHeight < minHeight)
throwError(ErrorSummary('BoxConstraints has both width and height constraints non-normalized.'));
if (maxWidth < minWidth)
throwError(ErrorSummary('BoxConstraints has non-normalized width constraints.'));
if (maxHeight < minHeight)
throwError(ErrorSummary('BoxConstraints has non-normalized height constraints.'));
if (isAppliedConstraint) {
if (minWidth.isInfinite && minHeight.isInfinite)
throwError(ErrorSummary('BoxConstraints forces an infinite width and infinite height.'));
if (minWidth.isInfinite)
throwError(ErrorSummary('BoxConstraints forces an infinite width.'));
if (minHeight.isInfinite)
throwError(ErrorSummary('BoxConstraints forces an infinite height.'));
}
assert(isNormalized);
return true;
}());
return isNormalized;
}
/// Returns a box constraints that [isNormalized].
///
/// The returned [maxWidth] is at least as large as the [minWidth]. Similarly,
/// the returned [maxHeight] is at least as large as the [minHeight].
BoxConstraints normalize() {
if (isNormalized)
return this;
final double minWidth = this.minWidth >= 0.0 ? this.minWidth : 0.0;
final double minHeight = this.minHeight >= 0.0 ? this.minHeight : 0.0;
return BoxConstraints(
minWidth: minWidth,
maxWidth: minWidth > maxWidth ? minWidth : maxWidth,
minHeight: minHeight,
maxHeight: minHeight > maxHeight ? minHeight : maxHeight,
);
}
@override
bool operator ==(Object other) {
assert(debugAssertIsValid());
if (identical(this, other))
return true;
if (other.runtimeType != runtimeType)
return false;
assert(other is BoxConstraints && other.debugAssertIsValid());
return other is BoxConstraints
&& other.minWidth == minWidth
&& other.maxWidth == maxWidth
&& other.minHeight == minHeight
&& other.maxHeight == maxHeight;
}
@override
int get hashCode {
assert(debugAssertIsValid());
return hashValues(minWidth, maxWidth, minHeight, maxHeight);
}
@override
String toString() {
final String annotation = isNormalized ? '' : '; NOT NORMALIZED';
if (minWidth == double.infinity && minHeight == double.infinity)
return 'BoxConstraints(biggest$annotation)';
if (minWidth == 0 && maxWidth == double.infinity &&
minHeight == 0 && maxHeight == double.infinity)
return 'BoxConstraints(unconstrained$annotation)';
String describe(double min, double max, String dim) {
if (min == max)
return '$dim=${min.toStringAsFixed(1)}';
return '${min.toStringAsFixed(1)}<=$dim<=${max.toStringAsFixed(1)}';
}
final String width = describe(minWidth, maxWidth, 'w');
final String height = describe(minHeight, maxHeight, 'h');
return 'BoxConstraints($width, $height$annotation)';
}
}
/// Method signature for hit testing a [RenderBox].
///
/// Used by [BoxHitTestResult.addWithPaintTransform] to hit test children
/// of a [RenderBox].
///
/// See also:
///
/// * [RenderBox.hitTest], which documents more details around hit testing
/// [RenderBox]es.
typedef BoxHitTest = bool Function(BoxHitTestResult result, Offset position);
/// The result of performing a hit test on [RenderBox]es.
///
/// An instance of this class is provided to [RenderBox.hitTest] to record the
/// result of the hit test.
class BoxHitTestResult extends HitTestResult {
/// Creates an empty hit test result for hit testing on [RenderBox].
BoxHitTestResult() : super();
/// Wraps `result` to create a [HitTestResult] that implements the
/// [BoxHitTestResult] protocol for hit testing on [RenderBox]es.
///
/// This method is used by [RenderObject]s that adapt between the
/// [RenderBox]-world and the non-[RenderBox]-world to convert a (subtype of)
/// [HitTestResult] to a [BoxHitTestResult] for hit testing on [RenderBox]es.
///
/// The [HitTestEntry] instances added to the returned [BoxHitTestResult] are
/// also added to the wrapped `result` (both share the same underlying data
/// structure to store [HitTestEntry] instances).
///
/// See also:
///
/// * [HitTestResult.wrap], which turns a [BoxHitTestResult] back into a
/// generic [HitTestResult].
/// * [SliverHitTestResult.wrap], which turns a [BoxHitTestResult] into a
/// [SliverHitTestResult] for hit testing on [RenderSliver] children.
BoxHitTestResult.wrap(HitTestResult result) : super.wrap(result);
/// Transforms `position` to the local coordinate system of a child for
/// hit-testing the child.
///
/// The actual hit testing of the child needs to be implemented in the
/// provided `hitTest` callback, which is invoked with the transformed
/// `position` as argument.
///
/// The provided paint `transform` (which describes the transform from the
/// child to the parent in 3D) is processed by
/// [PointerEvent.removePerspectiveTransform] to remove the
/// perspective component and inverted before it is used to transform
/// `position` from the coordinate system of the parent to the system of the
/// child.
///
/// If `transform` is null it will be treated as the identity transform and
/// `position` is provided to the `hitTest` callback as-is. If `transform`
/// cannot be inverted, the `hitTest` callback is not invoked and false is
/// returned. Otherwise, the return value of the `hitTest` callback is
/// returned.
///
/// The `position` argument may be null, which will be forwarded to the
/// `hitTest` callback as-is. Using null as the position can be useful if
/// the child speaks a different hit test protocol then the parent and the
/// position is not required to do the actual hit testing in that protocol.
///
/// {@tool snippet}
/// This method is used in [RenderBox.hitTestChildren] when the child and
/// parent don't share the same origin.
///
/// ```dart
/// abstract class Foo extends RenderBox {
///
/// final Matrix4 _effectiveTransform = Matrix4.rotationZ(50);
///
/// @override
/// void applyPaintTransform(RenderBox child, Matrix4 transform) {
/// transform.multiply(_effectiveTransform);
/// }
///
/// @override
/// bool hitTestChildren(BoxHitTestResult result, { Offset position }) {
/// return result.addWithPaintTransform(
/// transform: _effectiveTransform,
/// position: position,
/// hitTest: (BoxHitTestResult result, Offset position) {
/// return super.hitTestChildren(result, position: position);
/// },
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [addWithPaintOffset], which can be used for `transform`s that are just
/// simple matrix translations by an [Offset].
/// * [addWithRawTransform], which takes a transform matrix that is directly
/// used to transform the position without any pre-processing.
bool addWithPaintTransform({
@required Matrix4 transform,
@required Offset position,
@required BoxHitTest hitTest,
}) {
assert(hitTest != null);
if (transform != null) {
transform = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(transform));
if (transform == null) {
// Objects are not visible on screen and cannot be hit-tested.
return false;
}
}
return addWithRawTransform(
transform: transform,
position: position,
hitTest: hitTest,
);
}
/// Convenience method for hit testing children, that are translated by
/// an [Offset].
///
/// The actual hit testing of the child needs to be implemented in the
/// provided `hitTest` callback, which is invoked with the transformed
/// `position` as argument.
///
/// This method can be used as a convenience over [addWithPaintTransform] if
/// a parent paints a child at an `offset`.
///
/// A null value for `offset` is treated as if [Offset.zero] was provided.
///
/// Se also:
///
/// * [addWithPaintTransform], which takes a generic paint transform matrix and
/// documents the intended usage of this API in more detail.
bool addWithPaintOffset({
@required Offset offset,
@required Offset position,
@required BoxHitTest hitTest,
}) {
assert(hitTest != null);
return addWithRawTransform(
transform: offset != null ? Matrix4.translationValues(-offset.dx, -offset.dy, 0.0) : null,
position: position,
hitTest: hitTest,
);
}
/// Transforms `position` to the local coordinate system of a child for
/// hit-testing the child.
///
/// The actual hit testing of the child needs to be implemented in the
/// provided `hitTest` callback, which is invoked with the transformed
/// `position` as argument.
///
/// Unlike [addWithPaintTransform], the provided `transform` matrix is used
/// directly to transform `position` without any pre-processing.
///
/// If `transform` is null it will be treated as the identity transform ad
/// `position` is provided to the `hitTest` callback as-is.
///
/// The function returns the return value of the `hitTest` callback.
///
/// The `position` argument may be null, which will be forwarded to the
/// `hitTest` callback as-is. Using null as the position can be useful if
/// the child speaks a different hit test protocol then the parent and the
/// position is not required to do the actual hit testing in that protocol.
///
/// Se also:
///
/// * [addWithPaintTransform], which accomplishes the same thing, but takes a
/// _paint_ transform matrix.
bool addWithRawTransform({
@required Matrix4 transform,
@required Offset position,
@required BoxHitTest hitTest,
}) {
assert(hitTest != null);
final Offset transformedPosition = position == null || transform == null
? position
: MatrixUtils.transformPoint(transform, position);
if (transform != null) {
pushTransform(transform);
}
final bool isHit = hitTest(this, transformedPosition);
if (transform != null) {
popTransform();
}
return isHit;
}
}
/// A hit test entry used by [RenderBox].
class BoxHitTestEntry extends HitTestEntry {
/// Creates a box hit test entry.
///
/// The [localPosition] argument must not be null.
BoxHitTestEntry(RenderBox target, this.localPosition)
: assert(localPosition != null),
super(target);
@override
RenderBox get target => super.target as RenderBox;
/// The position of the hit test in the local coordinates of [target].
final Offset localPosition;
@override
String toString() => '${describeIdentity(target)}@$localPosition';
}
/// Parent data used by [RenderBox] and its subclasses.
class BoxParentData extends ParentData {
/// The offset at which to paint the child in the parent's coordinate system.
Offset offset = Offset.zero;
@override
String toString() => 'offset=$offset';
}
/// Abstract ParentData subclass for RenderBox subclasses that want the
/// ContainerRenderObjectMixin.
///
/// This is a convenience class that mixes in the relevant classes with
/// the relevant type arguments.
abstract class ContainerBoxParentData<ChildType extends RenderObject> extends BoxParentData with ContainerParentDataMixin<ChildType> { }
enum _IntrinsicDimension { minWidth, maxWidth, minHeight, maxHeight }
@immutable
class _IntrinsicDimensionsCacheEntry {
const _IntrinsicDimensionsCacheEntry(this.dimension, this.argument);
final _IntrinsicDimension dimension;
final double argument;
@override
bool operator ==(Object other) {
return other is _IntrinsicDimensionsCacheEntry
&& other.dimension == dimension
&& other.argument == argument;
}
@override
int get hashCode => hashValues(dimension, argument);
}
/// A render object in a 2D Cartesian coordinate system.
///
/// The [size] of each box is expressed as a width and a height. Each box has
/// its own coordinate system in which its upper left corner is placed at (0,
/// 0). The lower right corner of the box is therefore at (width, height). The
/// box contains all the points including the upper left corner and extending
/// to, but not including, the lower right corner.
///
/// Box layout is performed by passing a [BoxConstraints] object down the tree.
/// The box constraints establish a min and max value for the child's width and
/// height. In determining its size, the child must respect the constraints
/// given to it by its parent.
///
/// This protocol is sufficient for expressing a number of common box layout
/// data flows. For example, to implement a width-in-height-out data flow, call
/// your child's [layout] function with a set of box constraints with a tight
/// width value (and pass true for parentUsesSize). After the child determines
/// its height, use the child's height to determine your size.
///
/// ## Writing a RenderBox subclass
///
/// One would implement a new [RenderBox] subclass to describe a new layout
/// model, new paint model, new hit-testing model, or new semantics model, while
/// remaining in the Cartesian space defined by the [RenderBox] protocol.
///
/// To create a new protocol, consider subclassing [RenderObject] instead.
///
/// ### Constructors and properties of a new RenderBox subclass
///
/// The constructor will typically take a named argument for each property of
/// the class. The value is then passed to a private field of the class and the
/// constructor asserts its correctness (e.g. if it should not be null, it
/// asserts it's not null).
///
/// Properties have the form of a getter/setter/field group like the following:
///
/// ```dart
/// AxisDirection get axis => _axis;
/// AxisDirection _axis;
/// set axis(AxisDirection value) {
/// assert(value != null); // same check as in the constructor
/// if (value == _axis)
/// return;
/// _axis = value;
/// markNeedsLayout();
/// }
/// ```
///
/// The setter will typically finish with either a call to [markNeedsLayout], if
/// the layout uses this property, or [markNeedsPaint], if only the painter
/// function does. (No need to call both, [markNeedsLayout] implies
/// [markNeedsPaint].)
///
/// Consider layout and paint to be expensive; be conservative about calling
/// [markNeedsLayout] or [markNeedsPaint]. They should only be called if the
/// layout (or paint, respectively) has actually changed.
///
/// ### Children
///
/// If a render object is a leaf, that is, it cannot have any children, then
/// ignore this section. (Examples of leaf render objects are [RenderImage] and
/// [RenderParagraph].)
///
/// For render objects with children, there are four possible scenarios:
///
/// * A single [RenderBox] child. In this scenario, consider inheriting from
/// [RenderProxyBox] (if the render object sizes itself to match the child) or
/// [RenderShiftedBox] (if the child will be smaller than the box and the box
/// will align the child inside itself).
///
/// * A single child, but it isn't a [RenderBox]. Use the
/// [RenderObjectWithChildMixin] mixin.
///
/// * A single list of children. Use the [ContainerRenderObjectMixin] mixin.
///
/// * A more complicated child model.
///
/// #### Using RenderProxyBox
///
/// By default, a [RenderProxyBox] render object sizes itself to fit its child, or
/// to be as small as possible if there is no child; it passes all hit testing
/// and painting on to the child, and intrinsic dimensions and baseline
/// measurements similarly are proxied to the child.
///
/// A subclass of [RenderProxyBox] just needs to override the parts of the
/// [RenderBox] protocol that matter. For example, [RenderOpacity] just
/// overrides the paint method (and [alwaysNeedsCompositing] to reflect what the
/// paint method does, and the [visitChildrenForSemantics] method so that the
/// child is hidden from accessibility tools when it's invisible), and adds an
/// [RenderOpacity.opacity] field.
///
/// [RenderProxyBox] assumes that the child is the size of the parent and
/// positioned at 0,0. If this is not true, then use [RenderShiftedBox] instead.
///
/// See
/// [proxy_box.dart](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/rendering/proxy_box.dart)
/// for examples of inheriting from [RenderProxyBox].
///
/// #### Using RenderShiftedBox
///
/// By default, a [RenderShiftedBox] acts much like a [RenderProxyBox] but
/// without assuming that the child is positioned at 0,0 (the actual position
/// recorded in the child's [parentData] field is used), and without providing a
/// default layout algorithm.
///
/// See
/// [shifted_box.dart](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/rendering/shifted_box.dart)
/// for examples of inheriting from [RenderShiftedBox].
///
/// #### Kinds of children and child-specific data
///
/// A [RenderBox] doesn't have to have [RenderBox] children. One can use another
/// subclass of [RenderObject] for a [RenderBox]'s children. See the discussion
/// at [RenderObject].
///
/// Children can have additional data owned by the parent but stored on the
/// child using the [parentData] field. The class used for that data must
/// inherit from [ParentData]. The [setupParentData] method is used to
/// initialize the [parentData] field of a child when the child is attached.
///
/// By convention, [RenderBox] objects that have [RenderBox] children use the
/// [BoxParentData] class, which has a [BoxParentData.offset] field to store the
/// position of the child relative to the parent. ([RenderProxyBox] does not
/// need this offset and therefore is an exception to this rule.)
///
/// #### Using RenderObjectWithChildMixin
///
/// If a render object has a single child but it isn't a [RenderBox], then the
/// [RenderObjectWithChildMixin] class, which is a mixin that will handle the
/// boilerplate of managing a child, will be useful.