aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/examples/term.ui/rectangles.v
blob: 09e9d6ad54b0f940f88d1427123bd397935a9673 (plain)
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
import term.ui as tui
import rand

struct Rect {
mut:
	c  tui.Color
	x  int
	y  int
	x2 int
	y2 int
}

struct App {
mut:
	tui      &tui.Context = 0
	rects    []Rect
	cur_rect Rect
	is_drag  bool
	redraw   bool
}

fn random_color() tui.Color {
	return tui.Color{
		r: byte(rand.intn(256))
		g: byte(rand.intn(256))
		b: byte(rand.intn(256))
	}
}

fn event(e &tui.Event, x voidptr) {
	mut app := &App(x)
	match e.typ {
		.mouse_down {
			app.is_drag = true
			app.cur_rect = Rect{
				c: random_color()
				x: e.x
				y: e.y
				x2: e.x
				y2: e.y
			}
		}
		.mouse_drag {
			app.cur_rect.x2 = e.x
			app.cur_rect.y2 = e.y
		}
		.mouse_up {
			app.rects << app.cur_rect
			app.is_drag = false
		}
		.key_down {
			if e.code == .c {
				app.rects.clear()
			} else if e.code == .escape {
				exit(0)
			}
		}
		else {}
	}
	app.redraw = true
}

fn frame(x voidptr) {
	mut app := &App(x)
	if !app.redraw {
		return
	}

	app.tui.clear()

	for rect in app.rects {
		app.tui.set_bg_color(rect.c)
		app.tui.draw_rect(rect.x, rect.y, rect.x2, rect.y2)
	}

	if app.is_drag {
		r := app.cur_rect
		app.tui.set_bg_color(r.c)
		app.tui.draw_empty_rect(r.x, r.y, r.x2, r.y2)
	}

	app.tui.reset_bg_color()
	app.tui.flush()
	app.redraw = false
}

fn main() {
	mut app := &App{}
	app.tui = tui.init(
		user_data: app
		event_fn: event
		frame_fn: frame
		hide_cursor: true
		frame_rate: 60
	)
	app.tui.run() ?
}