urushi 0.1.1

Composable styling, components, and terminal rendering for Rust CLIs
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
//! Free-positioned, renderer-neutral drawing inside a finite [`Canvas`].
//!
//! A Canvas carries exactly one [`CanvasSizing`] value. Ordinary canvases use
//! viewport sizing and consume finite allocation; built-in presentations may
//! internally bind intrinsic requirements without deriving them from items.
//!
//! A Canvas owns immutable [`CanvasItem`] values. Resolution first fixes the
//! surface size, then calls each item once with a frame-scoped [`CanvasContext`].
//! Items record `View`, text, cell-space primitives, [`LineNetwork`], or
//! sparse-cell commands in paint order. After sizing, Canvas assembly
//! rasterizes one command at a time through a common internal contract and
//! immediately applies its cells through that command's [`Composition`].
//!
//! ```
//! use urushi::{
//!     Available, Canvas, CanvasContext, CanvasItem, Composition, Position,
//!     Size, TextStyle, View, resolve,
//! };
//!
//! #[derive(Debug, Clone, PartialEq)]
//! struct Label(&'static str);
//!
//! impl CanvasItem for Label {
//!     fn draw(&self, canvas: &mut CanvasContext) {
//!         // Responsive items see the final size, not a provisional measure.
//!         let x = canvas.size().width().saturating_sub(self.0.len()) as i64;
//!         canvas.text_with(
//!             Position::new(x, 0),
//!             self.0,
//!             TextStyle::new().bold(),
//!             Composition::Overlay,
//!         );
//!     }
//! }
//!
//! // Explicit extents make an otherwise-unbounded Canvas finite.
//! let view = View::canvas(Canvas::new().extent(Size::new(8, 2)).item(Label("ok")));
//! assert_eq!(resolve(&view, Available::NONE).unwrap().size(), Size::new(8, 2));
//!
//! // A parent allocation takes precedence over an explicit extent. Omit an
//! // extent only when that axis will always receive a finite allocation.
//! let allocated = View::canvas(Canvas::new().item(Label("ok")));
//! assert_eq!(resolve(&allocated, Available::size(12, 3)).unwrap().size(), Size::new(12, 3));
//! assert!(resolve(&allocated, Available::NONE).is_err());
//! ```

mod assemble;
mod cell;
mod cell_primitives;
mod command;
mod context;
mod line_network;
pub(crate) mod sizing;

use std::any::Any;
use std::fmt;

use super::geometry::Size;

pub use cell::{CanvasCell, CellContribution, Composition, PositionedCell};
pub use context::CanvasContext;
pub use line_network::{LineContinuations, LineGlyphs, LineNetwork};
pub(crate) use sizing::CanvasRequirements;
pub use sizing::CanvasSizing;

pub(in crate::view) use assemble::compose_canvas;

/// A signed cell position relative to a Canvas's top-left corner.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Position {
    pub x: i64,
    pub y: i64,
}

impl Position {
    pub const fn new(x: i64, y: i64) -> Self {
        Self { x, y }
    }
}

/// Immutable frame data that records drawing commands after Canvas size is known.
pub trait CanvasItem: fmt::Debug + Send + Sync + 'static {
    /// Records this item's commands after the Canvas size is final.
    fn draw(&self, context: &mut CanvasContext);
}

trait ErasedItem: fmt::Debug + Send + Sync {
    fn draw(&self, context: &mut CanvasContext);
    fn clone_box(&self) -> Box<dyn ErasedItem>;
    fn equals(&self, other: &dyn ErasedItem) -> bool;
    fn as_any(&self) -> &dyn Any;
}

impl<T> ErasedItem for T
where
    T: CanvasItem + Clone + PartialEq,
{
    fn draw(&self, context: &mut CanvasContext) {
        CanvasItem::draw(self, context);
    }

    fn clone_box(&self) -> Box<dyn ErasedItem> {
        Box::new(self.clone())
    }

    fn equals(&self, other: &dyn ErasedItem) -> bool {
        other.as_any().downcast_ref::<T>() == Some(self)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

#[derive(Debug)]
struct Item(Box<dyn ErasedItem>);

impl Clone for Item {
    fn clone(&self) -> Self {
        Self(self.0.clone_box())
    }
}

impl PartialEq for Item {
    fn eq(&self, other: &Self) -> bool {
        self.0.equals(&*other.0)
    }
}

/// A finite drawing surface and its ordered, owned frame items.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Canvas {
    sizing: CanvasSizing,
    items: Vec<Item>,
}

impl Canvas {
    pub const fn new() -> Self {
        Self {
            sizing: CanvasSizing::viewport(),
            items: Vec::new(),
        }
    }

    /// Replaces this Canvas's complete sizing policy.
    ///
    /// Ordinary callers use viewport sizing. Built-in presentations may bind
    /// an opaque intrinsic value internally; sizing remains independent of the
    /// Canvas's ordered items in either case.
    #[must_use]
    pub fn sizing(mut self, sizing: CanvasSizing) -> Self {
        self.sizing = sizing;
        self
    }

    /// States viewport sizing's extent on an unbounded width axis.
    ///
    /// # Panics
    ///
    /// Panics when a crate-provided intrinsic sizing value is already installed.
    pub const fn width(mut self, width: usize) -> Self {
        self.sizing.set_viewport_width(width);
        self
    }

    /// States viewport sizing's extent on an unbounded height axis.
    ///
    /// # Panics
    ///
    /// Panics when a crate-provided intrinsic sizing value is already installed.
    pub const fn height(mut self, height: usize) -> Self {
        self.sizing.set_viewport_height(height);
        self
    }

    /// States both unbounded-axis extents of viewport sizing.
    ///
    /// # Panics
    ///
    /// Panics when a crate-provided intrinsic sizing value is already installed.
    pub const fn extent(mut self, size: Size) -> Self {
        self.sizing.set_viewport_extent(size);
        self
    }

    /// Appends one owned item to the frame's drawing order.
    pub fn item<T>(mut self, item: T) -> Self
    where
        T: CanvasItem + Clone + PartialEq,
    {
        self.items.push(Item(Box::new(item)));
        self
    }

    /// Returns the directly owned items whose concrete type is `T`.
    ///
    /// This is the typed extension boundary for an adapter that owns a
    /// [`CanvasItem`] implementation. Core layout remains unaware of that
    /// item's meaning; the adapter can recover its own immutable values from
    /// a composed [`Canvas`] without exposing `Any` or a fallible downcast.
    pub fn items<T>(&self) -> impl Iterator<Item = &T>
    where
        T: CanvasItem + Clone + PartialEq,
    {
        self.items
            .iter()
            .filter_map(|item| item.0.as_any().downcast_ref::<T>())
    }

    pub(in crate::view) const fn explicit_width(&self) -> Option<usize> {
        self.sizing.explicit_width()
    }

    pub(in crate::view) const fn explicit_height(&self) -> Option<usize> {
        self.sizing.explicit_height()
    }

    pub(in crate::view) const fn uses_viewport_sizing(&self) -> bool {
        self.sizing.is_viewport()
    }

    pub(in crate::view) fn width_requirements(&self) -> sizing::Requirements {
        self.sizing.width_requirements()
    }

    pub(in crate::view) fn height_requirements(&self, width: usize) -> sizing::Requirements {
        self.sizing.height_requirements(width)
    }

    pub(super) fn draw(&self, size: Size) -> CanvasContext {
        let mut context = CanvasContext::new(size);
        for item in &self.items {
            item.0.draw(&mut context);
        }
        context
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use super::sizing::{CanvasMeasure, CanvasRequirements};
    use super::*;
    use crate::{Align, Available, BlockStyle, Grapheme, View, measure, resolve};

    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Event {
        Width,
        Height(usize),
        Draw(Size),
    }

    #[derive(Debug, Clone)]
    struct StagedMeasure {
        width: CanvasRequirements,
        height: CanvasRequirements,
        events: Arc<Mutex<Vec<Event>>>,
    }

    impl PartialEq for StagedMeasure {
        fn eq(&self, other: &Self) -> bool {
            self.width == other.width && self.height == other.height
        }
    }

    impl CanvasMeasure for StagedMeasure {
        fn width_requirements(&self) -> CanvasRequirements {
            self.events.lock().unwrap().push(Event::Width);
            self.width
        }

        fn height_requirements(&self, width: usize) -> CanvasRequirements {
            self.events.lock().unwrap().push(Event::Height(width));
            self.height
        }
    }

    #[derive(Debug, Clone)]
    struct DrawPastHeight(Arc<Mutex<Vec<Event>>>);

    impl PartialEq for DrawPastHeight {
        fn eq(&self, _other: &Self) -> bool {
            true
        }
    }

    impl CanvasItem for DrawPastHeight {
        fn draw(&self, context: &mut CanvasContext) {
            self.0.lock().unwrap().push(Event::Draw(context.size()));
            context.cells([PositionedCell::new(
                Position::new(0, 2),
                CellContribution::new().symbol(Grapheme::new("x")),
            )]);
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct Label(&'static str);

    impl CanvasItem for Label {
        fn draw(&self, _context: &mut CanvasContext) {}
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct Marker;

    impl CanvasItem for Marker {
        fn draw(&self, _context: &mut CanvasContext) {}
    }

    #[test]
    fn owned_items_can_be_inspected_by_their_concrete_type() {
        let canvas = Canvas::new()
            .item(Label("first"))
            .item(Marker)
            .item(Label("second"));

        assert_eq!(
            canvas.items::<Label>().collect::<Vec<_>>(),
            [&Label("first"), &Label("second")]
        );
        assert_eq!(canvas.items::<Marker>().count(), 1);
    }

    #[test]
    fn intrinsic_measurement_is_staged_once_before_drawing() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let sizing = CanvasSizing::intrinsic(StagedMeasure {
            width: CanvasRequirements::new(8, 3),
            height: CanvasRequirements::new(4, 2),
            events: Arc::clone(&events),
        });
        let view = View::canvas(
            Canvas::new()
                .sizing(sizing)
                .item(DrawPastHeight(Arc::clone(&events))),
        );

        assert_eq!(measure(&view), Size::new(8, 4));
        assert_eq!(
            *events.lock().unwrap(),
            [Event::Width, Event::Height(8)],
            "measurement never invokes Canvas items"
        );
        events.lock().unwrap().clear();

        let resolved = resolve(&view, Available::size(5, 2)).unwrap();

        assert_eq!(resolved.size(), Size::new(5, 2));
        assert_eq!(
            *events.lock().unwrap(),
            [Event::Width, Event::Height(5), Event::Draw(Size::new(5, 2))]
        );
        assert!(
            resolved
                .rows()
                .iter()
                .flatten()
                .all(|cell| cell.symbol() != "x"),
            "drawing beyond the selected height is cropped without reflow"
        );
    }

    #[test]
    fn intrinsic_equality_ignores_allocation_identity() {
        let first = CanvasSizing::intrinsic(StagedMeasure {
            width: CanvasRequirements::new(8, 3),
            height: CanvasRequirements::new(4, 2),
            events: Arc::new(Mutex::new(Vec::new())),
        });
        let same_value_in_another_allocation = CanvasSizing::intrinsic(StagedMeasure {
            width: CanvasRequirements::new(8, 3),
            height: CanvasRequirements::new(4, 2),
            events: Arc::new(Mutex::new(Vec::new())),
        });

        assert_eq!(first, same_value_in_another_allocation);
    }

    #[test]
    fn intrinsic_floors_win_before_the_final_safety_crop() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let sizing = CanvasSizing::intrinsic(StagedMeasure {
            width: CanvasRequirements::new(8, 3),
            height: CanvasRequirements::new(4, 3),
            events: Arc::clone(&events),
        });
        let view = View::canvas(
            Canvas::new()
                .sizing(sizing)
                .item(DrawPastHeight(Arc::clone(&events))),
        );

        let resolved = resolve(&view, Available::size(1, 1)).unwrap();

        assert_eq!(resolved.size(), Size::new(1, 1));
        assert_eq!(
            *events.lock().unwrap(),
            [Event::Width, Event::Height(3), Event::Draw(Size::new(3, 3))]
        );
    }

    #[test]
    fn selected_width_height_floors_propagate_through_ancestor_claims() {
        let first_events = Arc::new(Mutex::new(Vec::new()));
        let second_events = Arc::new(Mutex::new(Vec::new()));
        let intrinsic = |height, floor, events: &Arc<Mutex<Vec<Event>>>| {
            View::canvas(
                Canvas::new()
                    .sizing(CanvasSizing::intrinsic(StagedMeasure {
                        width: CanvasRequirements::new(1, 0),
                        height: CanvasRequirements::new(height, floor),
                        events: Arc::clone(events),
                    }))
                    .item(DrawPastHeight(Arc::clone(events))),
            )
        };
        let view = View::column(
            Align::Left,
            [
                View::block(BlockStyle::new(), intrinsic(10, 8, &first_events)),
                intrinsic(10, 0, &second_events),
            ],
        );

        let resolved = resolve(&view, Available::size(3, 10)).unwrap();

        assert_eq!(resolved.size(), Size::new(3, 10));
        assert_eq!(
            first_events.lock().unwrap().last(),
            Some(&Event::Draw(Size::new(1, 8)))
        );
        assert_eq!(
            second_events.lock().unwrap().last(),
            Some(&Event::Draw(Size::new(3, 2)))
        );
    }
}