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