futtl 0.4.0

Rust bindings for the FUTTL terminal UI library
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
//! A TUI library that's supposed to resemble something between ncurses and Ratatui-core

use crate::bindings::*;
use bitflags::bitflags;

#[allow(warnings)]
mod bindings;

/// Futtl Context object. Only used by internal tests, please disregard unless you absolutely have
/// to use it.
type Ctx = bindings::futtl_ctx;

/// Vector2 struct that stores an x component and a y component
#[derive(Clone, Copy)]
pub struct Vec2 {
    pub x: i32,
    pub y: i32
}

impl Vec2 {
    /// New Vec2
    pub fn new(x: i32, y: i32) -> Vec2 {
        Self { x, y }
    } 
}

/// Main windows context
pub struct Win {
    pub ctx: Ctx,
    pub children: Vec<Box<Container>>,
}

/// Container / Box context
pub struct Container {
    pub ctx: Ctx,
    pub children: Vec<Box<Container>>,
    pub owned_by_parent: bool,
}

/// Represents the colors that can be used by futtl::Color::ANSI()
#[derive(Clone, Copy)]
#[repr(u8)]
pub enum AnsiColor {
    Black       = bindings::ANSI_BLACK as u8,
    Red         = bindings::ANSI_RED as u8,
    Green       = bindings::ANSI_GREEN as u8,
    Yellow      = bindings::ANSI_YELLOW as u8,
    Blue        = bindings::ANSI_BLUE as u8,
    Magenta     = bindings::ANSI_MAGENTA as u8,
    Cyan        = bindings::ANSI_CYAN as u8,
    White       = bindings::ANSI_WHITE as u8,

    BrightBlack   = bindings::ANSI_BRIGHT_BLACK as u8,
    BrightRed     = bindings::ANSI_BRIGHT_RED as u8,
    BrightGreen   = bindings::ANSI_BRIGHT_GREEN as u8,
    BrightYellow  = bindings::ANSI_BRIGHT_YELLOW as u8,
    BrightBlue    = bindings::ANSI_BRIGHT_BLUE as u8,
    BrightMagenta = bindings::ANSI_BRIGHT_MAGENTA as u8,
    BrightCyan    = bindings::ANSI_BRIGHT_CYAN as u8,
    BrightWhite   = bindings::ANSI_BRIGHT_WHITE as u8,

    DefaultFG   = bindings::ANSI_DEFAULT_FG as u8,
    DefaultBG   = bindings::ANSI_DEFAULT_BG as u8,
}

/// Color type. Has RGB, Default, ANSI, and ANSI256 modes.
/// `Default` - Default color
/// `ANSI` - Default ANSI color code
/// `ANSI256` - Default ANSI-256 color code
/// `RGB` - Any color with Red, Green, and Blue components
#[derive(Clone, Copy)]
pub enum Color {
    Default,
    RGB(u8, u8, u8),
    ANSI(AnsiColor),
    ANSI256(u8),
}

/// Keys that aren't one-byte, but also not unicode
pub enum Key {
    Up = bindings::FUTTL_KEY_UP as isize,
    Down = bindings::FUTTL_KEY_DOWN as isize,
    Left = bindings::FUTTL_KEY_LEFT as isize,
    Right = bindings::FUTTL_KEY_RIGHT as isize,
    Home = bindings::FUTTL_KEY_HOME as isize,
    End = bindings::FUTTL_KEY_END as isize,
    Delete = bindings::FUTTL_KEY_DELETE as isize,
    Insert = bindings::FUTTL_KEY_INSERT as isize,
    PageUp = bindings::FUTTL_KEY_PAGE_UP as isize,
    PageDown = bindings::FUTTL_KEY_PAGE_DOWN as isize,
}

impl Color {
    fn into_c_color(self) -> bindings::futtl_color {
        match self {
            Self::Default => bindings::futtl_color {
                color_type: bindings::FUTTL_COLOR_DEFAULT as i32,
                __bindgen_anon_1: bindings::futtl_color__bindgen_ty_1 { ansi: 0 },
            },
            Self::RGB(r, g, b) => bindings::futtl_color {
                color_type: bindings::FUTTL_COLOR_RGB as i32,
                __bindgen_anon_1: bindings::futtl_color__bindgen_ty_1 {
                    rgb: bindings::futtl_color__bindgen_ty_1__bindgen_ty_1 { r, g, b },
                },
            },
            Self::ANSI(ansi) => bindings::futtl_color {
                color_type: bindings::FUTTL_COLOR_ANSI as i32,
                __bindgen_anon_1: bindings::futtl_color__bindgen_ty_1 { ansi: ansi as u8 },
            },
            Self::ANSI256(ansi256) => bindings::futtl_color {
                color_type: bindings::FUTTL_COLOR_ANSI256 as i32,
                __bindgen_anon_1: bindings::futtl_color__bindgen_ty_1 { ansi256 },
            },
        }
    }
}

/// A set of background and foreground colors
/// `fg` - The foreground color
/// `bg` - The background color
pub struct ColorSet {
    pub fg: Color,
    pub bg: Color
}

impl ColorSet {
    /// Creates a new ColorSet
    pub fn new(fg: Color, bg: Color) -> Self {
        Self { fg, bg }
    }

    /// Creates a new ColorSet with the Default terminal colors
    pub fn new_default() -> Self {
        Self {fg: Color::Default, bg: Color::Default}
    }
}

bitflags! {
    /// Attributes that modify cells with different styles.
    /// Can be combined with the or ('|') operator for multiple attributes on the same cell
    #[repr(transparent)]
    pub struct Attr: i32 {
        const NONE          = FUTTL_ATTR_NONE as i32;
        const BOLD          = FUTTL_ATTR_BOLD as i32;
        const DIM           = FUTTL_ATTR_DIM as i32;
        const ITALIC        = FUTTL_ATTR_ITALIC as i32;
        const UNDERLINE     = FUTTL_ATTR_UNDERLINE as i32;
        const BLINK         = FUTTL_ATTR_BLINK as i32;
        const INVERSE       = FUTTL_ATTR_INVERSE as i32;
        const HIDDEN        = FUTTL_ATTR_HIDDEN as i32;
        const STRIKETHROUGH = FUTTL_ATTR_STRIKETHROUGH as i32;
        const IGNORE_BG     = FUTTL_ATTR_IGNORE_BG as i32;
        const IGNORE_FG     = FUTTL_ATTR_IGNORE_FG as i32;
        const IGNORE_COLOR  = FUTTL_ATTR_IGNORE_COLOR as i32;
        const ALL           = FUTTL_ATTR_ALL as i32;
    }
}

/// Blocking or Non-Blocking input modes for the keyboard
pub enum InputMode {
    Blocking = FUTTL_INPUT_BLOCKING as isize,
    NonBlocking = FUTTL_INPUT_NONBLOCKING as isize
}

/// Hidden or Visible cursor
pub enum CursStyle {
    Hidden = FUTTL_CURS_HIDDEN as isize,
    Visible = FUTTL_CURS_VISIBLE as isize
}

/// Sets the input mode
/// `InputMode::Blocking` -> Waits for terminal input
/// `InputMode::NonBlocking` -> Doesn't wait, returns -1 if no button was pressed.
#[allow(dead_code)]
pub fn set_input_blocking(input_blocking: InputMode) {
    unsafe {futtl_set_input_blocking(input_blocking as i32)}
}

/// Flushes the screen
pub fn flush() {
    unsafe {futtl_flush()}
}

/// Internal trait implementing the core of both Win and Container
pub trait Futtl {
    /// Returns the current CTX
    fn ctx(&mut self) -> &mut Ctx;
    /// Returns a vector of the children
    fn children(&mut self) -> &mut Vec<Box<Container>>;

    /// Returns the terminal/container size
    fn get_size(&mut self) -> Vec2 {
        let term_size: bindings::vec2 = self.ctx().term_size;

        Vec2::new(term_size.x, term_size.y)
    }

    /// Returns the cursor position
    fn get_curs_pos(&mut self) -> Vec2 {
        let curs_pos: bindings::vec2 = self.ctx().curs_pos;

        Vec2::new(curs_pos.x, curs_pos.y)
    }

    /// Returns what character is in the same cell as the cursor
    fn get_char(&mut self) -> i32 {
        unsafe {bindings::futtl_get_char(self.ctx()) as i32}
    }

    /// Writes a character to the current cursor position
    /// `c` - Character to write
    fn write_char(&mut self, c: char) {
        unsafe {bindings::futtl_write_char(self.ctx(), c as i8)}
    }

    /// Writes a character to the current cursor position and moves the cursor one step, wrapping
    /// around if it hits the edge.
    /// `c` - Character to write
    fn put_char(&mut self, c: char) {
        unsafe {bindings::futtl_put_char(self.ctx(), c as i8)}
    }

    /// Writes a unicode character to the current cursor position
    /// `c` - Character to write
    fn write_unicode(&mut self, c: u32) {
        unsafe {bindings::futtl_write_unicode(self.ctx(), c)}
    }

    /// Writes a unicode character to the current cursor position and moves the cursor one step, wrapping
    /// around if it hits the edge.
    /// `c` - Character to write
    fn put_unicode(&mut self, c: u32) {
        unsafe {bindings::futtl_put_unicode(self.ctx(), c)}
    }

    /// Writes a string to the current cursor position without wrapping.
    /// Resets the cursor position when done writing.
    /// `s` - String to write
    /// Returns: amount of characters that didn't fit on the screen.
    fn write_str(&mut self, s: &str) -> i32 {
        let size = s.chars().count();

        let old_curs: bindings::vec2 = self.ctx().curs_pos;

        for (i, c) in s.chars().enumerate() {
            if self.ctx().curs_pos.y != old_curs.y {
                self.ctx().curs_pos = old_curs;
                return (size - i).try_into().unwrap();
            }

            self.put_unicode(c as u32);
        }

        self.ctx().curs_pos = old_curs;

        0
    }

    /// Writes a string to the current cursor position without wrapping.
    /// Doesn't reset the cursor position.
    /// `s` - String to write
    /// Returns: amount of characters that didn't fit on the screen.
    fn put_str(&mut self, s: &str) -> i32 {
        let size = s.chars().count();

        let old_curs: bindings::vec2 = self.ctx().curs_pos;

        for (i, c) in s.chars().enumerate() {
            if self.ctx().curs_pos.y != old_curs.y {
                return (size - i).try_into().unwrap();
            }

            self.put_unicode(c as u32);
        }

        0
    }

    /// Writes a string to the current cursor position and wraps when it hits the edge.
    /// Resets the cursor position when done writing.
    /// `s` - String to write
    fn write_wrap_str(&mut self, s: &str) -> i32 {
        let old_curs: bindings::vec2 = self.ctx().curs_pos;

        for c in s.chars() {
            self.put_unicode(c as u32);
        }

        self.ctx().curs_pos = old_curs;

        0
    }

    /// Writes a string to the current cursor position and wraps when it hits the edge.
    /// Doesn't reset the cursor position when done writing.
    /// `s` - String to write
    fn put_wrap_str(&mut self, s: &str) -> i32 {
        for c in s.chars() {
            self.put_unicode(c as u32);
        }

        0
    }

    /// Sets a certain color to a color set.
    /// `cs` - Color set to add.
    /// `idx` - What index to give the set
    fn add_color(&mut self, cs: ColorSet, idx: usize) {
        if idx >= (self.ctx().color_count as usize) {
            return;
        }

        let c_cs: bindings::futtl_color_set = bindings::futtl_color_set {
            fg: cs.fg.into_c_color(),
            bg: cs.bg.into_c_color(),
        };
        unsafe {
            *self.ctx().colors.add(idx) = c_cs;
        }
    }

    /// Sets the currently selected color to another pair.
    /// `idx` - Index of the color
    fn set_color(&mut self, idx: usize) {
        unsafe {futtl_set_color(self.ctx(), idx as i32)}
    }

    /// Adds an attribute to the current cursor position.
    /// `attribute` - Attribute(s) to add
    fn add_attribute(&mut self, attribute: Attr) {
        unsafe {futtl_add_attribute(self.ctx(), attribute.bits())}
    }

    /// Removess an attribute from the current cursor position.
    /// `attribute` - Attribute(s) to remove
    fn remove_attribute(&mut self, attribute: Attr) {
        unsafe {futtl_remove_attribute(self.ctx(), attribute.bits())}
    }

    /// Sets the cursor to Visible or Hidden
    fn set_curs_style(&mut self, style: CursStyle) {
        self.ctx().curs_visibility = style as i32;
    }

    /// Clears the internal screen buffer
    fn clear(&mut self) {
        unsafe {futtl_clear(self.ctx())}
    }

    /// Sets the cursor position
    /// `x` - X position
    /// `y` - Y position
    fn set_curs(&mut self, x: i32, y: i32) -> i32 {
        unsafe {futtl_set_curs(self.ctx(), x, y)}
    }

    /// Sets the cursor position
    /// `pos` - Position
    fn set_curs_vec2(&mut self, pos: Vec2) -> i32 {
        unsafe {futtl_set_curs(self.ctx(), pos.x, pos.y)}
    }

    /// Gets input from the user
    fn get_in(&mut self) -> i32 {
        unsafe {futtl_get_in(self.ctx())}
    }

    /// Adds a child container to the current context
    fn add_child(&mut self, child: &mut Container) -> i32 {
        unsafe {futtl_add_child(self.ctx(), child.ctx() as *mut Ctx)}
    }

    /// Removes a child container from the current context
    fn remove_child(&mut self, index: usize) -> i32 {
        if index >= self.children().len() {
            return -1;
        }

        let result = unsafe {
            futtl_remove_child(
                self.ctx() as *mut Ctx,
                self.children()[index].ctx().child_index
            )
        };

        if result == 0 {
            let mut child = self.children().remove(index);
            child.owned_by_parent = false;
        }

        result
    }

    /// Creates a container and returns its index in the context's children() vector
    /// `width` - The width of the container
    /// `height` - The height of the container
    fn create_container(&mut self, width: i32, height: i32) -> usize {
        let mut child = Box::new(Container {
            ctx: unsafe { std::mem::zeroed() },
            children: Vec::new(),
            owned_by_parent: true,
        });

        unsafe {
            bindings::futtl_box_init(
                &mut child.ctx,
                width,
                height,
                self.ctx() as *mut Ctx,
            );
        }

        self.children().push(child);

        self.children().len() - 1
    }
}

impl Futtl for Win {
    fn ctx(&mut self) -> &mut Ctx {
        &mut self.ctx
    }

    fn children(&mut self) -> &mut Vec<Box<Container>> {
        &mut self.children
    }
}

impl Futtl for Container {
    fn ctx(&mut self) -> &mut Ctx {
        &mut self.ctx
    }

    fn children(&mut self) -> &mut Vec<Box<Container>> {
        &mut self.children
    }
}

impl Drop for Win {
    fn drop(&mut self) {
        unsafe {
            bindings::futtl_deinit(self.ctx());
        }
    }
}

impl Drop for Container {
    fn drop(&mut self) {
        if !self.owned_by_parent {
            unsafe {
                bindings::futtl_box_deinit(self.ctx());
            }
        }
    }
}
impl Win {
    /// Initializes a Win ctx
    /// `color_count` - The amount of color pairs to support
    /// `default_attribute` - The default attribute to give each cell
    pub fn init(&mut self, color_count: i32, default_attribute: i32) {
        unsafe {
            bindings::futtl_init(
                self.ctx(),
                color_count,
                default_attribute,
            );
        }
    }

    /// Initializes a new Win ctx
    /// `color_count` - The amount of color pairs to support
    /// `default_attribute` - The default attribute to give each cell
    pub fn new(color_count: i32, default_attribute: Attr) -> Self {
        let mut this = Self {
            ctx: unsafe {std::mem::zeroed::<Ctx>()},
            children: Vec::new(),
        };
        
        this.init(color_count, default_attribute.bits());

        this
    }

    /// Displays the current frame buffer without flushing
    pub fn show(&mut self) {
        unsafe {futtl_show(self.ctx())}
    }
}

impl Container {
    /// Initializes a new container. Inherits from its parent
    /// `width` - The width of the container
    /// `height` - The height of the container
    /// `parent` - The parent CTX
    pub fn init(&mut self, width: i32, height: i32, parent: &mut dyn Futtl) {
        unsafe {
            bindings::futtl_box_init(
                self.ctx(),
                width,
                height,
                parent.ctx(),
            );
        }
    }

    /// Displays the current frame buffer without flushing
    /// `x` - Top-left corner x position
    /// `y` - Top-left corner y position
    pub fn show(&mut self, x: i32, y: i32) {
        unsafe {futtl_box_show(self.ctx(),x ,y)}
    }

    /// Sets the border of the current container.
    pub fn set_border(
        &mut self,
        top: u32,
        right: u32,
        bottom: u32,
        left: u32,
        top_right: u32,
        bottom_right: u32,
        bottom_left: u32,
        top_left: u32,
        color: i32,
    ) {
        unsafe {futtl_box_set_border(self.ctx(), top, right, bottom, left, top_right, bottom_right, bottom_left, top_left, color)}
    }
}

#[cfg(test)]
mod tests;