Debian Codegraph @

src/x.h

raw symbols SCIP
1 // SPDX-License-Identifier: MPL-2.0
2 // Copyright (c) 2018 Yuxuan Shui <[email protected]>
3
4 #pragma once
5 #include <X11/Xlib.h>
6 #include <stdbool.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <xcb/render.h>
10 #include <xcb/sync.h>
11 #include <xcb/xcb.h>
12 #include <xcb/xcb_renderutil.h>
13 #include <xcb/xfixes.h>
14
15 #include "atom.h"
16 #include "compiler.h"
17 #include "log.h"
18 #include "region.h"
19 #include "utils/kernel.h"
20 #include "utils/list.h"
21
22 typedef struct session session_t;
23 struct atom;
24
25 /// Structure representing Window property value.
26 typedef struct winprop {
27 union {
28 void *ptr;
29 int8_t *p8;
30 int16_t *p16;
31 int32_t *p32;
32 uint32_t *c32; // 32bit cardinal
33 xcb_atom_t *atom;
34 };
35 unsigned long nitems;
36 xcb_atom_t type;
37 int format;
38
39 xcb_get_property_reply_t *r;
40 } winprop_t;
41
42 enum x_error_action {
43 PENDING_REPLY_ACTION_IGNORE,
44 PENDING_REPLY_ACTION_ABORT,
45 PENDING_REPLY_ACTION_DEBUG_ABORT,
46 };
47
48 struct x_extensions {
49 /// The X Damage extension's base event number.
50 int damage_event;
51 /// The X Damage extension's base error number.
52 int damage_error;
53 /// The X Fixes extension's base error number.
54 int fixes_error;
55 /// MIT-SHM's base error number.
56 int shm_error;
57 /// MIT-SHM's base event number.
58 int shm_event;
59 /// The X GLX extension's presence.
60 bool has_glx;
61 /// The X GLX extension's base error number.
62 int glx_error;
63 /// The X Present extension's presence.
64 bool has_present;
65 /// The X RandR extension's presence.
66 bool has_randr;
67 /// The X RandR extension's base event number.
68 int randr_event;
69 /// The X Render extension's base error number.
70 int render_error;
71 /// The X Shape extension's presence.
72 bool has_shape;
73 /// The X Shape extension's base event number.
74 int shape_event;
75 /// The X Sync extension's presence.
76 bool has_sync;
77 /// The X Sync extension's base event number.
78 int sync_event;
79 /// The X Sync extension's base error number.
80 int sync_error;
81 };
82
83 struct x_connection {
84 // Public fields
85 // These are part of the public ABI, changing these
86 // requires bumping PICOM_API_MAJOR.
87 /// XCB connection.
88 xcb_connection_t *c;
89 /// Display in use.
90 Display *dpy;
91 /// Default screen
92 int screen;
93 /// Information about the X extensions.
94 struct x_extensions e;
95
96 // Private fields
97 /// The list of pending async requests that we have
98 /// yet to receive a reply for.
99 struct list_node pending_x_requests;
100 /// Previous handler of X errors
101 XErrorHandler previous_xerror_handler;
102 /// Information about the default screen
103 xcb_screen_t *screen_info;
104 /// The sequence number of the last message returned by
105 /// `x_poll_for_message`. Used for sequence number overflow
106 /// detection.
107 uint32_t last_sequence;
108 /// The sequence number of the last completed request.
109 uint32_t latest_completed_request;
110 /// The sequence number of the "event sync" request we sent. This is
111 /// a request we sent that is guaranteed to error, so we can be sure
112 /// `xcb_poll_for_event` will return something. This is akin to `xcb_aux_sync`,
113 /// except that guarantees a reply, this one guarantees an error.
114 ///
115 /// # Why do we need this?
116 ///
117 /// To understand why we need this, first notice we need a way to fetch replies
118 /// that are already in xcb's buffer, without reading from the X connection.
119 /// Because otherwise we can't going into sleep while being confident that there
120 /// is no buffered events we haven't handled.
121 ///
122 /// For events or unchecked errors (we will refer to both of them as events
123 /// without distinction), this is possible with `xcb_poll_for_queued_event`, but
124 /// for replies, there is no `xcb_poll_for_queued_reply` (ridiculous, if you
125 /// ask me). Luckily, if there is a reply already in the buffer,
126 /// `xcb_poll_for_reply` will return it without reading from X. And we can deduce
127 /// whether a reply is already received from the sequence number of received
128 /// events. The only problem, if no events are coming, we will be stuck
129 /// indefinitely, so we have to make our own events.
130 uint32_t event_sync;
131 };
132
133 /// Monitor info
134 struct x_monitors {
135 int count;
136 region_t *regions;
137 };
138
139 #define XCB_AWAIT_VOID(func, conn, ...) \
140 /* NOLINTBEGIN(bugprone-assignment-in-if-condition) */ \
141 ({ \
142 bool __success = true; \
143 __auto_type __e = \
144 xcb_request_check((conn)->c, func##_checked((conn)->c, __VA_ARGS__)); \
145 if (__e) { \
146 x_print_error(conn, __e->sequence, __e->major_code, \
147 __e->minor_code, __e->error_code); \
148 free(__e); \
149 __success = false; \
150 } \
151 __success; \
152 }) /* NOLINTEND(bugprone-assignment-in-if-condition) */
153
154 #define XCB_AWAIT(func, conn, ...) \
155 ({ \
156 xcb_generic_error_t *__e = NULL; \
157 __auto_type __r = \
158 func##_reply((conn)->c, func((conn)->c, ##__VA_ARGS__), &__e); \
159 if (__e) { \
160 x_print_error(conn, __e->sequence, __e->major_code, \
161 __e->minor_code, __e->error_code); \
162 free(__e); \
163 } \
164 __r; \
165 })
166
167 #define log_debug_x_error(c, e, fmt, ...) \
168 LOG(DEBUG, fmt " (%s)", ##__VA_ARGS__, x_strerror(c, e))
169 #define log_error_x_error(c, e, fmt, ...) \
170 LOG(ERROR, fmt " (%s)", ##__VA_ARGS__, x_strerror(c, e))
171 #define log_fatal_x_error(c, e, fmt, ...) \
172 LOG(FATAL, fmt " (%s)", ##__VA_ARGS__, x_strerror(c, e))
173
174 // xcb-render specific macros
175 #define XFIXED_TO_DOUBLE(value) (((double)(value)) / 65536)
176 #define DOUBLE_TO_XFIXED(value) ((xcb_render_fixed_t)(((double)(value)) * 65536))
177
178 /// Wraps x_new_id. abort the program if x_new_id returns error
179 static inline uint32_t x_new_id(struct x_connection *c) {
180 auto ret = xcb_generate_id(c->c);
181 if (ret == (uint32_t)-1) {
182 log_fatal("We seems to have run of XIDs. This is either a bug in the X "
183 "server, or a resource leakage in the compositor. Please open "
184 "an issue about this problem. The compositor will die.");
185 abort();
186 }
187 return ret;
188 }
189
190 /// Set error handler for a specific X request.
191 ///
192 /// @param c X connection
193 /// @param sequence sequence number of the X request to set error handler for
194 /// @param action action to take when error occurs
195 void x_set_error_action(struct x_connection *c, uint32_t sequence, enum x_error_action action,
196 const char *func, const char *file, int line);
197
198 /// Convenience wrapper for x_set_error_action with action `PENDING_REPLY_ACTION_IGNORE`
199 #define x_set_error_action_ignore(c, cookie) \
200 x_set_error_action(c, (cookie).sequence, PENDING_REPLY_ACTION_IGNORE, __func__, \
201 __FILE__, __LINE__)
202
203 /// Convenience wrapper for x_set_error_action with action `PENDING_REPLY_ACTION_ABORT`
204 #define x_set_error_action_abort(c, cookie) \
205 x_set_error_action(c, (cookie).sequence, PENDING_REPLY_ACTION_ABORT, __func__, \
206 __FILE__, __LINE__)
207
208 /// Convenience wrapper for x_set_error_action with action
209 /// `PENDING_REPLY_ACTION_DEBUG_ABORT`
210 #ifndef NDEBUG
211 #define x_set_error_action_debug_abort(c, cookie) \
212 x_set_error_action(c, (cookie).sequence, PENDING_REPLY_ACTION_DEBUG_ABORT, \
213 __func__, __FILE__, __LINE__)
214 #else
215 #define x_set_error_action_debug_abort(c, cookie) \
216 ((void)(c)); \
217 ((void)(cookie))
218 #endif
219
220 struct x_async_request_base {
221 struct list_node siblings;
222 /// The callback function to call when the reply is received. If `reply_or_error`
223 /// is NULL, it means the X connection is closed while waiting for the reply.
224 void (*callback)(struct x_connection *, struct x_async_request_base *,
225 const xcb_raw_generic_event_t *reply_or_error);
226 /// The sequence number of the X request.
227 unsigned int sequence;
228 /// This request doesn't expect a reply. If this is true, in the success case,
229 /// `callback` will be called with a dummy reply whose `response_type` is 1.
230 bool no_reply;
231 };
232
233 static inline void attr_unused free_x_connection(struct x_connection *c) {
234 list_foreach_safe(struct x_async_request_base, i, &c->pending_x_requests, siblings) {
235 list_remove(&i->siblings);
236 i->callback(c, i, NULL);
237 }
238
239 XSetErrorHandler(c->previous_xerror_handler);
240 }
241
242 /// Initialize the used X extensions and populate the x_extensions structure in an
243 /// x_connection structure with the information about them.
244 ///
245 /// Returns false if the X server doesn't have or support the required version of at least
246 /// one required X extension, true otherwise.
247 bool x_extensions_init(struct x_connection *c);
248
249 /// Initialize x_connection struct from an Xlib Display.
250 ///
251 /// Note this function doesn't take ownership of the Display, the caller is still
252 /// responsible for closing it after `free_x_connection` is called.
253 void x_connection_init(struct x_connection *c, Display *dpy);
254 void x_connection_init_xcb(struct x_connection *c, xcb_connection_t *conn, int screen);
255
256 /**
257 * Get a specific attribute of a window.
258 *
259 * Returns a blank structure if the returned type and format does not
260 * match the requested type and format.
261 *
262 * @param ps current session
263 * @param w window
264 * @param atom atom of attribute to fetch
265 * @param length length to read
266 * @param rtype atom of the requested type
267 * @param rformat requested format
268 * @return a <code>winprop_t</code> structure containing the attribute
269 * and number of items. A blank one on failure.
270 */
271 winprop_t x_get_prop_with_offset(const struct x_connection *c, xcb_window_t w, xcb_atom_t atom,
272 int offset, int length, xcb_atom_t rtype, int rformat);
273
274 /**
275 * Wrapper of wid_get_prop_adv().
276 */
277 static inline winprop_t
278 x_get_prop(const struct x_connection *c, xcb_window_t wid, xcb_atom_t atom, int length,
279 xcb_atom_t rtype, int rformat) {
280 return x_get_prop_with_offset(c, wid, atom, 0L, length, rtype, rformat);
281 }
282
283 /**
284 * Get the value of a type-<code>xcb_window_t</code> property of a window.
285 *
286 * @return the value if successful, 0 otherwise
287 */
288 xcb_window_t wid_get_prop_window(struct x_connection *c, xcb_window_t wid,
289 xcb_atom_t aprop, bool *exists);
290 bool wid_get_opacity_prop(struct x_connection *c, struct atom *atoms, xcb_window_t wid,
291 opacity_t def, opacity_t *out);
292
293 /**
294 * Get the value of a text property of a window.
295 *
296 * @param[out] pstrlst Out parameter for an array of strings, caller needs to free this
297 * array
298 * @param[out] pnstr Number of strings in the array
299 */
300 bool wid_get_text_prop(struct x_connection *c, struct atom *atoms, xcb_window_t wid,
301 xcb_atom_t prop, char ***pstrlst, int *pnstr);
302
303 static inline bool x_is_type_string(struct atom *atoms, xcb_atom_t type) {
304 return type == XCB_ATOM_STRING || type == atoms->aUTF8_STRING ||
305 type == atoms->aC_STRING;
306 }
307
308 const xcb_render_pictforminfo_t *
309 x_get_pictform_for_visual(struct x_connection *, xcb_visualid_t);
310
311 xcb_render_picture_t
312 x_create_picture_with_pictfmt_and_pixmap(struct x_connection *, xcb_render_pictformat_t pictfmt,
313 xcb_pixmap_t pixmap, uint32_t valuemask,
314 const xcb_render_create_picture_value_list_t *attr)
315 attr_nonnull(1);
316
317 xcb_render_picture_t
318 x_create_picture_with_visual_and_pixmap(struct x_connection *, xcb_visualid_t visual,
319 xcb_pixmap_t pixmap, uint32_t valuemask,
320 const xcb_render_create_picture_value_list_t *attr)
321 attr_nonnull(1);
322
323 xcb_render_picture_t
324 x_create_picture_with_standard_and_pixmap(struct x_connection *, xcb_pict_standard_t standard,
325 xcb_pixmap_t pixmap, uint32_t valuemask,
326 const xcb_render_create_picture_value_list_t *attr)
327 attr_nonnull(1);
328
329 xcb_render_picture_t
330 x_create_picture_with_standard(struct x_connection *c, int w, int h,
331 xcb_pict_standard_t standard, uint32_t valuemask,
332 const xcb_render_create_picture_value_list_t *attr)
333 attr_nonnull(1);
334
335 /**
336 * Create an picture.
337 */
338 xcb_render_picture_t
339 x_create_picture_with_pictfmt(struct x_connection *, int w, int h,
340 xcb_render_pictformat_t pictfmt, uint8_t depth, uint32_t valuemask,
341 const xcb_render_create_picture_value_list_t *attr)
342 attr_nonnull(1);
343
344 xcb_render_picture_t
345 x_create_picture_with_visual(struct x_connection *, int w, int h, xcb_visualid_t visual,
346 uint32_t valuemask,
347 const xcb_render_create_picture_value_list_t *attr)
348 attr_nonnull(1);
349
350 /// Fetch a X region and store it in a pixman region
351 bool x_fetch_region(struct x_connection *, xcb_xfixes_region_t r, region_t *res);
352
353 /// Set an X region to a pixman region
354 bool x_set_region(struct x_connection *c, xcb_xfixes_region_t dst, const region_t *src);
355
356 /// Create a X region from a pixman region
357 uint32_t x_create_region(struct x_connection *c, const region_t *reg);
358
359 void x_async_change_window_attributes(struct x_connection *c, xcb_window_t wid,
360 uint32_t mask, const uint32_t *values,
361 struct x_async_request_base *req);
362 void x_async_query_tree(struct x_connection *c, xcb_window_t wid,
363 struct x_async_request_base *req);
364 void x_async_get_property(struct x_connection *c, xcb_window_t wid, xcb_atom_t atom,
365 xcb_atom_t type, uint32_t long_offset, uint32_t long_length,
366 struct x_async_request_base *req);
367
368 /// Destroy a X region
369 void x_destroy_region(struct x_connection *c, uint32_t region);
370
371 void x_set_picture_clip_region(struct x_connection *, xcb_render_picture_t,
372 int16_t clip_x_origin, int16_t clip_y_origin, const region_t *);
373
374 void x_clear_picture_clip_region(struct x_connection *, xcb_render_picture_t pict);
375
376 /**
377 * Destroy a <code>Picture</code>.
378 *
379 * Picture must be valid.
380 */
381 void x_free_picture(struct x_connection *c, xcb_render_picture_t p);
382
383 /**
384 * Log a X11 error
385 */
386 void x_print_error_impl(struct x_connection *c, unsigned long serial, uint8_t major,
387 uint16_t minor, uint8_t error_code, const char *func);
388 #define x_print_error(c, serial, major, minor, error_code) \
389 x_print_error_impl(c, serial, major, minor, error_code, __func__)
390
391 /*
392 * Convert a xcb_generic_error_t to a string that describes the error
393 *
394 * @return a pointer to a string. this pointer shouldn NOT be freed, same buffer is used
395 * for multiple calls to this function,
396 */
397 const char *x_strerror(struct x_connection *c, const xcb_generic_error_t *e);
398
399 xcb_pixmap_t x_create_pixmap(struct x_connection *, uint8_t depth, int width, int height);
400
401 /**
402 * Free a <code>winprop_t</code>.
403 *
404 * @param pprop pointer to the <code>winprop_t</code> to free.
405 */
406 static inline void free_winprop(winprop_t *pprop) {
407 // Empty the whole structure to avoid possible issues
408 if (pprop->r) {
409 free(pprop->r);
410 }
411 pprop->ptr = NULL;
412 pprop->r = NULL;
413 pprop->nitems = 0;
414 }
415
416 /// Get the back pixmap of the root window
417 xcb_pixmap_t x_get_root_back_pixmap(struct x_connection *c, struct atom *atoms);
418
419 /// Return true if the atom refers to a property name that is used for the
420 /// root window background pixmap
421 bool x_is_root_back_pixmap_atom(struct atom *atoms, xcb_atom_t atom);
422
423 struct x_convolution_kernel {
424 int size;
425 int capacity;
426 xcb_render_fixed_t kernel[];
427 };
428
429 /**
430 * Convert a struct conv to a X picture convolution filter, normalizing the kernel
431 * in the process. Allow the caller to specify the element at the center of the kernel,
432 * for compatibility with legacy code.
433 *
434 * @param[in] kernel the convolution kernel
435 * @param[in] center the element to put at the center of the matrix
436 * @param[inout] ret pointer to an array of `size`, if `size` is too small, more space
437 * will be allocated, and `*ret` will be updated.
438 * @param[inout] size size of the array pointed to by `ret`.
439 */
440 void attr_nonnull(1, 3) x_create_convolution_kernel(const conv *kernel, double center,
441 struct x_convolution_kernel **ret);
442
443 /// Generate a search criteria for fbconfig from a X visual.
444 /// Returns {-1, -1, -1, -1, -1, -1} on failure
445 struct xvisual_info x_get_visual_info(struct x_connection *c, xcb_visualid_t visual);
446
447 xcb_visualid_t x_get_visual_for_standard(struct x_connection *c, xcb_pict_standard_t std);
448
449 xcb_visualid_t x_get_visual_for_depth(xcb_screen_t *screen, uint8_t depth);
450
451 xcb_render_pictformat_t
452 x_get_pictfmt_for_standard(struct x_connection *c, xcb_pict_standard_t std);
453
454 /// Populates a `struct x_monitors` with the current monitor configuration asynchronously.
455 void x_update_monitors_async(struct x_connection *, struct x_monitors *);
456 /// Free memory allocated for a `struct x_monitors`.
457 void x_free_monitor_info(struct x_monitors *);
458
459 uint32_t attr_deprecated xcb_generate_id(xcb_connection_t *c); // NOLINT(readability-redundant-declaration)
460
461 /// Ask X server to send us a notification for the next end of vblank.
462 void x_request_vblank_event(struct x_connection *c, xcb_window_t window, uint64_t msc);
463
464 /// Register an X request as async request. Its reply will be processed as part of the
465 /// event stream. i.e. the registered callback will only be called when all preceding
466 /// events have been retrieved via `x_poll_for_event`.
467 /// `req` store information about the request, including the callback. The callback is
468 /// responsible for freeing `req`.
469 static inline void x_await_request(struct x_connection *c, struct x_async_request_base *req) {
470 list_insert_before(&c->pending_x_requests, &req->siblings);
471 }
472
473 /// Flush all X buffers to ensure we don't sleep with outgoing messages not sent.
474 ///
475 /// If there are requests pending replies, an event sync request will
476 /// be sent if necessary. See comments on `event_sync` for more information. MUST be
477 /// called before sleep to ensure we can handle replies/events in a timely manner. This
478 /// function MIGHT read data from X into xcb buffer (because `xcb_flush` might read,
479 /// ridiculous, I know), so `x_poll_for_event(queued = true)` MUST be called after this to
480 /// drain the buffer.
481 bool x_prepare_for_sleep(struct x_connection *c);
482
483 /// Poll for the next X event. This is like `xcb_poll_for_event`, but also includes
484 /// machinery for handling async replies. Calling `xcb_poll_for_event` directly will
485 /// cause replies to async requests to be lost, so that should never be called.
486 ///
487 /// @param[out] queued if true, only return events that are already in the queue, don't
488 /// attempt to read from the X connection.
489 xcb_generic_event_t *x_poll_for_event(struct x_connection *c, bool queued);