]> Pileus Git - wmpus/blob - sys-xcb.c
c9259c3ef3cfe0366ca838714d74f7db2e28b755
[wmpus] / sys-xcb.c
1 /*
2  * Copyright (c) 2015 Andy Spencer <andy753421@gmail.com>
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  */
15
16 #define _GNU_SOURCE
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <search.h>
20 #include <string.h>
21
22 #include <xcb/xcb.h>
23 #include <xcb/xcb_event.h>
24 #include <xcb/xcb_keysyms.h>
25 #include <xcb/xcb_icccm.h>
26 #include <xcb/xcb_ewmh.h>
27 #include <xcb/xinerama.h>
28
29 #include "util.h"
30 #include "conf.h"
31 #include "types.h"
32 #include "sys.h"
33 #include "wm.h"
34
35 /* Configuration */
36 static int border     = 2;
37 static int stack      = 25;
38 static int no_capture = 0;
39
40 /* Internal structures */
41 typedef struct {
42         int left;
43         int right;
44         int top;
45         int bottom;
46 } strut_t;
47
48 struct win_sys {
49         xcb_window_t     xcb;    // xcb window id
50         xcb_event_mask_t events; // currently watch events
51         strut_t          strut;  // toolbar struts
52         int managed;             // window is managed by wm
53 };
54
55 typedef enum {
56         CLR_FOCUS,
57         CLR_UNFOCUS,
58         CLR_URGENT,
59         NCOLORS
60 } color_t;
61
62 /* Global data */
63 static xcb_connection_t      *conn;
64 static xcb_ewmh_connection_t  ewmh;
65 static xcb_key_symbols_t     *keysyms;
66 static xcb_colormap_t         colormap;
67 static xcb_window_t           root;
68 static xcb_event_mask_t       events;
69 static list_t                *screens;
70 static void                  *cache;
71 static xcb_pixmap_t           colors[NCOLORS];
72 static unsigned int           grabbed;
73 static xcb_atom_t             wm_protos;
74 static xcb_atom_t             wm_delete;
75
76 /************************
77  * Conversion functions *
78  ************************/
79
80 /* State names */
81 static char *state_map[] = {
82         [ST_HIDE ] "hide ",
83         [ST_SHOW ] "show ",
84         [ST_FULL ] "full ",
85         [ST_MAX  ] "max  ",
86         [ST_SHADE] "shade",
87         [ST_ICON ] "icon ",
88         [ST_CLOSE] "close",
89 };
90
91 /* Key presses */
92 static struct {
93         event_t      ev;
94         xcb_keysym_t sym;
95 } keysym_map[] = {
96         { EV_LEFT,     0xFF51 },
97         { EV_RIGHT,    0xFF53 },
98         { EV_UP,       0xFF52 },
99         { EV_DOWN,     0xFF54 },
100         { EV_HOME,     0xFF50 },
101         { EV_END,      0xFF57 },
102         { EV_PAGEUP,   0xFF55 },
103         { EV_PAGEDOWN, 0xFF56 },
104         { EV_F1,       0xFFBE },
105         { EV_F2,       0xFFBF },
106         { EV_F3,       0xFFC0 },
107         { EV_F4,       0xFFC1 },
108         { EV_F5,       0xFFC2 },
109         { EV_F6,       0xFFC3 },
110         { EV_F7,       0xFFC4 },
111         { EV_F8,       0xFFC5 },
112         { EV_F9,       0xFFC6 },
113         { EV_F10,      0xFFC7 },
114         { EV_F11,      0xFFC8 },
115         { EV_F12,      0xFFC9 },
116 };
117
118 /************************
119  * Conversion functions *
120  ************************/
121
122 static xcb_keycode_t *event_to_keycodes(event_t ev)
123 {
124         xcb_keycode_t *codes = NULL;
125
126         /* Get keysym */
127         xcb_keysym_t keysym = map_get(keysym_map, ev, ev, sym, ev);
128
129         /* Get keycodes */
130         if (!(codes = xcb_key_symbols_get_keycode(keysyms, keysym)))
131                 warn("no keycode found for %d->%d", ev, keysym);
132
133         return codes;
134 }
135
136 static event_t keycode_to_event(xcb_keycode_t code)
137 {
138         /* Get keysym */
139         xcb_keysym_t keysym = xcb_key_symbols_get_keysym(keysyms, code, 0);
140
141         /* Get event */
142         return map_get(keysym_map, sym,keysym, ev,keysym);
143 }
144
145 /* Button presses */
146 static event_t button_to_event(xcb_button_t btn)
147 {
148         return EV_MOUSE0 + btn;
149 }
150
151 static xcb_button_t event_to_button(event_t ev)
152 {
153         return ev - EV_MOUSE0;
154 }
155
156 /* Modifier masks */
157 static xcb_mod_mask_t mod_to_mask(mod_t mod)
158 {
159         xcb_mod_mask_t mask = 0;
160         if (mod.alt)   mask |= XCB_MOD_MASK_1;
161         if (mod.ctrl)  mask |= XCB_MOD_MASK_CONTROL;
162         if (mod.shift) mask |= XCB_MOD_MASK_SHIFT;
163         if (mod.win)   mask |= XCB_MOD_MASK_4;
164         return mask;
165 }
166
167 static mod_t mask_to_mod(xcb_mod_mask_t mask, int up)
168 {
169         mod_t mod = { .up = up };
170         if (mask & XCB_MOD_MASK_1)       mod.alt   = 1;
171         if (mask & XCB_MOD_MASK_CONTROL) mod.ctrl  = 1;
172         if (mask & XCB_MOD_MASK_SHIFT)   mod.shift = 1;
173         if (mask & XCB_MOD_MASK_4)       mod.win   = 1;
174         return mod;
175 }
176
177 /* Mouse pointers */
178 static ptr_t list_to_ptr(int16_t *list)
179 {
180         ptr_t ptr = {};
181         if (list) {
182                 ptr.rx = list[0]; // root_x
183                 ptr.ry = list[1]; // root_y
184                 ptr.x  = list[2]; // event_x
185                 ptr.y  = list[3]; // event_y
186         }
187         return ptr;
188 }
189
190 /********************
191  * Window functions *
192  ********************/
193
194 static int win_cmp(const void *_a, const void *_b)
195 {
196         const win_t *a = _a;
197         const win_t *b = _b;
198         if (a->sys->xcb < b->sys->xcb) return -1;
199         if (a->sys->xcb > b->sys->xcb) return  1;
200         return 0;
201 }
202
203 static win_t *win_get(xcb_window_t xcb)
204 {
205         win_sys_t sys = { .xcb =  xcb };
206         win_t     key = { .sys = &sys };
207
208         win_t   **win = tfind(&key, &cache, win_cmp);
209
210         if (!win) {
211                 warn("no window for %u", xcb);
212                 return NULL;
213         }
214
215         return *win;
216 }
217
218 /****************
219  * XCB Wrappers *
220  ****************/
221
222 static int do_query_tree(xcb_window_t win, xcb_window_t **kids)
223 {
224         xcb_query_tree_cookie_t cookie =
225                 xcb_query_tree(conn, win);
226         if (!cookie.sequence)
227                 return warn("do_query_tree: %d - bad cookie", win);
228
229         xcb_query_tree_reply_t *reply =
230                 xcb_query_tree_reply(conn, cookie, NULL);
231         if (!reply)
232                 return warn("do_query_tree: %d - no reply", win);
233
234         int nkids = xcb_query_tree_children_length(reply);
235         *kids = xcb_query_tree_children(reply);
236         printf("do_query_tree: %d - n=%d\n", win, nkids);
237         return nkids;
238 }
239
240 static int do_get_geometry(xcb_window_t win,
241                 int *x, int *y, int *w, int *h)
242 {
243         xcb_get_geometry_cookie_t cookie =
244                 xcb_get_geometry(conn, win);
245         if (!cookie.sequence)
246                 return warn("do_get_geometry: %d - bad cookie", win);
247
248         xcb_get_geometry_reply_t *reply =
249                 xcb_get_geometry_reply(conn, cookie, NULL);
250         if (!reply)
251                 return warn("do_get_geometry: %d - no reply", win);
252
253         printf("do_get_geometry: %d - %dx%d @ %d,%d\n",
254                         win, reply->width, reply->height, reply->x, reply->y);
255         *x = reply->x;
256         *y = reply->y;
257         *w = reply->width;
258         *h = reply->height;
259         return 1;
260 }
261
262 static int do_get_window_attributes(xcb_window_t win,
263                 int *override, int *mapped)
264 {
265         xcb_get_window_attributes_cookie_t cookie =
266                 xcb_get_window_attributes(conn, win);
267         if (!cookie.sequence)
268                 return warn("do_get_window_attributes: %d - bad cookie", win);
269
270         xcb_get_window_attributes_reply_t *reply =
271                 xcb_get_window_attributes_reply(conn, cookie, NULL);
272         if (!reply)
273                 return warn("do_get_window_attributes: %d - no reply ", win);
274
275         printf("do_get_window_attributes: %d - %d\n",
276                         win, reply->override_redirect);
277         *override = reply->override_redirect;
278         *mapped   = reply->map_state != XCB_MAP_STATE_UNMAPPED;
279         return 1;
280 }
281
282 static int do_xinerama_check(void)
283 {
284         const xcb_query_extension_reply_t *data =
285                 xcb_get_extension_data(conn, &xcb_xinerama_id);
286         if (!data || !data->present)
287                 return warn("do_xinerama_check: no ext");
288
289         xcb_xinerama_is_active_cookie_t cookie =
290                 xcb_xinerama_is_active(conn);
291         if (!cookie.sequence)
292                 return warn("do_xinerama_check: no cookie");
293
294         xcb_xinerama_is_active_reply_t *reply =
295                 xcb_xinerama_is_active_reply(conn, cookie, NULL);
296         if (!reply)
297                 warn("do_xinerama_check: no reply");
298
299         printf("do_xinerama_check: %d\n", reply->state);
300         return reply && reply->state;
301 }
302
303 static int do_query_screens(xcb_xinerama_screen_info_t **info)
304 {
305         xcb_xinerama_query_screens_cookie_t cookie =
306                 xcb_xinerama_query_screens(conn);
307         if (!cookie.sequence)
308                 return warn("do_query_screens: bad cookie");
309
310         xcb_xinerama_query_screens_reply_t *reply =
311                 xcb_xinerama_query_screens_reply(conn, cookie, NULL);
312         if (!reply)
313                 return warn("do_query_screens: no reply");
314
315         int ninfo = xcb_xinerama_query_screens_screen_info_length(reply);
316         *info = xcb_xinerama_query_screens_screen_info(reply);
317         printf("do_query_screens: %d screens\n", ninfo);
318         return ninfo;
319 }
320
321 static int do_get_input_focus(void)
322 {
323         xcb_get_input_focus_cookie_t cookie =
324                 xcb_get_input_focus(conn);
325         if (!cookie.sequence)
326                 return warn("do_get_input_focus: bad cookie");
327
328         xcb_get_input_focus_reply_t *reply =
329                 xcb_get_input_focus_reply(conn, cookie, NULL);
330         if (!reply)
331                 return warn("do_get_input_focus: no reply");
332
333         return reply->focus;
334 }
335
336 static xcb_atom_t do_intern_atom(const char *name)
337 {
338         xcb_intern_atom_cookie_t cookie =
339                 xcb_intern_atom(conn, 0, strlen(name), name);
340         if (!cookie.sequence)
341                 return warn("do_intern_atom: bad cookie");
342
343         xcb_intern_atom_reply_t *reply =
344                 xcb_intern_atom_reply(conn, cookie, NULL);
345         if (!reply)
346                 return warn("do_intern_atom: no reply");
347
348         return reply->atom;
349 }
350
351 static int do_ewmh_init_atoms(void)
352 {
353         xcb_intern_atom_cookie_t *cookies =
354                 xcb_ewmh_init_atoms(conn, &ewmh);
355         if (!cookies)
356                 return warn("do_ewmh_init_atoms: no cookies");
357
358         int status =
359                 xcb_ewmh_init_atoms_replies(&ewmh, cookies, NULL);
360         if (!status)
361                 return warn("do_ewmh_init_atoms: no status");
362         return status;
363 }
364
365 static int do_get_strut(xcb_window_t win, strut_t *strut)
366 {
367         xcb_get_property_cookie_t cookie =
368                 xcb_ewmh_get_wm_strut(&ewmh, win);
369         if (!cookie.sequence)
370                 return warn("do_get_strut: bad cookie");
371
372         xcb_ewmh_get_extents_reply_t ext = {};
373         int status =
374                 xcb_ewmh_get_wm_strut_reply(&ewmh, cookie, &ext, NULL);
375         if (!status)
376                 return warn("do_get_strut: no status");
377
378         strut->left   = ext.left;
379         strut->right  = ext.right;
380         strut->top    = ext.top;
381         strut->bottom = ext.bottom;
382
383         return ext.left || ext.right || ext.top || ext.bottom;
384 }
385
386 static xcb_pixmap_t do_alloc_color(uint32_t rgb)
387 {
388         uint16_t r = (rgb & 0xFF0000) >> 8;
389         uint16_t g = (rgb & 0x00FF00);
390         uint16_t b = (rgb & 0x0000FF) << 8;
391         xcb_alloc_color_cookie_t cookie =
392                 xcb_alloc_color(conn, colormap, r, g, b);
393         if (!cookie.sequence)
394                 return warn("do_alloc_color: bad cookie");
395
396         xcb_alloc_color_reply_t *reply =
397                 xcb_alloc_color_reply(conn, cookie, NULL);
398         if (!reply)
399                 return warn("do_alloc_color: no reply");
400
401         printf("do_alloc_color: %06x -> %06x\n", rgb, reply->pixel);
402         return reply->pixel;
403 }
404
405 static void do_grab_pointer(xcb_event_mask_t mask)
406 {
407         if (!grabbed)
408                 xcb_grab_pointer(conn, 0, root, mask,
409                                 XCB_GRAB_MODE_ASYNC,
410                                 XCB_GRAB_MODE_ASYNC,
411                                 0, 0, XCB_CURRENT_TIME);
412         grabbed++;
413 }
414
415 static void do_ungrab_pointer(void)
416 {
417         grabbed--;
418         if (!grabbed)
419                 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
420 }
421
422 static void do_configure_window(xcb_window_t win,
423                 int x, int y, int w, int h,
424                 int b, int s, int r)
425 {
426         int table[][2] = {
427                 { x, XCB_CONFIG_WINDOW_X            },
428                 { y, XCB_CONFIG_WINDOW_Y            },
429                 { w, XCB_CONFIG_WINDOW_WIDTH        },
430                 { h, XCB_CONFIG_WINDOW_HEIGHT       },
431                 { b, XCB_CONFIG_WINDOW_BORDER_WIDTH },
432                 { s, XCB_CONFIG_WINDOW_SIBLING      },
433                 { r, XCB_CONFIG_WINDOW_STACK_MODE   },
434         };
435
436         uint16_t mask    = 0;
437         uint32_t list[7] = {};
438         for (int i = 0; i < 7; i++) {
439                 if (table[i][0] >= 0) {
440                         list[i] = table[i][0];
441                         mask   |= table[i][1];
442                 }
443         }
444
445         xcb_configure_window(conn, win, mask, list);
446 }
447
448 static int do_client_message(xcb_window_t win, xcb_atom_t atom)
449 {
450         /* Get protocols */
451         xcb_get_property_cookie_t cookie =
452                 xcb_icccm_get_wm_protocols(conn, win, wm_protos);
453         if (!cookie.sequence)
454                 return warn("do_client_message: %d - bad cookie", win);
455
456         xcb_icccm_get_wm_protocols_reply_t protos = {};
457         if (!xcb_icccm_get_wm_protocols_reply(conn, cookie, &protos, NULL))
458                 return warn("do_client_message: %d - no reply", win);
459
460         /* Search for the atom */
461         int found = 0;
462         for (int i = 0; i < protos.atoms_len; i++)
463                 if (protos.atoms[i] == atom)
464                         found = 1;
465         if (!found)
466                 return warn("do_client_message: %d - no atom", win);
467
468         /* Send the message */
469         xcb_client_message_event_t msg = {
470                 .response_type  = XCB_CLIENT_MESSAGE,
471                 .format         = 32,
472                 .window         = win,
473                 .type           = wm_protos,
474                 .data.data32[0] = atom,
475                 .data.data32[1] = XCB_CURRENT_TIME,
476         };
477         xcb_send_event(conn, 0, win, XCB_EVENT_MASK_NO_EVENT,
478                         (const char *)&msg);
479         return 1;
480 }
481
482 /**************************
483  * Window Manager Helpers *
484  **************************/
485
486 /* Send event info */
487 static int send_event(event_t ev, xcb_window_t ewin)
488 {
489         win_t *win = win_get(ewin);
490         do_grab_pointer(0);
491         int status = wm_handle_event(win, ev, MOD(), PTR());
492         do_ungrab_pointer();
493         return status;
494 }
495
496 /* Send event info */
497 static int send_event_info(event_t ev, xcb_mod_mask_t mask, int up, int16_t *pos,
498                 xcb_window_t rwin, xcb_window_t ewin, xcb_window_t cwin)
499 {
500         xcb_window_t xcb = ewin == rwin ? cwin : ewin;
501         win_t *win = win_get(xcb);
502         mod_t  mod = mask_to_mod(mask, up);
503         ptr_t  ptr = list_to_ptr(pos);
504         do_grab_pointer(0);
505         int status = wm_handle_event(win, ev, mod, ptr);
506         do_ungrab_pointer();
507         return status;
508 }
509
510 /* Send pointer motion info */
511 static int send_pointer(int16_t *pos,
512                 xcb_window_t rwin, xcb_window_t ewin, xcb_window_t cwin)
513 {
514         xcb_window_t xcb = ewin == rwin ? cwin : ewin;
515         win_t *win = win_get(xcb);
516         ptr_t  ptr = list_to_ptr(pos);
517         do_grab_pointer(0);
518         int status = wm_handle_ptr(win, ptr);
519         do_ungrab_pointer();
520         return status;
521 }
522
523 /* Send window state info */
524 static void send_manage(win_t *win, int managed)
525 {
526         if (win->sys->managed == managed)
527                 return;
528         if (managed)
529                 wm_insert(win);
530         else
531                 wm_remove(win);
532         win->sys->managed = managed;
533 }
534
535 /* Send window state info */
536 static void send_state(win_t *win, state_t next)
537 {
538         if (!win->sys->managed)
539                 return;
540         if (win->state == next)
541                 return;
542         state_t prev = win->state;
543         win->state = next;
544         wm_handle_state(win, prev, next);
545 }
546
547 /**********************
548  * X11 Event Handlers *
549  **********************/
550
551 /* Specific events */
552 static void on_key_event(xcb_key_press_event_t *event, int up)
553 {
554         printf("on_key_event:         xcb=%-8u\n", event->event);
555         xcb_window_t focus = do_get_input_focus();
556         event_t ev = keycode_to_event(event->detail);
557         send_event_info(ev, event->state, up, &event->root_x,
558                 event->root, focus, event->child);
559 }
560
561 static void on_button_event(xcb_button_press_event_t *event, int up)
562 {
563         printf("on_button_event:      xcb=%-8u\n", event->event);
564         event_t ev = button_to_event(event->detail);
565         if (!send_event_info(ev, event->state, up, &event->root_x,
566                                 event->root, event->event, event->child))
567                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, event->time);
568         else if (!up)
569                 do_grab_pointer(XCB_EVENT_MASK_POINTER_MOTION |
570                                 XCB_EVENT_MASK_BUTTON_RELEASE);
571         else
572                 do_ungrab_pointer();
573
574 }
575
576 static void on_motion_notify(xcb_motion_notify_event_t *event)
577 {
578         printf("on_motion_notify:     xcb=%-8u - %d,%d / %d.%d\n", event->event,
579                         event->event_x, event->event_y,
580                         event->root_x,  event->root_y);
581         send_pointer(&event->root_x, event->root, event->event, event->child);
582 }
583
584 static void on_enter_notify(xcb_enter_notify_event_t *event)
585 {
586         if (event->mode != XCB_NOTIFY_MODE_NORMAL)
587                 return;
588         printf("on_enter_notify:      xcb=%-8u\n", event->event);
589         send_event_info(EV_ENTER, event->state, 0, &event->root_x,
590                 event->root, event->event, event->child);
591 }
592
593 static void on_leave_notify(xcb_leave_notify_event_t *event)
594 {
595         if (event->mode != XCB_NOTIFY_MODE_NORMAL)
596                 return;
597         printf("on_leave_notify:      xcb=%-8u\n", event->event);
598         send_event_info(EV_LEAVE, event->state, 0, &event->root_x,
599                 event->root, event->event, event->child);
600 }
601
602 static void on_focus_in(xcb_focus_in_event_t *event)
603 {
604         if (event->mode != XCB_NOTIFY_MODE_NORMAL &&
605             event->mode != XCB_NOTIFY_MODE_WHILE_GRABBED)
606                 return;
607         printf("on_focus_in:          xcb=%-8u mode=%d\n", event->event, event->mode);
608         xcb_change_window_attributes(conn, event->event,
609                         XCB_CW_BORDER_PIXEL, &colors[CLR_FOCUS]);
610         if (event->mode == XCB_NOTIFY_MODE_NORMAL)
611                 send_event(EV_FOCUS, event->event);
612 }
613
614 static void on_focus_out(xcb_focus_out_event_t *event)
615 {
616         if (event->mode != XCB_NOTIFY_MODE_NORMAL &&
617             event->mode != XCB_NOTIFY_MODE_WHILE_GRABBED)
618                 return;
619         printf("on_focus_out:         xcb=%-8u mode=%d\n", event->event, event->mode);
620         xcb_change_window_attributes(conn, event->event,
621                         XCB_CW_BORDER_PIXEL, &colors[CLR_UNFOCUS]);
622         if (event->mode == XCB_NOTIFY_MODE_NORMAL)
623                 send_event(EV_UNFOCUS, event->event);
624 }
625
626 static void on_create_notify(xcb_create_notify_event_t *event)
627 {
628         win_t     *win = new0(win_t);
629         win_sys_t *sys = new0(win_sys_t);
630
631         printf("on_create_notify:     xcb=%-8u -> win=%p\n",
632                         event->window, win);
633
634         win->x        = event->x;
635         win->y        = event->y;
636         win->w        = event->width;
637         win->h        = event->height;
638         win->sys      = sys;
639
640         sys->xcb      = event->window;
641
642         if (!event->override_redirect)
643                 send_manage(win, 1);
644
645         tsearch(win, &cache, win_cmp);
646 }
647
648 static void on_destroy_notify(xcb_destroy_notify_event_t *event)
649 {
650         win_t *win = win_get(event->window);
651         printf("on_destroy_notify:    xcb=%-8u -> win=%p\n",
652                         event->window, win);
653         if (!win) return;
654
655         send_manage(win, 0);
656
657         tdelete(win, &cache, win_cmp);
658
659         free(win->sys);
660         free(win);
661 }
662
663 static void on_unmap_notify(xcb_unmap_notify_event_t *event)
664 {
665         win_t *win = win_get(event->window);
666         printf("on_unmap_notify:      xcb=%-8u -> win=%p\n",
667                         event->window, win);
668         if (!win) return;
669
670         send_state(win, ST_HIDE);
671 }
672
673 static void on_map_notify(xcb_map_notify_event_t *event)
674 {
675         win_t *win = win_get(event->window);
676         printf("on_map_notify:        xcb=%-8u -> win=%p\n",
677                         event->window, win);
678         if (!win) return;
679
680         send_state(win, ST_SHOW);
681 }
682
683 static void on_map_request(xcb_map_request_event_t *event)
684 {
685         win_t *win = win_get(event->window);
686         printf("on_map_request:       xcb=%-8u -> win=%p\n",
687                         event->window, win);
688         if (!win) return;
689
690         if (do_get_strut(win->sys->xcb, &win->sys->strut))
691                 printf("Map: Got a strut!\n");
692         else
693                 printf("Map: No struts here!\n");
694
695         send_state(win, ST_SHOW);
696         xcb_map_window(conn, win->sys->xcb);
697         sys_move(win, win->x, win->y, win->w, win->h);
698 }
699
700 static void on_configure_request(xcb_configure_request_event_t *event)
701 {
702         win_t *win = win_get(event->window);
703         printf("on_configure_request: xcb=%-8u -> win=%p -- %dx%d @ %d,%d\n",
704                         event->window, win,
705                         event->width, event->height,
706                         event->x, event->y);
707         if (!win) return;
708
709         win->x = event->x;
710         win->y = event->y;
711         win->w = event->width;
712         win->h = event->height;
713
714         xcb_configure_notify_event_t resp = {
715                 .response_type = XCB_CONFIGURE_NOTIFY,
716                 .event         = win->sys->xcb,
717                 .window        = win->sys->xcb,
718                 .x             = win->x,
719                 .y             = win->y,
720                 .width         = win->w,
721                 .height        = win->h,
722                 .border_width  = border,
723         };
724
725         xcb_send_event(conn, 0, win->sys->xcb,
726                         XCB_EVENT_MASK_STRUCTURE_NOTIFY,
727                         (const char *)&resp);
728 }
729
730 /* Generic Event */
731 static void on_event(xcb_generic_event_t *event)
732 {
733         int type = XCB_EVENT_RESPONSE_TYPE(event);
734
735         switch (type) {
736                 /* Input handling */
737                 case XCB_KEY_PRESS:
738                         on_key_event((xcb_key_press_event_t *)event, 0);
739                         break;
740                 case XCB_KEY_RELEASE:
741                         on_key_event((xcb_key_release_event_t *)event, 1);
742                         break;
743                 case XCB_BUTTON_PRESS:
744                         on_button_event((xcb_button_press_event_t *)event, 0);
745                         break;
746                 case XCB_BUTTON_RELEASE:
747                         on_button_event((xcb_button_release_event_t *)event, 1);
748                         break;
749                 case XCB_MOTION_NOTIFY:
750                         on_motion_notify((xcb_motion_notify_event_t *)event);
751                         break;
752                 case XCB_ENTER_NOTIFY:
753                         on_enter_notify((xcb_enter_notify_event_t *)event);
754                         break;
755                 case XCB_LEAVE_NOTIFY:
756                         on_leave_notify((xcb_leave_notify_event_t *)event);
757                         break;
758                 case XCB_FOCUS_IN:
759                         on_focus_in((xcb_focus_in_event_t *)event);
760                         break;
761                 case XCB_FOCUS_OUT:
762                         on_focus_out((xcb_focus_out_event_t *)event);
763                         break;
764
765                 /* Window management */
766                 case XCB_CREATE_NOTIFY:
767                         on_create_notify((xcb_create_notify_event_t *)event);
768                         break;
769                 case XCB_DESTROY_NOTIFY:
770                         on_destroy_notify((xcb_destroy_notify_event_t *)event);
771                         break;
772                 case XCB_UNMAP_NOTIFY:
773                         on_unmap_notify((xcb_unmap_notify_event_t *)event);
774                         break;
775                 case XCB_MAP_NOTIFY:
776                         on_map_notify((xcb_map_notify_event_t *)event);
777                         break;
778                 case XCB_MAP_REQUEST:
779                         on_map_request((xcb_map_request_event_t *)event);
780                         break;
781                 case XCB_CONFIGURE_REQUEST:
782                         on_configure_request((xcb_configure_request_event_t *)event);
783                         break;
784
785                 /* Unknown events */
786                 default:
787                         printf("on_event: %d:%02X -> %s\n",
788                                 XCB_EVENT_SENT(event) != 0,
789                                 XCB_EVENT_RESPONSE_TYPE(event),
790                                 xcb_event_get_label(type) ?: "unknown_event");
791                         break;
792         }
793 }
794
795 /********************
796  * System functions *
797  ********************/
798
799 void sys_move(win_t *win, int x, int y, int w, int h)
800 {
801         printf("sys_move:  %p - %dx%d @ %d,%d\n",
802                         win, w, h, x, y);
803
804         int b = 2*border;
805
806         win->x = x;
807         win->y = y;
808         win->w = MAX(w,1+b);
809         win->h = MAX(h,1+b);
810         w      = MAX(w-b,1);
811         h      = MAX(h-b,1);
812
813         do_configure_window(win->sys->xcb, x, y, w, h, -1, -1, -1);
814 }
815
816 void sys_raise(win_t *win)
817 {
818         printf("sys_raise: %p\n", win);
819
820         uint16_t mask = XCB_CONFIG_WINDOW_STACK_MODE;
821         uint32_t list = XCB_STACK_MODE_ABOVE;
822
823         xcb_configure_window(conn, win->sys->xcb, mask, &list);
824 }
825
826 void sys_focus(win_t *win)
827 {
828         printf("sys_focus: %p\n", win);
829         xcb_window_t xcb = win ? win->sys->xcb : root;
830
831         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT,
832                         xcb, XCB_CURRENT_TIME);
833 }
834
835 void sys_show(win_t *win, state_t state)
836 {
837         printf("sys_show:  %p - %s -> %s\n", win,
838                         state_map[win->state], state_map[state]);
839         xcb_window_t xcb = win ? win->sys->xcb : root;
840
841         /* Find screen */
842         win_t *screen = NULL;
843         if (state == ST_FULL || state == ST_MAX) {
844                 for (list_t *cur = screens; cur; cur = cur->next) {
845                         screen = cur->data;
846                         if (win->x >= screen->x && win->x <= screen->x+screen->w &&
847                             win->y >= screen->y && win->y <= screen->y+screen->h)
848                                 break;
849                 }
850         }
851
852         /* Change window state */
853         switch (state) {
854                 case ST_HIDE:
855                         xcb_unmap_window(conn, xcb);
856                         break;
857
858                 case ST_SHOW:
859                         xcb_map_window(conn, xcb);
860                         do_configure_window(xcb, win->x, win->y,
861                                         MAX(win->w - 2*border, 1),
862                                         MAX(win->h - 2*border, 1),
863                                         border, -1, -1);
864                         break;
865
866                 case ST_FULL:
867                         xcb_map_window(conn, xcb);
868                         do_configure_window(xcb, screen->x, screen->y, screen->w, screen->h,
869                                         0, -1, XCB_STACK_MODE_ABOVE);
870                         xcb_circulate_window(conn, XCB_CIRCULATE_RAISE_LOWEST, xcb);
871                         break;
872
873                 case ST_MAX:
874                         xcb_map_window(conn, xcb);
875                         do_configure_window(xcb, screen->x, screen->y,
876                                         MAX(screen->w - 2*border, 1),
877                                         MAX(screen->h - 2*border, 1),
878                                         border, -1, XCB_STACK_MODE_ABOVE);
879                         break;
880
881                 case ST_SHADE:
882                         xcb_map_window(conn, xcb);
883                         do_configure_window(xcb, -1, -1, -1, stack,
884                                         border, -1, -1);
885                         break;
886
887                 case ST_ICON:
888                         xcb_map_window(conn, xcb);
889                         do_configure_window(xcb, -1, -1, 100, 100,
890                                         border, -1, -1);
891                         break;
892
893                 case ST_CLOSE:
894                         if (!do_client_message(xcb, wm_delete))
895                                 xcb_kill_client(conn, xcb);
896                         break;
897         }
898
899         /* Update state */
900         win->state = state;
901 }
902
903 void sys_watch(win_t *win, event_t ev, mod_t mod)
904 {
905         printf("sys_watch: %p - 0x%X,0x%X\n", win, ev, mod2int(mod));
906         xcb_window_t      xcb  = win ? win->sys->xcb     : root;
907         xcb_event_mask_t *mask = win ? &win->sys->events : &events;
908         xcb_mod_mask_t    mods = 0;
909         xcb_button_t      btn  = 0;
910         xcb_keycode_t    *code = 0;
911
912         switch (ev) {
913                 case EV_ENTER:
914                         *mask |= XCB_EVENT_MASK_ENTER_WINDOW;
915                         xcb_change_window_attributes(conn, xcb, XCB_CW_EVENT_MASK, mask);
916                         break;
917
918                 case EV_LEAVE:
919                         *mask |= XCB_EVENT_MASK_LEAVE_WINDOW;
920                         xcb_change_window_attributes(conn, xcb, XCB_CW_EVENT_MASK, mask);
921                         break;
922
923                 case EV_FOCUS:
924                 case EV_UNFOCUS:
925                         *mask |= XCB_EVENT_MASK_FOCUS_CHANGE;
926                         xcb_change_window_attributes(conn, xcb, XCB_CW_EVENT_MASK, mask);
927                         break;
928
929                 case EV_MOUSE0...EV_MOUSE7:
930                         btn    = event_to_button(ev);
931                         mods   = mod_to_mask(mod);
932                         *mask |= mod.up ? XCB_EVENT_MASK_BUTTON_RELEASE
933                                         : XCB_EVENT_MASK_BUTTON_PRESS;
934                         xcb_grab_button(conn, 0, xcb, *mask,
935                                         XCB_GRAB_MODE_ASYNC,
936                                         XCB_GRAB_MODE_ASYNC,
937                                         0, 0, btn, mods);
938                         break;
939
940                 default:
941                         code = event_to_keycodes(ev);
942                         mods = mod_to_mask(mod);
943                         for (int i = 0; code && code[i] != XCB_NO_SYMBOL; i++)
944                                 xcb_grab_key(conn, 1, xcb, mods, code[i],
945                                                 XCB_GRAB_MODE_ASYNC,
946                                                 XCB_GRAB_MODE_ASYNC);
947
948                         break;
949         }
950 }
951
952 void sys_unwatch(win_t *win, event_t ev, mod_t mod)
953 {
954         printf("sys_unwatch: %p - 0x%X,0x%X\n", win, ev, mod2int(mod));
955 }
956
957 list_t *sys_info(void)
958 {
959         printf("sys_info\n");
960
961         if (screens == NULL && do_xinerama_check()) {
962                 /* Add Xinerama screens */
963                 xcb_xinerama_screen_info_t *info = NULL;
964                 int ninfo = do_query_screens(&info);
965                 for (int i = 0; i < ninfo; i++) {
966                         win_t *screen = new0(win_t);
967
968                         screen->x = info[i].x_org;
969                         screen->y = info[i].y_org;
970                         screen->w = info[i].width;
971                         screen->h = info[i].height;
972
973                         screens = list_insert(NULL, screen);
974
975                         printf("sys_info: xinerama screen - %dx%d @ %d,%d\n",
976                                         screen->w, screen->h,
977                                         screen->x, screen->y);
978                 }
979         }
980
981         if (screens == NULL) {
982                 /* No xinerama support */
983                 const xcb_setup_t *setup = xcb_get_setup(conn);
984                 xcb_screen_t      *geom  = xcb_setup_roots_iterator(setup).data;
985
986                 win_t *screen = new0(win_t);
987
988                 screen->w = geom->width_in_pixels;
989                 screen->h = geom->height_in_pixels;
990
991                 screens = list_insert(NULL, screen);
992
993                 printf("sys_info: root screen - %dx%d\n",
994                                 screen->w, screen->h);
995         }
996
997         return screens;
998 }
999
1000 void sys_init(void)
1001 {
1002         printf("sys_init\n");
1003
1004         /* Load configuration */
1005         stack      = conf_get_int("main.stack",      stack);
1006         border     = conf_get_int("main.border",     border);
1007         no_capture = conf_get_int("main.no-capture", no_capture);
1008
1009         /* Connect to display */
1010         if (!(conn = xcb_connect(NULL, NULL)))
1011                 error("xcb connect failed");
1012         if (xcb_connection_has_error(conn))
1013                 error("xcb connection has errors");
1014
1015         /* Get root window */
1016         const xcb_setup_t     *setup = xcb_get_setup(conn);
1017         xcb_screen_iterator_t  iter  = xcb_setup_roots_iterator(setup);
1018         root     = iter.data->root;
1019         colormap = iter.data->default_colormap;
1020
1021         /* Setup X Atoms */
1022         wm_protos = do_intern_atom("WM_PROTOCOLS");
1023         wm_delete = do_intern_atom("WM_DELETE_WINDOW");
1024         if (!wm_protos || !wm_delete)
1025                 error("unable to setup atoms");
1026
1027         /* Setup EWMH connection */
1028         if (!do_ewmh_init_atoms())
1029                 error("ewmh setup failed");
1030
1031         /* Setup for for ST_CLOSE */
1032         xcb_set_close_down_mode(conn, XCB_CLOSE_DOWN_DESTROY_ALL);
1033
1034         /* Allocate key symbols */
1035         if (!(keysyms = xcb_key_symbols_alloc(conn)))
1036                 error("cannot allocate key symbols");
1037
1038         /* Read color information */
1039         colors[CLR_FOCUS]   = do_alloc_color(0xFF6060);
1040         colors[CLR_UNFOCUS] = do_alloc_color(0xD8D8FF);
1041         colors[CLR_URGENT]  = do_alloc_color(0xFF0000);
1042
1043         /* Request substructure redirect */
1044         xcb_void_cookie_t cookie;
1045         xcb_generic_error_t *err;
1046         events = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
1047                  XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY;
1048         cookie = xcb_change_window_attributes_checked(conn, root,
1049                         XCB_CW_EVENT_MASK, &events);
1050         if ((err = xcb_request_check(conn, cookie)))
1051                 error("another window manager is already running");
1052 }
1053
1054 void sys_run(void)
1055 {
1056         printf("sys_run\n");
1057
1058         /* Add each initial window */
1059         if (!no_capture) {
1060                 xcb_window_t *kids = NULL;
1061                 int nkids = do_query_tree(root, &kids);
1062                 for(int i = 0; i < nkids; i++) {
1063                         int override=0, mapped=0;
1064                         win_t *win = new0(win_t);
1065                         win->sys = new0(win_sys_t);
1066                         win->sys->xcb = kids[i];
1067                         tsearch(win, &cache, win_cmp);
1068                         do_get_geometry(kids[i], &win->x, &win->y, &win->w, &win->h);
1069                         do_get_window_attributes(kids[i], &override, &mapped);
1070                         if (!override)
1071                                 send_manage(win, 1);
1072                         if (mapped)
1073                                 send_state(win, ST_SHOW);
1074                 }
1075                 xcb_flush(conn);
1076         }
1077
1078         /* Main loop */
1079         while (1)
1080         {
1081                 int status;
1082                 xcb_generic_event_t *event;
1083                 if (!(event = xcb_wait_for_event(conn)))
1084                         break;
1085                 on_event(event);
1086                 free(event);
1087                 if (!(status = xcb_flush(conn)))
1088                         break;
1089         }
1090 }
1091
1092 void sys_exit(void)
1093 {
1094         printf("sys_exit\n");
1095         if (conn)
1096                 xcb_disconnect(conn);
1097         conn = NULL;
1098 }
1099
1100 void sys_free(void)
1101 {
1102         printf("sys_free\n");
1103         if (conn)
1104                 xcb_disconnect(conn);
1105         conn = NULL;
1106 }