azul-layout 0.0.7

Layout solver + font and image loader the Azul GUI framework
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
//! solver3/mod.rs
//!
//! Next-generation CSS layout engine with proper formatting context separation

pub mod cache;
pub mod calc;
pub mod counters;
pub mod display_list;
pub mod fc;
pub mod geometry;
pub mod getters;
pub mod layout_tree;
pub mod paged_layout;
pub mod pagination;
pub mod positioning;
pub mod scrollbar;
pub mod sizing;
pub mod taffy_bridge;

/// Lazy debug_info macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_info {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_info_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_warning macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_warning {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_warning_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_error macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_error {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_error_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_log macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_log {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_log_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_box_props macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_box_props {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_box_props_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_css_getter macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_css_getter {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_css_getter_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_bfc_layout macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_bfc_layout {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_bfc_layout_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_ifc_layout macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_ifc_layout {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_ifc_layout_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_table_layout macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_table_layout {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_table_layout_inner(format!($($arg)*));
        }
    };
}

/// Lazy debug_display_type macro - only evaluates format args when debug_messages is Some
#[macro_export]
macro_rules! debug_display_type {
    ($ctx:expr, $($arg:tt)*) => {
        if $ctx.debug_messages.is_some() {
            $ctx.debug_display_type_inner(format!($($arg)*));
        }
    };
}

// Test modules commented out until they are implemented
// #[cfg(test)]
// mod tests;
// #[cfg(test)]
// mod tests_arabic;

use std::{collections::BTreeMap, sync::Arc};

use azul_core::{
    dom::{DomId, NodeId},
    geom::{LogicalPosition, LogicalRect, LogicalSize},
    hit_test::{DocumentId, ScrollPosition},
    resources::RendererResources,
    selection::{SelectionState, TextCursor, TextSelection},
    styled_dom::StyledDom,
};

/// Sentinel value for "position not yet computed". No real position is ever f32::MIN.
pub const POSITION_UNSET: LogicalPosition = LogicalPosition { x: f32::MIN, y: f32::MIN };

/// Vec-based position storage indexed by layout-tree node index.
/// Replaces `BTreeMap<usize, LogicalPosition>` for O(1) access and cache-friendly iteration.
pub type PositionVec = Vec<LogicalPosition>;

/// Create a new PositionVec pre-sized for the given number of nodes.
#[inline]
pub fn new_position_vec(num_nodes: usize) -> PositionVec {
    vec![POSITION_UNSET; num_nodes]
}

/// Get position for node index, returning None if unset.
#[inline(always)]
pub fn pos_get(positions: &PositionVec, idx: usize) -> Option<LogicalPosition> {
    positions.get(idx).copied().filter(|p| p.x != f32::MIN)
}

/// Set position for node index. Grows the vec if needed.
#[inline(always)]
pub fn pos_set(positions: &mut PositionVec, idx: usize, pos: LogicalPosition) {
    if idx >= positions.len() {
        positions.resize(idx + 1, POSITION_UNSET);
    }
    positions[idx] = pos;
}

/// Check if position has been set for node index.
#[inline(always)]
pub fn pos_contains(positions: &PositionVec, idx: usize) -> bool {
    positions.get(idx).map_or(false, |p| p.x != f32::MIN)
}
use azul_css::{
    props::property::{CssProperty, CssPropertyCategory},
    LayoutDebugMessage, LayoutDebugMessageType,
};

use self::{
    display_list::generate_display_list,
    geometry::IntrinsicSizes,
    getters::get_writing_mode,
    layout_tree::{generate_layout_tree, LayoutTree},
    sizing::calculate_intrinsic_sizes,
};
#[cfg(feature = "text_layout")]
pub use crate::font_traits::TextLayoutCache;
use crate::{
    font_traits::ParsedFontTrait,
    solver3::{
        cache::LayoutCache,
        display_list::DisplayList,
        fc::{LayoutConstraints, LayoutResult},
        layout_tree::DirtyFlag,
    },
};

/// A map of hashes for each node to detect changes in content like text.
pub type NodeHashMap = BTreeMap<usize, u64>;

/// Central context for a single layout pass.
pub struct LayoutContext<'a, T: ParsedFontTrait> {
    pub styled_dom: &'a StyledDom,
    #[cfg(feature = "text_layout")]
    pub font_manager: &'a crate::font_traits::FontManager<T>,
    #[cfg(not(feature = "text_layout"))]
    pub font_manager: core::marker::PhantomData<&'a T>,
    /// Legacy per-node selection state (for backward compatibility)
    pub selections: &'a BTreeMap<DomId, SelectionState>,
    /// New multi-node text selection with anchor/focus model
    pub text_selections: &'a BTreeMap<DomId, TextSelection>,
    pub debug_messages: &'a mut Option<Vec<LayoutDebugMessage>>,
    pub counters: &'a mut BTreeMap<(usize, String), i32>,
    pub viewport_size: LogicalSize,
    /// Fragmentation context for CSS Paged Media (PDF generation)
    /// When Some, layout respects page boundaries and generates one DisplayList per page
    pub fragmentation_context: Option<&'a mut crate::paged::FragmentationContext>,
    /// Whether the text cursor should be drawn (managed by CursorManager blink timer)
    /// When false, the cursor is in the "off" phase of blinking and should not be rendered.
    /// When true (default), the cursor is visible.
    pub cursor_is_visible: bool,
    /// Current cursor location from CursorManager (dom_id, node_id, cursor)
    /// This is separate from selections - the cursor represents the text insertion point
    /// in a contenteditable element and should be painted independently.
    pub cursor_location: Option<(DomId, NodeId, TextCursor)>,
    /// Per-node multi-slot cache (Taffy-inspired 9+1 architecture).
    /// Moved out of LayoutCache via std::mem::take for the duration of layout,
    /// then moved back after the layout pass completes.
    pub cache_map: cache::LayoutCacheMap,
    /// System style containing colors, fonts, metrics, and theme information.
    /// Used for selection colors, caret styling, and other system-themed elements.
    pub system_style: Option<std::sync::Arc<azul_css::system::SystemStyle>>,
    /// Callback to get the current system time. Used for profiling inside layout.
    /// On WASM targets (where `std::time::Instant::now()` panics), callers should
    /// supply a no-op or platform-specific implementation.
    pub get_system_time_fn: azul_core::task::GetSystemTimeCallback,
}

impl<'a, T: ParsedFontTrait> LayoutContext<'a, T> {
    /// Check if debug messages are enabled (for use with lazy macros)
    #[inline]
    pub fn has_debug(&self) -> bool {
        self.debug_messages.is_some()
    }

    /// Internal method - called by debug_log! macro after checking has_debug()
    #[inline]
    pub fn debug_log_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage {
                message: message.into(),
                location: "solver3".into(),
                message_type: Default::default(),
            });
        }
    }

    /// Internal method - called by debug_info! macro after checking has_debug()
    #[inline]
    pub fn debug_info_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::info(message));
        }
    }

    /// Internal method - called by debug_warning! macro after checking has_debug()
    #[inline]
    pub fn debug_warning_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::warning(message));
        }
    }

    /// Internal method - called by debug_error! macro after checking has_debug()
    #[inline]
    pub fn debug_error_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::error(message));
        }
    }

    /// Internal method - called by debug_box_props! macro after checking has_debug()
    #[inline]
    pub fn debug_box_props_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::box_props(message));
        }
    }

    /// Internal method - called by debug_css_getter! macro after checking has_debug()
    #[inline]
    pub fn debug_css_getter_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::css_getter(message));
        }
    }

    /// Internal method - called by debug_bfc_layout! macro after checking has_debug()
    #[inline]
    pub fn debug_bfc_layout_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::bfc_layout(message));
        }
    }

    /// Internal method - called by debug_ifc_layout! macro after checking has_debug()
    #[inline]
    pub fn debug_ifc_layout_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::ifc_layout(message));
        }
    }

    /// Internal method - called by debug_table_layout! macro after checking has_debug()
    #[inline]
    pub fn debug_table_layout_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::table_layout(message));
        }
    }

    /// Internal method - called by debug_display_type! macro after checking has_debug()
    #[inline]
    pub fn debug_display_type_inner(&mut self, message: String) {
        if let Some(messages) = self.debug_messages.as_mut() {
            messages.push(LayoutDebugMessage::display_type(message));
        }
    }

    // DEPRECATED: Use debug_*!() macros instead for lazy evaluation
    // These methods always evaluate format!() arguments even when debug is disabled

    #[inline]
    #[deprecated(note = "Use debug_info! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_info(&mut self, message: impl Into<String>) {
        self.debug_info_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_warning! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_warning(&mut self, message: impl Into<String>) {
        self.debug_warning_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_error! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_error(&mut self, message: impl Into<String>) {
        self.debug_error_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_log! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_log(&mut self, message: &str) {
        self.debug_log_inner(message.to_string());
    }

    #[inline]
    #[deprecated(note = "Use debug_box_props! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_box_props(&mut self, message: impl Into<String>) {
        self.debug_box_props_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_css_getter! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_css_getter(&mut self, message: impl Into<String>) {
        self.debug_css_getter_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_bfc_layout! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_bfc_layout(&mut self, message: impl Into<String>) {
        self.debug_bfc_layout_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_ifc_layout! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_ifc_layout(&mut self, message: impl Into<String>) {
        self.debug_ifc_layout_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_table_layout! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_table_layout(&mut self, message: impl Into<String>) {
        self.debug_table_layout_inner(message.into());
    }

    #[inline]
    #[deprecated(note = "Use debug_display_type! macro for lazy evaluation")]
    #[allow(deprecated)]
    pub fn debug_display_type(&mut self, message: impl Into<String>) {
        self.debug_display_type_inner(message.into());
    }
}

/// Main entry point for the incremental, cached layout engine
#[cfg(feature = "text_layout")]
pub fn layout_document<T: ParsedFontTrait + Sync + 'static>(
    cache: &mut LayoutCache,
    text_cache: &mut TextLayoutCache,
    new_dom: StyledDom,
    viewport: LogicalRect,
    font_manager: &crate::font_traits::FontManager<T>,
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
    selections: &BTreeMap<DomId, SelectionState>,
    text_selections: &BTreeMap<DomId, TextSelection>,
    debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
    gpu_value_cache: Option<&azul_core::gpu::GpuValueCache>,
    renderer_resources: &azul_core::resources::RendererResources,
    id_namespace: azul_core::resources::IdNamespace,
    dom_id: azul_core::dom::DomId,
    cursor_is_visible: bool,
    cursor_location: Option<(DomId, NodeId, TextCursor)>,
    system_style: Option<std::sync::Arc<azul_css::system::SystemStyle>>,
    get_system_time_fn: azul_core::task::GetSystemTimeCallback,
) -> Result<DisplayList> {
    // Reset IFC ID counter at the start of each layout pass
    // This ensures IFCs get consistent IDs across frames when the DOM structure is stable
    crate::solver3::layout_tree::IfcId::reset_counter();

    if let Some(msgs) = debug_messages.as_mut() {
        msgs.push(LayoutDebugMessage::info(format!(
            "[Layout] layout_document called - viewport: ({:.1}, {:.1}) size ({:.1}x{:.1})",
            viewport.origin.x, viewport.origin.y, viewport.size.width, viewport.size.height
        )));
        msgs.push(LayoutDebugMessage::info(format!(
            "[Layout] DOM has {} nodes",
            new_dom.node_data.len()
        )));
    }

    // Create temporary context without counters for tree generation
    let mut counter_values = BTreeMap::new();
    let mut ctx_temp = LayoutContext {
        styled_dom: &new_dom,
        font_manager,
        selections,
        text_selections,
        debug_messages,
        counters: &mut counter_values,
        viewport_size: viewport.size,
        fragmentation_context: None,
        cursor_is_visible,
        cursor_location: cursor_location.clone(),
        cache_map: cache::LayoutCacheMap::default(), // temp context doesn't need real cache
        system_style: system_style.clone(),
        get_system_time_fn,
    };

    // --- Step 1: Reconciliation & Invalidation ---
    let (mut new_tree, mut recon_result) =
        cache::reconcile_and_invalidate(&mut ctx_temp, cache, viewport)?;

    // Step 1.2: Clear Taffy Caches for Dirty Nodes
    for &node_idx in &recon_result.intrinsic_dirty {
        if let Some(node) = new_tree.get_mut(node_idx) {
            node.taffy_cache.clear();
        }
    }

    // Step 1.3: Compute CSS Counters
    // This must be done after tree generation but before layout,
    // as list markers need counter values during formatting context layout
    cache::compute_counters(&new_dom, &new_tree, &mut counter_values);

    // Step 1.4: Resize and invalidate per-node cache (Taffy-inspired 9+1 slot cache)
    // Move cache_map out of LayoutCache for the duration of layout (avoids borrow conflicts).
    // It will be moved back after the layout pass completes.
    let mut cache_map = std::mem::take(&mut cache.cache_map);
    cache_map.resize_to_tree(new_tree.nodes.len());
    for &node_idx in &recon_result.intrinsic_dirty {
        cache_map.mark_dirty(node_idx, &new_tree.nodes);
    }
    for &node_idx in &recon_result.layout_roots {
        cache_map.mark_dirty(node_idx, &new_tree.nodes);
    }

    // Now create the real context with computed counters
    let mut ctx = LayoutContext {
        styled_dom: &new_dom,
        font_manager,
        selections,
        text_selections,
        debug_messages,
        counters: &mut counter_values,
        viewport_size: viewport.size,
        fragmentation_context: None,
        cursor_is_visible,
        cursor_location,
        cache_map, // Moved from LayoutCache; will be moved back after layout
        system_style,
        get_system_time_fn,
    };

    // --- Step 1.5: Early Exit Optimization ---
    if recon_result.is_clean() {
        ctx.debug_log("No changes, returning existing display list");
        let tree = cache.tree.as_ref().ok_or(LayoutError::InvalidTree)?;

        // Use cached scroll IDs if available, otherwise compute them
        let scroll_ids = if cache.scroll_ids.is_empty() {
            use crate::window::LayoutWindow;
            let (scroll_ids, scroll_id_to_node_id) =
                LayoutWindow::compute_scroll_ids(tree, &new_dom);
            cache.scroll_ids = scroll_ids.clone();
            cache.scroll_id_to_node_id = scroll_id_to_node_id;
            scroll_ids
        } else {
            cache.scroll_ids.clone()
        };

        return generate_display_list(
            &mut ctx,
            tree,
            &cache.calculated_positions,
            scroll_offsets,
            &scroll_ids,
            gpu_value_cache,
            renderer_resources,
            id_namespace,
            dom_id,
        );
    }

    // --- Step 2: Incremental Layout Loop (handles scrollbar-induced reflows) ---
    let mut calculated_positions = cache.calculated_positions.clone();
    let mut loop_count = 0;
    loop {
        loop_count += 1;
        if loop_count > 10 {
            // Safety limit to prevent infinite loops
            break;
        }

        calculated_positions = cache.calculated_positions.clone();
        let mut reflow_needed_for_scrollbars = false;

        calculate_intrinsic_sizes(&mut ctx, &mut new_tree, &recon_result.intrinsic_dirty)?;

        for &root_idx in &recon_result.layout_roots {
            let (cb_pos, cb_size) = get_containing_block_for_node(
                &new_tree,
                &new_dom,
                root_idx,
                &calculated_positions,
                viewport,
            );

            // For ROOT nodes (no parent), we need to account for their margin.
            // The containing block position from viewport is (0, 0), but the root's
            // content starts at (margin + border + padding, margin + border + padding).
            // We pass margin-adjusted position so calculate_content_box_pos works correctly.
            let root_node = &new_tree.nodes[root_idx];
            
            let is_root_with_margin = root_node.parent.is_none()
                && (root_node.box_props.margin.left != 0.0 || root_node.box_props.margin.top != 0.0);

            let adjusted_cb_pos = if is_root_with_margin {
                LogicalPosition::new(
                    cb_pos.x + root_node.box_props.margin.left,
                    cb_pos.y + root_node.box_props.margin.top,
                )
            } else {
                cb_pos
            };

            // DEBUG: Log containing block info for this root
            if let Some(debug_msgs) = ctx.debug_messages.as_mut() {
                let dom_name = root_node
                    .dom_node_id
                    .and_then(|id| new_dom.node_data.as_container().internal.get(id.index()))
                    .map(|n| format!("{:?}", n.node_type))
                    .unwrap_or_else(|| "Unknown".to_string());

                debug_msgs.push(LayoutDebugMessage::new(
                    LayoutDebugMessageType::PositionCalculation,
                    format!(
                        "[LAYOUT ROOT {}] {} - CB pos=({:.2}, {:.2}), adjusted=({:.2}, {:.2}), \
                         CB size=({:.2}x{:.2}), viewport=({:.2}x{:.2}), margin=({:.2}, {:.2})",
                        root_idx,
                        dom_name,
                        cb_pos.x,
                        cb_pos.y,
                        adjusted_cb_pos.x,
                        adjusted_cb_pos.y,
                        cb_size.width,
                        cb_size.height,
                        viewport.size.width,
                        viewport.size.height,
                        root_node.box_props.margin.left,
                        root_node.box_props.margin.top
                    ),
                ));
            }

            cache::calculate_layout_for_subtree(
                &mut ctx,
                &mut new_tree,
                text_cache,
                root_idx,
                adjusted_cb_pos,
                cb_size,
                &mut calculated_positions,
                &mut reflow_needed_for_scrollbars,
                &mut cache.float_cache,
                cache::ComputeMode::PerformLayout,
            )?;

            // CRITICAL: Insert the root node's own position into calculated_positions
            // This is necessary because calculate_layout_for_subtree only inserts
            // positions for children, not for the root itself.
            //
            // For root nodes, the position should be at (margin.left, margin.top) relative
            // to the viewport origin, because the margin creates space between the viewport
            // edge and the element's border-box.
            if !pos_contains(&calculated_positions, root_idx) {
                let root_node = &new_tree.nodes[root_idx];

                // Calculate the root's border-box position by adding margins to viewport origin
                // This is different from non-root nodes which inherit their position from
                // their containing block.
                let root_position = LogicalPosition::new(
                    cb_pos.x + root_node.box_props.margin.left,
                    cb_pos.y + root_node.box_props.margin.top,
                );

                // DEBUG: Log root positioning
                if let Some(debug_msgs) = ctx.debug_messages.as_mut() {
                    let dom_name = root_node
                        .dom_node_id
                        .and_then(|id| new_dom.node_data.as_container().internal.get(id.index()))
                        .map(|n| format!("{:?}", n.node_type))
                        .unwrap_or_else(|| "Unknown".to_string());

                    debug_msgs.push(LayoutDebugMessage::new(
                        LayoutDebugMessageType::PositionCalculation,
                        format!(
                            "[ROOT POSITION {}] {} - Inserting position=({:.2}, {:.2}) (viewport origin + margin), \
                             margin=({:.2}, {:.2}, {:.2}, {:.2})",
                            root_idx,
                            dom_name,
                            root_position.x,
                            root_position.y,
                            root_node.box_props.margin.top,
                            root_node.box_props.margin.right,
                            root_node.box_props.margin.bottom,
                            root_node.box_props.margin.left
                        ),
                    ));
                }

                pos_set(&mut calculated_positions, root_idx, root_position);
            }
        }

        cache::reposition_clean_subtrees(
            &new_dom,
            &new_tree,
            &recon_result.layout_roots,
            &mut calculated_positions,
        );

        if reflow_needed_for_scrollbars {
            ctx.debug_log(&format!(
                "Scrollbars changed container size, starting full reflow (loop {})",
                loop_count
            ));
            recon_result.layout_roots.clear();
            recon_result.layout_roots.insert(new_tree.root);
            recon_result.intrinsic_dirty = (0..new_tree.nodes.len()).collect();
            continue;
        }

        break;
    }

    // --- Step 3: Adjust Relatively Positioned Elements ---
    // This must be done BEFORE positioning out-of-flow elements, because
    // relatively positioned elements establish containing blocks for their
    // absolutely positioned descendants. If we adjust relative positions after
    // positioning absolute elements, the absolute elements will be positioned
    // relative to the wrong (pre-adjustment) position of their containing block.
    // Pass the viewport to correctly resolve percentage offsets for the root element.
    positioning::adjust_relative_positions(
        &mut ctx,
        &new_tree,
        &mut calculated_positions,
        viewport,
    )?;

    // --- Step 3.5: Position Out-of-Flow Elements ---
    // This must be done AFTER adjusting relative positions, so that absolutely
    // positioned elements are positioned relative to the final (post-adjustment)
    // position of their relatively positioned containing blocks.
    positioning::position_out_of_flow_elements(
        &mut ctx,
        &mut new_tree,
        &mut calculated_positions,
        viewport,
    )?;

    // --- Step 3.75: Compute Stable Scroll IDs ---
    // This must be done AFTER layout but BEFORE display list generation
    use crate::window::LayoutWindow;
    let (scroll_ids, scroll_id_to_node_id) = LayoutWindow::compute_scroll_ids(&new_tree, &new_dom);

    // --- Step 4: Generate Display List & Update Cache ---
    let display_list = generate_display_list(
        &mut ctx,
        &new_tree,
        &calculated_positions,
        scroll_offsets,
        &scroll_ids,
        gpu_value_cache,
        renderer_resources,
        id_namespace,
        dom_id,
    )?;

    // Move cache_map back into LayoutCache before dropping ctx
    let cache_map_back = std::mem::take(&mut ctx.cache_map);

    cache.tree = Some(new_tree);
    cache.calculated_positions = calculated_positions;
    cache.viewport = Some(viewport);
    cache.scroll_ids = scroll_ids;
    cache.scroll_id_to_node_id = scroll_id_to_node_id;
    cache.counters = counter_values;
    cache.cache_map = cache_map_back;

    Ok(display_list)
}

// STUB: This helper is required by the main loop
fn get_containing_block_for_node(
    tree: &LayoutTree,
    styled_dom: &StyledDom,
    node_idx: usize,
    calculated_positions: &PositionVec,
    viewport: LogicalRect,
) -> (LogicalPosition, LogicalSize) {
    if let Some(parent_idx) = tree.get(node_idx).and_then(|n| n.parent) {
        if let Some(parent_node) = tree.get(parent_idx) {
            let pos = calculated_positions
                .get(parent_idx)
                .copied()
                .unwrap_or_default();
            let size = parent_node.used_size.unwrap_or_default();
            // Position in calculated_positions is the margin-box position
            // To get content-box, add: border + padding (NOT margin, that's already in pos)
            let content_pos = LogicalPosition::new(
                pos.x + parent_node.box_props.border.left + parent_node.box_props.padding.left,
                pos.y + parent_node.box_props.border.top + parent_node.box_props.padding.top,
            );

            if let Some(dom_id) = parent_node.dom_node_id {
                let styled_node_state = &styled_dom
                    .styled_nodes
                    .as_container()
                    .get(dom_id)
                    .map(|n| &n.styled_node_state)
                    .cloned()
                    .unwrap_or_default();
                let writing_mode =
                    get_writing_mode(styled_dom, dom_id, styled_node_state).unwrap_or_default();
                let content_size = parent_node.box_props.inner_size(size, writing_mode);
                return (content_pos, content_size);
            }

            return (content_pos, size);
        }
    }
    
    // For ROOT nodes: the containing block is the viewport.
    // Do NOT subtract margin here - margins are handled in calculate_used_size().
    // The margin creates space between viewport edge and element's border-box,
    // but the available space for calculating width/height percentages
    // is still the full viewport size.
    (viewport.origin, viewport.size)
}

#[derive(Debug)]
pub enum LayoutError {
    InvalidTree,
    SizingFailed,
    PositioningFailed,
    DisplayListFailed,
    Text(crate::font_traits::LayoutError),
}

impl std::fmt::Display for LayoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LayoutError::InvalidTree => write!(f, "Invalid layout tree"),
            LayoutError::SizingFailed => write!(f, "Sizing calculation failed"),
            LayoutError::PositioningFailed => write!(f, "Position calculation failed"),
            LayoutError::DisplayListFailed => write!(f, "Display list generation failed"),
            LayoutError::Text(e) => write!(f, "Text layout error: {:?}", e),
        }
    }
}

impl From<crate::font_traits::LayoutError> for LayoutError {
    fn from(err: crate::font_traits::LayoutError) -> Self {
        LayoutError::Text(err)
    }
}

impl std::error::Error for LayoutError {}

pub type Result<T> = std::result::Result<T, LayoutError>;