icmd 0.1.0

A command-line software 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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Module providing the core Node abstraction and concrete UI components.

use std::{
    any::{Any, TypeId},
    fmt::Debug,
    mem,
    sync::Arc,
};

use downcast_trait::{downcast_trait_impl_convert_to, DowncastTrait};
use parking_lot::{Mutex, RwLock};

use crate::{
    canvas::Canvas,
    core::{
        interactor::GeneralListener,
        renderer::{FrameBuffer, Renderable},
    },
    event::{KeyPressEvent, KeyboardPress, MouseClick, MouseEvent, NodeUpdate},
    measure::{self, HorizontalMeasure, Left, Top, VerticalMeasure},
    style::{
        color::{self},
        pattern::NoBorder,
        GeneralBorderPattern, GeneralStyle, NoStyle, TString,
    },
    utils::{LazyMeasure, NodeRef},
};

/// The base trait for all UI nodes, combining rendering, downcasting,
/// event handling, visibility and z‐order controls.
pub trait Node: DowncastTrait + Renderable + Send + Sync {
    /// Returns the x-coordinate of the left edge.
    fn get_left(&self) -> i32 {
        Renderable::get_left(self)
    }

    /// Returns the y-coordinate of the top edge.
    fn get_top(&self) -> i32 {
        Renderable::get_top(self)
    }

    /// Returns the x-coordinate of the right edge.
    fn get_right(&self) -> i32 {
        Renderable::get_right(self)
    }

    /// Returns the y-coordinate of the bottom edge.
    fn get_bottom(&self) -> i32 {
        Renderable::get_bottom(self)
    }

    /// Hide this node (set visibility to false).
    fn hide(&self) {
        *self.get_visibility().write() = false;
    }

    /// Show this node (set visibility to true).
    fn show(&self) {
        *self.get_visibility().write() = true;
    }

    /// Check whether this node is currently visible.
    fn is_visible(&self) -> bool {
        *self.get_visibility().read()
    }

    /// Move this node one step back in the parent’s z-order.
    fn backward(&self)
    where
        Self: Sized,
    {
        let parent = self.parent().unwrap();
        let mut children = parent.children().write();
        let index = children
            .iter()
            .position(|child| std::ptr::eq(child.as_ref(), self))
            .unwrap();
        if index > 0 {
            let child = children.remove(index);
            children.insert(index - 1, child);
        }
    }

    /// Send this node to the very back of the parent’s z-order.
    fn put_rear(&self)
    where
        Self: Sized,
    {
        let parent = self.parent().unwrap();
        let mut children = parent.children().write();
        let index = children
            .iter()
            .position(|child| std::ptr::eq(child.as_ref(), self))
            .unwrap();
        if index < children.len() - 1 {
            let child = children.remove(index);
            children.insert(0, child);
        }
    }

    /// Bring this node to the very front of the parent’s z-order.
    fn put_front(&self)
    where
        Self: Sized,
    {
        let parent = self.parent().unwrap();
        let mut children = parent.children().write();
        let index = children
            .iter()
            .position(|child| std::ptr::eq(child.as_ref(), self))
            .unwrap();
        if index > 0 {
            let child = children.remove(index);
            children.push(child);
        }
    }
}

/// Trait for nodes that support background/foreground styling.
pub trait HasStyle: Node {
    /// Set the solid background of this node.
    fn set_background(&self, background: Background) {
        self.get_style_attributes().unwrap().lock().background = background;
    }

    /// Fill the background and border with the given style.
    fn fill_background(&self, style: impl Into<GeneralStyle>) {
        let style_ = style.into().clone();
        self.get_style_attributes().unwrap().lock().background =
            Background::FillStyle(style_.clone());
        self.get_style_attributes().unwrap().lock().border_style = style_;
    }

    /// Set the foreground (text) style of this node.
    fn set_foreground(&self, style: impl Into<GeneralStyle>) {
        self.get_style_attributes().unwrap().lock().foreground = style.into();
    }
}

/// Trait for nodes that can register event listeners.
pub trait HasListener: Node {
    /// Access the internal listener list.
    fn get_listeners(&self) -> &RwLock<Vec<GeneralListener>>;

    /// Register a mouse‐event handler.
    fn on_mouse_event(
        &self,
        func: Box<dyn FnMut(NodeRef, MouseEvent) -> bool + Send + Sync + 'static>,
    ) {
        self.get_listeners().write().push(MouseClick(func).into())
    }

    /// Register a key‐press event handler.
    fn on_key_event(
        &self,
        func: Box<dyn FnMut(NodeRef, KeyPressEvent) -> bool + Send + Sync + 'static>,
    ) {
        self.get_listeners()
            .write()
            .push(KeyboardPress(func).into())
    }

    /// Register an update (tick) event handler.
    fn on_update_event(&self, func: Box<dyn FnMut(NodeRef, u64) -> bool + Send + Sync + 'static>) {
        self.get_listeners().write().push(NodeUpdate(func).into())
    }
}

/// Trait for nodes that can be laid out relative to other nodes.
pub trait Alignable: Node {
    /// Align this node’s left edge to a horizontal measure.
    fn left_to(self: &Arc<Self>, r: impl Into<LazyMeasure> + HorizontalMeasure) {
        self.get_layout_attributes().write().l = r.into();
    }

    /// Align this node’s right edge to a horizontal measure.
    fn right_to(self: &Arc<Self>, r: impl Into<LazyMeasure> + HorizontalMeasure) {
        self.get_layout_attributes().write().r = r.into();
    }

    /// Align this node’s top edge to a vertical measure.
    fn top_to(self: &Arc<Self>, r: impl Into<LazyMeasure> + VerticalMeasure) {
        self.get_layout_attributes().write().t = r.into();
    }

    /// Align this node’s bottom edge to a vertical measure.
    fn bottom_to(self: &Arc<Self>, r: impl Into<LazyMeasure> + VerticalMeasure) {
        self.get_layout_attributes().write().b = r.into();
    }

    /// Set a fixed width via a negative right offset.
    fn set_width(self: &Arc<Self>, width: u16)
    where
        Self: Sized + Sync + 'static,
    {
        self.right_to(Left::away_from(&self, -(width as i32)));
    }

    /// Set a fixed height via a negative bottom offset.
    fn set_height(self: &Arc<Self>, height: u16)
    where
        Self: Sized + Sync + 'static,
    {
        self.bottom_to(Top::away_from(&self, -(height as i32)));
    }

    /// Offset the left edge by a delta.
    fn offset_left(&self, offset: i32) {
        take_mut::take(&mut self.get_layout_attributes().write().l, |l| {
            LazyMeasure::new(move || l.get() + offset)
        });
    }

    /// Offset the top edge by a delta.
    fn offset_top(&self, offset: i32) {
        take_mut::take(&mut self.get_layout_attributes().write().t, |t| {
            LazyMeasure::new(move || t.get() + offset)
        });
    }

    /// Offset the right edge by a delta.
    fn offset_right(&self, offset: i32) {
        take_mut::take(&mut self.get_layout_attributes().write().r, |r| {
            LazyMeasure::new(move || r.get() + offset)
        });
    }

    /// Offset the bottom edge by a delta.
    fn offset_bottom(&self, offset: i32) {
        take_mut::take(&mut self.get_layout_attributes().write().b, |b| {
            LazyMeasure::new(move || b.get() + offset)
        });
    }

    /// Compute the current width (right − left).
    fn get_width(&self) -> i32 {
        Node::get_right(self) - Node::get_left(self)
    }

    /// Compute the current height (bottom − top).
    fn get_height(&self) -> i32 {
        Node::get_bottom(self) - Node::get_top(self)
    }

    /// Check if a point falls within this node’s bounds.
    fn is_within(&self, x: i32, y: i32) -> bool {
        let left = Node::get_left(self);
        let right = Node::get_right(self);
        let top = Node::get_top(self);
        let bottom = Node::get_bottom(self);
        x >= left && x <= right && y >= top && y <= bottom
    }
}

/// Background fill options for a node.
#[derive(Debug, Clone)]
pub enum Background {
    /// Fill the background area with a solid style.
    FillStyle(GeneralStyle),

    /// Use text content as the background.
    Text(TString),
}

/// Stores the four edge measures for layout.
#[derive(Debug)]
pub struct LayoutAttribute {
    /// Left measure.
    pub(crate) l: LazyMeasure,
    /// Top measure.
    pub(crate) t: LazyMeasure,
    /// Right measure.
    pub(crate) r: LazyMeasure,
    /// Bottom measure.
    pub(crate) b: LazyMeasure,
}

/// Style configuration for a node.
#[derive(Debug, Clone)]
pub struct StyleAttribute {
    /// Background fill setting.
    pub background: Background,

    /// Default text style.
    pub foreground: GeneralStyle,

    /// Border color style.
    pub border_style: GeneralStyle,

    /// Border drawing pattern.
    pub border_pattern: GeneralBorderPattern,
}

impl Default for StyleAttribute {
    /// Initialize with no border, black background and white text.
    fn default() -> Self {
        Self {
            background: Background::FillStyle(color::AsBackground(color::Black).into()),
            foreground: color::White.into(),
            border_style: NoStyle.into(),
            border_pattern: NoBorder.into(),
        }
    }
}

/// Macro to generate a node struct with common fields.
macro_rules! node_struct {
    ($name:ident) => {
        #[derive(Debug)]
        /// A node struct generated by the macro.
        pub struct $name {
            /// The name of the node.
            pub name: String,

            /// Children of the node.
            pub children: RwLock<Vec<NodeRef>>,

            /// Parent of the node.
            pub parent: Option<NodeRef>,

            /// Listeners of the node.
            pub listeners: RwLock<Vec<GeneralListener>>,

            /// Style attributes of the node.
            style: Mutex<StyleAttribute>,

            /// Layout attributes of the node.
            layout: RwLock<LayoutAttribute>,

            /// Visibility of the node.
            visibility: RwLock<bool>,
        }
    };
    ($name:ident, $($field:ident: $type:ty),*) => {
        #[derive(Debug)]
        pub struct $name {
            /// The name of the node.
            pub name: String,

            /// Children of the node.
            pub children: RwLock<Vec<NodeRef>>,

            /// Parent of the node.
            pub parent: Option<NodeRef>,

            /// Listeners of the node.
            pub listeners: RwLock<Vec<GeneralListener>>,

            /// Style attributes of the node.
            style: Mutex<StyleAttribute>,

            /// Layout attributes of the node.
            layout: RwLock<LayoutAttribute>,

            /// Visibility of the node.
            visibility: RwLock<bool>,

            // Other fields
            $(pub $field: $type),*
        }
    };
}

/// Macro to implement standard traits for a node type.
#[macro_export]
macro_rules! node_impl_traits {
    ($name:ident) => {
        impl Alignable for $name {}
        impl DowncastTrait for $name {
            downcast_trait_impl_convert_to!(dyn HasListener);
        }
        impl Node for $name {}
        impl HasStyle for $name {}
        impl HasListener for $name {
            fn get_listeners(&self) -> &RwLock<Vec<GeneralListener>> {
                &self.listeners
            }
        }
    };
}

node_struct!(Container);
node_impl_traits!(Container);

impl Container {
    /// Create a new container node with the given parent and name.
    pub fn create(parent: &Arc<impl Node + Sync + 'static>, name: &str) -> Arc<Self> {
        let v = Arc::new(Self {
            name: name.to_string(),
            children: RwLock::new(vec![]),
            style: Mutex::new(StyleAttribute::default()),
            layout: RwLock::new(LayoutAttribute {
                l: measure::Left::of(parent).into(),
                t: measure::Top::of(parent).into(),
                r: measure::Fixed(4).into(),
                b: measure::Fixed(4).into(),
            }),
            parent: Some(parent.clone()),
            listeners: RwLock::new(vec![]),
            visibility: RwLock::new(true),
        });
        parent.children().write().push(v.clone());
        v
    }

    /// Set the border pattern and style for the container.
    pub fn set_border(
        self: &Arc<Self>,
        pattern: impl Into<GeneralBorderPattern>,
        style: impl Into<GeneralStyle>,
    ) {
        self.style.lock().border_pattern = pattern.into();
        self.style.lock().border_style = style.into();
    }

    /// Create a new container node with the given parent and size.
    pub fn new(parent: &Arc<impl Node + Sync + 'static>, size: (u16, u16)) -> Arc<Self> {
        let v = Self::create(parent, "container");
        v.left_to(Left::of(parent));
        v.top_to(Top::of(parent));
        v.set_width(size.0);
        v.set_height(size.1);

        let style = v.style.lock();
        let background = style.background.clone();
        drop(style);
        match background {
            Background::FillStyle(ref style) => v.set_border(NoBorder, style.clone()),
            Background::Text(_) => panic!("Text background not supported"),
        }
        v
    }
}

impl Renderable for Container {
    fn render(&self) -> FrameBuffer {
        let style = self.style.lock();
        let border_pattern = style.border_pattern.clone();
        let border_style = style.border_style.clone();
        drop(style);

        Canvas::new_and_fill(self, ' ', {
            match self.style.lock().background {
                Background::FillStyle(ref style) => style.clone(),
                Background::Text(ref _text) => todo!("Image"),
            }
        })
        .draw_border(
            Alignable::get_width(self),
            Alignable::get_height(self),
            border_pattern,
            border_style,
        )
        .finish()
    }

    fn get_style_attributes(&self) -> Option<&Mutex<StyleAttribute>> {
        Some(&self.style)
    }

    fn get_layout_attributes(&self) -> &RwLock<LayoutAttribute> {
        &self.layout
    }

    fn parent(&self) -> Option<&NodeRef> {
        self.parent.as_ref()
    }

    fn children(&self) -> &RwLock<Vec<NodeRef>> {
        &self.children
    }

    fn get_visibility(&self) -> &RwLock<bool> {
        &self.visibility
    }
}

node_struct!(Text, text: Mutex<String>);
node_impl_traits!(Text);

impl Text {
    /// Create a new text node with the given parent and name.
    pub fn create(parent: &Arc<impl Node + Sync + 'static>, name: &str) -> Arc<Self> {
        let v = Arc::new(Self {
            name: name.to_string(),
            children: RwLock::new(vec![]),
            style: Mutex::new(StyleAttribute::default()),
            layout: RwLock::new(LayoutAttribute {
                l: measure::Left::of(parent).into(),
                t: measure::Top::of(parent).into(),
                r: measure::Fixed(4).into(),
                b: measure::Fixed(4).into(),
            }),
            parent: Some(parent.clone()),
            listeners: RwLock::new(vec![]),
            text: "text".to_string().into(),
            visibility: RwLock::new(true),
        });
        parent.children().write().push(v.clone());
        v
    }

    /// Create a new text node with the given parent, text, and position.
    pub fn new(
        parent: &Arc<impl Node + Sync + 'static>,
        text: &'static str,
        position: (i32, i32),
    ) -> Arc<Self> {
        let v = Self::create(parent, "text");
        *v.text.lock() = text.to_string();
        v.left_to(Left::away_from(parent, -position.0));
        v.top_to(Top::away_from(parent, -position.1));
        v.set_width(text.len() as u16);
        v.set_height(1);
        v
    }

    /// Get the text content of the node.
    pub fn get_text(&self) -> String {
        self.text.lock().clone()
    }

    /// Set the text content of the node.
    pub fn set_text(self: &Arc<Self>, text: &str) {
        *self.text.lock() = text.to_string();
        self.set_width(text.len() as u16);
    }
}

impl Renderable for Text {
    fn render(&self) -> FrameBuffer {
        let text = self.text.lock();
        let text_cloned = text.clone();
        let style = self.style.lock();
        let style_cloned = style.foreground.clone();
        drop(text);
        drop(style);
        FrameBuffer {
            data: vec![TString::from_str(
                text_cloned.as_str(),
                GeneralStyle::from_style(style_cloned),
            )],
            left: Renderable::get_left(self),
            top: Renderable::get_top(self),
            right: Renderable::get_right(self),
            bottom: Renderable::get_bottom(self),
        }
    }

    fn get_style_attributes(&self) -> Option<&Mutex<StyleAttribute>> {
        Some(&self.style)
    }

    fn get_layout_attributes(&self) -> &RwLock<LayoutAttribute> {
        &self.layout
    }
    fn parent(&self) -> Option<&NodeRef> {
        self.parent.as_ref()
    }
    fn children(&self) -> &RwLock<Vec<NodeRef>> {
        &self.children
    }

    fn get_visibility(&self) -> &RwLock<bool> {
        &self.visibility
    }
}

node_struct!(DrawingBoard, canvas: Mutex<Option<Canvas>>);
node_impl_traits!(DrawingBoard);

impl DrawingBoard {
    /// Create a new drawing board node with the given parent, name, and size.
    pub fn new(
        parent: &Arc<impl Node + Sync + 'static>,
        name: &str,
        size: (u16, u16),
    ) -> Arc<Self> {
        let v = Arc::new(Self {
            name: name.to_string(),
            children: RwLock::new(vec![]),
            style: Mutex::new(StyleAttribute::default()),
            layout: RwLock::new(LayoutAttribute {
                l: measure::Left::of(parent).into(),
                t: measure::Top::of(parent).into(),
                r: measure::Fixed(size.0 as i32).into(),
                b: measure::Fixed(size.1 as i32).into(),
            }),
            canvas: Mutex::new(None),
            parent: Some(parent.clone()),
            listeners: RwLock::new(vec![]),
            visibility: RwLock::new(true),
        });
        parent.children().write().push(v.clone());
        *v.canvas.lock() = Some(Canvas::new_template(v.as_ref()));
        v
    }

    /// Set the canvas for the drawing board.
    pub fn set_canvas(self: &Arc<Self>, canvas: Canvas) {
        *self.canvas.lock() = Some(canvas);
    }

    /// Update the canvas using a mapping function.
    pub fn update_canvas(self: &Arc<Self>, map: impl Fn(Canvas) -> Canvas) {
        let mut canvas = self.canvas.lock();
        take_mut::take(&mut *canvas, |canvas| {
            canvas.map(|mut c| {
                c.buffer.top = Renderable::get_top(self.as_ref());
                c.buffer.left = Renderable::get_left(self.as_ref());
                c.buffer.right = Renderable::get_right(self.as_ref());
                c.buffer.bottom = Renderable::get_bottom(self.as_ref());
                map(c)
            })
        });
    }
}

impl Renderable for DrawingBoard {
    fn render(&self) -> FrameBuffer {
        let canvas = self.canvas.lock();
        let mut buffer = canvas.as_ref().unwrap().finish();
        buffer.top = Renderable::get_top(self);
        buffer.left = Renderable::get_left(self);
        buffer.right = Renderable::get_right(self);
        buffer.bottom = Renderable::get_bottom(self);
        drop(canvas);
        buffer
    }
    fn get_style_attributes(&self) -> Option<&Mutex<StyleAttribute>> {
        Some(&self.style)
    }
    fn get_layout_attributes(&self) -> &RwLock<LayoutAttribute> {
        &self.layout
    }
    fn parent(&self) -> Option<&NodeRef> {
        self.parent.as_ref()
    }
    fn children(&self) -> &RwLock<Vec<NodeRef>> {
        &self.children
    }
    fn get_visibility(&self) -> &RwLock<bool> {
        &self.visibility
    }
}