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