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