altui 0.2.0

A state-driven TUI runtime built on top of altui-core
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
use altui_core::layout::Layout;
use altui_core::layout::Rect;

use crate::context::ViewCtx;

/// A zero‑sized rectangle used to efficiently skip areas in the layout pipeline.
///
/// This constant is a low‑level building block for situations where a widget
/// must be hidden while keeping the total number of consumed rectangles
/// unchanged. Instead of performing expensive [`Layout::split`] operations or
/// constructing custom arrays, prefer the high‑level [`skip_areas`] method.
///
/// # Usage
/// Direct use of `EMPTY_AREA` is rarely needed. To hide a widget without
/// altering the area count, call:
/// ```rust,ignore
/// ctx.skip_areas(1);   // skip a single area
/// ctx.skip_areas(n);   // skip n areas
/// ```
/// This is both simpler and more efficient than manually creating arrays of
/// `EMPTY_AREA`.
pub const EMPTY_AREA: Rect = Rect {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
};

/// Per-view layout cache used during rendering.
///
/// `AreaCache` is passed to every [`View::render`](crate::View::render) call
/// and is meant for view-local splitting work performed inside `render`.
///
/// It is not just a thin wrapper around [`Layout::split`] and
/// [`Layout::split_ext`]. `altui` intentionally does not rely on the legacy
/// cache from `altui-core`; instead it keeps a frame-local cache here and uses
/// the faster `Layout::cache_eq` comparison to decide whether a cached split can
/// be reused.
///
/// In practice, `AreaCache` is useful when a view repeatedly performs the same
/// internal splits while only the outer area or scroll position changes, for
/// example inside popup or wrapped-content rendering.
#[derive(Debug, Default)]
pub struct AreaCache {
    cached: Vec<CachedSplit>,
    pub(crate) current_split: usize,
}

impl AreaCache {
    /// Splits `area` with caching local to the current render pass.
    ///
    /// Use this inside [`View::render`](crate::View::render) when the same view
    /// performs repeatable internal layout work across frames.
    pub fn split(&mut self, layout: Layout, area: Rect) -> Vec<Rect> {
        let cached = match self.cached.get_mut(self.current_split) {
            Some(v) => v,
            None => {
                let result = layout.split(area);
                self.cached
                    .push(CachedSplit::new(layout.clone(), area, result.clone()));
                self.current_split += 1;
                return result;
            }
        };

        self.current_split += 1;

        if cached.offsets.len() > 1 {
            panic!("Failed to use 'CtxStore::split' method after 'CtxStore::split_ext'")
        }

        match cached.layout.cache_eq(&layout) {
            true => match area == cached.prev_area {
                true => cached.offsets[0].clone(),
                false => {
                    cached.prev_area = area;
                    let result = layout.split(area);
                    cached.offsets[0] = result.clone();
                    result
                }
            },
            false => {
                cached.prev_area = area;
                cached.layout = layout.clone();
                let result = layout.split(area);
                cached.offsets[0] = result.clone();
                result
            }
        }
    }

    /// Cached scrolling variant of [`split`](Self::split).
    ///
    /// This stores distinct cached results per scroll offset and is useful for
    /// render-time layouts that scroll inside a single view.
    pub fn split_ext(
        &mut self,
        layout: Layout,
        area: Rect,
        scrollstate: &mut u16,
        scroll: &mut u16,
    ) -> Vec<Rect> {
        if *scroll > 0 && scrollstate > scroll {
            *scrollstate = *scroll;
        }

        let idx: usize = *scrollstate as usize;

        let cached_layout = match self.cached.get_mut(self.current_split) {
            Some(v) => v,
            None => {
                let result = layout.split_ext(area, scrollstate, scroll);
                self.cached
                    .push(CachedSplit::new(layout.clone(), area, result.clone()));
                self.current_split += 1;
                return result;
            }
        };

        self.current_split += 1;

        if !cached_layout.layout.cache_eq(&layout) {
            cached_layout.layout = layout.clone();
            cached_layout.offsets.clear();
        }

        cached_layout.offsets.resize_with(idx + 1, Vec::new);

        if area == cached_layout.prev_area && !cached_layout.offsets[idx].is_empty() {
            return cached_layout.offsets[idx].clone();
        }

        let result = layout.split_ext(area, scrollstate, scroll);
        cached_layout.offsets[idx] = result.clone();
        cached_layout.prev_area = area;
        result
    }
}

#[derive(Debug, Default)]
struct CachedSplit {
    layout: Layout,
    prev_area: Rect,
    offsets: Vec<Vec<Rect>>,
}

impl CachedSplit {
    fn new(layout: Layout, prev_area: Rect, area: Vec<Rect>) -> Self {
        Self {
            layout,
            prev_area,
            offsets: vec![area],
        }
    }
}

/// Layout context manager used by the `areas` closure.
///
/// `CtxStore` is the runtime-side companion of [`ViewFactory`](crate::ViewFactory):
///
/// - it stores one [`ViewCtx`] per inserted view
/// - it assigns rectangles to those views in insertion order
/// - it tracks the interactive navigation list
/// - it exposes cached layout helpers for the `areas` closure
///
/// The key rule is simple: the `areas` closure must consume exactly as many
/// rectangles as the `views` closure inserted views.
///
/// Typical patterns:
///
/// - `simple_pages`: use `skip_areas` for hidden page views while preserving
///   the required rectangle count
/// - `scroll_layout`: use `split_ext` to drive a shared scroll state
/// - `wrap_with_scroll`: use `split_ext` together with wrapping so the layout
///   scrolls by wrapped rows
pub struct CtxStore {
    pub(crate) contexts: Vec<ViewCtx>,
    pub(crate) interactive: Vec<usize>,
    // TODO: probably need to be renamed: current_interactive_idx
    pub(crate) current_interactive_idx: usize,
    pub(crate) is_hovered: bool,
    pub(crate) current_area: usize,
    pub(crate) scroll_step: usize,
    pub(crate) layout_cache: AreaCache,
}

impl Default for CtxStore {
    fn default() -> Self {
        Self {
            contexts: Default::default(),
            interactive: Default::default(),
            current_interactive_idx: Default::default(),
            is_hovered: false,
            current_area: Default::default(),
            scroll_step: 2,
            layout_cache: AreaCache::default(),
        }
    }
}

impl CtxStore {
    /// Splits an area for use in the `areas` closure.
    ///
    /// This is the usual helper for non-scrolling layouts such as page shells,
    /// button rows, or fixed sections. It uses [`AreaCache`] under the hood, so
    /// repeated frames avoid unnecessary work when the same layout is reused.
    ///
    /// Use this in the `areas` closure, not inside `render`. For render-time
    /// local layout work, use the [`AreaCache`] passed to the view instead.
    pub fn split(&mut self, layout: Layout, area: Rect) -> Vec<Rect> {
        self.layout_cache.split(layout, area)
    }

    /// Scrolling variant of [`split`](Self::split) for the `areas` closure.
    ///
    /// This is the main helper for scroll-aware page layout. It is used when
    /// the layout itself depends on an external scroll state, as in
    /// `scroll_layout` and `wrap_with_scroll`.
    ///
    /// `scrollstate` is the current position, while `scroll` stores the total
    /// content length reported by the layout.
    pub fn split_ext(
        &mut self,
        layout: Layout,
        area: Rect,
        scrollstate: &mut u16,
        scroll: &mut u16,
    ) -> Vec<Rect> {
        self.layout_cache
            .split_ext(layout, area, scrollstate, scroll)
    }

    /// Assigns one rectangle to the next view in insertion order.
    ///
    /// This is the most explicit way to bind a computed rectangle to one view.
    /// Areas are consumed in FIFO order: the first call to `next_area`
    /// corresponds to the first inserted view, the second call to the second
    /// view, and so on.
    ///
    /// ### Arguments
    /// * `area` – The rectangle to assign to the next view.
    ///
    /// ### Important
    /// The number of areas passed across all calls to `next_area` and
    /// [`next_areas`](Self::next_areas) **must** exactly match the total number of
    /// views. Otherwise altui runtime will panic.
    ///
    /// ## See also
    /// - [`next_areas`](Self::next_areas) for assigning multiple rectangles at once.
    /// - [`skip_areas`](Self::skip_areas) for efficiently skipping areas without splits.
    pub fn next_area(&mut self, area: Rect) {
        match self.contexts.get_mut(self.current_area) {
            Some(contexts) => {
                contexts.set_area(area);
                self.current_area += 1;
            }
            None => {
                panic!(
                    "Failed to find {}'s View while setting areas",
                    self.current_area
                )
            }
        }
    }

    /// Assigns several consecutive rectangles to the next views.
    ///
    /// This is a convenience wrapper around repeated [`next_area`](Self::next_area)
    /// calls and is useful when a split already produced an ordered batch of
    /// areas that map directly to a consecutive group of views.
    ///
    /// ### Arguments
    /// * `areas` - A slice of [`Rect`] elements to be assigned in order.
    ///
    /// ### Important
    /// The number of areas passed across all calls to `next_areas` and
    /// [`next_area`](Self::next_area) **must** exactly match the total number of
    /// views. Otherwise altui runtime will panic.
    ///
    /// ## See also
    /// - [`next_area`](Self::next_area) for assigning a single rectangle.
    /// - [`skip_areas`](Self::skip_areas) for efficiently skipping areas without splits.
    pub fn next_areas(&mut self, areas: &[Rect]) {
        for area in areas {
            match self.contexts.get_mut(self.current_area) {
                Some(contexts) => {
                    contexts.set_area(*area);
                    self.current_area += 1;
                }
                None => {
                    panic!(
                        "Failed to find {}'s View while setting areas",
                        self.current_area
                    )
                }
            }
        }
    }

    /// Skips the next `number` views by assigning [`EMPTY_AREA`] to them.
    ///
    /// This is the main tool for conditional pages and layers. It lets the
    /// runtime keep the required view/area alignment without spending time on
    /// real layout work for views that are currently hidden.
    ///
    /// The `simple_pages` example uses this pattern: hidden pages still own two
    /// views, so the `areas` closure must still provide two rectangles. Instead
    /// of splitting a real layout, `skip_areas(2)` injects two empty rectangles.
    ///
    /// ### Arguments
    /// * `number` - Number of areas to skip.
    ///
    /// ### Example
    /// ```rust,ignore
    /// // Before:
    /// // const HIDDEN_AREAS: &[Rect; 2] = &[EMPTY_AREA; 2];
    /// // ctx.next_areas(HIDDEN_AREAS);
    ///
    /// // After:
    /// ctx.skip_areas(2);
    /// ```
    ///
    /// See:
    /// <https://altlinux.space/writers/altui/src/branch/main/examples/simple_pages>
    pub fn skip_areas(&mut self, number: usize) {
        for _ in 0..number {
            match self.contexts.get_mut(self.current_area) {
                Some(contexts) => {
                    contexts.set_area(EMPTY_AREA);
                    self.current_area += 1;
                }
                None => {
                    panic!(
                        "Failed to find {}'s View while setting areas",
                        self.current_area
                    )
                }
            }
        }
    }

    #[inline(always)]
    fn get_current_index(&self) -> usize {
        self.interactive[self.current_interactive_idx]
    }

    pub(crate) fn set_vscroll(&mut self, step: usize) {
        self.scroll_step = step.clamp(1, 20);
    }

    pub(crate) fn push(&mut self, ctx: ViewCtx) {
        self.contexts.push(ctx);
    }

    pub(crate) fn push_interactive(&mut self, ctx: ViewCtx) {
        let index = self.contexts.len();
        self.contexts.push(ctx);
        self.interactive.push(index);
    }

    pub(crate) fn first(&mut self) {
        if !self.interactive.is_empty() {
            self.current_interactive_idx = self.interactive.len() - 1;
            self.is_hovered = true;
            self.next();
        }
    }

    pub(crate) fn last(&mut self) {
        if !self.interactive.is_empty() {
            self.current_interactive_idx = 0;
            self.is_hovered = true;
            self.previous();
        }
    }

    pub(crate) fn next(&mut self) {
        let len = self.interactive.len() - 1;
        let start = self.current_interactive_idx;
        loop {
            match self.is_hovered {
                true => match self.current_interactive_idx != len {
                    true => self.current_interactive_idx = self.current_interactive_idx + 1,
                    false => self.current_interactive_idx = 0,
                },
                false => self.is_hovered = true,
            }
            let ctx = &self.contexts[self.get_current_index()];
            match ctx.is_visible() && ctx.is_interactive() {
                true => {
                    ctx.set_hover();
                    break;
                }
                false => match self.current_interactive_idx == start {
                    true => break,
                    false => continue,
                },
            }
        }
    }

    pub(crate) fn previous(&mut self) {
        let len = self.interactive.len() - 1;
        let start = self.current_interactive_idx;
        loop {
            match self.is_hovered {
                true => match self.current_interactive_idx != 0 {
                    true => self.current_interactive_idx = self.current_interactive_idx - 1,
                    false => self.current_interactive_idx = len,
                },
                false => self.is_hovered = true,
            }

            let ctx = &self.contexts[self.get_current_index()];
            match ctx.is_visible() && ctx.is_interactive() {
                true => {
                    ctx.set_hover();
                    break;
                }
                false => match self.current_interactive_idx == start {
                    true => break,
                    false => continue,
                },
            }
        }
    }

    pub(crate) fn down(&mut self) {
        let len = self.interactive.len() - 1;
        let start = self.current_interactive_idx;
        let mut count = 1;
        loop {
            match self.is_hovered {
                true => match self.current_interactive_idx != len {
                    true => self.current_interactive_idx = self.current_interactive_idx + 1,
                    false => self.current_interactive_idx = 0,
                },
                false => self.is_hovered = true,
            }

            let ctx = &self.contexts[self.get_current_index()];
            match ctx.is_visible() && ctx.is_interactive() {
                true => match count == self.scroll_step {
                    true => {
                        ctx.set_hover();
                        break;
                    }
                    false => count += 1,
                },
                false => match self.current_interactive_idx == start {
                    true => break,
                    false => continue,
                },
            }
        }
    }

    pub(crate) fn up(&mut self) {
        let len = self.interactive.len() - 1;
        let start = self.current_interactive_idx;
        let mut count = 1;
        loop {
            match self.is_hovered {
                true => match self.current_interactive_idx != 0 {
                    true => self.current_interactive_idx = self.current_interactive_idx - 1,
                    false => self.current_interactive_idx = len,
                },
                false => self.is_hovered = true,
            }

            let state = &self.contexts[self.get_current_index()];
            match state.is_visible() && state.is_interactive() {
                true => match count == self.scroll_step {
                    true => {
                        state.set_hover();
                        break;
                    }
                    false => count += 1,
                },
                false => match self.current_interactive_idx == start {
                    true => break,
                    false => continue,
                },
            }
        }
    }

    pub(crate) fn mouse_set_hover(&mut self, x: u16, y: u16) {
        for (interactive_i, currrent_i) in self.interactive.iter().enumerate() {
            let state = &self.contexts[*currrent_i];
            if state.is_visible() && state.is_interactive() && state.get_area_ref().inhere(x, y) {
                state.set_hover();
                self.current_interactive_idx = interactive_i;
                self.is_hovered = true;
                break;
            }
        }
    }

    pub(crate) fn mouse_is_hovered(&mut self, x: u16, y: u16) -> bool {
        match self.interactive.is_empty() {
            true => false,
            false => {
                let state = &self.contexts[self.get_current_index()];
                match state.get_area_ref().inhere(x, y) {
                    true => true && self.is_hovered && state.is_visible() && state.is_interactive(),
                    false => {
                        self.is_hovered = false;
                        false
                    }
                }
            }
        }
    }
}