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