futtlui 0.1.6

A high-level Rust UI library built on top of FUTTL.
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use futtl::Futtl;
use std::ops::{Add, Sub};

pub const SINGLE_BORDER: BorderStyle = BorderStyle {
    top: '' as i32,
    bottom: '' as i32,
    left: '' as i32,
    right: '' as i32,
    top_left: '' as i32,
    top_right: '' as i32,
    bottom_right: '' as i32,
    bottom_left: '' as i32,
};

pub const DOUBLE_BORDER: BorderStyle = BorderStyle {
    top: '' as i32,
    bottom: '' as i32,
    left: '' as i32,
    right: '' as i32,
    top_left: '' as i32,
    top_right: '' as i32,
    bottom_right: '' as i32,
    bottom_left: '' as i32,
};

pub const NO_BORDER: BorderStyle = BorderStyle {
    top: '\0' as i32,
    bottom: '\0' as i32,
    left: '\0' as i32,
    right: '\0' as i32,
    top_left: '\0' as i32,
    top_right: '\0' as i32,
    bottom_right: '\0' as i32,
    bottom_left: '\0' as i32,
};

#[derive(Clone)]
pub enum Layout {
    Vh(i32),
    Vw(i32),
    Percent(i32),
    Cell(i32),
    Auto,

    Add(Box<Layout>, Box<Layout>),
    Sub(Box<Layout>, Box<Layout>),
}

impl Add for Layout {
    type Output = Layout;

    fn add(self, rhs: Layout) -> Layout {
        Layout::Add(Box::new(self), Box::new(rhs))
    }
}

impl Sub for Layout {
    type Output = Layout;

    fn sub(self, rhs: Layout) -> Layout {
        Layout::Sub(Box::new(self), Box::new(rhs))
    }
}

#[derive(Copy, Clone)]
pub enum Alignment {
    Left,
    Center,
    Right
}

#[derive(Copy, Clone)]
pub struct BorderStyle {
    pub top: i32,
    pub bottom: i32,
    pub left: i32,
    pub right: i32,
    pub top_left: i32,
    pub top_right: i32,
    pub bottom_right: i32,
    pub bottom_left: i32,
}

#[derive(Copy, Clone)]
pub enum Border {
    Single,
    Double,
    Custom(BorderStyle),
    None
}

#[derive(Clone)]
pub struct LayoutVec2 {
    pub x: Layout,
    pub y: Layout
}

impl LayoutVec2 {
    pub fn new(x: Layout, y: Layout) -> Self {
        Self {x, y}
    }
}

pub struct Style {
    pub position: LayoutVec2,
    pub size: LayoutVec2,
    pub margin: LayoutVec2,
    pub color: futtl::ColorSet,
    pub attributes: futtl::Attr,
    pub widget_border: Border,
    pub alignment_type: Alignment
}

pub enum WidgetCtx {
    Box(usize),
    None
}

pub struct Text {
    pub text: String,
    pub style: Style
}

pub struct Widget {
    pub ctx: WidgetCtx,
    pub style: Style,
    pub children: Vec<Widget>,
    pub content: Vec<Text>,
    pub pos: futtl::Vec2
}

pub struct Win {
    pub ctx: futtl::Win,
    pub children: Vec<Widget>,
    pub color: futtl::ColorSet
}

impl Style {
    pub fn new() -> Self {
        Self {
            position: LayoutVec2 {x: Layout::Auto, y: Layout::Auto},
            size: LayoutVec2 {x: Layout::Auto, y: Layout::Auto},
            margin: LayoutVec2 {x: Layout::Auto, y: Layout::Auto},
            color: futtl::ColorSet::new_default(),
            attributes: futtl::Attr::NONE,
            widget_border: Border::None,
            alignment_type: Alignment::Left
        }
    }
}

#[derive(Copy, Clone)]
enum Axis {
    X,
    Y,
}

fn evaluate_layout(term_size: futtl::Vec2, parent_size: futtl::Vec2, layout: &Layout, axis: Axis) -> i32 {
    match layout {
        Layout::Auto => 0,

        Layout::Vw(n) => match axis {
            Axis::X => term_size.x * n / 100,
            Axis::Y => 0,
        },

        Layout::Vh(n) => match axis {
            Axis::X => 0,
            Axis::Y => term_size.y * n / 100,
        },

        Layout::Percent(n) => match axis {
            Axis::X => parent_size.x * n / 100,
            Axis::Y => parent_size.y * n / 100,
        },

        Layout::Cell(n) => *n,

        Layout::Add(a, b) => {
            evaluate_layout(term_size, parent_size, a, axis)
                + evaluate_layout(term_size, parent_size, b, axis)
        }

        Layout::Sub(a, b) => {
            evaluate_layout(term_size, parent_size, a, axis)
                - evaluate_layout(term_size, parent_size, b, axis)
        }
    }
}

fn evaluate_size(term_size: futtl::Vec2, parent_size: futtl::Vec2, size_obj: LayoutVec2) -> futtl::Vec2 {
    futtl::Vec2::new(
        evaluate_layout(term_size, parent_size, &size_obj.x, Axis::X),
        evaluate_layout(term_size, parent_size, &size_obj.y, Axis::Y),
    )
}

fn evaluate_pos(term_size: futtl::Vec2, parent_size: futtl::Vec2, pos_obj: LayoutVec2) -> futtl::Vec2 {
    futtl::Vec2::new(
        evaluate_layout(term_size, parent_size, &pos_obj.x, Axis::X),
        evaluate_layout(term_size, parent_size, &pos_obj.y, Axis::Y),
    )
}

impl Win {
    pub fn new() -> Self {
        Self {
            ctx: futtl::Win::new(256, futtl::Attr::NONE),
            children: Vec::new(),
            color: futtl::ColorSet::new(
                futtl::Color::ANSI(futtl::AnsiColor::DefaultFG),
                futtl::Color::ANSI(futtl::AnsiColor::DefaultBG),
            ),
        }
    }

    pub fn pack(&mut self, widget: Widget) {
        self.children.push(widget);
    }

    fn evaluate_members(&mut self) {
        let term_size = self.ctx.get_size();

        let auto_x = self.children
            .iter()
            .filter(|child| matches!(child.style.size.x, Layout::Auto))
            .count();

        let auto_y = self.children
            .iter()
            .filter(|child| matches!(child.style.size.y, Layout::Auto))
            .count();

        let mut remaining_x = term_size.x;
        let mut remaining_y = term_size.y;

        // Calculate the space consumed by non-Auto children.
        for child in &self.children {
            let size = evaluate_size(
                term_size,
                term_size,
                child.style.size.clone(),
            );

            if !matches!(child.style.size.x, Layout::Auto) {
                remaining_x -= size.x;
            }

            if !matches!(child.style.size.y, Layout::Auto) {
                remaining_y -= size.y;
            }
        }

        remaining_x = remaining_x.max(0);
        remaining_y = remaining_y.max(0);

        // Divide the remaining space equally between Auto children.
        let auto_x_size = if auto_x > 0 {
            remaining_x / auto_x as i32
        } else {
            0
        };

        let auto_y_size = if auto_y > 0 {
            remaining_y / auto_y as i32
        } else {
            0
        };

        let mut current_x = 0;
        let mut current_y = 0;

        for child in self.children.iter_mut() {
            let child_size = evaluate_size(
                term_size,
                term_size,
                child.style.size.clone(),
            );

            let x_size = match child.style.size.x {
                Layout::Auto => auto_x_size,
                _ => child_size.x.min(term_size.x),
            };

            let y_size = match child.style.size.y {
                Layout::Auto => auto_y_size,
                _ => child_size.y.min(term_size.y),
            };

            child.pos = evaluate_pos(
                term_size,
                term_size,
                child.style.position.clone(),
            );

            // Auto position means "place me after the previous child".
            if matches!(child.style.position.x, Layout::Auto) {
                child.pos.x = current_x;
            }

            if matches!(child.style.position.y, Layout::Auto) {
                child.pos.y = current_y;
            }

            // Every child consumes space in the flow.
            current_x += x_size;
            current_y += y_size;

            let idx = self.ctx.create_container(x_size, y_size);

            child.ctx = WidgetCtx::Box(idx);
        }
    }

    pub fn mainloop(&mut self) {
        self.evaluate_members();

        for child in self.children.iter_mut() {
            match child.ctx {
                WidgetCtx::None => {},
                WidgetCtx::Box(_) => {
                    child.show(child.pos, &mut self.ctx);
                }
            }
        }

        futtl::flush();

        let c = self.ctx.get_in();
        if !((c == 'q' as i32) || (c == 27)) {
            self.mainloop();
        }
    }
}

pub trait Stylable: Sized {
    fn style(&mut self) -> &mut Style;

    fn foreground(mut self, col: futtl::Color) -> Self {
        self.style().color.fg = col;
        self
    }

    fn background(mut self, col: futtl::Color) -> Self {
        self.style().color.bg = col;
        self
    }

    fn position(mut self, x: Layout, y: Layout) -> Self {
        self.style().position.x = x;
        self.style().position.y = y;
        self
    }

    fn position_x(mut self, x: Layout) -> Self {
        self.style().position.x = x;
        self
    }

    fn position_y(mut self, y: Layout) -> Self {
        self.style().position.y = y;
        self
    }

    fn size(mut self, x: Layout, y: Layout) -> Self {
        self.style().size.x = x;
        self.style().size.y = y;
        self
    }

    fn size_x(mut self, x: Layout) -> Self {
        self.style().size.x = x;
        self
    }

    fn size_y(mut self, y: Layout) -> Self {
        self.style().size.y = y;
        self
    }

    fn margin(mut self, x: Layout, y: Layout) -> Self {
        self.style().margin.x = x;
        self.style().margin.y = y;
        self
    }

    fn margin_x(mut self, x: Layout) -> Self {
        self.style().margin.x = x;
        self
    }

    fn margin_y(mut self, y: Layout) -> Self {
        self.style().margin.y = y;
        self
    }

    fn attribute(mut self, attr: futtl::Attr) -> Self {
        self.style().attributes |= attr;
        self
    }

    fn remove_attribute(mut self, attr: futtl::Attr) -> Self {
        self.style().attributes &= !attr;
        self
    }

    fn border(mut self, border: Border) -> Self {
        self.style().widget_border = border;
        self
    }

    fn color(mut self, cs: futtl::ColorSet) -> Self {
        self.style().color = cs;
        self
    }
    
    fn align(mut self, alignment: Alignment) -> Self {
        self.style().alignment_type = alignment;
        self
    }
}

pub trait BorrowStylable {
    fn style(&mut self) -> &mut Style;

    fn foreground(&mut self, col: futtl::Color) -> &mut Self {
        self.style().color.fg = col;
        self
    }

    fn background(&mut self, col: futtl::Color) -> &mut Self {
        self.style().color.bg = col;
        self
    }

    fn position(&mut self, x: Layout, y: Layout) -> &mut Self {
        self.style().position.x = x;
        self.style().position.y = y;
        self
    }

    fn position_x(&mut self, x: Layout) -> &mut Self {
        self.style().position.x = x;
        self
    }

    fn position_y(&mut self, y: Layout) -> &mut Self {
        self.style().position.y = y;
        self
    }

    fn size(&mut self, x: Layout, y: Layout) -> &mut Self {
        self.style().size.x = x;
        self.style().size.y = y;
        self
    }

    fn size_x(&mut self, x: Layout) -> &mut Self {
        self.style().size.x = x;
        self
    }

    fn size_y(&mut self, y: Layout) -> &mut Self {
        self.style().size.y = y;
        self
    }

    fn margin(&mut self, x: Layout, y: Layout) -> &mut Self {
        self.style().margin.x = x;
        self.style().margin.y = y;
        self
    }

    fn margin_x(&mut self, x: Layout) -> &mut Self {
        self.style().margin.x = x;
        self
    }

    fn margin_y(&mut self, y: Layout) -> &mut Self {
        self.style().margin.y = y;
        self
    }

    fn attribute(&mut self, attr: futtl::Attr) -> &mut Self {
        self.style().attributes |= attr;
        self
    }

    fn remove_attribute(&mut self, attr: futtl::Attr) -> &mut Self {
        self.style().attributes &= !attr;
        self
    }

    fn border(&mut self, border: Border) -> &mut Self {
        self.style().widget_border = border;
        self
    }

    fn color(&mut self, cs: futtl::ColorSet) -> &mut Self {
        self.style().color = cs;
        self
    }

    fn align(&mut self, alignment: Alignment) -> &mut Self {
        self.style().alignment_type = alignment;
        self
    }
}

impl Stylable for Widget {
    fn style(&mut self) -> &mut Style {
        &mut self.style
    }
}

impl BorrowStylable for Text {
    fn style(&mut self) -> &mut Style {
        &mut self.style
    }
}

impl Text {
    pub fn show(&self, parent_ctx: &mut futtl::Container, offset: futtl::Vec2, size: futtl::Vec2, idx: usize) {
        let pos = evaluate_pos(size, size, self.style.position.clone());

        let text_size = futtl::Vec2::new(
            self.text
                .lines()
                .map(|line| line.chars().count())
                .max()
                .unwrap_or(0) as i32,
            self.text.lines().count() as i32,
        );

        let text_offset = match self.style.alignment_type {
            Alignment::Left => futtl::Vec2::new(0, 0),
            Alignment::Right => text_size,
            Alignment::Center => futtl::Vec2::new(text_size.x / 2, text_size.y / 2),
        };

        parent_ctx.set_curs(
            (pos.x - text_offset.x).max(0) + offset.x, 
            pos.y.max(0) + offset.y
        );

        parent_ctx.add_color(self.style.color, idx);
        parent_ctx.set_color(idx);

        parent_ctx.write_str(&self.text);
    }
}

impl Widget {
    pub fn new() -> Self {
        Self {
            ctx: WidgetCtx::None,
            style: Style::new(),
            children: Vec::new(),
            content: Vec::new(),
            pos: futtl::Vec2::new(0, 0)
        }
    }

    pub fn style(&mut self, style: Style) {
        self.style = style;
    }

    pub fn text(&mut self, text: impl Into<String>) -> &mut Text {
        let mut style = Style::new();
        style.color = self.style.color;

        self.content.push(Text {
            text: text.into(),
            style,
        });

        self.content.last_mut().unwrap()
    }

    fn set_border(&mut self, box_ctx: &mut futtl::Container, border: Border) {
        let border = match border {
            Border::Single => SINGLE_BORDER,
            Border::Double => DOUBLE_BORDER,
            Border::Custom(border) => border,
            Border::None => NO_BORDER
        };

        box_ctx.add_color(self.style.color, 255);

        box_ctx.set_border(
            border.top as u32,
            border.right as u32,
            border.bottom as u32,
            border.left as u32,
            border.top_right as u32,
            border.bottom_right as u32,
            border.bottom_left as u32,
            border.top_left as u32,
            255,
        );
    }

    pub fn show(&mut self, widget_pos: futtl::Vec2, f_ctx: &mut futtl::Win) {
        match self.ctx {
            WidgetCtx::None => {}

            WidgetCtx::Box(ctx) => {
                let box_ctx = &mut f_ctx.children()[ctx];

                box_ctx.clear();

                self.set_border(box_ctx, self.style.widget_border);

                let offset = match self.style.widget_border {
                    Border::None => futtl::Vec2::new(0, 0),
                    _ => futtl::Vec2::new(1, 1),
                };

                let size = match self.style.widget_border {
                    Border::None => box_ctx.get_size(),
                    _ => futtl::Vec2::new(box_ctx.get_size().x - 2, box_ctx.get_size().y - 2),
                };

                for (i, item) in self.content.iter().enumerate() {
                    item.show(box_ctx, offset, size, i);
                }

                box_ctx.show(widget_pos.x, widget_pos.y);
            }
        }
    }
}


impl Default for Win {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for Widget {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for Style {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        let mut ctx = Win::new();

        let mut text_widget = Widget::new()
            .position_x(Layout::Cell(0))
            .position_y(Layout::Cell(0))
            .size_x(Layout::Vw(50))
            .size_y(Layout::Vh(100) - Layout::Cell(2))
            .border(Border::Double)
            .foreground(futtl::Color::ANSI256(69));

        text_widget.text("test")
            .position_x(Layout::Percent(50))
            .align(Alignment::Left);


        ctx.pack(text_widget);

        let mut widget2 = Widget::new()
            .position_x(Layout::Auto)
            .position_y(Layout::Cell(0))
            .size_x(Layout::Vw(50))
            .size_y(Layout::Vh(100) - Layout::Cell(1))
            .border(Border::Single);

        widget2.text("Left".to_string())
            .position_x(Layout::Percent(50))
            .color(futtl::ColorSet::new(
                futtl::Color::ANSI(futtl::AnsiColor::Red),
                futtl::Color::ANSI(futtl::AnsiColor::DefaultBG)
            ));

        widget2.text("Center".to_string())
            .position(
                Layout::Percent(50),
                Layout::Cell(1)
            )
            .color(futtl::ColorSet::new(
                futtl::Color::ANSI(futtl::AnsiColor::Green),
                futtl::Color::ANSI(futtl::AnsiColor::DefaultBG)
            ))
            .align(Alignment::Center);

        widget2.text("Right".to_string())
            .position(
                Layout::Percent(50),
                Layout::Cell(2)
            )
            .color(futtl::ColorSet::new(
                futtl::Color::ANSI(futtl::AnsiColor::Blue),
                futtl::Color::ANSI(futtl::AnsiColor::DefaultBG)
            ))
            .align(Alignment::Right);


        ctx.pack(widget2);

        ctx.mainloop();
    }
}