v / examples / term.ui
Raw file | 95 loc (85 sloc) | 1.31 KB | Latest commit hash 868908b80
1import term.ui as tui
2import rand
3
4struct Rect {
5mut:
6 c tui.Color
7 x int
8 y int
9 x2 int
10 y2 int
11}
12
13struct App {
14mut:
15 tui &tui.Context = unsafe { nil }
16 rects []Rect
17 cur_rect Rect
18 is_drag bool
19 redraw bool
20}
21
22fn random_color() tui.Color {
23 return tui.Color{
24 r: rand.u8()
25 g: rand.u8()
26 b: rand.u8()
27 }
28}
29
30fn event(e &tui.Event, mut app App) {
31 match e.typ {
32 .mouse_down {
33 app.is_drag = true
34 app.cur_rect = Rect{
35 c: random_color()
36 x: e.x
37 y: e.y
38 x2: e.x
39 y2: e.y
40 }
41 }
42 .mouse_drag {
43 app.cur_rect.x2 = e.x
44 app.cur_rect.y2 = e.y
45 }
46 .mouse_up {
47 app.rects << app.cur_rect
48 app.is_drag = false
49 }
50 .key_down {
51 if e.code == .c {
52 app.rects.clear()
53 } else if e.code == .escape {
54 exit(0)
55 }
56 }
57 else {}
58 }
59 app.redraw = true
60}
61
62fn frame(mut app App) {
63 if !app.redraw {
64 return
65 }
66
67 app.tui.clear()
68
69 for rect in app.rects {
70 app.tui.set_bg_color(rect.c)
71 app.tui.draw_rect(rect.x, rect.y, rect.x2, rect.y2)
72 }
73
74 if app.is_drag {
75 r := app.cur_rect
76 app.tui.set_bg_color(r.c)
77 app.tui.draw_empty_rect(r.x, r.y, r.x2, r.y2)
78 }
79
80 app.tui.reset_bg_color()
81 app.tui.flush()
82 app.redraw = false
83}
84
85fn main() {
86 mut app := &App{}
87 app.tui = tui.init(
88 user_data: app
89 event_fn: event
90 frame_fn: frame
91 hide_cursor: true
92 frame_rate: 60
93 )
94 app.tui.run()!
95}