khora_core/ui/layout.rs
1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Interface for UI layout computation.
16
17use crate::ecs::entity::EntityId;
18use crate::ui::types::{UiNode, UiTransform};
19use std::any::Any;
20
21/// A trait providing a read/write view of UI data for layout computation.
22///
23/// This allows layout systems (in `khora-infra`) to operate on UI data without
24/// depending on the specific ECS implementation (in `khora-data`).
25pub trait UiLayoutView {
26 /// Returns the IDs of all entities that should be considered for layout.
27 fn get_all_ui_entities(&self) -> Vec<EntityId>;
28
29 /// Returns the UI node definition for a given entity.
30 fn get_node(&self, entity: EntityId) -> Option<UiNode>;
31
32 /// Returns the children of a given entity.
33 fn get_children(&self, entity: EntityId) -> Vec<EntityId>;
34
35 /// Returns true if the entity has a parent.
36 fn has_parent(&self, entity: EntityId) -> bool;
37
38 /// Writes the computed transform back to the entity.
39 fn set_transform(&mut self, entity: EntityId, transform: UiTransform);
40
41 /// The available layout viewport in physical pixels `(width, height)`.
42 ///
43 /// Layout systems use this as the root `AvailableSpace` so percentage and
44 /// `flex` sizing resolve against the real surface rather than a fixed
45 /// assumption. The default returns `(1920, 1080)` for views that do not
46 /// track a surface size; implementors backed by a live surface should
47 /// override it (e.g. the ECS `World` exposing the current surface size).
48 fn viewport_size(&self) -> (u32, u32) {
49 (1920, 1080)
50 }
51}
52
53/// A trait defining a system capable of computing UI layouts.
54pub trait LayoutSystem: Send + Sync {
55 /// Computes layouts using the provided UI view.
56 fn compute_layouts(&mut self, view: &mut dyn UiLayoutView);
57
58 /// Allows downcasting to concrete implementations.
59 fn as_any(&self) -> &dyn Any;
60
61 /// Allows mutable downcasting to concrete implementations.
62 fn as_any_mut(&mut self) -> &mut dyn Any;
63}