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
// In a new file, layout/src/text3/tests4.rs

use azul_core::{
    geom::{LogicalPosition, LogicalRect, LogicalSize},
    selection::*,
};

use super::{create_mock_font_manager, default_style, MockFont};
use crate::text3::{
    cache::*,
    edit::{edit_text, TextEdit},
    tests::MockFontManager,
};

#[test]
fn test_hittest_simple_ltr() {
    let manager = create_mock_font_manager();
    let content = vec![InlineContent::Text(StyledRun {
        text: "hello".into(), // h=9, e=8, l=4, l=4, o=9
        style: default_style(),
        logical_start_byte: 0,
    })];
    let constraints = UnifiedConstraints {
        available_width: 200.0,
        ..Default::default()
    };

    let mut cache = LayoutCache::<MockFont>::new();
    let flow_chain = vec![LayoutFragment {
        id: "main".into(),
        constraints,
    }];

    let layout = cache
        .layout_flow(&content, &[], &flow_chain, &manager)
        .unwrap();
    let main_layout = layout.fragment_layouts.get("main").unwrap();

    // Hit test near the 'e' character (h is 9px wide)
    let cursor = main_layout
        .hittest_cursor(LogicalPosition { x: 12.0, y: 5.0 })
        .unwrap();

    let expected_cluster = GraphemeClusterId {
        source_run: 0,
        start_byte_in_run: 1,
    }; // 'e' is at byte 1
    assert_eq!(cursor.cluster_id, expected_cluster);
    assert_eq!(cursor.affinity, CursorAffinity::Leading); // 9 + (8/2) = 13. 12 < 13 -> Leading

    // Hit test at the end of the word
    let cursor_end = main_layout
        .hittest_cursor(LogicalPosition { x: 40.0, y: 5.0 })
        .unwrap();
    let expected_cluster_end = GraphemeClusterId {
        source_run: 0,
        start_byte_in_run: 4,
    }; // 'o'
    assert_eq!(cursor_end.cluster_id, expected_cluster_end);
    assert_eq!(cursor_end.affinity, CursorAffinity::Trailing);
}

#[test]
fn test_get_selection_rects_single_line() {
    let manager = create_mock_font_manager();
    let content = vec![InlineContent::Text(StyledRun {
        text: "hello world".into(),
        style: default_style(),
        logical_start_byte: 0,
    })];
    let constraints = UnifiedConstraints {
        available_width: 200.0,
        ..Default::default()
    };

    let mut cache = LayoutCache::<MockFont>::new();
    let flow_chain = vec![LayoutFragment {
        id: "main".into(),
        constraints,
    }];

    let layout = cache
        .layout_flow(&content, &[], &flow_chain, &manager)
        .unwrap();
    let main_layout = layout.fragment_layouts.get("main").unwrap();

    let selection = SelectionRange {
        start: TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: 0,
                start_byte_in_run: 2,
            },
            affinity: CursorAffinity::Leading,
        }, // "l"
        end: TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: 0,
                start_byte_in_run: 8,
            },
            affinity: CursorAffinity::Trailing,
        }, // "r"
    };

    let rects = main_layout.get_selection_rects(&selection);

    // This is a placeholder test, since the implementation is a stub
    assert!(
        !rects.is_empty(),
        "Should generate at least one rectangle for selection"
    );
}

/// Creates a standard multi-line layout for testing navigation.
fn create_test_layout() -> (UnifiedLayout<MockFont>, MockFontManager) {
    let manager = create_mock_font_manager();
    // Use a single run to ensure "hello world" is treated as one logical unit
    let content = vec![InlineContent::Text(StyledRun {
        text: "hello world second line".into(),
        style: default_style(),
        logical_start_byte: 0,
    })];
    let constraints = UnifiedConstraints {
        available_width: 60.0, // "hello " fits, "world" wraps to next line
        line_height: 12.0,
        ..Default::default()
    };

    let mut cache = LayoutCache::<MockFont>::new();
    let flow_chain = vec![LayoutFragment {
        id: "main".into(),
        constraints,
    }];
    let layout_result = cache
        .layout_flow(&content, &[], &flow_chain, &manager)
        .unwrap();
    (
        layout_result
            .fragment_layouts
            .get("main")
            .unwrap()
            .as_ref()
            .clone(),
        manager,
    )
}

#[test]
fn test_move_cursor_up_down() {
    let (layout, _) = create_test_layout();

    // Cursor is on "o" in "world" on the second line.
    let start_cursor = TextCursor {
        cluster_id: GraphemeClusterId {
            source_run: 0,
            start_byte_in_run: 7,
        }, // 'o' in "world"
        affinity: CursorAffinity::Leading,
    };

    // Moving up should land on the first line, near the same X coordinate.
    let mut goal_x = None;
    let mut debug = Some(Vec::new());
    let up_cursor = layout.move_cursor_up(start_cursor, &mut goal_x, &mut debug);

    if let Some(d) = &debug {
        for msg in d {
            println!("{}", msg);
        }
    }

    // The 'l' in "hello" is roughly above 'o' in "world"
    assert_eq!(
        up_cursor.cluster_id.start_byte_in_run, 1,
        "Cursor should be on 'e'"
    );

    // Moving back down should return to the original character.
    let mut debug = Some(Vec::new());
    let down_cursor = layout.move_cursor_down(up_cursor, &mut goal_x, &mut debug);

    if let Some(d) = &debug {
        for msg in d {
            println!("{}", msg);
        }
    }
    assert_eq!(
        down_cursor.cluster_id.start_byte_in_run, 7,
        "Cursor should return to 'o'"
    );
}

#[test]
fn test_move_cursor_line_start_end() {
    let (layout, _) = create_test_layout();

    // Cursor is on "o" in "world" on the second line.
    let start_cursor = TextCursor {
        cluster_id: GraphemeClusterId {
            source_run: 0,
            start_byte_in_run: 7,
        },
        affinity: CursorAffinity::Leading,
    };

    let mut debug = Some(Vec::new());
    let line_start_cursor = layout.move_cursor_to_line_start(start_cursor, &mut debug);

    if let Some(d) = &debug {
        for msg in d {
            println!("{}", msg);
        }
    }

    assert_eq!(
        line_start_cursor.cluster_id.start_byte_in_run, 6,
        "Cursor should be at start of 'world'"
    );

    let mut debug = Some(Vec::new());
    let line_end_cursor = layout.move_cursor_to_line_end(start_cursor, &mut debug);

    if let Some(d) = &debug {
        for msg in d {
            println!("{}", msg);
        }
    }
    assert_eq!(
        line_end_cursor.cluster_id.start_byte_in_run, 11,
        "Cursor should be at end of 'world ' (including trailing space)"
    );
}

#[test]
fn test_edit_insert_char() {
    let content = vec![InlineContent::Text(StyledRun {
        text: "helo".into(),
        style: default_style(),
        logical_start_byte: 0,
    })];

    let cursor = Selection::Cursor(TextCursor {
        cluster_id: GraphemeClusterId {
            source_run: 0,
            start_byte_in_run: 2,
        }, // After 'e'
        affinity: CursorAffinity::Leading,
    });

    let (new_content, _) = edit_text(&content, &[cursor], &TextEdit::Insert("l".to_string()));

    let new_text = match &new_content[0] {
        InlineContent::Text(run) => &run.text,
        _ => panic!(),
    };

    assert_eq!(new_text, "hello");
}

#[test]
fn test_edit_delete_backward() {
    let content = vec![InlineContent::Text(StyledRun {
        text: "hel lo".into(),
        style: default_style(),
        logical_start_byte: 0,
    })];

    let cursor = Selection::Cursor(TextCursor {
        cluster_id: GraphemeClusterId {
            source_run: 0,
            start_byte_in_run: 4,
        }, // After space
        affinity: CursorAffinity::Leading,
    });

    let (new_content, _) = edit_text(&content, &[cursor], &TextEdit::DeleteBackward);

    let new_text = match &new_content[0] {
        InlineContent::Text(run) => &run.text,
        _ => panic!(),
    };

    assert_eq!(new_text, "hello");
}

/// Creates a standard multi-line layout for testing navigation.
fn create_test_layout_2() -> (UnifiedLayout<MockFont>, MockFontManager) {
    let manager = create_mock_font_manager();
    // Use a text that will definitely wrap to test multi-line navigation
    let content = vec![InlineContent::Text(StyledRun {
        text: "hello beautiful world".into(),
        style: default_style(),
        logical_start_byte: 0,
    })];
    let constraints = UnifiedConstraints {
        available_width: 60.0, // "hello " fits, "beautiful" wraps
        line_height: 12.0,
        ..Default::default()
    };

    let mut cache = LayoutCache::<MockFont>::new();
    let flow_chain = vec![LayoutFragment {
        id: "main".into(),
        constraints,
    }];
    let layout_result = cache
        .layout_flow(&content, &[], &flow_chain, &manager)
        .unwrap();
    (
        layout_result
            .fragment_layouts
            .get("main")
            .unwrap()
            .as_ref()
            .clone(),
        manager,
    )
}

#[test]
fn test_move_cursor_left_right_simple() {
    let (layout, _) = create_test_layout_2();

    // Start cursor at the beginning of 'e' in "hello"
    let start_cursor = TextCursor {
        cluster_id: GraphemeClusterId {
            source_run: 0,
            start_byte_in_run: 1,
        }, // 'e'
        affinity: CursorAffinity::Leading,
    };

    // Move right -> trailing edge of 'e'
    let c1 = layout.move_cursor_right(start_cursor, &mut None);
    assert_eq!(c1.cluster_id.start_byte_in_run, 1);
    assert_eq!(c1.affinity, CursorAffinity::Trailing);

    // Move right again -> leading edge of 'l'
    let c2 = layout.move_cursor_right(c1, &mut None);
    assert_eq!(c2.cluster_id.start_byte_in_run, 2);
    assert_eq!(c2.affinity, CursorAffinity::Leading);

    // Move left -> trailing edge of 'e'
    let c3 = layout.move_cursor_left(c2, &mut None);
    assert_eq!(c3.cluster_id.start_byte_in_run, 1);
    assert_eq!(c3.affinity, CursorAffinity::Trailing);

    // Move left again -> leading edge of 'e'
    let c4 = layout.move_cursor_left(c3, &mut None);
    assert_eq!(c4, start_cursor);
}

#[test]
fn test_edit_text_multi_cursor_insert() {
    let content = vec![InlineContent::Text(StyledRun {
        text: "cat hat".into(),
        style: default_style(),
        logical_start_byte: 0,
    })];
    let selections = vec![
        Selection::Cursor(TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: 0,
                start_byte_in_run: 1,
            }, // after 'c'
            affinity: CursorAffinity::Leading,
        }),
        Selection::Cursor(TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: 0,
                start_byte_in_run: 5,
            }, // after 'h'
            affinity: CursorAffinity::Leading,
        }),
    ];

    let (new_content, new_selections) =
        edit_text(&content, &selections, &TextEdit::Insert(" ".to_string()));

    let new_text = match &new_content[0] {
        InlineContent::Text(run) => &run.text,
        _ => panic!(),
    };

    assert_eq!(new_text, "c at h at");

    // Check that the new cursors are in the correct positions
    assert_eq!(new_selections.len(), 2);
    if let Selection::Cursor(c1) = new_selections[0] {
        assert_eq!(c1.cluster_id.start_byte_in_run, 2); // after "c "
    }
    if let Selection::Cursor(c2) = new_selections[1] {
        assert_eq!(c2.cluster_id.start_byte_in_run, 7); // after "h " (original 5 + 1 for first
                                                        // insert + 1 for second)
    }
}

#[test]
fn test_edit_delete_range_across_runs() {
    let content = vec![
        InlineContent::Text(StyledRun {
            text: "one".into(),
            style: default_style(),
            logical_start_byte: 0,
        }),
        InlineContent::Text(StyledRun {
            text: " two ".into(),
            style: default_style(),
            logical_start_byte: 4,
        }),
        InlineContent::Text(StyledRun {
            text: "three".into(),
            style: default_style(),
            logical_start_byte: 9,
        }),
    ];

    let range = SelectionRange {
        start: TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: 0,
                start_byte_in_run: 2,
            }, // after "on"
            affinity: CursorAffinity::Leading,
        },
        end: TextCursor {
            cluster_id: GraphemeClusterId {
                source_run: 2,
                start_byte_in_run: 3,
            }, // after "thr"
            affinity: CursorAffinity::Leading,
        },
    };

    // STUB: Full multi-run deletion is complex. This test will fail with the stub
    // but demonstrates the required behavior.
    let (new_content, new_cursor) = crate::text3::edit::delete_range(&content, &range);

    // Expected result: a single run "onree"
    // assert_eq!(new_content.len(), 1);
    // if let InlineContent::Text(run) = &new_content[0] {
    //     assert_eq!(run.text, "onree");
    // }
    // assert_eq!(new_cursor.cluster_id.start_byte_in_run, 2);
}