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
//! Basic component layout engine.
//!
//! This module provides a layout engine for component diagrams
//! using a simple, deterministic algorithm.
use std::{
collections::{HashMap, HashSet, VecDeque},
rc::Rc,
};
use orrery_core::{
draw::{self, Drawable},
geometry::{Insets, Point, Size},
identifier::Id,
semantic,
};
use crate::{
error::RenderError,
layout::{
component::{Component, Layout, LayoutRelation, adjust_positioned_contents_offset},
engines::{ComponentEngine, EmbeddedLayouts},
layer::{ContentStack, PositionedContent},
},
structure::{ComponentGraph, ContainmentScope},
};
/// Basic layout engine for component diagrams.
///
/// Assigns components to layers using BFS traversal and positions them
/// in a left-to-right arrangement. Relation labels influence inter-layer
/// spacing, and containment scopes are processed from innermost to
/// outermost.
#[derive(Default)]
pub struct Engine {
/// Padding inside component shapes.
padding: Insets,
/// Padding around text elements.
text_padding: f32,
/// Minimum spacing between adjacent components.
min_spacing: f32,
}
impl Engine {
/// Create a new basic component layout engine.
pub fn new() -> Self {
Self {
text_padding: 20.0,
..Self::default()
}
}
/// Set the padding around components.
pub fn set_padding(&mut self, padding: Insets) -> &mut Self {
self.padding = padding;
self
}
/// Set the padding for text elements.
#[allow(dead_code)]
pub fn set_text_padding(&mut self, padding: f32) -> &mut Self {
self.text_padding = padding;
self
}
/// Set the minimum spacing between components.
pub fn set_min_spacing(&mut self, spacing: f32) -> &mut Self {
self.min_spacing = spacing;
self
}
/// Calculate the layout for a component diagram.
///
/// # Arguments
///
/// * `graph` - The component diagram graph to lay out.
/// * `embedded_layouts` - Pre-calculated layouts for embedded diagrams.
///
/// # Errors
///
/// Returns [`RenderError::Layout`] if position or shape calculation fails.
pub fn calculate_layout<'a>(
&self,
graph: &'a ComponentGraph<'a, '_>,
embedded_layouts: &EmbeddedLayouts<'a>,
) -> Result<ContentStack<Layout<'a>>, RenderError> {
let mut content_stack = ContentStack::<Layout<'a>>::new();
let mut positioned_content_sizes = HashMap::<Id, Size>::new();
for containment_scope in graph.containment_scopes() {
// Calculate component shapes - they contain all sizing information
let mut component_shapes = self.calculate_component_shapes(
graph,
containment_scope,
&positioned_content_sizes,
embedded_layouts,
)?;
// Calculate positions for components
let positions = self.positions(graph, containment_scope, &component_shapes)?;
// Build the final component list using the pre-configured shapes
let components: Vec<Component> = graph
.scope_nodes(containment_scope)
.map(|node| {
let mut position = *positions.get(&node.id()).ok_or_else(|| {
RenderError::Layout(format!(
"Position not found for node '{node}' during component layout"
))
})?;
let shape_with_text = component_shapes.remove(&node.id()).ok_or_else(|| {
RenderError::Layout(format!(
"Shape not found for node '{node}' during component layout"
))
})?;
// If this node contains an embedded diagram, adjust position to normalize
// the embedded layout's coordinate system to start at origin
if let semantic::Block::Diagram(_) = node.block()
&& let Some(layout) = embedded_layouts.get(&node.id())
{
position = position.add_point(layout.normalize_offset());
}
Ok(Component::new(node, shape_with_text, position))
})
.collect::<Result<Vec<_>, RenderError>>()?;
// Map node IDs to their component indices
let component_indices: HashMap<_, _> = components
.iter()
.enumerate()
.map(|(idx, component)| (component.node_id(), idx))
.collect();
// Build the list of relations between components
let relations: Vec<LayoutRelation> = graph
.scope_relations(containment_scope)
.filter_map(|relation| {
// Only include relations between visible components
// (not including relations within inner blocks)
if let (Some(&source_index), Some(&target_index)) = (
component_indices.get(&relation.source()),
component_indices.get(&relation.target()),
) {
Some(LayoutRelation::from_ast(
relation,
source_index,
target_index,
))
} else {
None
}
})
.collect();
let positioned_content = PositionedContent::new(Layout::new(components, relations));
if let Some(container) = containment_scope.container() {
// If this layer is a container, we need to adjust its size based on its contents
let size = positioned_content.layout_size();
positioned_content_sizes.insert(container, size);
}
content_stack.push(positioned_content);
}
adjust_positioned_contents_offset(&mut content_stack, graph)?;
Ok(content_stack)
}
/// Calculate component shapes with proper content size and padding.
fn calculate_component_shapes<'a>(
&self,
graph: &'a ComponentGraph<'a, '_>,
containment_scope: &ContainmentScope,
positioned_content_sizes: &HashMap<Id, Size>,
embedded_layouts: &EmbeddedLayouts<'a>,
) -> Result<HashMap<Id, draw::ShapeWithText<'a>>, RenderError> {
let mut component_shapes: HashMap<Id, draw::ShapeWithText<'a>> = HashMap::new();
// TODO: move it to the best place.
for node in graph.scope_nodes(containment_scope) {
let mut shape = draw::Shape::new(Rc::clone(node.shape_definition()));
shape.set_padding(self.padding);
let text = draw::Text::new(node.shape_definition().text(), node.display_text());
let mut shape_with_text = draw::ShapeWithText::new(shape, Some(text));
match node.block() {
semantic::Block::Diagram(_) => {
// Since we process in post-order (innermost to outermost),
// embedded diagram layouts should already be calculated and available
let layout = embedded_layouts.get(&node.id()).ok_or_else(|| {
RenderError::Layout(format!(
"Embedded layout not found for diagram block '{node}'"
))
})?;
let content_size = layout.calculate_size();
shape_with_text
.set_inner_content_size(content_size)
.map_err(|err| {
RenderError::Layout(format!(
"Failed to set content size for diagram block '{node}': {err}"
))
})?;
}
semantic::Block::Scope(_) => {
let content_size =
*positioned_content_sizes.get(&node.id()).ok_or_else(|| {
RenderError::Layout(format!("Scope size not found for node '{node}'"))
})?;
shape_with_text
.set_inner_content_size(content_size)
.map_err(|err| {
RenderError::Layout(format!(
"Failed to set content size for scope block '{node}': {err}"
))
})?;
}
semantic::Block::None => {
// No content to size, so don't call set_inner_content_size
}
};
component_shapes.insert(node.id(), shape_with_text);
}
Ok(component_shapes)
}
/// Calculate positions for components in a containment scope.
fn positions<'a>(
&self,
graph: &'a ComponentGraph<'a, '_>,
containment_scope: &ContainmentScope,
component_shapes: &HashMap<Id, draw::ShapeWithText<'a>>,
) -> Result<HashMap<Id, Point>, RenderError> {
// Step 1: Assign layers for the top-level nodes
let layers = Self::assign_layers_for_containment_scope_graph(graph, containment_scope)?;
// Step 2: Calculate layer metrics (widths and spacings)
let (layer_widths, layer_spacings) =
self.calculate_layer_metrics(graph, containment_scope, &layers, component_shapes)?;
// Step 3: Calculate X positions for each layer
let layer_x_positions = self.calculate_layer_x_positions(&layer_widths, &layer_spacings);
// Step 4: Position nodes within their layers
self.position_nodes_in_layers(&layers, &layer_x_positions, component_shapes)
}
/// Calculate metrics for each layer: widths and spacings between layers.
fn calculate_layer_metrics<'a>(
&self,
graph: &'a ComponentGraph<'a, '_>,
containment_scope: &ContainmentScope,
layers: &[Vec<Id>],
component_shapes: &HashMap<Id, draw::ShapeWithText<'a>>,
) -> Result<(Vec<f32>, Vec<f32>), RenderError> {
// Calculate max width for each layer
let layer_widths: Vec<f32> = layers
.iter()
.map(|layer| {
layer.iter().try_fold(0.0_f32, |max_width, &node_idx| {
let width = component_shapes
.get(&node_idx)
.map(|shape| shape.size().width())
.ok_or_else(|| {
RenderError::Layout(format!(
"Component shape not found for node '{}' during layer metrics calculation",
node_idx
))
})?;
Ok(max_width.max(width))
})
})
.collect::<Result<Vec<f32>, RenderError>>()?;
// Initialize spacings with default padding
let mut layer_spacings =
vec![self.padding.horizontal_sum() / 2.0; layers.len().saturating_sub(1)];
// Adjust spacings based on relation labels
for relation in graph.scope_relations(containment_scope) {
if let Some(text) = relation.text() {
let label_width = text.calculate_size().width();
// Find layers for source and target nodes
let (source_layer, target_layer) = self.find_node_layers(relation, layers);
if let (Some(src), Some(tgt)) = (source_layer, target_layer)
&& src != tgt
{
// Only adjust spacing for relations between different layers
let min_layer = src.min(tgt);
let needed_spacing = label_width + 30.0; // Add some padding
// Update spacing if label requires more space
if min_layer < layer_spacings.len() {
layer_spacings[min_layer] = layer_spacings[min_layer].max(needed_spacing);
}
}
}
}
Ok((layer_widths, layer_spacings))
}
/// Find which layer contains nodes for a given relation.
// PERF: Deprecate this method in favor of a more efficient approach.
fn find_node_layers(
&self,
relation: &semantic::Relation,
layers: &[Vec<Id>],
) -> (Option<usize>, Option<usize>) {
let mut source_layer = None;
let mut target_layer = None;
for (layer_idx, layer_nodes) in layers.iter().enumerate() {
for node_id in layer_nodes {
if *node_id == relation.source() {
source_layer = Some(layer_idx);
}
if *node_id == relation.target() {
target_layer = Some(layer_idx);
}
}
}
(source_layer, target_layer)
}
/// Calculate X positions for each layer based on widths and spacings.
fn calculate_layer_x_positions(
&self,
layer_widths: &[f32],
layer_spacings: &[f32],
) -> Vec<f32> {
let mut layer_x_positions = Vec::with_capacity(layer_widths.len());
let mut x_pos = 0.0;
for (i, width) in layer_widths.iter().enumerate() {
layer_x_positions.push(x_pos + width / 2.0);
let spacing = if i < layer_spacings.len() {
layer_spacings[i]
} else {
self.padding.horizontal_sum() / 2.0
};
x_pos += width + spacing;
}
layer_x_positions
}
/// Position nodes within their layers.
fn position_nodes_in_layers<'a>(
&self,
layers: &[Vec<Id>],
layer_x_positions: &[f32],
component_shapes: &HashMap<Id, draw::ShapeWithText<'a>>,
) -> Result<HashMap<Id, Point>, RenderError> {
let mut positions = HashMap::new();
for (layer_idx, layer_nodes) in layers.iter().enumerate() {
let x = layer_x_positions[layer_idx];
// Calculate heights for vertical positioning
let mut y_pos = 0.0;
for (j, &node_idx) in layer_nodes.iter().enumerate() {
let node_height = component_shapes
.get(&node_idx)
.ok_or_else(|| {
RenderError::Layout(format!(
"Component shape not found for node '{}' during position calculation",
node_idx
))
})?
.size()
.height();
if j > 0 {
y_pos += self.padding.vertical_sum() / 2.0; // Space between components
}
let y = y_pos + node_height / 2.0;
positions.insert(node_idx, Point::new(x, y));
y_pos += node_height;
}
}
Ok(positions)
}
/// Helper method to assign layers for a specific graph.
fn assign_layers_for_containment_scope_graph(
graph: &ComponentGraph,
containment_scope: &ContainmentScope,
) -> Result<Vec<Vec<Id>>, RenderError> {
let mut layers = Vec::new();
let mut visited = HashSet::new();
// Find root nodes
let root_nodes: Vec<_> = graph.scope_roots(containment_scope).collect();
let start_nodes = if root_nodes.is_empty() {
graph.scope_nodes(containment_scope).take(1).collect()
} else {
root_nodes
};
// Perform BFS to assign layers
let mut queue = VecDeque::new();
for node in start_nodes {
queue.push_back((node, 0));
}
while let Some((node, layer)) = queue.pop_front() {
if !visited.insert(node.id()) {
continue;
}
while layers.len() <= layer {
layers.push(Vec::new());
}
layers[layer].push(node.id());
for neighbor in graph
.scope_outgoing_neighbors(containment_scope, node.id())
.filter(|node| !visited.contains(&node.id()))
{
queue.push_back((neighbor, layer + 1));
}
}
// Handle disconnected components by processing any remaining unvisited nodes
while visited.len() < containment_scope.nodes_count() {
// Find an unvisited node to start a new component
// PERF: This can be an outer loop for a single iteration.
let unvisited_node_id = containment_scope
.node_ids()
.find(|id| !visited.contains(id))
.ok_or_else(|| {
RenderError::Layout("Expected unvisited nodes but none found".to_string())
})?;
let unvisited_node = graph.node_by_id(unvisited_node_id).ok_or_else(|| {
RenderError::Layout(format!(
"Node '{}' from containment scope not found in graph",
unvisited_node_id
))
})?;
queue.push_back((unvisited_node, 0));
// Process this disconnected component using the same BFS logic
// TODO: this is a duplicated code.
while let Some((node, layer)) = queue.pop_front() {
if !visited.insert(node.id()) {
continue;
}
while layers.len() <= layer {
layers.push(Vec::new());
}
layers[layer].push(node.id());
for neighbor in graph
.scope_outgoing_neighbors(containment_scope, node.id())
.filter(|node| !visited.contains(&node.id()))
{
queue.push_back((neighbor, layer + 1));
}
}
}
Ok(layers)
}
}
impl ComponentEngine for Engine {
fn calculate<'a>(
&self,
graph: &'a ComponentGraph<'a, '_>,
embedded_layouts: &EmbeddedLayouts<'a>,
) -> Result<ContentStack<Layout<'a>>, RenderError> {
self.calculate_layout(graph, embedded_layouts)
}
}