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