/
ConstraintLayout.kt
1537 lines (1393 loc) · 57.4 KB
/
ConstraintLayout.kt
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 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.constraintlayout.compose
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.LayoutScopeMarker
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateObserver
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.layout.*
import androidx.compose.ui.platform.InspectorValueInfo
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.*
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastForEachIndexed
import androidx.constraintlayout.core.parser.CLObject
import androidx.constraintlayout.core.parser.CLParser
import androidx.constraintlayout.core.parser.CLParsingException
import androidx.constraintlayout.core.state.*
import androidx.constraintlayout.core.state.Dimension.*
import androidx.constraintlayout.core.widgets.*
import androidx.constraintlayout.core.widgets.ConstraintWidget.*
import androidx.constraintlayout.core.widgets.ConstraintWidget.DimensionBehaviour.*
import androidx.constraintlayout.core.widgets.analyzer.BasicMeasure
import androidx.constraintlayout.core.widgets.analyzer.BasicMeasure.Measure.TRY_GIVEN_DIMENSIONS
import androidx.constraintlayout.core.widgets.analyzer.BasicMeasure.Measure.USE_GIVEN_DIMENSIONS
import kotlinx.coroutines.channels.Channel
import org.intellij.lang.annotations.Language
import java.util.*
/**
* Layout that positions its children according to the constraints between them.
*
* Example usage:
* @sample androidx.constraintlayout.compose.samples.DemoInlineDSL
*/
@Composable
inline fun ConstraintLayout(
modifier: Modifier = Modifier,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
crossinline content: @Composable ConstraintLayoutScope.() -> Unit
) {
val measurer = remember { Measurer() }
val scope = remember { ConstraintLayoutScope() }
val remeasureRequesterState = remember { mutableStateOf(false) }
val (measurePolicy, onHelpersChanged) = rememberConstraintLayoutMeasurePolicy(
optimizationLevel,
scope,
remeasureRequesterState,
measurer
)
@Suppress("Deprecation")
MultiMeasureLayout(
modifier = modifier.semantics { designInfoProvider = measurer },
measurePolicy = measurePolicy,
content = {
val previousHelpersHashCode = scope.helpersHashCode
scope.reset()
scope.content()
if (scope.helpersHashCode != previousHelpersHashCode) onHelpersChanged()
}
)
}
@Composable
@PublishedApi
internal fun rememberConstraintLayoutMeasurePolicy(
optimizationLevel: Int,
scope: ConstraintLayoutScope,
remeasureRequesterState: MutableState<Boolean>,
measurer: Measurer
): Pair<MeasurePolicy, () -> Unit> {
val constraintSet = remember { ConstraintSetForInlineDsl(scope) }
return remember(optimizationLevel) {
val measurePolicy = MeasurePolicy { measurables, constraints ->
val layoutSize = measurer.performMeasure(
constraints,
layoutDirection,
constraintSet,
measurables,
optimizationLevel,
this
)
// We read the remeasurement requester state, to request remeasure when the value
// changes. This will happen when the scope helpers are changing at recomposition.
remeasureRequesterState.value
layout(layoutSize.width, layoutSize.height) {
with(measurer) { performLayout(measurables) }
}
}
val onHelpersChanged = {
// If the helpers have changed, we need to request remeasurement. To achieve this,
// we are changing this boolean state that is read during measurement.
remeasureRequesterState.value = !remeasureRequesterState.value
constraintSet.knownDirty = true
}
measurePolicy to onHelpersChanged
}
}
private class ConstraintSetForInlineDsl(
val scope: ConstraintLayoutScope
) : ConstraintSet, RememberObserver {
private var handler: Handler? = null
private val observer = SnapshotStateObserver {
if (Looper.myLooper() == Looper.getMainLooper()) {
it()
} else {
val h = handler ?: Handler(Looper.getMainLooper()).also { h -> handler = h }
h.post(it)
}
}
override fun applyTo(state: State, measurables: List<Measurable>) {
scope.applyTo(state)
previousDatas.clear()
observer.observeReads(Unit, onCommitAffectingConstrainLambdas) {
measurables.fastForEach { measurable ->
val parentData = measurable.parentData as? ConstraintLayoutParentData
// Run the constrainAs block of the child, to obtain its constraints.
if (parentData != null) {
val constrainScope = ConstrainScope(parentData.ref.id)
parentData.constrain(constrainScope)
constrainScope.applyTo(state)
}
previousDatas.add(parentData)
}
}
knownDirty = false
}
var knownDirty = true
private val onCommitAffectingConstrainLambdas = { _: Unit -> knownDirty = true }
override fun isDirty(measurables: List<Measurable>): Boolean {
if (knownDirty || measurables.size != previousDatas.size) return true
measurables.fastForEachIndexed { index, measurable ->
if (measurable.parentData as? ConstraintLayoutParentData != previousDatas[index]) {
return true
}
}
return false
}
private val previousDatas = mutableListOf<ConstraintLayoutParentData?>()
override fun onRemembered() {
observer.start()
}
override fun onForgotten() {
observer.stop()
observer.clear()
}
override fun onAbandoned() {}
}
/**
* Layout that positions its children according to the constraints between them.
*
* Example usage:
* @sample androidx.constraintlayout.compose.samples.DemoConstraintSet
*
* When recomposed with different constraintsets, you can use the animateChanges parameter
* to animate the layout changes (animationSpec and finishedAnimationListener attributes can
* also be useful in this mode). This is only intended for basic transitions, if more control
* is needed, we recommend using MotionLayout instead.
*/
@Suppress("NOTHING_TO_INLINE")
@Composable
inline fun ConstraintLayout(
constraintSet: ConstraintSet,
modifier: Modifier = Modifier,
optimizationLevel: Int = Optimizer.OPTIMIZATION_STANDARD,
animateChanges: Boolean = false,
animationSpec: AnimationSpec<Float> = tween<Float>(),
noinline finishedAnimationListener: (() -> Unit)? = null,
noinline content: @Composable () -> Unit
) {
if (animateChanges) {
var startConstraint by remember { mutableStateOf(constraintSet) }
var endConstraint by remember { mutableStateOf(constraintSet) }
val progress = remember { Animatable(0.0f) }
val channel = remember { Channel<ConstraintSet>(Channel.CONFLATED) }
val direction = remember { mutableStateOf(1) }
SideEffect {
channel.trySend(constraintSet)
}
LaunchedEffect(channel) {
for (constraints in channel) {
val newConstraints = channel.tryReceive().getOrNull() ?: constraints
val currentConstraints = if (direction.value == 1) startConstraint else endConstraint
if (newConstraints != currentConstraints) {
if (direction.value == 1) {
endConstraint = newConstraints
} else {
startConstraint = newConstraints
}
progress.animateTo(direction.value.toFloat(), animationSpec)
direction.value = if (direction.value == 1) 0 else 1
finishedAnimationListener?.invoke()
}
}
}
MotionLayout(
start = startConstraint,
end = endConstraint,
progress = progress.value,
modifier = modifier,
content = { content() })
} else {
val needsUpdate = remember {
mutableStateOf(0L)
}
val measurer = remember { Measurer() }
val measurePolicy = rememberConstraintLayoutMeasurePolicy(
optimizationLevel,
needsUpdate,
constraintSet,
measurer
)
if (constraintSet is EditableJSONLayout) {
constraintSet.setUpdateFlag(needsUpdate)
}
measurer.addLayoutInformationReceiver(constraintSet as? LayoutInformationReceiver)
val forcedScaleFactor = measurer.forcedScaleFactor
if (!forcedScaleFactor.isNaN()) {
var mod = modifier.scale(measurer.forcedScaleFactor)
Box {
@Suppress("DEPRECATION")
MultiMeasureLayout(
modifier = mod.semantics { designInfoProvider = measurer },
measurePolicy = measurePolicy,
content = {
measurer.createDesignElements()
content()
}
)
with(measurer) {
drawDebugBounds(forcedScaleFactor)
}
}
} else {
@Suppress("DEPRECATION")
MultiMeasureLayout(
modifier = modifier.semantics { designInfoProvider = measurer },
measurePolicy = measurePolicy,
content = {
measurer.createDesignElements()
content()
}
)
}
}
}
@Composable
@PublishedApi
internal fun rememberConstraintLayoutMeasurePolicy(
optimizationLevel: Int,
needsUpdate: MutableState<Long>,
constraintSet: ConstraintSet,
measurer: Measurer
) = remember(optimizationLevel, needsUpdate.value, constraintSet) {
measurer.parseDesignElements(constraintSet)
MeasurePolicy { measurables, constraints ->
val layoutSize = measurer.performMeasure(
constraints,
layoutDirection,
constraintSet,
measurables,
optimizationLevel,
this
)
layout(layoutSize.width, layoutSize.height) {
with(measurer) { performLayout(measurables) }
}
}
}
/**
* Scope used by the inline DSL of [ConstraintLayout].
*/
@LayoutScopeMarker
class ConstraintLayoutScope @PublishedApi internal constructor() : ConstraintLayoutBaseScope() {
/**
* Creates one [ConstrainedLayoutReference], which needs to be assigned to a layout within the
* [ConstraintLayout] as part of [Modifier.constrainAs]. To create more references at the
* same time, see [createRefs].
*/
fun createRef() = childrenRefs.getOrNull(childId++) ?:
ConstrainedLayoutReference(childId).also { childrenRefs.add(it) }
/**
* Convenient way to create multiple [ConstrainedLayoutReference]s, which need to be assigned
* to layouts within the [ConstraintLayout] as part of [Modifier.constrainAs]. To create just
* one reference, see [createRef].
*/
@Stable
fun createRefs() =
referencesObject ?: ConstrainedLayoutReferences().also { referencesObject = it }
private var referencesObject: ConstrainedLayoutReferences? = null
private val ChildrenStartIndex = 0
private var childId = ChildrenStartIndex
private val childrenRefs = ArrayList<ConstrainedLayoutReference>()
override fun reset() {
super.reset()
childId = ChildrenStartIndex
}
/**
* Convenience API for creating multiple [ConstrainedLayoutReference] via [createRefs].
*/
inner class ConstrainedLayoutReferences internal constructor() {
operator fun component1() = createRef()
operator fun component2() = createRef()
operator fun component3() = createRef()
operator fun component4() = createRef()
operator fun component5() = createRef()
operator fun component6() = createRef()
operator fun component7() = createRef()
operator fun component8() = createRef()
operator fun component9() = createRef()
operator fun component10() = createRef()
operator fun component11() = createRef()
operator fun component12() = createRef()
operator fun component13() = createRef()
operator fun component14() = createRef()
operator fun component15() = createRef()
operator fun component16() = createRef()
}
/**
* [Modifier] that defines the constraints, as part of a [ConstraintLayout], of the layout
* element.
*/
@Stable
fun Modifier.constrainAs(
ref: ConstrainedLayoutReference,
constrainBlock: ConstrainScope.() -> Unit
) = this.then(ConstrainAsModifier(ref, constrainBlock))
@Stable
private class ConstrainAsModifier(
private val ref: ConstrainedLayoutReference,
private val constrainBlock: ConstrainScope.() -> Unit
) : ParentDataModifier, InspectorValueInfo(
debugInspectorInfo {
name = "constrainAs"
properties["ref"] = ref
properties["constrainBlock"] = constrainBlock
}
) {
override fun Density.modifyParentData(parentData: Any?) =
ConstraintLayoutParentData(ref, constrainBlock)
override fun hashCode() = constrainBlock.hashCode()
override fun equals(other: Any?) =
constrainBlock == (other as? ConstrainAsModifier)?.constrainBlock
}
}
/**
* Scope used by the [ConstraintSet] DSL.
*/
@LayoutScopeMarker
class ConstraintSetScope internal constructor() : ConstraintLayoutBaseScope() {
/**
* Creates one [ConstrainedLayoutReference] corresponding to the [ConstraintLayout] element
* with [id].
*/
fun createRefFor(id: Any) = ConstrainedLayoutReference(id)
/**
* Specifies the constraints associated to the layout identified with [ref].
*/
fun constrain(
ref: ConstrainedLayoutReference,
constrainBlock: ConstrainScope.() -> Unit
) = ConstrainScope(ref.id).apply {
constrainBlock()
this@ConstraintSetScope.tasks.addAll(this.tasks)
}
}
/**
* Parent data provided by `Modifier.constrainAs`.
*/
@Stable
private class ConstraintLayoutParentData(
val ref: ConstrainedLayoutReference,
val constrain: ConstrainScope.() -> Unit
) : LayoutIdParentData {
override val layoutId: Any = ref.id
override fun equals(other: Any?) = other is ConstraintLayoutParentData &&
ref.id == other.ref.id && constrain == other.constrain
override fun hashCode() = ref.id.hashCode() * 31 + constrain.hashCode()
}
/**
* Convenience for creating ids corresponding to layout references that cannot be referred
* to from the outside of the scope (e.g. barriers, layout references in the modifier-based API,
* etc.).
*/
internal fun createId() = object : Any() {}
/**
* Represents a dimension that can be assigned to the width or height of a [ConstraintLayout]
* [child][ConstrainedLayoutReference].
*/
// TODO(popam, b/157781841): It is unfortunate that this interface is top level in
// `foundation-layout`. This will be ok if we move constraint layout to its own module or at
// least subpackage.
interface Dimension {
/**
* A [Dimension] that can be assigned both min and max bounds.
*/
interface Coercible : Dimension
/**
* A [Dimension] that can be assigned a min bound.
*/
interface MinCoercible : Dimension
/**
* A [Dimension] that can be assigned a max bound.
*/
interface MaxCoercible : Dimension
companion object {
/**
* Links should be specified from both sides corresponding to this dimension, in order for
* this to work.
*
* Creates a [Dimension] such that if the constraints allow it, will have the size given by
* [dp], otherwise will take the size remaining within the constraints.
*
* This is effectively a shorthand for [fillToConstraints] with a max value.
*
* To make the value fixed (respected regardless the [ConstraintSet]), [value] should
* be used instead.
*/
fun preferredValue(dp: Dp): Dimension.MinCoercible =
DimensionDescription { state -> SolverDimension.Suggested(state.convertDimension(dp)).suggested(SPREAD_DIMENSION) }
/**
* Creates a [Dimension] representing a fixed dp size. The size will not change
* according to the constraints in the [ConstraintSet].
*/
fun value(dp: Dp): Dimension =
DimensionDescription { state -> SolverDimension.Fixed(state.convertDimension(dp)) }
/**
* Sets the dimensions to be defined as a ratio of the width and height. The assigned
* dimension will be considered to also be [fillToConstraints].
*
* The string to define a ratio is defined by the format: 'W:H'.
* Where H is the height as a proportion of W (the width).
*
* Eg: width = Dimension.ratio('1:2') sets the width to be half as large as the height.
*
* Note that only one dimension should be defined as a ratio.
*/
fun ratio(ratio: String): Dimension =
DimensionDescription { SolverDimension.Ratio(ratio).suggested(SPREAD_DIMENSION) }
/**
* Links should be specified from both sides corresponding to this dimension, in order for
* this to work.
*
* A [Dimension] with suggested wrap content behavior. The wrap content size
* will be respected unless the constraints in the [ConstraintSet] do not allow it.
* To make the value fixed (respected regardless the [ConstraintSet]), [wrapContent]
* should be used instead.
*/
val preferredWrapContent: Dimension.Coercible
get() = DimensionDescription { SolverDimension.Suggested(WRAP_DIMENSION) }
/**
* A fixed [Dimension] with wrap content behavior. The size will not change
* according to the constraints in the [ConstraintSet].
*/
val wrapContent: Dimension
get() = DimensionDescription { SolverDimension.Fixed(WRAP_DIMENSION) }
/**
* A fixed [Dimension] that matches the dimensions of the root ConstraintLayout. The size
* will not change accoring to the constraints in the [ConstraintSet].
*/
val matchParent: Dimension
get() = DimensionDescription { SolverDimension.Parent() }
/**
* Links should be specified from both sides corresponding to this dimension, in order for
* this to work.
*
* A [Dimension] that spreads to match constraints.
*/
val fillToConstraints: Dimension.Coercible
get() = DimensionDescription { SolverDimension.Suggested(SPREAD_DIMENSION) }
/**
* A [Dimension] that is a percent of the parent in the corresponding direction.
*/
fun percent(percent: Float): Dimension =
// TODO(popam, b/157880732): make this nicer when possible in future solver releases
DimensionDescription { SolverDimension.Percent(0, percent).suggested(0) }
}
}
/**
* Sets the lower bound of the current [Dimension] to be the wrap content size of the child.
*/
val Dimension.Coercible.atLeastWrapContent: Dimension.MaxCoercible
get() = (this as DimensionDescription).also { it.minSymbol = WRAP_DIMENSION }
/**
* Sets the lower bound of the current [Dimension] to a fixed [dp] value.
*/
fun Dimension.Coercible.atLeast(dp: Dp): Dimension.MaxCoercible =
(this as DimensionDescription).also { it.min = dp }
/**
* Sets the upper bound of the current [Dimension] to a fixed [dp] value.
*/
fun Dimension.Coercible.atMost(dp: Dp): Dimension.MinCoercible =
(this as DimensionDescription).also { it.max = dp }
/**
* Sets the upper bound of the current [Dimension] to be the wrap content size of the child.
*/
val Dimension.Coercible.atMostWrapContent: Dimension.MinCoercible
get() = (this as DimensionDescription).also { it.maxSymbol = WRAP_DIMENSION }
/**
* Sets the lower bound of the current [Dimension] to a fixed [dp] value.
*/
@Deprecated(message = "Unintended method name, use atLeast(dp) instead", replaceWith = ReplaceWith("this.atLeast(dp)", "androidx.constraintlayout.compose.atLeast"))
fun Dimension.MinCoercible.atLeastWrapContent(dp: Dp): Dimension =
(this as DimensionDescription).also { it.min = dp }
/**
* Sets the lower bound of the current [Dimension] to a fixed [dp] value.
*/
fun Dimension.MinCoercible.atLeast(dp: Dp): Dimension =
(this as DimensionDescription).also { it.min = dp }
/**
* Sets the lower bound of the current [Dimension] to be the wrap content size of the child.
*/
val Dimension.MinCoercible.atLeastWrapContent: Dimension
get() = (this as DimensionDescription).also { it.minSymbol = WRAP_DIMENSION }
/**
* Sets the upper bound of the current [Dimension] to a fixed [dp] value.
*/
fun Dimension.MaxCoercible.atMost(dp: Dp): Dimension =
(this as DimensionDescription).also { it.max = dp }
/**
* Sets the upper bound of the current [Dimension] to be the [Wrap] size of the child.
*/
val Dimension.MaxCoercible.atMostWrapContent: Dimension
get() = (this as DimensionDescription).also { it.maxSymbol = WRAP_DIMENSION }
/**
* Describes a sizing behavior that can be applied to the width or height of a
* [ConstraintLayout] child. The content of this class should not be instantiated
* directly; helpers available in the [Dimension]'s companion object should be used.
*/
internal class DimensionDescription internal constructor(
private val baseDimension: (State) -> SolverDimension
) : Dimension.Coercible, Dimension.MinCoercible, Dimension.MaxCoercible, Dimension {
var min: Dp? = null
var minSymbol: Any? = null
var max: Dp? = null
var maxSymbol: Any? = null
internal fun toSolverDimension(state: State) = baseDimension(state).also {
if (minSymbol != null) {
it.min(minSymbol)
} else if (min != null) {
it.min(state.convertDimension(min!!))
}
if (maxSymbol != null) {
it.max(maxSymbol)
} else if (max != null) {
it.max(state.convertDimension(max!!))
}
}
}
@SuppressLint("ComposableNaming")
@Composable
fun ConstraintSet(@Language("json5") content : String,
@Language("json5") overrideVariables: String? = null) : ConstraintSet {
val constraintset = remember(content, overrideVariables) {
JSONConstraintSet(content, overrideVariables)
}
return constraintset
}
/**
* Handles update back to the composable
*/
@PublishedApi
internal abstract class EditableJSONLayout(@Language("json5") content: String) :
LayoutInformationReceiver {
private var forcedWidth: Int = Int.MIN_VALUE
private var forcedHeight: Int = Int.MIN_VALUE
private var forcedDrawDebug: MotionLayoutDebugFlags = MotionLayoutDebugFlags.UNKNOWN
private var updateFlag: MutableState<Long>? = null
private var layoutInformationMode: LayoutInfoFlags = LayoutInfoFlags.BOUNDS
private var layoutInformation = ""
private var last = System.nanoTime();
private var debugName : String? = null
private var currentContent = content
protected fun initialization() {
try {
onNewContent(currentContent)
if (debugName != null) {
val mainHandler = Handler(Looper.getMainLooper())
val callback = object : RegistryCallback {
override fun onNewMotionScene(content: String?) {
if (content == null) {
return
}
mainHandler.post {
try {
onNewContent(content)
} catch (e : Exception) {}
}
}
override fun onProgress(progress: Float) {
mainHandler.post {
try {
onNewProgress(progress)
} catch (e : Exception) {}
}
}
override fun onDimensions(width: Int, height: Int) {
mainHandler.post {
try {
onNewDimensions(width, height)
} catch (e : Exception) {}
}
}
override fun currentMotionScene(): String {
return currentContent
}
override fun currentLayoutInformation() : String {
return layoutInformation
}
override fun setLayoutInformationMode(mode: Int) {
mainHandler.post {
try {
onLayoutInformation(mode)
} catch (e : Exception) {}
}
}
override fun getLastModified(): Long {
return last;
}
override fun setDrawDebug(debugMode: Int) {
mainHandler.post {
try {
onDrawDebug(debugMode)
} catch (e : Exception) {}
}
}
}
val registry = Registry.getInstance()
registry.register(debugName, callback)
}
} catch (e : CLParsingException) {
}
}
///////////////////////////////////////////////////////////////////////////
// Accessors
///////////////////////////////////////////////////////////////////////////
fun setUpdateFlag(needsUpdate: MutableState<Long>) {
updateFlag = needsUpdate
}
protected fun signalUpdate() {
if (updateFlag != null) {
updateFlag!!.value = updateFlag!!.value + 1
}
}
fun setCurrentContent(content: String) {
currentContent = content
}
fun getCurrentContent() : String{
return currentContent
}
fun setDebugName(name: String?) {
debugName = name
}
fun getDebugName() : String?{
return debugName
}
fun getForcedDrawDebug(): MotionLayoutDebugFlags {
return forcedDrawDebug
}
override fun getForcedWidth(): Int {
return forcedWidth
}
override fun getForcedHeight(): Int {
return forcedHeight
}
override fun setLayoutInformation(information: String) {
last = System.nanoTime();
layoutInformation = information
}
fun getLayoutInformation() : String {
return layoutInformation
}
override fun getLayoutInformationMode(): LayoutInfoFlags {
return layoutInformationMode
}
///////////////////////////////////////////////////////////////////////////
// on update methods
///////////////////////////////////////////////////////////////////////////
protected open fun onNewContent(content: String) {
currentContent = content
try {
val json = CLParser.parse(currentContent)
if (json is CLObject) {
val firstTime = debugName == null
if (firstTime) {
val debug = json.getObjectOrNull("Header")
if (debug != null) {
debugName = debug.getStringOrNull("exportAs")
}
}
if (!firstTime) {
signalUpdate()
}
}
} catch (e : CLParsingException) {
// nothing (content might be invalid, sent by live edit)
} catch (e : Exception) {
// nothing (content might be invalid, sent by live edit)
}
}
protected open fun onNewProgress(progress: Float) {
// nothing for ConstraintSet
}
fun onNewDimensions(width: Int, height: Int) {
forcedWidth = width
forcedHeight = height
signalUpdate()
}
protected fun onLayoutInformation(mode: Int) {
when (mode) {
LayoutInfoFlags.NONE.ordinal -> layoutInformationMode = LayoutInfoFlags.NONE
LayoutInfoFlags.BOUNDS.ordinal -> layoutInformationMode = LayoutInfoFlags.BOUNDS
}
signalUpdate()
}
protected fun onDrawDebug(debugMode: Int) {
when (debugMode) {
-1 -> forcedDrawDebug = MotionLayoutDebugFlags.UNKNOWN
MotionLayoutDebugFlags.UNKNOWN.ordinal -> forcedDrawDebug = MotionLayoutDebugFlags.UNKNOWN
MotionLayoutDebugFlags.NONE.ordinal -> forcedDrawDebug = MotionLayoutDebugFlags.NONE
MotionLayoutDebugFlags.SHOW_ALL.ordinal -> forcedDrawDebug = MotionLayoutDebugFlags.SHOW_ALL
}
signalUpdate()
}
}
internal data class DesignElement(var id: String, var type: String, var params: HashMap<String, String>)
/**
* Creates a [ConstraintSet] from a [jsonContent] string.
*/
fun ConstraintSet(@Language(value = "json5") jsonContent: String): ConstraintSet =
JSONConstraintSet(content = jsonContent)
/**
* Creates a [ConstraintSet] from a [jsonContent] string that extends the changes applied by
* [extendConstraintSet].
*/
fun ConstraintSet(
extendConstraintSet: ConstraintSet,
@Language(value = "json5") jsonContent: String
): ConstraintSet =
JSONConstraintSet(content = jsonContent, extendFrom = extendConstraintSet)
/**
* Creates a [ConstraintSet].
*/
fun ConstraintSet(description: ConstraintSetScope.() -> Unit): ConstraintSet =
DslConstraintSet(description)
/**
* Creates a [ConstraintSet] that extends the changes applied by [extendConstraintSet].
*/
fun ConstraintSet(
extendConstraintSet: ConstraintSet,
description: ConstraintSetScope.() -> Unit
): ConstraintSet =
DslConstraintSet(description, extendConstraintSet)
/**
* The state of the [ConstraintLayout] solver.
*/
class State(val density: Density) : SolverState() {
var rootIncomingConstraints: Constraints = Constraints()
lateinit var layoutDirection: LayoutDirection
internal val baselineNeeded = mutableListOf<Any>()
private var dirtyBaselineNeededWidgets = true
private val baselineNeededWidgets = mutableSetOf<ConstraintWidget>()
override fun convertDimension(value: Any?): Int {
return if (value is Dp) {
with(density) { value.roundToPx() }
} else {
super.convertDimension(value)
}
}
override fun reset() {
// TODO(b/158197001): this should likely be done by the solver
mReferences.forEach { ref ->
ref.value?.constraintWidget?.reset()
}
mReferences.clear()
mReferences[PARENT] = mParent
baselineNeeded.clear()
dirtyBaselineNeededWidgets = true
super.reset()
}
internal fun baselineNeededFor(id: Any) {
baselineNeeded.add(id)
dirtyBaselineNeededWidgets = true
}
internal fun isBaselineNeeded(constraintWidget: ConstraintWidget): Boolean {
if (dirtyBaselineNeededWidgets) {
baselineNeededWidgets.clear()
baselineNeeded.forEach { id ->
val widget = mReferences[id]?.constraintWidget
if (widget != null) baselineNeededWidgets.add(widget)
}
dirtyBaselineNeededWidgets = false
}
return constraintWidget in baselineNeededWidgets
}
internal fun getKeyId(helperWidget: HelperWidget): Any? {
return mHelperReferences.entries.firstOrNull { it.value.helperWidget == helperWidget }?.key
}
}
interface LayoutInformationReceiver {
fun setLayoutInformation(information: String)
fun getLayoutInformationMode() : LayoutInfoFlags
fun getForcedWidth(): Int
fun getForcedHeight(): Int
}
@PublishedApi
internal open class Measurer : BasicMeasure.Measurer, DesignInfoProvider {
private var computedLayoutResult: String = ""
protected var layoutInformationReceiver: LayoutInformationReceiver? = null
protected val root = ConstraintWidgetContainer(0, 0).also { it.measurer = this }
protected val placeables = mutableMapOf<Measurable, Placeable>()
private val lastMeasures = mutableMapOf<Measurable, Array<Int>>()
protected val frameCache = mutableMapOf<Measurable, WidgetFrame>()
protected lateinit var density: Density
protected lateinit var measureScope: MeasureScope
protected val state by lazy(LazyThreadSafetyMode.NONE) { State(density) }
private val widthConstraintsHolder = IntArray(2)
private val heightConstraintsHolder = IntArray(2)
var forcedScaleFactor = Float.NaN
var layoutCurrentWidth: Int = 0
var layoutCurrentHeight: Int = 0
/**
* Method called by Compose tooling. Returns a JSON string that represents the Constraints
* defined for this ConstraintLayout Composable.
*/
override fun getDesignInfo(startX: Int, startY: Int, args: String) =
parseConstraintsToJson(root, state, startX, startY)
override fun measure(constraintWidget: ConstraintWidget, measure: BasicMeasure.Measure) {
val measurable = constraintWidget.companionWidget
if (measurable !is Measurable) return
if (DEBUG) {
Log.d(
"CCL",
"Measuring ${measurable.layoutId} with: " +
constraintWidget.toDebugString() + "\n" + measure.toDebugString()
)
}
var constraints: Constraints
run {
val measurableLastMeasures = lastMeasures[measurable]
obtainConstraints(
measure.horizontalBehavior,
measure.horizontalDimension,
constraintWidget.mMatchConstraintDefaultWidth,
measure.measureStrategy,
(measurableLastMeasures?.get(1) ?: 0) == constraintWidget.height,
constraintWidget.isResolvedHorizontally,
state.rootIncomingConstraints.maxWidth,
widthConstraintsHolder
)
obtainConstraints(
measure.verticalBehavior,
measure.verticalDimension,
constraintWidget.mMatchConstraintDefaultHeight,