dc_layout 0.39.1

Figma node layout library for Android
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
// Copyright 2023 Google LLC
//
// 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.

use crate::android_interface::{FromTaffyLayout as _, LayoutChangedResponseUnchangedWithState};
use crate::into_taffy::TryIntoTaffy;
use dc_bundle::jni_layout::{Layout, LayoutChangedResponse};
use dc_bundle::layout_style::LayoutStyle;
use dc_bundle::Error;
use log::{error, trace};
use std::collections::{HashMap, HashSet};
use taffy::prelude::{AvailableSpace, Size};
use taffy::{NodeId, TaffyTree};
// Customizations that can applied to a node
struct Customizations {
    sizes: HashMap<i32, Size<u32>>,
}
impl Customizations {
    fn new() -> Self {
        Customizations { sizes: HashMap::new() }
    }

    fn add_size(&mut self, layout_id: i32, width: u32, height: u32) {
        self.sizes.insert(layout_id, Size { width, height });
    }

    fn get_size(&self, layout_id: i32) -> Option<&Size<u32>> {
        self.sizes.get(&layout_id)
    }

    fn remove(&mut self, layout_id: &i32) {
        self.sizes.remove(layout_id);
    }
}

pub struct LayoutManager {
    // taffy object that does all the layout computations
    taffy: TaffyTree<i32>,
    // node id -> Taffy layout
    layouts: HashMap<taffy::tree::NodeId, Layout>,
    // A struct that keeps track of all customizations
    customizations: Customizations,
    // Incrementing ID used to keep track of layout changes. Incremented
    // every time relayout is done
    layout_state: i32,

    // layout id -> Taffy node used to calculate layout
    layout_id_to_taffy_node: HashMap<i32, taffy::tree::NodeId>,
    // Taffy node -> layout id
    taffy_node_to_layout_id: HashMap<taffy::tree::NodeId, i32>,
    // layout id -> name
    layout_id_to_name: HashMap<i32, String>,
    // A list of root level layout IDs used to recompute layout whenever
    // something has changed
    root_layout_ids: HashSet<i32>,

    // A "measure" function that the layout engine calls to consult on the
    // size of an item.
    #[allow(clippy::type_complexity)]
    measure_func: Box<
        dyn FnMut(
                Size<Option<f32>>,
                Size<AvailableSpace>,
                NodeId,
                Option<&mut i32>,
                &taffy::Style,
            ) -> Size<f32>
            + Sync
            + Send,
    >,
}
impl LayoutManager {
    pub fn new(
        mut measure_func: impl FnMut(i32, f32, f32, f32, f32) -> (f32, f32) + Sync + Send + 'static,
    ) -> Self {
        let layout_measure_func = move |size: Size<Option<f32>>,
                                        available_size: Size<AvailableSpace>,
                                        _node_id: NodeId,
                                        layout_id: Option<&mut i32>,
                                        _style: &taffy::Style|
              -> Size<f32> {
            let layout_id = if let Some(&mut id) = layout_id { id } else { return Size::ZERO };
            let width = size.width.unwrap_or(0.0);
            let height = size.height.unwrap_or(0.0);
            let available_width = match available_size.width {
                AvailableSpace::Definite(w) => w,
                AvailableSpace::MaxContent => f32::MAX,
                AvailableSpace::MinContent => 0.0,
            };
            let available_height = match available_size.height {
                AvailableSpace::Definite(h) => h,
                AvailableSpace::MaxContent => f32::MAX,
                AvailableSpace::MinContent => 0.0,
            };
            let result = measure_func(layout_id, width, height, available_width, available_height);
            Size { width: result.0, height: result.1 }
        };

        LayoutManager {
            taffy: TaffyTree::new(),
            layouts: HashMap::new(),
            customizations: Customizations::new(),
            layout_state: 0,

            layout_id_to_taffy_node: HashMap::new(),
            taffy_node_to_layout_id: HashMap::new(),
            layout_id_to_name: HashMap::new(),
            root_layout_ids: HashSet::new(),
            measure_func: Box::new(layout_measure_func),
        }
    }

    fn update_layout_internal(
        &mut self,
        layout_id: i32,
        parent_layout_id: i32,
        changed: &mut HashMap<i32, Layout>,
    ) {
        let node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(node) = node {
            let layout = self.taffy.layout(*node);
            if let Ok(layout) = layout {
                let layout = Layout::from_taffy_layout(layout);
                let old_layout = self.layouts.get(node);
                let mut layout_changed = false;
                if let Some(old_layout) = old_layout {
                    if &layout != old_layout {
                        layout_changed = true;
                    }
                } else {
                    layout_changed = true;
                }

                // If a layout change is detected, add the node that changed and its parent.
                // The parent is needed because layout positioning for a child is done in the
                // parent's layout function.
                if layout_changed {
                    changed.insert(layout_id, layout.clone());
                    if parent_layout_id >= 0 {
                        if let std::collections::hash_map::Entry::Vacant(e) =
                            changed.entry(parent_layout_id)
                        {
                            let parent_node = self.layout_id_to_taffy_node.get(&parent_layout_id);
                            if let Some(parent_node) = parent_node {
                                let parent_layout = self.layouts.get(parent_node);
                                if let Some(parent_layout) = parent_layout {
                                    e.insert(parent_layout.clone());
                                }
                            }
                        }
                    }
                    self.layouts.insert(*node, layout);
                }
            }

            let children_result = self.taffy.children(*node);
            match children_result {
                Ok(children) => {
                    for child in children {
                        let child_layout_id = self.taffy_node_to_layout_id.get(&child);
                        if let Some(child_layout_id) = child_layout_id {
                            self.update_layout_internal(*child_layout_id, layout_id, changed);
                        }
                    }
                }
                Err(e) => {
                    error!("taffy children error: {}", e);
                }
            }
        }
    }

    // Update the layout for the specified layout_id and its children, and
    // return a hash of layouts that changed.
    fn update_layout(&mut self, layout_id: i32) -> HashMap<i32, Layout> {
        let mut changed: HashMap<i32, Layout> = HashMap::new();
        self.update_layout_internal(layout_id, -1, &mut changed);
        changed
    }

    // Get the computed layout for the given node
    pub fn get_node_layout(&self, layout_id: i32) -> Option<Layout> {
        let node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(node) = node {
            let layout = self.taffy.layout(*node);
            if let Ok(layout) = layout {
                return Some(Layout::from_taffy_layout(layout));
            }
        }
        None
    }

    pub fn update_children(&mut self, parent_layout_id: i32, children: &[i32]) {
        if let Some(parent_node) = self.layout_id_to_taffy_node.get(&parent_layout_id) {
            let child_nodes: Vec<_> = children
                .iter()
                .filter_map(|child_id| self.layout_id_to_taffy_node.get(child_id).copied())
                .collect();
            if let Err(e) = self.taffy.set_children(*parent_node, child_nodes.as_slice()) {
                error!("error setting children! {:?}", e);
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn add_style(
        &mut self,
        layout_id: i32,
        parent_layout_id: i32,
        child_index: i32,
        style: LayoutStyle,
        name: String,
        use_measure_func: bool,
        fixed_width: Option<i32>,
        fixed_height: Option<i32>,
    ) -> Result<(), Error> {
        let mut node_style: taffy::style::Style = (&style).try_into_taffy()?;

        self.apply_customizations(layout_id, &mut node_style);
        self.apply_fixed_size(&mut node_style, fixed_width, fixed_height);

        let node_context = if use_measure_func { Some(layout_id) } else { None };

        let node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(node) = node {
            // We already have this view in our tree. Update its style
            if let Err(e) = self.taffy.set_style(*node, node_style) {
                error!("taffy set_style error: {}", e);
            }

            // Add the measure function.
            let _ = self.taffy.set_node_context(*node, node_context);
            return Ok(());
        }

        // This is a new view to add to our tree. Create a new node and add it
        let node = match self.taffy.new_leaf(node_style) {
            Ok(node) => node,
            Err(e) => {
                error!("taffy_new_leaf error: {}", e);
                // TODO: return a proper error.
                return Ok(());
            }
        };

        // Add the measure function.
        let _ = self.taffy.set_node_context(node, node_context);

        self.taffy_node_to_layout_id.insert(node, layout_id);
        self.layout_id_to_taffy_node.insert(layout_id, node);
        self.layout_id_to_name.insert(layout_id, name.clone());

        match self.layout_id_to_taffy_node.get(&parent_layout_id) {
            Some(parent_node) => {
                // It's not a root layout node.
                self.root_layout_ids.remove(&layout_id);

                if child_index < 0 {
                    // Don't bother inserting into the parent's child list. The caller will invoke set_children
                    // manually instead.
                } else {
                    // This has a parent node, so add it as a child
                    let children_result = self.taffy.children(*parent_node);
                    match children_result {
                        Ok(mut children) => {
                            children.insert(child_index as usize, node);
                            let set_children_result =
                                self.taffy.set_children(*parent_node, children.as_ref());
                            if let Some(e) = set_children_result.err() {
                                error!("taffy set_children error: {}", e);
                            }
                        }
                        Err(e) => {
                            error!("taffy_children error: {}", e);
                        }
                    }
                }
            }
            None => {
                // It's a root layout node.
                self.root_layout_ids.insert(layout_id);
            }
        }
        Ok(())
    }

    pub fn remove_view(
        &mut self,
        layout_id: i32,
        root_layout_id: i32,
        compute_layout: bool,
    ) -> LayoutChangedResponse {
        let taffy_node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(taffy_node) = taffy_node {
            let parent = self.taffy.parent(*taffy_node);
            if let Some(parent) = parent {
                // We need to mark the parent as dirty, otherwise layout doesn't get recomputed
                // on the parent, so if this node is in middle of a list, there will be a gap.
                // This may be a bug with taffy.
                let dirty_result = self.taffy.mark_dirty(parent);
                if let Some(e) = dirty_result.err() {
                    error!("taffy dirty error: {}", e);
                }
            }
            let remove_result = self.taffy.remove(*taffy_node);
            match remove_result {
                Ok(removed_node) => {
                    // Remove from all our hashes
                    self.taffy_node_to_layout_id.remove(&removed_node);
                    self.layout_id_to_taffy_node.remove(&layout_id);
                    self.layout_id_to_name.remove(&layout_id);
                    self.root_layout_ids.remove(&layout_id);
                    self.customizations.remove(&layout_id);
                }
                Err(e) => {
                    error!("taffy remove error: {}", e);
                }
            }
        } else {
            error!("no taffy node for layout_id {}", layout_id);
        }

        if compute_layout {
            self.compute_node_layout(root_layout_id)
        } else {
            LayoutChangedResponse::unchanged_with_state(self.layout_state)
        }
    }

    pub fn mark_dirty(&mut self, layout_id: i32) {
        if let Some(&taffy_node) = self.layout_id_to_taffy_node.get(&layout_id) {
            if let Err(e) = self.taffy.mark_dirty(taffy_node) {
                error!("taffy: mark dirty error: {}", e);
            }
        }
    }

    // Set the given node's size to a fixed value, recompute layout, and return
    // the changed nodes
    pub fn set_node_size(
        &mut self,
        layout_id: i32,
        root_layout_id: i32,
        width: u32,
        height: u32,
    ) -> LayoutChangedResponse {
        let node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(node) = node {
            let result = self.taffy.style(*node);
            match result {
                Ok(style) => {
                    let mut new_style = style.clone();
                    new_style.min_size.width = taffy::prelude::Dimension::Length(width as f32);
                    new_style.min_size.height = taffy::prelude::Dimension::Length(height as f32);
                    new_style.size.width = taffy::prelude::Dimension::Length(width as f32);
                    new_style.size.height = taffy::prelude::Dimension::Length(height as f32);
                    new_style.max_size.width = taffy::prelude::Dimension::Length(width as f32);
                    new_style.max_size.height = taffy::prelude::Dimension::Length(height as f32);

                    let result = self.taffy.set_style(*node, new_style);
                    if let Some(e) = result.err() {
                        error!("taffy set_style error: {}", e);
                    } else {
                        self.customizations.add_size(layout_id, width, height);
                    }
                }
                Err(e) => {
                    error!("taffy style error: {}", e);
                }
            }
        }

        self.compute_node_layout(root_layout_id)
    }

    // Apply any customizations that have been saved for this node
    fn apply_customizations(&self, layout_id: i32, style: &mut taffy::style::Style) {
        let size = self.customizations.get_size(layout_id);
        if let Some(size) = size {
            style.min_size.width = taffy::prelude::Dimension::Length(size.width as f32);
            style.min_size.height = taffy::prelude::Dimension::Length(size.height as f32);
            style.size.width = taffy::prelude::Dimension::Length(size.width as f32);
            style.size.height = taffy::prelude::Dimension::Length(size.height as f32);
            style.max_size.width = taffy::prelude::Dimension::Length(size.width as f32);
            style.max_size.height = taffy::prelude::Dimension::Length(size.height as f32);
        }
    }

    fn apply_fixed_size(
        &self,
        style: &mut taffy::style::Style,
        fixed_width: Option<i32>,
        fixed_height: Option<i32>,
    ) {
        if let Some(fixed_width) = fixed_width {
            style.min_size.width = taffy::prelude::Dimension::Length(fixed_width as f32);
        }
        if let Some(fixed_height) = fixed_height {
            style.min_size.height = taffy::prelude::Dimension::Length(fixed_height as f32);
        }
    }

    // Compute the layout on the node with the given layout_id. This should always be
    // a root level node.
    pub fn compute_node_layout(&mut self, layout_id: i32) -> LayoutChangedResponse {
        trace!("compute_node_layout {}", layout_id);
        let node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(node) = node {
            let result = self.taffy.compute_layout_with_measure(
                *node,
                Size {
                    // TODO get this size from somewhere
                    height: AvailableSpace::Definite(500.0),
                    width: AvailableSpace::Definite(500.0),
                },
                &mut self.measure_func,
            );
            if let Some(e) = result.err() {
                error!("compute_node_layout_internal: compute_layoute error: {}", e);
            }
        }

        let changed_layouts = self.update_layout(layout_id);
        self.layout_state += 1;

        LayoutChangedResponse {
            layout_state: self.layout_state,
            changed_layouts,
            ..Default::default()
        }
    }

    pub fn print_layout(self, layout_id: i32, print_func: fn(String) -> ()) {
        self.print_layout_recurse(layout_id, "".to_string(), print_func);
    }

    fn print_layout_recurse(&self, layout_id: i32, space: String, print_func: fn(String) -> ()) {
        let layout_node = self.layout_id_to_taffy_node.get(&layout_id);
        if let Some(layout_node) = layout_node {
            let layout = self.taffy.layout(*layout_node);
            if let Ok(layout) = layout {
                let name_result = self.layout_id_to_name.get(&layout_id);
                if let Some(name) = name_result {
                    print_func(format!("{}Node {} {}:", space, name, layout_id));
                    print_func(format!("  {}{:?}", space, layout));
                }

                let children_result = self.taffy.children(*layout_node);
                if let Ok(children) = children_result {
                    for child in children {
                        let layout_id = self.taffy_node_to_layout_id.get(&child);
                        if let Some(child_layout_id) = layout_id {
                            self.print_layout_recurse(
                                *child_layout_id,
                                format!("{}  ", space),
                                print_func,
                            );
                        }
                    }
                }
            }
        }
    }

    /// Print the layout tree as an HTML document. This is useful for debugging layout issues -- either to
    /// compare against a browser's rendition of the same flexbox tree, or to use the browser's inspector
    /// to quickly try changing values as a rapid debug tool.
    pub fn print_layout_as_html(self, layout_id: i32, print_func: fn(String) -> ()) {
        let root_node_id = if let Some(node_id) = self.layout_id_to_taffy_node.get(&layout_id) {
            *node_id
        } else {
            return;
        };
        crate::debug::print_tree_as_html(&self.taffy, root_node_id, print_func);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dc_bundle::geometry::{DimensionProto, DimensionRect, Size as GeoSize};
    use dc_bundle::positioning::{
        item_spacing, AlignContent, AlignItems, AlignSelf, FlexDirection, ItemSpacing,
        JustifyContent, PositionType,
    };
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use std::sync::Mutex;

    fn create_valid_layout_style() -> LayoutStyle {
        let mut style = LayoutStyle::default();
        let rect = DimensionRect {
            start: DimensionProto::new_points(0.0),
            end: DimensionProto::new_points(0.0),
            top: DimensionProto::new_points(0.0),
            bottom: DimensionProto::new_points(0.0),
            ..Default::default()
        };
        style.padding = Some(rect.clone()).into();
        style.margin = Some(rect).into();

        style.width = DimensionProto::new_auto();
        style.height = DimensionProto::new_auto();
        style.min_width = DimensionProto::new_auto();
        style.min_height = DimensionProto::new_auto();
        style.max_width = DimensionProto::new_auto();
        style.max_height = DimensionProto::new_auto();

        style.left = DimensionProto::new_auto();
        style.right = DimensionProto::new_auto();
        style.top = DimensionProto::new_auto();
        style.bottom = DimensionProto::new_auto();

        style.flex_basis = DimensionProto::new_auto();
        style.item_spacing = Some(ItemSpacing {
            ItemSpacingType: Some(item_spacing::ItemSpacingType::Fixed(0)),
            ..Default::default()
        })
        .into();

        style.align_content = AlignContent::ALIGN_CONTENT_FLEX_START.into();
        style.justify_content = JustifyContent::JUSTIFY_CONTENT_FLEX_START.into();
        style.align_items = AlignItems::ALIGN_ITEMS_FLEX_START.into();
        style.align_self = AlignSelf::ALIGN_SELF_AUTO.into();
        style.flex_direction = FlexDirection::FLEX_DIRECTION_ROW.into();
        style.position_type = PositionType::POSITION_TYPE_RELATIVE.into();

        style
    }

    #[test]
    fn test_customizations() {
        let mut customizations = Customizations::new();
        let layout_id = 1;
        let width = 100;
        let height = 200;

        // Test add_size and get_size
        customizations.add_size(layout_id, width, height);
        let size = customizations.get_size(layout_id);
        assert_eq!(size, Some(&Size { width, height }));

        // Test remove
        customizations.remove(&layout_id);
        let size = customizations.get_size(layout_id);
        assert_eq!(size, None);
    }

    fn create_layout_manager() -> LayoutManager {
        LayoutManager::new(|_, _, _, _, _| (0.0, 0.0))
    }

    #[test]
    fn test_measure_func_called() {
        let called = Arc::new(AtomicBool::new(false));
        let called_clone = called.clone();
        let mut layout_manager = LayoutManager::new(move |_, _, _, _, _| {
            called_clone.store(true, Ordering::SeqCst);
            (0.0, 0.0)
        });

        let layout_id = 1;
        // Add a style with use_measure_func = true
        layout_manager
            .add_style(
                layout_id,
                -1,
                0,
                create_valid_layout_style(),
                "node".to_string(),
                true,
                None,
                None,
            )
            .unwrap();
        layout_manager.compute_node_layout(layout_id);

        assert!(called.load(Ordering::SeqCst));
    }

    #[test]
    fn test_add_style_and_get_layout() {
        let mut layout_manager = create_layout_manager();
        let layout_id = 1;
        let style = create_valid_layout_style();
        let name = "test_node".to_string();

        layout_manager.add_style(layout_id, -1, 0, style, name, false, None, None).unwrap();
        layout_manager.compute_node_layout(layout_id);

        let layout = layout_manager.get_node_layout(layout_id);
        assert!(layout.is_some());
    }

    #[test]
    fn test_add_child_node() {
        let mut layout_manager = create_layout_manager();
        let parent_id = 1;
        let child_id = 2;

        layout_manager
            .add_style(
                parent_id,
                -1,
                0,
                create_valid_layout_style(),
                "parent".to_string(),
                false,
                None,
                None,
            )
            .unwrap();
        layout_manager
            .add_style(
                child_id,
                parent_id,
                0,
                create_valid_layout_style(),
                "child".to_string(),
                false,
                None,
                None,
            )
            .unwrap();

        let parent_node = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
        let children = layout_manager.taffy.children(*parent_node).unwrap();
        assert_eq!(children.len(), 1);

        let child_node = layout_manager.layout_id_to_taffy_node.get(&child_id).unwrap();
        assert_eq!(children[0], *child_node);
    }

    #[test]
    fn test_remove_view() {
        let mut layout_manager = create_layout_manager();
        let parent_id = 1;
        let child_id = 2;

        layout_manager
            .add_style(
                parent_id,
                -1,
                0,
                create_valid_layout_style(),
                "parent".to_string(),
                false,
                None,
                None,
            )
            .unwrap();
        layout_manager
            .add_style(
                child_id,
                parent_id,
                0,
                create_valid_layout_style(),
                "child".to_string(),
                false,
                None,
                None,
            )
            .unwrap();

        // Check child exists
        let parent_node = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
        let children_before_remove = layout_manager.taffy.children(*parent_node).unwrap();
        assert_eq!(children_before_remove.len(), 1);

        layout_manager.remove_view(child_id, parent_id, true);

        // Check child is removed
        let parent_node_after_remove =
            layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
        let children_after_remove =
            layout_manager.taffy.children(*parent_node_after_remove).unwrap();
        assert_eq!(children_after_remove.len(), 0);

        assert!(layout_manager.layout_id_to_taffy_node.get(&child_id).is_none());
    }

    #[test]
    fn test_set_node_size() {
        let mut layout_manager = create_layout_manager();
        let layout_id = 1;
        let width = 200;
        let height = 300;

        layout_manager
            .add_style(
                layout_id,
                -1,
                0,
                create_valid_layout_style(),
                "node".to_string(),
                false,
                None,
                None,
            )
            .unwrap();
        layout_manager.set_node_size(layout_id, layout_id, width, height);

        let layout = layout_manager.get_node_layout(layout_id).unwrap();
        assert_eq!(layout.width, width as f32);
        assert_eq!(layout.height, height as f32);

        // Also check customization is saved
        let custom_size = layout_manager.customizations.get_size(layout_id);
        assert_eq!(custom_size, Some(&Size { width, height }));
    }

    #[test]
    fn test_update_children() {
        let mut layout_manager = create_layout_manager();
        let parent_id = 1;
        let child1_id = 2;
        let child2_id = 3;

        layout_manager
            .add_style(
                parent_id,
                -1,
                0,
                create_valid_layout_style(),
                "parent".to_string(),
                false,
                None,
                None,
            )
            .unwrap();
        layout_manager
            .add_style(
                child1_id,
                -1,
                0,
                create_valid_layout_style(),
                "child1".to_string(),
                false,
                None,
                None,
            )
            .unwrap();
        layout_manager
            .add_style(
                child2_id,
                -1,
                0,
                create_valid_layout_style(),
                "child2".to_string(),
                false,
                None,
                None,
            )
            .unwrap();

        let parent_node = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
        let children_before = layout_manager.taffy.children(*parent_node).unwrap();
        assert_eq!(children_before.len(), 0);

        layout_manager.update_children(parent_id, &vec![child1_id, child2_id]);

        let parent_node_after = layout_manager.layout_id_to_taffy_node.get(&parent_id).unwrap();
        let children_after = layout_manager.taffy.children(*parent_node_after).unwrap();
        assert_eq!(children_after.len(), 2);

        let child1_node = layout_manager.layout_id_to_taffy_node.get(&child1_id).unwrap();
        let child2_node = layout_manager.layout_id_to_taffy_node.get(&child2_id).unwrap();
        assert_eq!(children_after[0], *child1_node);
        assert_eq!(children_after[1], *child2_node);
    }

    #[test]
    fn test_mark_dirty() {
        let mut layout_manager = create_layout_manager();
        let layout_id = 1;
        layout_manager
            .add_style(
                layout_id,
                -1,
                0,
                create_valid_layout_style(),
                "node".to_string(),
                false,
                None,
                None,
            )
            .unwrap();

        // Just check that it doesn't crash
        layout_manager.mark_dirty(layout_id);
        layout_manager.mark_dirty(999); // non-existent id
    }

    static PRINT_OUTPUT: std::sync::LazyLock<Mutex<Vec<String>>> =
        std::sync::LazyLock::new(|| Mutex::new(Vec::new()));

    fn test_print_callback(s: String) {
        PRINT_OUTPUT.lock().unwrap().push(s);
    }

    #[test]
    fn test_print_layout() {
        let mut layout_manager = create_layout_manager();
        let parent_id = 1;
        let child_id = 2;

        layout_manager
            .add_style(
                parent_id,
                -1,
                0,
                create_valid_layout_style(),
                "parent".to_string(),
                false,
                None,
                None,
            )
            .unwrap();
        layout_manager
            .add_style(
                child_id,
                parent_id,
                0,
                create_valid_layout_style(),
                "child".to_string(),
                false,
                None,
                None,
            )
            .unwrap();

        layout_manager.compute_node_layout(parent_id);

        PRINT_OUTPUT.lock().unwrap().clear();
        layout_manager.print_layout(parent_id, test_print_callback);

        let output = PRINT_OUTPUT.lock().unwrap();
        assert_eq!(output.len(), 4);
        assert_eq!(output[0], "Node parent 1:");
        assert!(output[1].starts_with("  Layout {"));
        assert_eq!(output[2], "  Node child 2:");
        assert!(output[3].starts_with("    Layout {"));
    }

    // --- Layout behavior tests (Issue #405) ---

    /// Helper: creates a layout style with a fixed size (width x height in points).
    fn create_sized_style(width: f32, height: f32) -> LayoutStyle {
        let mut style = create_valid_layout_style();
        style.width = DimensionProto::new_points(width);
        style.height = DimensionProto::new_points(height);
        style.bounding_box = Some(GeoSize { width, height, ..Default::default() }).into();
        style
    }

    /// Helper: creates a layout style with fixed size and a flex direction.
    fn create_container_style(width: f32, height: f32, direction: FlexDirection) -> LayoutStyle {
        let mut style = create_sized_style(width, height);
        style.flex_direction = direction.into();
        style
    }

    #[test]
    fn test_horizontal_layout_children_side_by_side() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(200.0, 100.0, FlexDirection::FLEX_DIRECTION_ROW),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        lm.add_style(2, 1, 0, create_sized_style(60.0, 40.0), "a".into(), false, None, None)
            .unwrap();
        lm.add_style(3, 1, 1, create_sized_style(80.0, 50.0), "b".into(), false, None, None)
            .unwrap();
        lm.compute_node_layout(1);
        let la = lm.get_node_layout(2).unwrap();
        let lb = lm.get_node_layout(3).unwrap();
        assert_eq!(la.left, 0.0);
        assert_eq!(la.width, 60.0);
        assert_eq!(lb.left, 60.0);
        assert_eq!(lb.width, 80.0);
    }

    #[test]
    fn test_vertical_layout_children_stacked() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(100.0, 200.0, FlexDirection::FLEX_DIRECTION_COLUMN),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        lm.add_style(2, 1, 0, create_sized_style(50.0, 30.0), "a".into(), false, None, None)
            .unwrap();
        lm.add_style(3, 1, 1, create_sized_style(60.0, 40.0), "b".into(), false, None, None)
            .unwrap();
        lm.compute_node_layout(1);
        let la = lm.get_node_layout(2).unwrap();
        let lb = lm.get_node_layout(3).unwrap();
        assert_eq!(la.top, 0.0);
        assert_eq!(la.height, 30.0);
        assert_eq!(lb.top, 30.0);
        assert_eq!(lb.height, 40.0);
    }

    #[test]
    fn test_absolute_positioning() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_sized_style(200.0, 200.0),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        let mut abs_style = create_sized_style(50.0, 50.0);
        abs_style.position_type = PositionType::POSITION_TYPE_ABSOLUTE.into();
        abs_style.left = DimensionProto::new_points(10.0);
        abs_style.top = DimensionProto::new_points(20.0);
        lm.add_style(2, 1, 0, abs_style, "abs_child".into(), false, None, None).unwrap();
        lm.compute_node_layout(1);
        let lc = lm.get_node_layout(2).unwrap();
        assert_eq!(lc.left, 10.0);
        assert_eq!(lc.top, 20.0);
        assert_eq!(lc.width, 50.0);
        assert_eq!(lc.height, 50.0);
    }

    #[test]
    fn test_nested_layout() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(300.0, 300.0, FlexDirection::FLEX_DIRECTION_ROW),
            "root".into(),
            false,
            None,
            None,
        )
        .unwrap();
        lm.add_style(
            2,
            1,
            0,
            create_container_style(150.0, 200.0, FlexDirection::FLEX_DIRECTION_COLUMN),
            "col".into(),
            false,
            None,
            None,
        )
        .unwrap();
        lm.add_style(3, 2, 0, create_sized_style(100.0, 40.0), "gc_a".into(), false, None, None)
            .unwrap();
        lm.add_style(4, 2, 1, create_sized_style(100.0, 60.0), "gc_b".into(), false, None, None)
            .unwrap();
        lm.compute_node_layout(1);
        let la = lm.get_node_layout(3).unwrap();
        let lb = lm.get_node_layout(4).unwrap();
        assert_eq!(la.top, 0.0);
        assert_eq!(la.height, 40.0);
        assert_eq!(lb.top, 40.0);
        assert_eq!(lb.height, 60.0);
    }

    #[test]
    fn test_padding_offsets_children() {
        let mut lm = create_layout_manager();
        let mut parent_style = create_sized_style(200.0, 200.0);
        parent_style.padding = Some(DimensionRect {
            start: DimensionProto::new_points(10.0),
            end: DimensionProto::new_points(10.0),
            top: DimensionProto::new_points(20.0),
            bottom: DimensionProto::new_points(20.0),
            ..Default::default()
        })
        .into();
        lm.add_style(1, -1, 0, parent_style, "parent".into(), false, None, None).unwrap();
        lm.add_style(2, 1, 0, create_sized_style(50.0, 50.0), "child".into(), false, None, None)
            .unwrap();
        lm.compute_node_layout(1);
        let lc = lm.get_node_layout(2).unwrap();
        assert_eq!(lc.left, 10.0);
        assert_eq!(lc.top, 20.0);
    }

    #[test]
    fn test_flex_grow_distributes_space() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(300.0, 100.0, FlexDirection::FLEX_DIRECTION_ROW),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        let mut sa = create_valid_layout_style();
        sa.height = DimensionProto::new_points(50.0);
        sa.bounding_box = Some(GeoSize { width: 0.0, height: 50.0, ..Default::default() }).into();
        sa.flex_grow = 1.0;
        let mut sb = create_valid_layout_style();
        sb.height = DimensionProto::new_points(50.0);
        sb.bounding_box = Some(GeoSize { width: 0.0, height: 50.0, ..Default::default() }).into();
        sb.flex_grow = 2.0;
        lm.add_style(2, 1, 0, sa, "a".into(), false, None, None).unwrap();
        lm.add_style(3, 1, 1, sb, "b".into(), false, None, None).unwrap();
        lm.compute_node_layout(1);
        assert_eq!(lm.get_node_layout(2).unwrap().width, 100.0);
        assert_eq!(lm.get_node_layout(3).unwrap().width, 200.0);
    }

    #[test]
    fn test_removal_relayouts_siblings() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(300.0, 100.0, FlexDirection::FLEX_DIRECTION_ROW),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        lm.add_style(2, 1, 0, create_sized_style(50.0, 50.0), "a".into(), false, None, None)
            .unwrap();
        lm.add_style(3, 1, 1, create_sized_style(60.0, 50.0), "b".into(), false, None, None)
            .unwrap();
        lm.add_style(4, 1, 2, create_sized_style(70.0, 50.0), "c".into(), false, None, None)
            .unwrap();
        lm.compute_node_layout(1);
        assert_eq!(lm.get_node_layout(4).unwrap().left, 110.0);
        lm.remove_view(3, 1, true);
        assert_eq!(lm.get_node_layout(4).unwrap().left, 50.0);
    }

    #[test]
    fn test_fixed_size_overrides_style() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_sized_style(100.0, 100.0),
            "node".into(),
            false,
            Some(200),
            None,
        )
        .unwrap();
        lm.compute_node_layout(1);
        assert!(lm.get_node_layout(1).unwrap().width >= 200.0);
    }

    #[test]
    fn test_percentage_sizing() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_sized_style(400.0, 300.0),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        let mut pct = create_valid_layout_style();
        pct.width = DimensionProto::new_percent(0.5);
        pct.height = DimensionProto::new_percent(0.25);
        lm.add_style(2, 1, 0, pct, "child".into(), false, None, None).unwrap();
        lm.compute_node_layout(1);
        let lc = lm.get_node_layout(2).unwrap();
        assert_eq!(lc.width, 200.0);
        assert_eq!(lc.height, 75.0);
    }

    #[test]
    fn test_layout_state_increments() {
        let mut lm = create_layout_manager();
        lm.add_style(1, -1, 0, create_sized_style(100.0, 100.0), "node".into(), false, None, None)
            .unwrap();
        let s1 = lm.compute_node_layout(1).layout_state;
        let s2 = lm.compute_node_layout(1).layout_state;
        assert_eq!(s2, s1 + 1);
    }

    #[test]
    fn test_child_ordering_in_column() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(200.0, 400.0, FlexDirection::FLEX_DIRECTION_COLUMN),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        for i in 0..4 {
            lm.add_style(
                10 + i,
                1,
                i,
                create_sized_style(100.0, 50.0),
                format!("child_{}", i),
                false,
                None,
                None,
            )
            .unwrap();
        }
        lm.compute_node_layout(1);
        for i in 0..4 {
            let l = lm.get_node_layout(10 + i).unwrap();
            assert_eq!(l.top, (i as f32) * 50.0, "child {} top mismatch", i);
            assert_eq!(l.height, 50.0, "child {} height mismatch", i);
        }
    }

    #[test]
    fn test_update_children_reorders_layout() {
        let mut lm = create_layout_manager();
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(200.0, 100.0, FlexDirection::FLEX_DIRECTION_ROW),
            "parent".into(),
            false,
            None,
            None,
        )
        .unwrap();
        lm.add_style(2, 1, 0, create_sized_style(60.0, 50.0), "a".into(), false, None, None)
            .unwrap();
        lm.add_style(3, 1, 1, create_sized_style(80.0, 50.0), "b".into(), false, None, None)
            .unwrap();
        lm.compute_node_layout(1);
        assert_eq!(lm.get_node_layout(2).unwrap().left, 0.0);
        assert_eq!(lm.get_node_layout(3).unwrap().left, 60.0);
        lm.update_children(1, &vec![3, 2]);
        lm.compute_node_layout(1);
        assert_eq!(lm.get_node_layout(3).unwrap().left, 0.0);
        assert_eq!(lm.get_node_layout(2).unwrap().left, 80.0);
    }

    /// Absolute-positioned child inside a flex (AutoLayout) parent should be
    /// positioned using its insets (left/top), NOT placed in the flex sequence.
    #[test]
    fn test_absolute_position_in_autolayout() {
        let mut lm = create_layout_manager();

        // Parent is a horizontal AutoLayout (flex row) container
        lm.add_style(
            1,
            -1,
            0,
            create_container_style(400.0, 300.0, FlexDirection::FLEX_DIRECTION_ROW),
            "autolayout_parent".into(),
            false,
            None,
            None,
        )
        .unwrap();

        // Normal flex child (participates in flow)
        lm.add_style(
            2,
            1,
            0,
            create_sized_style(100.0, 50.0),
            "flex_child".into(),
            false,
            None,
            None,
        )
        .unwrap();

        // Absolute-positioned child (should NOT participate in flow)
        let mut abs_style = create_sized_style(80.0, 60.0);
        abs_style.position_type = PositionType::POSITION_TYPE_ABSOLUTE.into();
        abs_style.left = DimensionProto::new_points(150.0);
        abs_style.top = DimensionProto::new_points(100.0);
        lm.add_style(3, 1, 1, abs_style, "abs_child".into(), false, None, None).unwrap();

        // Another normal flex child
        lm.add_style(
            4,
            1,
            2,
            create_sized_style(120.0, 50.0),
            "flex_child2".into(),
            false,
            None,
            None,
        )
        .unwrap();

        lm.compute_node_layout(1);

        // The first flex child should be at left=0 (start of flow)
        let l_flex1 = lm.get_node_layout(2).unwrap();
        assert_eq!(l_flex1.left, 0.0, "First flex child should start at left=0");

        // The absolute child should be at its specified inset position,
        // NOT after the first flex child in the flow
        let l_abs = lm.get_node_layout(3).unwrap();
        assert_eq!(l_abs.left, 150.0, "Absolute child should use left inset");
        assert_eq!(l_abs.top, 100.0, "Absolute child should use top inset");
        assert_eq!(l_abs.width, 80.0);
        assert_eq!(l_abs.height, 60.0);

        // The second flex child should be placed right after the first flex child,
        // as if the absolute child doesn't exist in the flow
        let l_flex2 = lm.get_node_layout(4).unwrap();
        assert_eq!(
            l_flex2.left, 100.0,
            "Second flex child should be placed after first (at 100.0), ignoring absolute child"
        );
    }
}