cotis-layout 0.1.0-alpha.1

Flexbox-style layout engine for Cotis
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
use crate::layout_algorithm::axis_utils::Axis;
use crate::layout_algorithm::commands::{calculate_render_commands, sort_commands};
use crate::layout_algorithm::positions::calculate_child_positions;
use crate::layout_algorithm::sizing::fit_grow_shrink_children_axis;
use crate::layout_algorithm::wrapping::recursive_wrap_left_to_right;
use crate::layout_struct::layout_states::{
    ChildWrapping, LayoutElementConfig, LayoutElementInfo, LayoutElementStyle, element_info_states,
};
use crate::layout_struct::layout_tree::{
    LayoutElement, LayoutTree, LayoutTreeCursor, LayoutTreeCursorBorrow, LayoutTreeIndex,
};
use crate::layout_struct::{RenderCommandOutput, TextDrawPayload};
use crate::text::TextMeasuringFun;
use cotis::utils::ElementId;
use cotis::utils::ElementIdConfig;
use cotis::utils::OwnedOrRef;
use cotis_defaults::element_configs::style::sizing::Sizing::DoubleAxis;
use cotis_defaults::element_configs::style::sizing::{AxisSizing, DoubleAxisSizing};
use cotis_defaults::element_configs::style::types::{
    Alignment, LayoutAlignmentX, LayoutAlignmentY, LayoutDirection, Padding,
};
use cotis_defaults::element_configs::text_config::TextConfig as DefaultTextConfig;
use cotis_utils::math::Dimensions;
use cotis_utils::text::{LayoutTextMeasuring, TextMeasurer};
use std::collections::{HashMap, VecDeque};

/// Owns the layout tree, viewport size, text measurer, and post-frame element cache.
///
/// Implement [`LayoutManager`](cotis::layout::LayoutManager) via [`crate::cotis_traits`] and
/// wire into [`CotisApp`](cotis::cotis_app::CotisApp) with a pipe (e.g.
/// `CotisLayoutToRenderListPipeForGenerics` from `cotis-pipes`).
///
/// The renderer initializes text measurement and viewport dimensions through
/// [`LayoutManagerCompatible`](cotis::layout::LayoutManagerCompatible).
pub struct CotisLayoutManager {
    root_id: ElementIdConfig<'static>,
    root: LayoutTree,
    screen_dimensions: Dimensions,
    cache_elements: HashMap<ElementId, LayoutElement>,
    /// Child layout slot (`ElementId::get_id()`) → parent slot, from the last `clear_tree`.
    element_parent: HashMap<ElementId, ElementId>,
    text_dim_fun: Option<TextMeasuringFun>,
}

/// Per-frame element tree configurator returned by [`LayoutManager::begin_frame`](cotis::layout::LayoutManager::begin_frame).
///
/// Implements [`ConfigureElements`](cotis::element_configuring::ConfigureElements) when `Config`
/// implements [`CotisLayoutCompatible`](crate::layout_traits::CotisLayoutCompatible). Call
/// [`LayoutFrameManager::end`](cotis::layout::LayoutFrameManager::end) (or
/// [`finalize_layouts`](Self::finalize_layouts) directly) to run layout and obtain
/// [`RenderCommandOutput`](crate::layout_struct::RenderCommandOutput) values.
pub struct CotisLayoutRun<'layout, Config> {
    pub(crate) layout_manager: &'layout mut CotisLayoutManager,
    open_element_index: LayoutTreeIndex,
    configs: HashMap<ElementId, Config>,
    pub(crate) text_fragments: HashMap<ElementId, TextDrawPayload>,
}

impl CotisLayoutManager {
    /// Installs a function that measures text for layout.
    ///
    /// Normally set automatically by [`LayoutManagerCompatible::init`](cotis::layout::LayoutManagerCompatible::init)
    /// from the renderer's [`RendererTextMeasuringProvider`](cotis_utils::text::RendererTextMeasuringProvider).
    /// Override only for custom measurement or testing.
    pub fn set_text_dim_fun(&mut self, fun: TextMeasuringFun) {
        self.text_dim_fun = Some(fun);
    }

    pub(crate) fn text_dim_fun(&self) -> Option<&TextMeasuringFun> {
        self.text_dim_fun.as_ref()
    }
}

impl LayoutTextMeasuring<DefaultTextConfig> for CotisLayoutManager {
    fn set_text_measuring_function(&mut self, text: Box<TextMeasurer<'_, DefaultTextConfig>>) {
        // SAFETY: Renderer implementations return 'static closures (they clone owned
        // resources such as font tables into the closure). The trait's elided lifetime is
        // tied to `&mut self`, not the closure's capture.
        self.text_dim_fun = Some(unsafe {
            std::mem::transmute::<Box<TextMeasurer<'_, DefaultTextConfig>>, TextMeasuringFun>(text)
        });
    }
}

impl CotisLayoutManager {
    fn default_node(&self) -> LayoutElement {
        LayoutElement {
            id: self.root_id.get_handle(),
            name: "Root".to_string(),
            info: LayoutElementInfo::NotInitialized,
            config: LayoutElementConfig {
                layout: LayoutElementStyle {
                    sizing: DoubleAxis(DoubleAxisSizing {
                        width: AxisSizing::Fixed(self.screen_dimensions.width),
                        height: AxisSizing::Fixed(self.screen_dimensions.height),
                    }),
                    padding: Padding {
                        top: 0.0,
                        bottom: 0.0,
                        right: 0.0,
                        left: 0.0,
                    },
                    child_gap: 0.0,
                    child_alignment: Alignment {
                        x: LayoutAlignmentX::Left,
                        y: LayoutAlignmentY::Top,
                    },
                    layout_direction: LayoutDirection::LeftToRight,
                    wrapping: ChildWrapping::None,
                },
                ..LayoutElementConfig::default()
            },
        }
    }

    /// Creates a layout manager whose root element fills `screen_dimensions`.
    pub fn new(screen_dimensions: Dimensions) -> Self {
        let root = LayoutTree::new();
        let root_id = ElementIdConfig::new_empty();
        let mut res = Self {
            root_id,
            root,
            screen_dimensions,
            cache_elements: Default::default(),
            element_parent: Default::default(),
            text_dim_fun: None,
        };
        res.root.add_root(res.default_node());
        res.configure_roots();
        res
    }

    /// Updates the viewport size used for the root element.
    ///
    /// Also called from [`LayoutManagerCompatible::prepare`](cotis::layout::LayoutManagerCompatible::prepare)
    /// each frame.
    pub fn set_dimensions(&mut self, screen_dimensions: Dimensions) {
        self.screen_dimensions = screen_dimensions;
    }

    /// Returns an element from the **last completed frame** layout cache.
    ///
    /// Populated when [`CotisLayoutRun::finalize_layouts`](CotisLayoutRun::finalize_layouts) finishes. The returned
    /// `LayoutElement` is an internal engine type — not a stable public path API; visibility
    /// is under review. Use [`crate::cotis_traits::secondary_traits`] and
    /// [`cotis_utils::element_state`] traits for structured inspection.
    pub fn get_cache_element(&self, id: ElementId) -> Option<&LayoutElement> {
        self.cache_elements.get(&id)
    }

    pub(crate) fn cached_element_ids(&self) -> Vec<ElementId> {
        self.cache_elements.values().map(|e| e.id).collect()
    }

    pub(crate) fn parent_layout_slot_of(&self, child_slot: ElementId) -> Option<ElementId> {
        self.element_parent.get(&child_slot).copied()
    }

    pub(crate) fn direct_child_slots(&self, parent_slot: ElementId) -> Vec<ElementId> {
        self.element_parent
            .iter()
            .filter_map(|(child, &parent)| (parent == parent_slot).then_some(*child))
            .collect()
    }

    pub(crate) fn clear_tree_no_cache(&mut self) {
        self.root.clear_tree_structure();
        // Rebuild tree roots
        self.root.add_root(self.default_node());

        self.configure_roots();
    }
    pub(crate) fn clear_tree(&mut self) {
        let (cache_elements, parent_map) = self.root.clear_tree_structure_with_parent_map();
        self.cache_elements = cache_elements;
        self.element_parent = parent_map;
    }

    pub(crate) fn tree(&mut self) -> &mut LayoutTree {
        &mut self.root
    }

    pub(crate) fn configure_roots(&mut self) {
        //make roots size of screen
        let mut root_element = self
            .root
            .get_node_mut(&LayoutTreeIndex::new(&[self.root_id.get_handle()]))
            .unwrap();
        let root_element = root_element.get_local().self_element;
        root_element.info =
            LayoutElementInfo::TotalSizedAndPosition(element_info_states::TotalSizedAndPosition {
                x: 0.0,
                y: 0.0,
                width: self.screen_dimensions.width,
                height: self.screen_dimensions.height,
            });
    }
}

impl<'layout, Config> CotisLayoutRun<'layout, Config> {
    /// Starts a new frame: clears the live tree and opens the root element.
    pub fn new(layout_manager: &'layout mut CotisLayoutManager) -> Self {
        layout_manager.clear_tree_no_cache();
        let root_id = layout_manager.root_id.get_handle();
        Self {
            layout_manager,
            open_element_index: LayoutTreeIndex::new(&[root_id]),
            configs: Default::default(),
            text_fragments: Default::default(),
        }
    }

    /// Returns a mutable cursor to the currently open element in the layout tree.
    ///
    /// # Panics
    ///
    /// Panics if the open element index is invalid (internal inconsistency).
    pub fn get_tree_cursor(&mut self) -> LayoutTreeCursor<'_> {
        LayoutTreeCursor::new_from_index(self.layout_manager.tree(), &self.open_element_index)
            .unwrap()
    }

    /// Adds a new child under the currently open element and opens it.
    ///
    /// # Panics
    ///
    /// Panics if the open element no longer exists in the tree.
    pub fn new_child_element(&mut self) {
        let id_conf = ElementIdConfig::new_empty();
        let element = LayoutElement::new(id_conf.get_handle(), String::new());
        let child_index = self
            .layout_manager
            .root
            .add_child(&self.open_element_index, element)
            .expect("[Cotis Layout] New Element added to missing parent element");
        self.open_element_index.push(child_index);
    }

    /// Applies layout style and user config to the currently open element, then initializes sizing state.
    ///
    /// Called internally by [`ConfigureElements::set_config`](cotis::element_configuring::ConfigureElements::set_config).
    ///
    /// # Panics
    ///
    /// Panics if no element is open.
    pub fn set_open_element_config(
        &mut self,
        config: LayoutElementConfig,
        id: ElementId,
        name: Option<OwnedOrRef<str>>,
        true_config: Config,
    ) {
        let mut current_id = self.open_element_id();
        let mut node = self
            .layout_manager
            .root
            .get_node_mut(&self.open_element_index)
            .expect("[Cotis Layout] Tried to set config for open element, but no element is open");
        if id != current_id {
            current_id = id;
            node.change_node_id(id);
            self.open_element_index.pop();
            self.open_element_index.push(id);
        }
        {
            let node = node.get_local().self_element;
            node.config = config;
            if let Some(name) = name {
                node.name += name.as_ref();
            }
        }
        self.configs.insert(current_id, true_config);
        node.get_local().open_configuration()
    }

    /// Returns the [`ElementId`] of the currently open tree node.
    ///
    /// # Panics
    ///
    /// Panics if no element is open.
    pub fn open_element_id(&self) -> ElementId {
        let node = self
            .layout_manager
            .root
            .get_node(&self.open_element_index)
            .expect("[Cotis Layout] Tried to set config for open element, but no element is open");
        node.get_local().self_element.id
    }

    pub(crate) fn set_open_element_layout_direction(&mut self, layout_direction: LayoutDirection) {
        let mut node = self.layout_manager.root.get_node_mut(&self.open_element_index).expect("[Cotis Layout] Tried to set layout direction for open element, but no element is open");
        node.get_local().self_element.config.layout.layout_direction = layout_direction;
    }

    pub(crate) fn get_config(&self, id: ElementId) -> Option<&Config> {
        self.configs.get(&id)
    }

    /// Finalizes sizing for the open element and moves the cursor to its parent.
    pub fn close_open_element(&mut self) {
        let mut cursor = self.get_tree_cursor();
        cursor.get_local().close_element();
        self.open_element_index.pop();
    }

    fn calculate_final_layout_sizes(&mut self) {
        self.layout_manager.configure_roots();

        for root in self
            .layout_manager
            .root
            .get_root_nodes()
            .map(|c| LayoutTreeIndex::new(&[c.tree_node_id]))
            .collect::<Vec<_>>()
        {
            let tree = &mut self.layout_manager.root;
            // Width: Fit -> Grow & Shrink
            fit_grow_shrink_children_axis(
                &mut LayoutTreeCursor::new_from_index(tree, &root).unwrap(),
                Axis::Width,
            );
            // Wrap text
            recursive_wrap_left_to_right(
                &mut LayoutTreeCursor::new_from_index(tree, &root).unwrap(),
            );
            // Height: Fit -> Grow & Shrink
            fit_grow_shrink_children_axis(
                &mut LayoutTreeCursor::new_from_index(tree, &root).unwrap(),
                Axis::Height,
            );
        }
    }

    fn calculate_positions(&mut self) {
        for root in self
            .layout_manager
            .root
            .get_root_nodes()
            .map(|c| LayoutTreeIndex::new(&[c.tree_node_id]))
            .collect::<Vec<_>>()
        {
            let tree = self.layout_manager.tree();
            calculate_child_positions(&mut LayoutTreeCursor::new_from_index(tree, &root).unwrap());
        }
    }

    fn calculate_render_commands(&mut self) -> Vec<RenderCommandOutput<Config>> {
        let mut render_commands = Vec::new();
        let mut open_nodes = VecDeque::new();
        for root_id in self
            .layout_manager
            .root
            .get_root_nodes_borrow()
            .map(|c| c.tree_node_id)
            .collect::<Vec<_>>()
        {
            let mut render_commands_buffer = Vec::new();
            let root = LayoutTreeIndex::new(&[root_id]);
            open_nodes.push_back(root);
            while let Some(node) = open_nodes.pop_front() {
                calculate_render_commands(
                    &self.layout_manager.root,
                    node,
                    &mut open_nodes,
                    &mut render_commands_buffer,
                    &mut self.configs,
                    &self.text_fragments,
                );
            }
            let root = LayoutTreeIndex::new(&[root_id]);
            let self_node =
                LayoutTreeCursorBorrow::new_from_index(&self.layout_manager.root, &root).unwrap();
            sort_commands(
                &mut render_commands_buffer,
                self_node.get_local().self_element.config.floating.z_index,
            );
            render_commands.append(&mut render_commands_buffer);
        }
        render_commands
    }

    /// Runs the full layout pipeline and returns render commands for this frame.
    ///
    /// Order: fit/grow/shrink (width) → text wrap → fit/grow/shrink (height) → positioning →
    /// render command emission. Clears the live tree and populates the manager's element cache
    /// for inspection traits.
    ///
    /// Prefer [`LayoutFrameManager::end`](cotis::layout::LayoutFrameManager::end) when using
    /// the standard Cotis frame API.
    pub fn finalize_layouts(&mut self) -> Vec<RenderCommandOutput<Config>> {
        if let Some(id) = self.open_element_index.pop()
            && id != self.layout_manager.root_id.get_handle()
        {
            println!("[Cotis Layout] Not all elements have been closed");
        }

        // Finalized layout
        self.calculate_final_layout_sizes();
        self.calculate_positions();
        let res = self.calculate_render_commands();
        self.layout_manager.clear_tree();
        res
    }

    /// Removes and returns the user config for `element_id` after render command extraction.
    ///
    /// # Panics
    ///
    /// Panics if no config exists for `element_id`.
    pub fn remove_custom(&mut self, element_id: ElementId) -> Config {
        self.configs
            .remove(&element_id)
            .expect("[Cotis Layout] Can't find config from element id")
    }
}