v / examples / term.ui / rectangles.v
100 lines · 87 sloc · 1.41 KB · 8e35f4d9848f7ad35d857a187dddbfd2eca5e19d
Raw
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
60 app.redraw = true
61}
62
63fn frame(mut app App) {
64 if !app.redraw {
65 return
66 }
67
68 app.tui.clear()
69
70 for rect in app.rects {
71 app.tui.set_bg_color(rect.c)
72 app.tui.draw_rect(rect.x, rect.y, rect.x2, rect.y2)
73 }
74
75 if app.is_drag {
76 r := app.cur_rect
77 app.tui.set_bg_color(r.c)
78 app.tui.draw_empty_rect(r.x, r.y, r.x2, r.y2)
79 }
80
81 app.tui.reset_bg_color()
82 app.tui.flush()
83 app.redraw = false
84}
85
86type EventFn = fn (&tui.Event, voidptr)
87
88type FrameFn = fn (voidptr)
89
90fn main() {
91 mut app := &App{}
92 app.tui = tui.init(
93 user_data: app
94 event_fn: EventFn(event)
95 frame_fn: FrameFn(frame)
96 hide_cursor: true
97 frame_rate: 60
98 )
99 app.tui.run()!
100}
101