vx11 / render / render.v
820 lines · 738 sloc · 29.12 KB · 6de7c1113616d30335010eea79fd03d19722b474
Raw
1// Native XRender helpers. Pictures and glyph sets are owned handles that borrow
2// an Extension and its connection; formats and filter lists are V-owned copies.
3module render
4
5import math
6import vx11
7
8#include "@VMODROOT/render/bridge.h"
9
10fn C.vx11_render_backdrop(&vx11.Display, i32, i32, i32, i32) vx11.Pixmap
11
12// Largest polygon for polygon(): libXrender allocates points² trapezoids.
13pub const max_polygon_points = 1024
14
15pub fn available(connection &vx11.Connection) !bool {
16 mut events := i32(0)
17 mut errors := i32(0)
18 return query_extension(connection.raw()!, &events, &errors) != 0
19}
20
21// Extension borrows its connection and owns no server resources. Handles it
22// creates must be closed before the connection; methods fail after it closes.
23@[heap; noinit]
24pub struct Extension {
25 connection &vx11.Connection
26pub:
27 event_base int
28 error_base int
29 major int
30 minor int
31}
32
33// bind negotiates the protocol version and loads libXrender's format cache.
34pub fn bind(connection &vx11.Connection) !&Extension {
35 d := connection.raw()!
36 mut events := i32(0)
37 mut errors := i32(0)
38 if query_extension(d, &events, &errors) == 0 {
39 return error('XRender extension is unavailable')
40 }
41 mut major := i32(0)
42 mut minor := i32(0)
43 if query_version(d, &major, &minor) == 0 { return error('cannot query XRender version') }
44 if query_formats(d) == 0 { return error('cannot query XRender picture formats') }
45 return &Extension{ connection: connection, event_base: int(events), error_base: int(errors), major: int(major), minor: int(minor) }
46}
47
48// supports reports whether the negotiated version is at least major.minor.
49pub fn (e &Extension) supports(major int, minor int) bool {
50 return e.major > major || (e.major == major && e.minor >= minor)
51}
52
53fn (e &Extension) require(major int, minor int, feature string) ! {
54 if !e.supports(major, minor) {
55 return error('${feature} requires XRender ${major}.${minor}; server provides ${e.major}.${e.minor}')
56 }
57}
58
59fn fits_i16(value int) bool { return value >= -32768 && value <= 32767 }
60
61fn fits_u16(value int) bool { return value >= 0 && value <= 65535 }
62
63// check_op rejects operators the negotiated version does not define.
64fn (e &Extension) check_op(op int) ! {
65 if op >= op_minimum && op <= op_maximum { return }
66 if (op >= op_disjoint_minimum && op <= op_disjoint_maximum)
67 || (op >= op_conjoint_minimum && op <= op_conjoint_maximum) {
68 return e.require(0, 2, 'disjoint and conjoint operators')
69 }
70 if op >= op_blend_minimum && op <= op_blend_maximum {
71 return e.require(0, 11, 'blend mode operators')
72 }
73 return error('invalid XRender operator ${op}')
74}
75
76// request_fits checks a request length in 4-byte units against the server limit.
77fn request_fits(d &vx11.Display, words i64) bool {
78 mut limit := i64(vx11.extended_max_request_size(d))
79 if limit <= 0 { limit = i64(vx11.max_request_size(d)) }
80 return words <= limit
81}
82
83// to_fixed converts a coordinate to 16.16 notation after checking its range.
84pub fn to_fixed(value f64) !Fixed {
85 if math.is_nan(value) || math.is_inf(value, 0) || value < -32768.0 || value >= 32768.0 {
86 return error('value ${value} is outside the XRender fixed-point range')
87 }
88 return fixed(value)
89}
90
91// premultiplied scales the color channels by alpha, as fill colors require.
92pub fn premultiplied(red u16, green u16, blue u16, alpha u16) Color {
93 a := u32(alpha)
94 return Color{
95 red: u16((u32(red) * a + 0x7fff) / 0xffff)
96 green: u16((u32(green) * a + 0x7fff) / 0xffff)
97 blue: u16((u32(blue) * a + 0x7fff) / 0xffff)
98 alpha: alpha
99 }
100}
101
102// identity_transform returns the 16.16 fixed-point identity matrix.
103pub fn identity_transform() Transform {
104 mut t := Transform{}
105 for i in 0 .. 3 { t.matrix[i][i] = fixed(1.0) }
106 return t
107}
108
109// scale_transform maps destination pixels to source pixels: sample the source
110// at (x * sx, y * sy). Use 1/2 to enlarge twofold.
111pub fn scale_transform(sx f64, sy f64) !Transform {
112 mut t := identity_transform()
113 t.matrix[0][0] = to_fixed(sx)!
114 t.matrix[1][1] = to_fixed(sy)!
115 return t
116}
117
118// Formats
119
120// formats lists every picture format the server supports.
121pub fn (e &Extension) formats() ![]Format {
122 d := e.connection.raw()!
123 template := Format{}
124 mut result := []Format{}
125 for i := 0; i < 0x7fffffff; i++ {
126 f := find_format(d, 0, &template, i32(i))
127 if f == unsafe { nil } { break }
128 result << *f
129 }
130 return result
131}
132
133// find_format returns the index-th format whose mask-selected fields (format_*
134// bits) equal those of template.
135pub fn (e &Extension) find_format(mask vx11.CULong, template Format, index int) ?Format {
136 if index < 0 || index > 0x7fffffff { return none }
137 d := e.connection.raw() or { return none }
138 f := find_format(d, mask, &template, i32(index))
139 if f == unsafe { nil } { return none }
140 return *f
141}
142
143// standard_format returns one of the standard_* formats.
144pub fn (e &Extension) standard_format(kind int) !Format {
145 if kind < 0 || kind >= standard_num { return error('invalid standard format ${kind}') }
146 f := find_standard_format(e.connection.raw()!, i32(kind))
147 if f == unsafe { nil } { return error('the server has no standard format ${kind}') }
148 return *f
149}
150
151pub fn (e &Extension) visual_format(visual &vx11.Visual) !Format {
152 if visual == unsafe { nil } { return error('invalid visual') }
153 f := find_visual_format(e.connection.raw()!, visual)
154 if f == unsafe { nil } { return error('the visual has no XRender format') }
155 return *f
156}
157
158// default_format matches the default visual of the default screen.
159pub fn (e &Extension) default_format() !Format {
160 d := e.connection.raw()!
161 return e.visual_format(vx11.default_visual(d, vx11.default_screen(d)))
162}
163
164// index_values copies the colormap entries of an indexed format.
165pub fn (e &Extension) index_values(format Format) ![]IndexValue {
166 e.require(0, 7, 'picture index values')!
167 if format.@type != pict_type_indexed { return error('format is not indexed') }
168 mut count := i32(0)
169 p := query_pict_index_values(e.connection.raw()!, &format, &count)
170 defer { if p != unsafe { nil } { vx11.free(p) } }
171 if p == unsafe { nil } || count < 0 { return error('cannot query picture index values') }
172 mut result := []IndexValue{cap: int(count)}
173 for i in 0 .. int(count) { result << unsafe { p[i] } }
174 return result
175}
176
177// subpixel_order returns a subpixel_* value for a screen.
178pub fn (e &Extension) subpixel_order(screen int) !int {
179 d := e.connection.raw()!
180 if screen < 0 || screen >= int(vx11.screen_count(d)) {
181 return error('invalid screen ${screen}')
182 }
183 return int(query_subpixel_order(d, i32(screen)))
184}
185
186// set_subpixel_order changes libXrender's cached order for this client only.
187pub fn (e &Extension) set_subpixel_order(screen int, order int) ! {
188 d := e.connection.raw()!
189 if screen < 0 || screen >= int(vx11.screen_count(d)) {
190 return error('invalid screen ${screen}')
191 }
192 if order < subpixel_unknown || order > subpixel_none { return error('invalid subpixel order') }
193 if set_subpixel_order(d, i32(screen), i32(order)) == 0 {
194 return error('cannot set the subpixel order')
195 }
196}
197
198// FilterInfo names a filter. alias is the name of the filter it stands for, or
199// '' when it is a filter in its own right.
200pub struct FilterInfo {
201pub:
202 name string
203 alias string
204}
205
206// filters lists the filters available for pictures on drawable's screen.
207pub fn (e &Extension) filters(drawable vx11.Drawable) ![]FilterInfo {
208 e.require(0, 6, 'picture filters')!
209 if drawable == 0 { return error('invalid drawable') }
210 p := query_filters(e.connection.raw()!, drawable)
211 if p == unsafe { nil } { return error('cannot query XRender filters') }
212 defer { vx11.free(p) }
213 if p.nfilter < 0 || p.nalias < 0 || (p.nfilter > 0 && p.filter == unsafe { nil })
214 || (p.nalias > 0 && p.alias == unsafe { nil }) {
215 return error('invalid XRender filter list')
216 }
217 mut names := []string{cap: int(p.nfilter)}
218 for i in 0 .. int(p.nfilter) {
219 names << unsafe { cstring_to_vstring(p.filter[i]) }
220 }
221 mut result := []FilterInfo{cap: names.len}
222 for i, filter_name in names {
223 mut target := ''
224 if i < int(p.nalias) {
225 index := int(u16(unsafe { p.alias[i] }))
226 if index != 0xffff && index < names.len { target = names[index] }
227 }
228 result << FilterInfo{ name: filter_name, alias: target }
229 }
230 return result
231}
232
233// parse_color accepts X color names, #rgb forms and rgba:r/g/b/a. The result
234// is premultiplied, ready for fill and solid_fill.
235pub fn (e &Extension) parse_color(spec string) !Color {
236 if spec == '' || spec.contains('\x00') { return error('invalid color specification') }
237 mut c := Color{}
238 if parse_color(e.connection.raw()!, &char(spec.str), &c) == 0 {
239 return error('cannot parse color "${spec}"')
240 }
241 return c
242}
243
244// Pictures
245
246@[params]
247pub struct PictureOptions {
248pub:
249 repeat int = repeat_none
250 poly_edge int = poly_edge_smooth
251 poly_mode int = poly_mode_precise
252 component_alpha bool
253 include_inferiors bool
254}
255
256// PictureHandle owns one Picture. Close it before its drawable is destroyed
257// (a window's pictures die with it) and before the connection.
258@[heap; noinit]
259pub struct PictureHandle {
260 extension &Extension
261pub:
262 // drawable is 0 for solid fills and gradients.
263 drawable vx11.Drawable
264 width int
265 height int
266 depth int
267mut:
268 handle Picture
269 root vx11.Window
270}
271
272fn (e &Extension) check_repeat(mode int) ! {
273 if mode == repeat_none || mode == repeat_normal { return }
274 if mode == repeat_pad || mode == repeat_reflect {
275 return e.require(0, 10, 'pad and reflect repeat modes')
276 }
277 return error('invalid repeat mode ${mode}')
278}
279
280// create_picture wraps a pixmap or window. format.depth must match the
281// drawable, and a window needs its visual's format (see window_picture).
282pub fn (e &Extension) create_picture(drawable vx11.Drawable, format Format, options PictureOptions) !&PictureHandle {
283 if drawable == 0 { return error('invalid drawable') }
284 if format.id == 0 { return error('invalid picture format') }
285 e.check_repeat(options.repeat)!
286 if options.poly_edge !in [poly_edge_sharp, poly_edge_smooth] {
287 return error('invalid polygon edge mode')
288 }
289 if options.poly_mode !in [poly_mode_precise, poly_mode_imprecise] {
290 return error('invalid polygon mode')
291 }
292 d := e.connection.raw()!
293 mut root := vx11.Window(0)
294 mut x := i32(0)
295 mut y := i32(0)
296 mut w := u32(0)
297 mut h := u32(0)
298 mut border := u32(0)
299 mut depth := u32(0)
300 if vx11.get_geometry(d, drawable, &root, &x, &y, &w, &h, &border, &depth) == 0 {
301 return error('cannot query drawable geometry')
302 }
303 if int(depth) != int(format.depth) {
304 return error('format depth ${format.depth} does not match drawable depth ${depth}')
305 }
306 attributes := PictureAttributes{
307 repeat: i32(options.repeat)
308 poly_edge: i32(options.poly_edge)
309 poly_mode: i32(options.poly_mode)
310 component_alpha: if options.component_alpha { 1 } else { 0 }
311 subwindow_mode: if options.include_inferiors {
312 vx11.include_inferiors
313 } else {
314 vx11.clip_by_children
315 }
316 }
317 mask := cp_repeat | cp_poly_edge | cp_poly_mode | cp_component_alpha | cp_subwindow_mode
318 id := create_picture(d, drawable, &format, mask, &attributes)
319 if id == 0 { return error('cannot create picture') }
320 return &PictureHandle{ extension: e, drawable: drawable, width: int(w), height: int(h), depth: int(depth), handle: id, root: root }
321}
322
323// window_picture wraps a window using the format of its visual.
324pub fn (e &Extension) window_picture(window vx11.Window, options PictureOptions) !&PictureHandle {
325 if window == 0 { return error('invalid window') }
326 mut attributes := vx11.XWindowAttributes{}
327 if vx11.get_window_attributes(e.connection.raw()!, window, &attributes) == 0 {
328 return error('cannot query window attributes')
329 }
330 return e.create_picture(vx11.Drawable(window), e.visual_format(attributes.visual)!, options)
331}
332
333fn (e &Extension) source_picture(id Picture, what string) !&PictureHandle {
334 if id == 0 { return error('cannot create ${what}') }
335 return &PictureHandle{ extension: e, handle: id }
336}
337
338// solid_fill creates an infinite single-color source. color is premultiplied.
339pub fn (e &Extension) solid_fill(color Color) !&PictureHandle {
340 e.require(0, 10, 'solid fills')!
341 return e.source_picture(create_solid_fill(e.connection.raw()!, &color), 'solid fill')
342}
343
344// Point is a position in pixels; gradient helpers convert it to 16.16 notation.
345pub struct Point {
346pub:
347 x f64
348 y f64
349}
350
351fn (p Point) fixed() !PointFixed { return PointFixed{ x: to_fixed(p.x)!, y: to_fixed(p.y)! } }
352
353// ColorStop places a non-premultiplied color at offset 0..1 along a gradient.
354pub struct ColorStop {
355pub:
356 offset f64
357 color Color
358}
359
360fn gradient_stops(d &vx11.Display, stops []ColorStop, header_words int) !([]Fixed, []Color) {
361 offsets, colors := stop_arrays(stops)!
362 if !request_fits(d, i64(header_words) + i64(stops.len) * 3) {
363 return error('too many gradient stops for one request')
364 }
365 return offsets, colors
366}
367
368// stop_arrays checks that offsets rise within [0, 1] and splits the stops.
369fn stop_arrays(stops []ColorStop) !([]Fixed, []Color) {
370 if stops.len == 0 { return error('a gradient needs at least one color stop') }
371 mut offsets := []Fixed{cap: stops.len}
372 mut colors := []Color{cap: stops.len}
373 mut previous := 0.0
374 for s in stops {
375 if math.is_nan(s.offset) || s.offset < 0 || s.offset > 1 || s.offset < previous {
376 return error('gradient stop offsets must rise from 0 to 1')
377 }
378 previous = s.offset
379 offsets << fixed(s.offset)
380 colors << s.color
381 }
382 return offsets, colors
383}
384
385pub fn (e &Extension) linear_gradient(start Point, end Point, stops []ColorStop) !&PictureHandle {
386 e.require(0, 10, 'gradients')!
387 gradient := LinearGradient{ p1: start.fixed()!, p2: end.fixed()! }
388 if gradient.p1.x == gradient.p2.x && gradient.p1.y == gradient.p2.y {
389 return error('a linear gradient needs distinct end points')
390 }
391 d := e.connection.raw()!
392 offsets, colors := gradient_stops(d, stops, 7)!
393 return e.source_picture(create_linear_gradient(d, &gradient, offsets.data, colors.data, i32(stops.len)), 'linear gradient')
394}
395
396pub fn (e &Extension) radial_gradient(inner_center Point, inner_radius f64, outer_center Point, outer_radius f64, stops []ColorStop) !&PictureHandle {
397 e.require(0, 10, 'gradients')!
398 if !(inner_radius >= 0) || !(outer_radius >= 0) {
399 return error('gradient radii must not be negative')
400 }
401 ic := inner_center.fixed()!
402 oc := outer_center.fixed()!
403 gradient := RadialGradient{
404 inner: Circle{ x: ic.x, y: ic.y, radius: to_fixed(inner_radius)! }
405 outer: Circle{ x: oc.x, y: oc.y, radius: to_fixed(outer_radius)! }
406 }
407 d := e.connection.raw()!
408 offsets, colors := gradient_stops(d, stops, 9)!
409 return e.source_picture(create_radial_gradient(d, &gradient, offsets.data, colors.data, i32(stops.len)), 'radial gradient')
410}
411
412// conical_gradient sweeps the stops around center, starting at angle degrees.
413pub fn (e &Extension) conical_gradient(center Point, angle f64, stops []ColorStop) !&PictureHandle {
414 e.require(0, 10, 'gradients')!
415 gradient := ConicalGradient{ center: center.fixed()!, angle: to_fixed(angle)! }
416 d := e.connection.raw()!
417 offsets, colors := gradient_stops(d, stops, 6)!
418 return e.source_picture(create_conical_gradient(d, &gradient, offsets.data, colors.data, i32(stops.len)), 'conical gradient')
419}
420
421pub fn (p &PictureHandle) id() !Picture {
422 if p.handle == 0 { return error('picture is closed') }
423 p.extension.connection.raw()!
424 return p.handle
425}
426
427pub fn (mut p PictureHandle) close() {
428 if p.handle != 0 {
429 if d := p.extension.connection.raw() { free_picture(d, p.handle) }
430 p.handle = 0
431 }
432}
433
434fn (p &PictureHandle) display() !(&vx11.Display, Picture) {
435 id := p.id()!
436 return p.extension.connection.raw()!, id
437}
438
439// set_transform maps destination coordinates to source coordinates.
440pub fn (p &PictureHandle) set_transform(transform Transform) ! {
441 p.extension.require(0, 6, 'picture transforms')!
442 d, id := p.display()!
443 set_picture_transform(d, id, &transform)
444}
445
446// set_filter selects a filter from Extension.filters. Only convolution takes
447// parameters: width and height as whole 16.16 numbers, then width*height values.
448pub fn (p &PictureHandle) set_filter(filter string, params []Fixed) ! {
449 p.extension.require(0, 6, 'picture filters')!
450 if filter == '' || filter.contains('\x00') { return error('invalid filter name') }
451 d, id := p.display()!
452 // Source-only pictures use the first screen's filters, as the server does.
453 root := if p.root != 0 { p.root } else { vx11.root_window(d, 0) }
454 known := p.extension.filters(vx11.Drawable(root))!
455 if !known.any(it.name == filter) { return error('the server has no "${filter}" filter') }
456 if filter == filter_convolution {
457 if params.len < 3 || params[0] & 0xffff != 0 || params[1] & 0xffff != 0 || params[0] <= 0
458 || params[1] <= 0 || i64(params[0] >> 16) * i64(params[1] >> 16) > i64(params.len - 2) {
459 return error('convolution needs width, height and width*height values')
460 }
461 } else if params.len > 0 && filter in [filter_nearest, filter_bilinear, filter_fast, filter_good,
462 filter_best] {
463 return error('the ${filter} filter takes no parameters')
464 }
465 if !request_fits(d, 3 + (i64(filter.len) + 3) / 4 + i64(params.len)) {
466 return error('too many filter parameters for one request')
467 }
468 set_picture_filter(d, id, &char(filter.str), if params.len == 0 {
469 unsafe { nil }
470 } else {
471 params.data
472 }, i32(params.len))
473}
474
475pub fn (p &PictureHandle) set_repeat(mode int) ! {
476 p.extension.check_repeat(mode)!
477 d, id := p.display()!
478 attributes := PictureAttributes{ repeat: i32(mode) }
479 change_picture(d, id, cp_repeat, &attributes)
480}
481
482pub fn (p &PictureHandle) set_component_alpha(enabled bool) ! {
483 d, id := p.display()!
484 attributes := PictureAttributes{ component_alpha: if enabled { 1 } else { 0 } }
485 change_picture(d, id, cp_component_alpha, &attributes)
486}
487
488// Rectangle uses native integers; conversion checks the protocol's 16-bit limits.
489pub struct Rectangle {
490pub:
491 x int
492 y int
493 width int
494 height int
495}
496
497// x_rectangles converts rectangles. header_words < 0 skips the request length
498// check, for calls that libXrender splits into several requests.
499fn x_rectangles(d &vx11.Display, rectangles []Rectangle, header_words int) ![]vx11.XRectangle {
500 if header_words >= 0 && !request_fits(d, i64(header_words) + i64(rectangles.len) * 2) {
501 return error('too many rectangles for one request')
502 }
503 mut raw := []vx11.XRectangle{cap: rectangles.len}
504 for r in rectangles {
505 if !fits_i16(r.x) || !fits_i16(r.y) || !fits_u16(r.width) || !fits_u16(r.height) {
506 return error('rectangle exceeds X11 coordinate limits')
507 }
508 raw << vx11.XRectangle{ x: i16(r.x), y: i16(r.y), width: u16(r.width), height: u16(r.height) }
509 }
510 return raw
511}
512
513// set_clip limits drawing to rectangles; an empty list hides everything.
514pub fn (p &PictureHandle) set_clip(rectangles []Rectangle) ! {
515 d, id := p.display()!
516 raw := x_rectangles(d, rectangles, 3)!
517 set_picture_clip_rectangles(d, id, 0, 0, raw.data, i32(raw.len))
518}
519
520pub fn (p &PictureHandle) clear_clip() ! {
521 d, id := p.display()!
522 attributes := PictureAttributes{ clip_mask: 0 }
523 change_picture(d, id, cp_clip_mask, &attributes)
524}
525
526// fill combines a premultiplied color with each rectangle of this picture.
527pub fn (p &PictureHandle) fill(op int, color Color, rectangles []Rectangle) ! {
528 p.extension.check_op(op)!
529 d, id := p.display()!
530 if rectangles.len == 0 { return }
531 raw := x_rectangles(d, rectangles, -1)!
532 fill_rectangles(d, i32(op), id, &color, raw.data, i32(raw.len))
533}
534
535@[params]
536pub struct CompositeOptions {
537pub:
538 mask &PictureHandle = unsafe { nil }
539 src_x int
540 src_y int
541 mask_x int
542 mask_y int
543 dst_x int
544 dst_y int
545 width int
546 height int
547}
548
549// composite combines src (through an optional mask) into this picture.
550pub fn (p &PictureHandle) composite(op int, src &PictureHandle, options CompositeOptions) ! {
551 p.extension.check_op(op)!
552 d, id := p.display()!
553 source := src.id()!
554 mask := if options.mask == unsafe { nil } { Picture(0) } else { options.mask.id()! }
555 for v in [options.src_x, options.src_y, options.mask_x, options.mask_y, options.dst_x,
556 options.dst_y] {
557 if !fits_i16(v) { return error('composite offset exceeds X11 coordinate limits') }
558 }
559 if !fits_u16(options.width) || !fits_u16(options.height) {
560 return error('composite size exceeds X11 limits')
561 }
562 composite(d, i32(op), source, mask, id, i32(options.src_x), i32(options.src_y), i32(options.mask_x), i32(options.mask_y), i32(options.dst_x), i32(options.dst_y), u32(options.width), u32(options.height))
563}
564
565@[params]
566pub struct ShapeOptions {
567pub:
568 src_x int
569 src_y int
570 // antialias accumulates edges in an A8 mask; false uses A1.
571 antialias bool = true
572 // even_odd selects the even-odd fill rule instead of nonzero winding.
573 even_odd bool
574}
575
576fn (e &Extension) shape_mask(options ShapeOptions) !Format {
577 return e.standard_format(if options.antialias { standard_a8 } else { standard_a1 })
578}
579
580// polygon fills a closed polygon with src. libXrender tessellates it into
581// trapezoids; at most max_polygon_points points are accepted.
582pub fn (p &PictureHandle) polygon(op int, src &PictureHandle, points []Point, options ShapeOptions) ! {
583 p.extension.require(0, 4, 'polygons')!
584 p.extension.check_op(op)!
585 if points.len < 3 { return error('a polygon needs at least three points') }
586 if points.len > max_polygon_points {
587 return error('a polygon may have at most ${max_polygon_points} points')
588 }
589 if !fits_i16(options.src_x) || !fits_i16(options.src_y) {
590 return error('source offset exceeds X11 limits')
591 }
592 d, id := p.display()!
593 source := src.id()!
594 mut raw := []PointDouble{cap: points.len}
595 for pt in points {
596 to_fixed(pt.x)!
597 to_fixed(pt.y)!
598 raw << PointDouble{ x: pt.x, y: pt.y }
599 }
600 mask := p.extension.shape_mask(options)!
601 composite_double_poly(d, i32(op), source, id, &mask, i32(options.src_x), i32(options.src_y), 0, 0, raw.data, i32(raw.len), if options.even_odd {
602 0
603 } else {
604 1
605 })
606}
607
608// triangles fills each group of three points with src.
609pub fn (p &PictureHandle) triangles(op int, src &PictureHandle, points []Point, options ShapeOptions) ! {
610 p.extension.require(0, 4, 'triangles')!
611 p.extension.check_op(op)!
612 if points.len == 0 || points.len % 3 != 0 {
613 return error('triangles need a multiple of three points')
614 }
615 if points.len / 3 > 0x7fffffff { return error('too many triangles') }
616 if !fits_i16(options.src_x) || !fits_i16(options.src_y) {
617 return error('source offset exceeds X11 limits')
618 }
619 d, id := p.display()!
620 source := src.id()!
621 mut raw := []Triangle{cap: points.len / 3}
622 for i := 0; i < points.len; i += 3 {
623 raw << Triangle{ p1: points[i].fixed()!, p2: points[i + 1].fixed()!, p3: points[i + 2].fixed()! }
624 }
625 mask := p.extension.shape_mask(options)!
626 composite_triangles(d, i32(op), source, id, &mask, i32(options.src_x), i32(options.src_y), raw.data, i32(raw.len))
627}
628
629// Glyph sets
630
631// GlyphMetrics mirrors GlyphInfo as a V struct, so the map holding it needs no
632// C-aligned allocation.
633struct GlyphMetrics {
634 width u16
635 height u16
636 x i16
637 y i16
638 x_off i16
639 y_off i16
640}
641
642// GlyphSetHandle owns one GlyphSet and tracks the glyphs added through it.
643// Close it before the connection.
644@[heap; noinit]
645pub struct GlyphSetHandle {
646 extension &Extension
647pub:
648 format Format
649mut:
650 handle GlyphSet
651 bits_per_pixel int
652 glyphs map[u64]GlyphMetrics
653}
654
655pub fn (e &Extension) create_glyph_set(format Format) !&GlyphSetHandle {
656 if format.id == 0 { return error('invalid glyph format') }
657 d := e.connection.raw()!
658 mut count := i32(0)
659 formats := vx11.list_pixmap_formats(d, &count)
660 if formats == unsafe { nil } { return error('cannot query pixmap formats') }
661 mut bpp := 0
662 for i in 0 .. int(count) {
663 f := unsafe { formats[i] }
664 if f.depth == format.depth { bpp = int(f.bits_per_pixel) }
665 }
666 vx11.free(formats)
667 if bpp == 0 { return error('the server has no pixmap format for depth ${format.depth}') }
668 id := create_glyph_set(d, &format)
669 if id == 0 { return error('cannot create glyph set') }
670 return &GlyphSetHandle{ extension: e, format: format, handle: id, bits_per_pixel: bpp }
671}
672
673pub fn (g &GlyphSetHandle) id() !GlyphSet {
674 if g.handle == 0 { return error('glyph set is closed') }
675 g.extension.connection.raw()!
676 return g.handle
677}
678
679pub fn (mut g GlyphSetHandle) close() {
680 if g.handle != 0 {
681 if d := g.extension.connection.raw() { free_glyph_set(d, g.handle) }
682 g.handle = 0
683 g.glyphs.clear()
684 }
685}
686
687// stride returns the bytes per image row for a glyph of this set's format.
688pub fn (g &GlyphSetHandle) stride(width int) int {
689 return int((i64(width) * g.bits_per_pixel + 31) / 32 * 4)
690}
691
692// add stores or replaces a glyph. image is a Z-format bitmap of
693// info.height rows, each stride(info.width) bytes; the bytes are copied.
694pub fn (mut g GlyphSetHandle) add(id Glyph, info GlyphInfo, image []u8) ! {
695 set := g.id()!
696 d := g.extension.connection.raw()!
697 if id > Glyph(0xffffffff) { return error('glyph IDs are 32-bit') }
698 expected := i64(g.stride(int(info.width))) * i64(info.height)
699 if i64(image.len) != expected {
700 return error('glyph image has ${image.len} bytes; expected ${expected}')
701 }
702 if !request_fits(d, 3 + 1 + 3 + expected / 4) {
703 return error('glyph image is too large for one request')
704 }
705 gid := id
706 images := if image.len == 0 { &char(unsafe { nil }) } else { &char(image.data) }
707 add_glyphs(d, set, &gid, &info, 1, images, i32(image.len))
708 g.glyphs[u64(id)] = GlyphMetrics{info.width, info.height, info.x, info.y, info.xOff, info.yOff}
709}
710
711// remove frees glyphs that were added through this handle.
712pub fn (mut g GlyphSetHandle) remove(ids []Glyph) ! {
713 set := g.id()!
714 for id in ids {
715 if u64(id) !in g.glyphs { return error('glyph ${id} was not added to this glyph set') }
716 }
717 if ids.len == 0 { return }
718 d := g.extension.connection.raw()!
719 if !request_fits(d, 2 + i64(ids.len)) { return error('too many glyphs for one request') }
720 free_glyphs(d, set, ids.data, i32(ids.len))
721 for id in ids { g.glyphs.delete(u64(id)) }
722}
723
724pub fn (g &GlyphSetHandle) contains(id Glyph) bool { return u64(id) in g.glyphs }
725
726// info returns the metrics of a glyph added through this handle.
727pub fn (g &GlyphSetHandle) info(id Glyph) ?GlyphInfo {
728 m := g.glyphs[u64(id)] or { return none }
729 return GlyphInfo{ width: m.width, height: m.height, x: m.x, y: m.y, xOff: m.x_off, yOff: m.y_off }
730}
731
732@[params]
733pub struct GlyphOptions {
734pub:
735 src_x int
736 src_y int
737 // separate composites each glyph on its own instead of through a mask in
738 // the glyph set's format. Use it for color glyphs.
739 separate bool
740}
741
742// glyphs draws glyph IDs from set with their origin at (x, y), advancing by
743// each glyph's offset. The server skips IDs the set does not contain.
744pub fn (p &PictureHandle) glyphs(op int, src &PictureHandle, set &GlyphSetHandle, x int, y int, ids []Glyph, options GlyphOptions) ! {
745 p.extension.check_op(op)!
746 for v in [x, y, options.src_x, options.src_y] {
747 if !fits_i16(v) { return error('glyph position exceeds X11 coordinate limits') }
748 }
749 if ids.len > 0x7fffffff { return error('too many glyphs') }
750 d, id := p.display()!
751 source := src.id()!
752 glyph_set := set.id()!
753 if ids.len == 0 { return }
754 mut chars := []u32{cap: ids.len}
755 for g in ids {
756 if g > Glyph(0xffffffff) { return error('glyph IDs are 32-bit') }
757 chars << u32(g)
758 }
759 mask := if options.separate { &Format(unsafe { nil }) } else { &set.format }
760 composite_string32(d, i32(op), source, id, mask, glyph_set, i32(options.src_x), i32(options.src_y), i32(x), i32(y), chars.data, i32(chars.len))
761}
762
763// Cursors
764
765// create_cursor makes a cursor from a drawable-backed picture. The hot spot
766// must lie inside it. The caller owns the cursor: release it with
767// vx11.free_cursor before closing the connection.
768pub fn (e &Extension) create_cursor(source &PictureHandle, hot_x int, hot_y int) !vx11.Cursor {
769 e.require(0, 5, 'picture cursors')!
770 id := source.id()!
771 if source.drawable == 0 { return error('cursors need a picture backed by a drawable') }
772 if hot_x < 0 || hot_y < 0 || hot_x >= source.width || hot_y >= source.height {
773 return error('cursor hot spot lies outside the picture')
774 }
775 cursor := create_cursor(e.connection.raw()!, id, u32(hot_x), u32(hot_y))
776 if cursor == 0 { return error('cannot create cursor') }
777 return cursor
778}
779
780// CursorFrame shows cursor for delay_ms milliseconds.
781pub struct CursorFrame {
782pub:
783 cursor vx11.Cursor
784 delay_ms int
785}
786
787// create_anim_cursor copies the frames into a new cursor. The caller keeps
788// ownership of the frame cursors and owns the result; free each with
789// vx11.free_cursor.
790pub fn (e &Extension) create_anim_cursor(frames []CursorFrame) !vx11.Cursor {
791 e.require(0, 8, 'animated cursors')!
792 if frames.len == 0 { return error('an animated cursor needs at least one frame') }
793 d := e.connection.raw()!
794 if !request_fits(d, 2 + i64(frames.len) * 2) {
795 return error('too many cursor frames for one request')
796 }
797 mut raw := []AnimCursor{cap: frames.len}
798 for f in frames {
799 if f.cursor == 0 { return error('invalid cursor frame') }
800 if f.delay_ms < 0 || i64(f.delay_ms) > 0xffffffff { return error('invalid frame delay') }
801 raw << AnimCursor{ cursor: f.cursor, delay: vx11.CULong(f.delay_ms) }
802 }
803 cursor := create_anim_cursor(d, i32(raw.len), raw.data)
804 if cursor == 0 { return error('cannot create animated cursor') }
805 return cursor
806}
807
808// Snapshots
809
810// dimmed_snapshot copies a visible root region and applies a dark translucent
811// tint. Capture before mapping an overlay. Caller owns the returned pixmap and
812// must free it before closing c. Target uses the default screen visual/depth.
813pub fn dimmed_snapshot(c &vx11.Connection, x int, y int, width int, height int) !vx11.Pixmap {
814 if !available(c)! { return error('XRender extension is unavailable') }
815 sw, sh := c.dimensions()!
816 if x < 0 || y < 0 || width <= 0 || height <= 0 || width > sw || height > sh || x > sw - width || y > sh - height {
817 return error('snapshot region is outside the root window')
818 }
819 return C.vx11_render_backdrop(c.raw()!, i32(x), i32(y), i32(width), i32(height))
820}
821