vx11 / graphics.v
74 lines · 63 sloc · 2.54 KB · c4bc47d81a04ec4c69336c7c85575735cb003365
Raw
1module vx11
2
3// Graphics owns a GC and borrows its window. Free it before destroying the window.
4@[heap; noinit]
5pub struct Graphics {
6mut:
7 window &WindowHandle = unsafe { nil }
8 handle GC
9 closed bool
10}
11
12pub fn (w &WindowHandle) graphics() !&Graphics {
13 gc := create_gc(w.display()!, Drawable(w.id), 0, unsafe { nil })
14 if gc == unsafe { nil } { return error('cannot create graphics context') }
15 return &Graphics{ window: w, handle: gc }
16}
17
18fn (g &Graphics) display() !&Display {
19 if g.closed { return error('graphics context is closed') }
20 return g.window.display()
21}
22
23pub fn (mut g Graphics) close() {
24 if !g.closed {
25 if g.window.connection.display != unsafe { nil } {
26 free_gc(g.window.connection.display, g.handle)
27 }
28 g.closed = true
29 }
30}
31
32pub fn (g &Graphics) foreground(pixel CULong) ! { set_foreground(g.display()!, g.handle, pixel) }
33
34pub fn (g &Graphics) background(pixel CULong) ! { set_background(g.display()!, g.handle, pixel) }
35
36pub fn (g &Graphics) line(x1 int, y1 int, x2 int, y2 int) ! {
37 draw_line(g.display()!, Drawable(g.window.id), g.handle, i32(x1), i32(y1), i32(x2), i32(y2))
38}
39
40pub fn (g &Graphics) rectangle(x int, y int, width int, height int, filled bool) ! {
41 if width < 0 || height < 0 || width > 65535 || height > 65535 {
42 return error('invalid rectangle dimensions')
43 }
44 d := g.display()!
45 if filled {
46 fill_rectangle(d, Drawable(g.window.id), g.handle, i32(x), i32(y), u32(width), u32(height))
47 } else {
48 draw_rectangle(d, Drawable(g.window.id), g.handle, i32(x), i32(y), u32(width), u32(height))
49 }
50}
51
52// text draws bytes using the GC's core font. For Unicode use XFontSet/Xutf8DrawString.
53pub fn (g &Graphics) text(x int, y int, text string) ! {
54 if text.len > 0x7fffffff { return error('text is too long') }
55 draw_string(g.display()!, Drawable(g.window.id), g.handle, i32(x), i32(y), &char(text.str), i32(text.len))
56}
57
58pub fn (g &Graphics) points(points []XPoint) ! {
59 if points.len > 0x7fffffff { return error('too many points') }
60 draw_points(g.display()!, Drawable(g.window.id), g.handle, points.data, i32(points.len), coord_mode_origin)
61}
62
63// color allocates a named color in the default colormap. Release allocated colors
64// with free_colors when using a mutable/limited colormap.
65pub fn (c &Connection) color(name string) !CULong {
66 if name.contains('\x00') { return error('color name contains NUL') }
67 d := c.raw()!
68 mut screen := XColor{}
69 mut exact := XColor{}
70 if alloc_named_color(d, default_colormap(d, default_screen(d)), &char(name.str), &screen, &exact) == 0 {
71 return error('cannot allocate color "${name}"')
72 }
73 return screen.pixel
74}
75