]> git.neil.brown.name Git - edlib.git/blob - display-x11-xcb.c
tile: don't use "Free", just "Close".
[edlib.git] / display-x11-xcb.c
1 /*
2  * Copyright Neil Brown ©2021-2023 <neil@brown.name>
3  * May be distributed under terms of GPLv2 - see file:COPYING
4  *
5  * X11 display driver for edlib, using xcb, cairopango, libxkbcommon etc.
6  *
7  * A different connection to the server will be created for each
8  * display.  Maybe that can be optimised one day.
9  */
10
11 #include <unistd.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <stdint.h>
15 #include <fcntl.h>
16 #include <string.h>
17 #include <xcb/xcb.h>
18 #include <stdarg.h>
19 #include <sys/wait.h>
20 #ifndef __CHECKER__
21 #include <xcb/xkb.h>
22 #else
23 /* xkb.h has a 'long' in an enum :-( */
24 enum {
25         XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY,
26         XCB_XKB_EVENT_TYPE_MAP_NOTIFY,
27         XCB_XKB_NEW_KEYBOARD_NOTIFY,
28         XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
29         XCB_XKB_MAP_PART_MODIFIER_MAP,
30         XCB_XKB_STATE_PART_MODIFIER_LOCK,
31         XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS,
32         XCB_XKB_STATE_PART_GROUP_BASE,
33         XCB_XKB_MAP_PART_KEY_ACTIONS,
34         XCB_XKB_STATE_PART_GROUP_LATCH,
35         XCB_XKB_MAP_PART_VIRTUAL_MODS,
36         XCB_XKB_STATE_PART_GROUP_LOCK,
37         XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP,
38         XCB_XKB_NKN_DETAIL_KEYCODES,
39         XCB_XKB_MAP_PART_KEY_TYPES,
40         XCB_XKB_MAP_PART_KEY_SYMS,
41         XCB_XKB_STATE_PART_MODIFIER_BASE,
42         XCB_XKB_STATE_PART_MODIFIER_LATCH,
43         XCB_XKB_MAP_NOTIFY,
44         XCB_XKB_STATE_NOTIFY,
45 };
46 typedef uint16_t xcb_xkb_device_spec_t;
47 typedef struct xcb_xkb_select_events_details_t {
48         uint16_t affectNewKeyboard;
49         uint16_t newKeyboardDetails;
50         uint16_t affectState;
51         uint16_t stateDetails;
52         /* and other fields */
53 } xcb_xkb_select_events_details_t;
54 typedef struct xcb_xkb_new_keyboard_notify_event_t {
55         uint8_t         deviceID;
56         uint16_t        changed;
57         /* and other fields */
58 } xcb_xkb_new_keyboard_notify_event_t;
59 typedef struct xcb_xkb_state_notify_event_t {
60         uint8_t         deviceID;
61         uint8_t         baseMods;
62         uint8_t         latchedMods;
63         uint8_t         lockedMods;
64         int16_t         baseGroup;
65         int16_t         latchedGroup;
66         uint8_t         lockedGroup;
67         /* and other fields */
68 } xcb_xkb_state_notify_event_t;
69 typedef struct xcb_xkb_map_notify_event_t {
70         uint8_t         deviceID;
71 } xcb_xkb_map_notify_event_t;
72 xcb_void_cookie_t
73 xcb_xkb_select_events_aux_checked(xcb_connection_t              *c,
74                                   xcb_xkb_device_spec_t         deviceSpec,
75                                   uint16_t                      affectWhich,
76                                   uint16_t                      clear,
77                                   uint16_t                      selectAll,
78                                   uint16_t                      affectMap,
79                                   uint16_t                      map,
80                                   const xcb_xkb_select_events_details_t *details);
81
82 #endif
83 #include <xcb/xcbext.h>
84 #include <ctype.h>
85 #include <math.h>
86 #include <locale.h>
87
88 #include <cairo.h>
89 #include <cairo-xcb.h>
90
91 #include <wand/MagickWand.h>
92 #ifdef __CHECKER__
93 // enums confuse sparse...
94 #define MagickBooleanType int
95 #endif
96
97 #ifndef __CHECKER__
98 #include <pango/pango.h>
99 #include <pango/pangocairo.h>
100 #else
101 typedef struct PangoFontDescription {} PangoFontDescription;
102 typedef struct PangoLayout {} PangoLayout;
103 typedef struct PangoContext {} PangoContext;
104 typedef struct PangoFontMetrics {} PangoFontMetrics;
105 typedef struct PangoRectangle { int x,y,width,height;} PangoRectangle;
106 typedef enum { PANGO_STYLE_NORMAL, PANGO_STYLE_OBLIQUE, PANGO_STYLE_ITALIC
107 } PangoStyle;
108 typedef enum { PANGO_VARIANT_NORMAL, PANGO_VARIANT_SMALL_CAPS } PangoVariant;
109 typedef enum { PANGO_WEIGHT_NORMAL, PANGO_WEIGHT_BOLD } PangoWeight;
110 PangoFontDescription *pango_font_description_new(void);
111 void pango_font_description_set_family_static(PangoFontDescription*, char*);
112 void pango_font_description_set_family(PangoFontDescription*, char*);
113 void pango_font_description_set_size(PangoFontDescription*, int);
114 void pango_font_description_set_style(PangoFontDescription*, PangoStyle);
115 void pango_font_description_set_variant(PangoFontDescription*, PangoVariant);
116 void pango_font_description_set_weight(PangoFontDescription*, PangoWeight);
117 #define PANGO_SCALE (1024)
118
119 PangoLayout *pango_cairo_create_layout(cairo_t*);
120 void g_object_unref(PangoLayout*);
121 PangoContext *pango_cairo_create_context(cairo_t *);
122 void pango_cairo_show_layout(cairo_t *, PangoLayout *);
123 PangoFontMetrics *pango_context_get_metrics(PangoContext*, PangoFontDescription*, void*);
124 void pango_font_description_free(PangoFontDescription*);
125 int pango_font_metrics_get_approximate_char_width(PangoFontMetrics *);
126 int pango_font_metrics_get_ascent(PangoFontMetrics *);
127 int pango_font_metrics_get_descent(PangoFontMetrics *);
128 void pango_font_metrics_unref(PangoFontMetrics *);
129 PangoContext* pango_layout_get_context(PangoLayout *);
130 int pango_layout_get_baseline(PangoLayout *);
131 void pango_layout_get_extents(PangoLayout *, PangoRectangle *, PangoRectangle *);
132 void pango_layout_get_pixel_extents(PangoLayout *, PangoRectangle *, PangoRectangle *);
133 void pango_layout_set_font_description(PangoLayout *, PangoFontDescription *);
134 void pango_layout_set_text(PangoLayout*, const char *, int);
135 void pango_layout_xy_to_index(PangoLayout*, int, int, int*, int*);
136 void pango_layout_index_to_pos(PangoLayout*, int, PangoRectangle*);
137 #endif
138
139 #include <xkbcommon/xkbcommon.h>
140 #include <xkbcommon/xkbcommon-compose.h>
141 #include <xkbcommon/xkbcommon-x11.h>
142
143 #include "xcb.h"
144
145 #undef True
146 #undef False
147
148 #define PANE_DATA_TYPE struct xcb_data
149 #include "core.h"
150
151 enum my_atoms {
152         a_NONE = 0,
153         a_WM_STATE, a_STATE_FULLSCREEN,
154         a_WM_NAME, a_NET_WM_NAME,
155         a_WM_ICON_NAME, a_NET_WM_ICON_NAME,
156         a_WM_PROTOCOLS, a_WM_DELETE_WINDOW,
157         a_NET_WM_PING,
158         a_NET_WM_ICON,
159         a_WM_CLIENT_MACHINE,
160         a_UTF8_STRING,
161         NR_ATOMS
162 };
163 static const char *atom_names[NR_ATOMS] = {
164         [a_NONE]                = "NONE",
165         [a_WM_STATE]            = "_NET_WM_STATE",
166         [a_STATE_FULLSCREEN]    = "_NET_WM_STATE_FULLSCREEN",
167         [a_WM_NAME]             = "WM_NAME",
168         [a_NET_WM_NAME]         = "_NET_WM_NAME",
169         [a_WM_ICON_NAME]        = "WM_ICON_NAME",
170         [a_NET_WM_ICON_NAME]    = "_NET_WM_ICON_NAME",
171         [a_WM_PROTOCOLS]        = "WM_PROTOCOLS",
172         [a_WM_DELETE_WINDOW]    = "WM_DELETE_WINDOW",
173         [a_NET_WM_PING]         = "_NET_WM_PING",
174         [a_NET_WM_ICON]         = "_NET_WM_ICON",
175         [a_WM_CLIENT_MACHINE]   = "WM_CLIENT_MACHINE",
176         [a_UTF8_STRING]         = "UTF8_STRING",
177 };
178
179 struct rgb {
180         double r,g,b;
181 };
182
183 struct xcb_data {
184         xcb_connection_t        *conn safe;
185         char                    *display safe;
186         char                    *disp_auth;
187
188         const xcb_setup_t       *setup safe;
189         const xcb_screen_t      *screen safe;
190         xcb_atom_t              atoms[NR_ATOMS];
191
192         long                    last_event;
193         xcb_window_t            win;
194         xcb_visualtype_t        *visual;
195         cairo_t                 *cairo safe;
196         cairo_surface_t         *surface safe;
197         PangoFontDescription    *fd safe;
198         int                     charwidth, lineheight;
199         cairo_region_t          *need_update;
200
201         bool                    motion_blocked;
202         bool                    in_focus;
203
204         struct xkb_context      *xkb;
205         uint8_t                 first_xkb_event;
206         int32_t                 xkb_device_id;
207         struct xkb_state        *xkb_state;
208         struct xkb_compose_state *compose_state;
209         struct xkb_compose_table *compose_table;
210         struct xkb_keymap       *xkb_keymap;
211
212         struct pids {
213                 pid_t           pid;
214                 struct pids     *next;
215         }                       *pids;
216
217         /* FIXME use hash?? */
218         struct panes {
219                 struct panes    *next;
220                 struct pane     *p safe;
221                 cairo_rectangle_int_t r;
222                 cairo_t         *ctx;
223                 struct rgb      bg;
224                 xcb_pixmap_t    draw;
225                 cairo_surface_t *surface;
226                 cairo_region_t  *need_update;
227         } *panes;
228 };
229 #include "core-pane.h"
230
231 /* panes->r.x is NEVER_DRAWN if the pane has not been drawn */
232 #define NEVER_DRAWN (-60000)
233
234 static struct map *xcb_map;
235 DEF_LOOKUP_CMD(xcb_handle, xcb_map);
236
237 static struct panes *get_pixmap(struct pane *home safe,
238                                 struct pane *p safe)
239 {
240         struct xcb_data *xd = home->data;
241         struct panes **pp, *ps;
242
243         for (pp = &xd->panes; (ps = *pp) != NULL; pp = &(*pp)->next) {
244                 if (ps->p != p)
245                         continue;
246                 if (ps->r.width == p->w && ps->r.height == p->h)
247                         return ps;
248                 *pp = ps->next;
249                 if (ps->r.x != NEVER_DRAWN) {
250                         if (!xd->need_update)
251                                 xd->need_update = cairo_region_create();
252                         cairo_region_union_rectangle(xd->need_update, &ps->r);
253                 }
254                 if (ps->ctx)
255                         cairo_destroy(ps->ctx);
256                 if (ps->surface)
257                         cairo_surface_destroy(ps->surface);
258                 if (ps->draw)
259                         xcb_free_pixmap(xd->conn, ps->draw);
260                 free(ps);
261                 break;
262         }
263         alloc(ps, pane);
264         ps->p = p;
265         ps->r.x = ps->r.y = NEVER_DRAWN;
266         ps->r.width = p->w;
267         ps->r.height = p->h;
268         ps->bg.r = ps->bg.g = ps->bg.b = 0;
269
270         pane_add_notify(home, p, "Notify:Close");
271         ps->next = *pp;
272         *pp = ps;
273         return ps;
274 }
275
276 static void instantiate_pixmap(struct xcb_data *xd safe,
277                           struct panes *ps safe)
278 {
279         ps->draw = xcb_generate_id(xd->conn);
280         xcb_create_pixmap(xd->conn, xd->screen->root_depth, ps->draw,
281                           xd->win, ps->r.width, ps->r.height);
282         ps->surface = cairo_xcb_surface_create(
283                 xd->conn, ps->draw, xd->visual, ps->r.width, ps->r.height);
284         if (!ps->surface)
285                 goto free_ps;
286         ps->ctx = cairo_create(ps->surface);
287         if (!ps->ctx)
288                 goto free_surface;
289         cairo_set_source_rgb(ps->ctx, ps->bg.r, ps->bg.g, ps->bg.b);
290         cairo_paint(ps->ctx);
291         return;
292
293 free_surface:
294         cairo_surface_destroy(ps->surface);
295         ps->surface = NULL;
296 free_ps:
297         xcb_free_pixmap(xd->conn, ps->draw);
298         ps->draw = 0;
299 }
300
301 static struct panes *find_pixmap(struct xcb_data *xd safe, struct pane *p safe,
302                                  int *xp safe, int *yp safe)
303 {
304         int x = 0, y = 0;
305         struct panes *ret = NULL;
306
307         while (!ret && p->parent != p) {
308                 struct panes *ps;
309                 for (ps = xd->panes; ps ; ps = ps->next)
310                         if (ps->p == p) {
311                                 ret = ps;
312                                 break;
313                         }
314                 if (!ret) {
315                         x += p->x;
316                         y += p->y;
317                         p = p->parent;
318                 }
319         }
320         *xp = x;
321         *yp = y;
322         return ret;
323 }
324
325 static inline double cvt(int i)
326 {
327         return (float)i / 1000.0;
328 }
329
330 static void parse_attrs(
331         struct pane *home safe, const char *cattrs, int scale,
332         struct rgb *fgp, struct rgb *bgp, bool *underline,
333         PangoFontDescription **fdp)
334 {
335         char *attrs = strdup(cattrs ?: "");
336         char *ap = attrs;
337         char *word;
338         char *fg = NULL, *bg = NULL;
339         bool ul = False;
340         bool inv = False;
341         int size = 12*1000;
342         PangoFontDescription *fd = NULL;
343         PangoStyle style = PANGO_STYLE_NORMAL;
344         PangoVariant variant = PANGO_VARIANT_NORMAL;
345         PangoWeight weight = PANGO_WEIGHT_NORMAL;
346
347         if (fdp) {
348                 fd = pango_font_description_new();
349                 *fdp = fd;
350                 pango_font_description_set_family_static(fd, "monospace");
351         }
352
353         while ((word = strsep(&ap, ",")) != NULL) {
354                 if (fd && strstarts(word, "family:"))
355                         pango_font_description_set_family(fd, word+7);
356                 if (strcmp(word, "large") == 0)
357                         size = 14 * 1000;
358                 if (strcmp(word, "small") == 0)
359                         size = 9 * 1000;
360                 if (isdigit(word[0])) {
361                         char *end = NULL;
362                         double s = strtod(word, &end);
363                         if (end && end != word && !*end)
364                                 size = trunc(s * 1000.0);
365                         else
366                                 size = 10*1000;
367                 }
368                 if (strcmp(word, "oblique") == 0)
369                         style = PANGO_STYLE_OBLIQUE;
370                 if (strcmp(word, "italic") == 0)
371                         style = PANGO_STYLE_ITALIC;
372                 if (strcmp(word, "normal") == 0)
373                         style = PANGO_STYLE_NORMAL;
374                 if (strcmp(word, "small-caps") == 0)
375                         variant = PANGO_VARIANT_SMALL_CAPS;
376
377                 if (strcmp(word, "bold") == 0)
378                         weight = PANGO_WEIGHT_BOLD;
379                 if (strcmp(word, "nobold") == 0)
380                         weight = PANGO_WEIGHT_NORMAL;
381
382                 if (strstarts(word, "fg:"))
383                         fg = word + 3;
384                 if (strstarts(word, "bg:"))
385                         bg = word + 3;
386                 if (strcmp(word, "inverse") == 0)
387                         inv = True;
388                 if (strcmp(word, "noinverse") == 0)
389                         inv = False;
390                 if (strcmp(word, "underline") == 0)
391                         ul = True;
392                 if (strcmp(word, "nounderline") == 0)
393                         ul = False;
394         }
395
396         if (inv) {
397                 char *t = bg;
398                 bg = fg;
399                 fg = t;
400                 if (!fg)
401                         fg = "white";
402                 if (!bg)
403                         bg = "black";
404         } else if (!fg)
405                 fg = "black";
406
407         if (fg && fgp) {
408                 struct call_return ret = call_ret(all, "colour:map", home,
409                                                   0, NULL, fg);
410                 fgp->r = cvt(ret.i);
411                 fgp->g = cvt(ret.i2);
412                 fgp->b = cvt(ret.x);
413         } else if (fgp)
414                 fgp->g = -1;
415         if (bg && bgp) {
416                 struct call_return ret = call_ret(all, "colour:map", home,
417                                                   0, NULL, bg);
418                 bgp->r = cvt(ret.i);
419                 bgp->g = cvt(ret.i2);
420                 bgp->b = cvt(ret.x);
421         } else if (bgp)
422                 bgp->g = -1;
423         if (fd) {
424                 pango_font_description_set_size(fd, PANGO_SCALE * size /1000 * scale / 1000);
425                 if (style != PANGO_STYLE_NORMAL)
426                         pango_font_description_set_style(fd, style);
427                 if (variant != PANGO_VARIANT_NORMAL)
428                         pango_font_description_set_variant(fd, variant);
429                 if (weight != PANGO_WEIGHT_NORMAL)
430                         pango_font_description_set_weight(fd, weight);
431         }
432         if (underline)
433                 *underline = ul;
434         free(attrs);
435 }
436
437 DEF_CB(cnt_disp)
438 {
439         struct call_return *cr = container_of(ci->comm, struct call_return, c);
440
441         cr->i += 1;
442         return 1;
443 }
444
445 DEF_CMD(xcb_close_display)
446 {
447         /* If this is only display, then refuse to close this one */
448         struct call_return cr;
449         char *nc = attr_find(ci->home->attrs, "no-close");
450
451         if (nc) {
452                 call("Message", ci->focus, 0, NULL, nc);
453                 return 1;
454         }
455         cr.c = cnt_disp;
456         cr.i = 0;
457         call_comm("editor:notify:all-displays", ci->focus, &cr.c);
458         if (cr.i > 1)
459                 return Efallthrough;
460         else
461                 call("Message", ci->focus, 0, NULL,
462                      "Cannot close only window.");
463         return 1;
464 }
465
466 DEF_CMD(xcb_set_attr)
467 {
468         const char *attr = ci->str2;
469
470         if (!attr)
471                 attr = ksuffix(ci, "Display:set:");
472         attr_set_str(&ci->home->attrs, attr, ci->str);
473         return 1;
474 }
475
476 static void wait_for(struct xcb_data *xd safe)
477 {
478         struct pids **pp = &xd->pids;
479
480         while (*pp) {
481                 struct pids *p = *pp;
482                 if (waitpid(p->pid, NULL, WNOHANG) > 0) {
483                         *pp = p->next;
484                         free(p);
485                 } else
486                         pp = &p->next;
487         }
488 }
489
490 DEF_CMD(xcb_external_viewer)
491 {
492         struct xcb_data *xd = ci->home->data;
493         const char *path = ci->str;
494         struct pids *p;
495         int pid;
496         int fd;
497
498         if (!path)
499                 return Enoarg;
500         switch (pid = fork()) {
501         case -1:
502                 return Efail;
503         case 0: /* Child */
504                 setenv("DISPLAY", xd->display, 1);
505                 if (xd->disp_auth)
506                         setenv("XAUTHORITY", xd->disp_auth, 1);
507                 fd = open("/dev/null", O_RDWR);
508                 if (fd) {
509                         dup2(fd, 0);
510                         dup2(fd, 1);
511                         dup2(fd, 2);
512                         if (fd > 2)
513                                 close(fd);
514                 }
515                 execlp("xdg-open", "xdg-open", path, NULL);
516                 exit(1);
517         default: /* parent */
518                 p = malloc(sizeof(*p));
519                 p->pid = pid;
520                 p->next = xd->pids;
521                 xd->pids = p;
522                 break;
523         }
524         wait_for(xd);
525         return 1;
526 }
527
528 DEF_CMD(xcb_fullscreen)
529 {
530         struct xcb_data *xd = ci->home->data;
531         xcb_client_message_event_t msg = {};
532
533         msg.response_type = XCB_CLIENT_MESSAGE;
534         msg.format = 32;
535         msg.window = xd->win;
536         msg.type = xd->atoms[a_WM_STATE];
537         if (ci->num > 0)
538                 msg.data.data32[0] = 1; /* ADD */
539         else
540                 msg.data.data32[0] = 0; /* REMOVE */
541         msg.data.data32[1] = xd->atoms[a_STATE_FULLSCREEN];
542         msg.data.data32[2] = 0;
543         msg.data.data32[3] = 1; /* source indicator */
544
545         xcb_send_event(xd->conn, 0, xd->screen->root,
546                        XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
547                        XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT,
548                        (void*)&msg);
549         xcb_flush(xd->conn);
550         return 1;
551 }
552
553 static void panes_free(struct xcb_data *xd safe)
554 {
555         while (xd->panes) {
556                 struct panes *ps = xd->panes;
557                 xd->panes = ps->next;
558                 if (ps->ctx)
559                         cairo_destroy(ps->ctx);
560                 if (ps->surface)
561                         cairo_surface_destroy(ps->surface);
562                 if (ps->draw)
563                         xcb_free_pixmap(xd->conn, ps->draw);
564                 free(ps);
565         }
566 }
567
568 static void kbd_free(struct xcb_data *xd safe);
569
570 DEF_CMD(xcb_close)
571 {
572         struct xcb_data *xd = ci->home->data;
573
574         xcb_destroy_window(xd->conn, xd->win);
575         kbd_free(xd);
576         panes_free(xd);
577
578         pango_font_description_free(xd->fd);
579         cairo_destroy(xd->cairo);
580         cairo_device_finish(cairo_surface_get_device(xd->surface));
581         cairo_surface_destroy(xd->surface);
582         free(xd->display);
583         free(xd->disp_auth);
584         xcb_disconnect(xd->conn);
585         if (xd->need_update)
586                 cairo_region_destroy(xd->need_update);
587         return 1;
588 }
589
590 DEF_CMD(xcb_clear)
591 {
592         struct xcb_data *xd = ci->home->data;
593         const char *attr = ci->str;
594         struct panes *src = NULL, *dest;
595         struct rgb bg;
596         int x=0, y=0;
597         cairo_rectangle_int_t r;
598
599         if (attr) {
600                 parse_attrs(ci->home, attr, PANGO_SCALE, NULL, &bg, NULL, NULL);
601                 if (bg.g < 0)
602                         bg.r = bg.g = bg.b = 1.0;
603         } else {
604                 src = find_pixmap(xd, ci->focus->parent, &x, &y);
605                 x += ci->focus->x;
606                 y += ci->focus->y;
607                 if (!src)
608                         bg.r = bg.g = bg.b = 1.0;
609                 else if (src->bg.g >= 0)
610                         bg = src->bg;
611                 else if (src->surface == NULL)
612                         bg.r = bg.g = bg.b = 1.0;
613                 else
614                         bg.g = -1;
615         }
616
617         dest = get_pixmap(ci->home, ci->focus);
618         if (!dest)
619                 return 1;
620         if (bg.g >= 0) {
621                 if (dest->ctx) {
622                         cairo_set_source_rgb(dest->ctx, bg.r, bg.g, bg.b);
623                         cairo_paint(dest->ctx);
624                 }
625                 dest->bg = bg;
626         } else if (src) {
627                 if (!dest->ctx)
628                         instantiate_pixmap(xd, dest);
629                 if (dest->ctx) {
630                         cairo_set_source_surface(dest->ctx, src->surface, -x, -y);
631                         cairo_paint(dest->ctx);
632                         dest->bg.g = -1;
633                 }
634         }
635         pane_damaged(ci->home, DAMAGED_POSTORDER);
636
637         if (!dest->need_update)
638                 dest->need_update = cairo_region_create();
639         r.x = 0;
640         r.y = 0;
641         r.width = ci->focus->w;
642         r.height = ci->focus->h;
643         cairo_region_union_rectangle(dest->need_update, &r);
644         return 1;
645 }
646
647 DEF_CMD(xcb_text_size)
648 {
649         struct xcb_data *xd = ci->home->data;
650         const char *attr = ci->str2 ?: "";
651         const char *str = ci->str ?: "";
652         int scale = ci->num2;
653         PangoLayout *layout;
654         PangoFontDescription *fd;
655         PangoRectangle log;
656         int baseline;
657         int max_bytes;
658
659         if (scale <= 0)
660                 scale = 1000;
661         if (!utf8_valid(str))
662                 str = "*INV*";
663         parse_attrs(ci->home, attr, scale, NULL, NULL, NULL, &fd);
664         /* If we use an empty string, line-height is wrong */
665         layout = pango_cairo_create_layout(xd->cairo);
666         pango_layout_set_text(layout, *str ? str : "M", -1);
667         pango_layout_set_font_description(layout, fd);
668         pango_layout_get_pixel_extents(layout, NULL, &log);
669         baseline = pango_layout_get_baseline(layout) / PANGO_SCALE;
670
671         if (ci->num < 0)
672                 max_bytes = 0;
673         else if (log.width <= ci->num)
674                 max_bytes = strlen(str);
675         else
676                 pango_layout_xy_to_index(layout, PANGO_SCALE*ci->num,
677                                          baseline, &max_bytes, NULL);
678
679         comm_call(ci->comm2, "cb", ci->focus, max_bytes, NULL, NULL,
680                   baseline, NULL, NULL,
681                   str && *str ? log.width : 0,
682                   log.height);
683
684         pango_font_description_free(fd);
685         g_object_unref(layout);
686         return 1;
687 }
688
689 DEF_CMD(xcb_draw_text)
690 {
691         struct xcb_data *xd = ci->home->data;
692         const char *str = ci->str;
693         const char *attr = ci->str2;
694         int scale = 1000;
695         struct panes *ps;
696         cairo_t *ctx;
697         PangoLayout *layout;
698         PangoFontDescription *fd;
699         PangoRectangle log;
700         struct rgb fg, bg;
701         bool ul;
702         int baseline;
703         int xo = 0, yo = 0;
704         int x,y;
705
706         if (!str)
707                 return Enoarg;
708         ps = find_pixmap(xd, ci->focus, &xo, &yo);
709         if (!ps)
710                 return Einval;
711         if (!ps->ctx)
712                 instantiate_pixmap(xd, ps);
713         ps->bg.g = -1;
714         ctx = ps->ctx;
715         if (!ctx)
716                 return Efail;
717
718         if (!utf8_valid(str))
719                 str = "*INV*";
720
721         pane_damaged(ci->home, DAMAGED_POSTORDER);
722
723         if (ci->num2 > 0)
724                 scale = ci->num2 * 10 / xd->charwidth;
725
726         parse_attrs(ci->home, attr, scale, &fg, &bg, &ul, &fd);
727
728         x = ci->x + xo;
729         y = ci->y + yo;
730         layout = pango_cairo_create_layout(ctx);
731         pango_layout_set_text(layout, str, -1);
732         pango_layout_set_font_description(layout, fd);
733         pango_layout_get_pixel_extents(layout, NULL, &log);
734         baseline = pango_layout_get_baseline(layout) / PANGO_SCALE;
735         cairo_save(ctx);
736         if (bg.g >= 0) {
737                 cairo_set_source_rgb(ctx, bg.r, bg.g, bg.b);
738                 cairo_rectangle(ctx, x+log.x, y - baseline + log.y,
739                                 log.width, log.height);
740                 cairo_fill(ctx);
741         }
742         cairo_set_source_rgb(ctx, fg.r, fg.g, fg.b);
743         if (ul) {
744                 /* Draw an underline */
745                 cairo_rectangle(ctx, x+log.x, y+2+log.y,
746                                 log.width, 1);
747                 cairo_fill(ctx);
748         }
749
750         cairo_move_to(ctx, x, y - baseline);
751         pango_cairo_show_layout(ctx, layout);
752         cairo_stroke(ctx);
753
754         if (ci->num >= 0) {
755                 /* draw a cursor - outline box if not in-focus,
756                  * inverse-video if it is.
757                  */
758                 PangoRectangle curs;
759                 bool in_focus = xd->in_focus;
760                 struct pane *f = ci->focus;
761
762                 pango_layout_index_to_pos(layout, ci->num, &curs);
763                 if (curs.width <= 0) {
764                         /* EOL?*/
765                         pango_layout_set_text(layout, "M", 1);
766                         pango_layout_get_extents(layout, NULL, &log);
767                         curs.width = log.width;
768                 }
769                 cairo_rectangle(ctx, x+curs.x/PANGO_SCALE, y-baseline+curs.y/PANGO_SCALE,
770                                 (curs.width - PANGO_SCALE/2) / PANGO_SCALE,
771                                 (curs.height - PANGO_SCALE/2) / PANGO_SCALE);
772                 cairo_set_line_width(ctx, 1.0);
773                 cairo_stroke(ctx);
774
775                 while (in_focus && f->parent->parent != f &&
776                        f->parent != ci->home) {
777                         if (f->parent->focus != f && f->z >= 0)
778                                 in_focus = False;
779                         f = f->parent;
780                 }
781                 if (in_focus) {
782                         if (fg.g >= 0)
783                                 cairo_set_source_rgb(ctx, fg.r, fg.g, fg.b);
784                         cairo_rectangle(ctx, x+curs.x/PANGO_SCALE,
785                                         y-baseline+curs.y/PANGO_SCALE,
786                                         curs.width / PANGO_SCALE,
787                                         curs.height / PANGO_SCALE);
788                         cairo_fill(ctx);
789                         if (ci->num < (int)strlen(str)) {
790                                 const char *cp = str + ci->num;
791                                 get_utf8(&cp, NULL);
792                                 pango_layout_set_text(layout, str + ci->num,
793                                                       cp - (str + ci->num));
794                                 if (bg.g >= 0)
795                                         cairo_set_source_rgb(ctx, bg.r, bg.g, bg.b);
796                                 else
797                                         cairo_set_source_rgb(ctx, 1.0, 1.0, 1.0);
798                                 cairo_move_to(ctx,
799                                               x + curs.x / PANGO_SCALE,
800                                               y - baseline + curs.y / PANGO_SCALE);
801                                 pango_cairo_show_layout(ctx, layout);
802                         }
803                 }
804         }
805         cairo_restore(ctx);
806         pango_font_description_free(fd);
807         g_object_unref(layout);
808         return 1;
809 }
810
811 DEF_CMD(xcb_draw_image)
812 {
813         /* 'str' identifies the image. Options are:
814          *     file:filename  - load file from fs
815          *     comm:command   - run command collecting bytes
816          * 'num' is '16' if image should be stretched to fill pane
817          * Otherwise it is the 'or' of
818          *   0,1,2 for left/middle/right in x direction
819          *   0,4,8 for top/middle/bottom in y direction
820          * only one of these can be used as image will fill pane
821          * in other direction.
822          * If 'x' and 'y' are both positive, draw cursor box at
823          * p->cx, p->cy of a size so that 'x' will fit across and
824          * 'y' will fit down.
825          */
826         struct xcb_data *xd = ci->home->data;
827         bool stretch = ci->num & 16;
828         int pos = ci->num;
829         int w = ci->focus->w, h = ci->focus->h;
830         int x = 0, y = 0;
831         int xo, yo;
832         int stride;
833         struct panes *ps;
834         MagickBooleanType status;
835         MagickWand *wd;
836         int fmt[2];
837         unsigned char *buf;
838         cairo_surface_t *surface;
839
840         if (!ci->str)
841                 return Enoarg;
842         ps = find_pixmap(xd, ci->focus, &xo, &yo);
843         if (!ps)
844                 return Einval;
845         if (!ps->ctx)
846                 instantiate_pixmap(xd, ps);
847         ps->bg.g = -1;
848         if (!ps->ctx)
849                 return Efail;
850         if (strstarts(ci->str, "file:")) {
851                 wd = NewMagickWand();
852                 status = MagickReadImage(wd, ci->str + 5);
853                 if (status == MagickFalse) {
854                         DestroyMagickWand(wd);
855                         return Efail;
856                 }
857         } else if (strstarts(ci->str, "comm:")) {
858                 struct call_return cr;
859                 wd = NewMagickWand();
860                 cr = call_ret(bytes, ci->str+5, ci->focus, 0, NULL, ci->str2);
861                 if (!cr.s) {
862                         DestroyMagickWand(wd);
863                         return Efail;
864                 }
865                 status = MagickReadImageBlob(wd, cr.s, cr.i);
866                 free(cr.s);
867                 if (status == MagickFalse) {
868                         DestroyMagickWand(wd);
869                         return Efail;
870                 }
871         } else
872                 return Einval;
873
874         MagickAutoOrientImage(wd);
875         if (!stretch) {
876                 int ih = MagickGetImageHeight(wd);
877                 int iw = MagickGetImageWidth(wd);
878
879                 if (iw <= 0 || iw <= 0) {
880                         DestroyMagickWand(wd);
881                         return Efail;
882                 }
883                 if (iw * h > ih * w) {
884                         /* Image is wider than space, use less height */
885                         ih = ih * w / iw;
886                         switch(pos & (8+4)) {
887                         case 4: /* center */
888                                 y = (h - ih) / 2; break;
889                         case 8: /* bottom */
890                                 y = h - ih; break;
891                         }
892                         h = ih;
893                 } else {
894                         /* image is too tall, use less width */
895                         iw = iw * h / ih;
896                         switch (pos & (1+2)) {
897                         case 1: /* center */
898                                 x = (w - iw) / 2; break;
899                         case 2: /* right */
900                                 x = w - iw ; break;
901                         }
902                         w = iw;
903                 }
904         }
905         MagickAdaptiveResizeImage(wd, w, h);
906         stride = cairo_format_stride_for_width(CAIRO_FORMAT_RGB24, w);
907         buf = malloc(h * stride);
908         // Cairo expects 32bit values with A in the high byte, then RGB.
909         // Magick provides 8bit values in the order requests.
910         // So depending on byte order, a different string is needed
911
912         fmt[0] = ('A'<<24) | ('R' << 16) | ('G' << 8) | ('B' << 0);
913         fmt[1] = 0;
914         MagickExportImagePixels(wd, 0, 0, w, h, (char*)fmt, CharPixel, buf);
915         surface = cairo_image_surface_create_for_data(buf, CAIRO_FORMAT_ARGB32,
916                                                       w, h, stride);
917         cairo_set_source_surface(ps->ctx, surface, x + xo, y + yo);
918         cairo_paint(ps->ctx);
919         cairo_surface_destroy(surface);
920         free(buf);
921
922         if (ci->x > 0 && ci->y > 0 && ci->focus->cx >= 0) {
923                 struct pane *p = ci->focus;
924                 cairo_rectangle(ps->ctx, p->cx + xo, p->cy + yo,
925                                 w/ci->x, h/ci->y);
926                 cairo_set_line_width(ps->ctx, 1.0);
927                 cairo_set_source_rgb(ps->ctx, 1.0, 0.0, 0.0);
928                 cairo_stroke(ps->ctx);
929         }
930         DestroyMagickWand(wd);
931
932         pane_damaged(ci->home, DAMAGED_POSTORDER);
933
934         return 1;
935 }
936
937 DEF_CMD(xcb_image_size)
938 {
939         MagickBooleanType status;
940         MagickWand *wd;
941         int ih, iw;
942
943         if (!ci->str)
944                 return Enoarg;
945         if (strstarts(ci->str, "file:")) {
946                 wd = NewMagickWand();
947                 status = MagickReadImage(wd, ci->str + 5);
948                 if (status == MagickFalse) {
949                         DestroyMagickWand(wd);
950                         return Efail;
951                 }
952         } else if (strstarts(ci->str, "comm:")) {
953                 struct call_return cr;
954                 wd = NewMagickWand();
955                 cr = call_ret(bytes, ci->str+5, ci->focus, 0, NULL, ci->str2);
956                 if (!cr.s) {
957                         DestroyMagickWand(wd);
958                         return Efail;
959                 }
960                 status = MagickReadImageBlob(wd, cr.s, cr.i);
961                 free(cr.s);
962                 if (status == MagickFalse) {
963                         DestroyMagickWand(wd);
964                         return Efail;
965                 }
966         } else
967                 return Einval;
968
969         MagickAutoOrientImage(wd);
970         ih = MagickGetImageHeight(wd);
971         iw = MagickGetImageWidth(wd);
972
973         DestroyMagickWand(wd);
974         comm_call(ci->comm2, "callback:size", ci->focus,
975                   0, NULL, NULL, 0, NULL, NULL,
976                   iw, ih);
977         return 1;
978 }
979
980 static struct panes *sort_split(struct panes *p)
981 {
982         /* consider 'p' to be a list of panes with
983          * ordered subsets (ordered by p->abs_z).
984          * Remove every other such subset and return them
985          * linked together.
986          * If p is ordered, this means we return NULL.
987          */
988         struct panes *ret, **end = &ret;
989         struct panes *next;
990
991         for (; p && p->next; p = next) {
992                 /* If these are not ordered, attach p->next at
993                  * 'end', and make 'end' point to &p->next.
994                  */
995                 next = p->next;
996                 if (p->p->abs_z < next->p->abs_z) {
997                         *end = next;
998                         end = &p->next;
999                 }
1000         }
1001         *end = NULL;
1002         return ret;
1003 }
1004
1005 static struct panes *sort_merge(struct panes *p1, struct panes *p2)
1006 {
1007         /* merge p1 and p2 and return result */
1008         struct panes *ret, **end = &ret;
1009         struct panes *prev = NULL;
1010
1011         while (p1 && p2) {
1012                 /* Make p1 the largest (or be added first.
1013                  * Then in prev is between them add p2, else p1
1014                  */
1015                 if (p1->p->abs_z < p2->p->abs_z) {
1016                         struct panes *t = p1;
1017                         p1 = p2;
1018                         p2 = t;
1019                 }
1020                 if (prev &&
1021                     p1->p->abs_z > prev->p->abs_z &&
1022                     prev->p->abs_z >= p2->p->abs_z) {
1023                         /* p2 is the better choice */
1024                         prev = p2;
1025                         p2 = p2->next;
1026                 } else {
1027                         prev = p1;
1028                         p1 = p1->next;
1029                 }
1030                 *end = prev;
1031                 end = &prev->next;
1032         }
1033         if (p1)
1034                 *end = p1;
1035         else
1036                 *end = p2;
1037         return ret;
1038 }
1039
1040 DEF_CMD(xcb_refresh_post)
1041 {
1042         struct xcb_data *xd = ci->home->data;
1043         struct panes *ps;
1044
1045         time_start(TIME_WINDOW);
1046         /* First: ensure panes are sorted */
1047         while ((ps = sort_split(xd->panes)) != NULL)
1048                 xd->panes = sort_merge(xd->panes, ps);
1049
1050         /* Then merge all update rectanges, checking for movement */
1051         if (!xd->need_update)
1052                 xd->need_update = cairo_region_create();
1053         for (ps = xd->panes; ps ; ps = ps->next)
1054         {
1055                 struct xy rel;
1056
1057                 rel = pane_mapxy(ps->p, ci->home, 0, 0, False);
1058                 if (ps->r.x == NEVER_DRAWN) {
1059                         ps->r.x = rel.x;
1060                         ps->r.y = rel.y;
1061                         cairo_region_union_rectangle(xd->need_update, &ps->r);
1062                 } else if (rel.x != ps->r.x || rel.y != ps->r.y) {
1063                         /* Moved, so refresh all.
1064                          * This rectangle might be too big if it is clipped,
1065                          * but that doesn't really matter.
1066                          */
1067                         cairo_region_union_rectangle(xd->need_update, &ps->r);
1068                         ps->r.x = rel.x;
1069                         ps->r.y = rel.y;
1070                         cairo_region_union_rectangle(xd->need_update, &ps->r);
1071                 } else if (ps->need_update) {
1072                         cairo_region_translate(ps->need_update, rel.x, rel.y);
1073                         cairo_region_union(xd->need_update, ps->need_update);
1074                 }
1075                 if (ps->need_update)
1076                         cairo_region_destroy(ps->need_update);
1077                 ps->need_update = NULL;
1078         }
1079         /* Now copy all panes onto the window where an update is needed */
1080         for (ps = xd->panes; ps ; ps = ps->next) {
1081                 struct xy rel, lo, hi;
1082                 cairo_region_t *cr;
1083                 cairo_rectangle_int_t r;
1084                 int nr, i;
1085
1086                 cr = cairo_region_copy(xd->need_update);
1087
1088                 rel = pane_mapxy(ps->p, ci->home, 0, 0, False);
1089
1090                 cairo_save(xd->cairo);
1091                 if (ps->bg.g >= 0)
1092                         cairo_set_source_rgb(xd->cairo,
1093                                              ps->bg.r, ps->bg.g, ps->bg.b);
1094                 else
1095                         cairo_set_source_surface(xd->cairo, ps->surface,
1096                                                  rel.x, rel.y);
1097
1098                 lo = pane_mapxy(ps->p, ci->home, 0, 0, True);
1099                 hi = pane_mapxy(ps->p, ci->home, ps->r.width, ps->r.height, True);
1100                 r.x = lo.x; r.y = lo.y;
1101                 r.width = hi.x - lo.x; r.height = hi.y - lo.y;
1102                 cairo_region_intersect_rectangle(cr, &r);
1103                 cairo_region_subtract_rectangle(xd->need_update, &r);
1104                 nr = cairo_region_num_rectangles(cr);
1105                 for (i = 0; i < nr; i++) {
1106                         cairo_region_get_rectangle(cr, i, &r);
1107                         cairo_rectangle(xd->cairo, r.x, r.y, r.width, r.height);
1108                         cairo_fill(xd->cairo);
1109                 }
1110                 cairo_restore(xd->cairo);
1111         }
1112
1113         cairo_region_destroy(xd->need_update);
1114         xd->need_update = NULL;
1115         time_stop(TIME_WINDOW);
1116         xcb_flush(xd->conn);
1117         return 1;
1118 }
1119
1120 DEF_CMD(xcb_refresh_size)
1121 {
1122         /* FIXME: should I consider resizing the window?
1123          * For now, just ensure we redraw everything.
1124          */
1125         struct xcb_data *xd = ci->home->data;
1126         cairo_rectangle_int_t r = {
1127                 .x = 0,
1128                 .y = 0,
1129                 .width = ci->home->w,
1130                 .height = ci->home->h,
1131         };
1132
1133         if (!xd->need_update)
1134                 xd->need_update = cairo_region_create();
1135         cairo_region_union_rectangle(xd->need_update, &r);
1136         /* Ask common code to notify children */
1137         return Efallthrough;
1138 }
1139
1140 DEF_CMD(xcb_pane_close)
1141 {
1142         struct xcb_data *xd = ci->home->data;
1143         struct panes **pp, *ps;
1144
1145         for (pp = &xd->panes; (ps = *pp) != NULL; pp = &(*pp)->next) {
1146                 if (ps->p != ci->focus)
1147                         continue;
1148
1149                 if (!xd->need_update)
1150                         xd->need_update = cairo_region_create();
1151                 if (ps->r.x != NEVER_DRAWN)
1152                         cairo_region_union_rectangle(xd->need_update, &ps->r);
1153
1154                 *pp = ps->next;
1155                 ps->next = NULL;
1156                 if (ps->need_update)
1157                         cairo_region_destroy(ps->need_update);
1158                 cairo_destroy(ps->ctx);
1159                 cairo_surface_destroy(ps->surface);
1160                 xcb_free_pixmap(xd->conn, ps->draw);
1161                 free(ps);
1162                 pane_damaged(ci->home, DAMAGED_POSTORDER);
1163                 break;
1164         }
1165         return 1;
1166 }
1167
1168 DEF_CMD(xcb_notify_display)
1169 {
1170         struct xcb_data *xd = ci->home->data;
1171         comm_call(ci->comm2, "callback:display", ci->home, xd->last_event);
1172         return 1;
1173 }
1174
1175 static void handle_button(struct pane *home safe,
1176                           xcb_button_press_event_t *be safe)
1177 {
1178         struct xcb_data *xd = home->data;
1179         bool press = (be->response_type & 0x7f) == XCB_BUTTON_PRESS;
1180         char mod[2+2+2+1];
1181         char key[2+2+2+9+1+1];
1182
1183         xcb_set_input_focus(xd->conn, XCB_INPUT_FOCUS_POINTER_ROOT,
1184                             xd->win, XCB_CURRENT_TIME);
1185         mod[0] = 0;
1186         if (press) {
1187                 xd->motion_blocked = False;
1188                 if (be->state & XCB_KEY_BUT_MASK_MOD_1)
1189                         strcat(mod, ":A");
1190                 if (be->state & XCB_KEY_BUT_MASK_CONTROL)
1191                         strcat(mod, ":C");
1192                 if (be->state & XCB_KEY_BUT_MASK_SHIFT)
1193                         strcat(mod, ":S");
1194                 strcpy(key, mod);
1195                 strcat(key, ":Press-X");
1196         } else if (be->detail >= 4)
1197                 /* ignore 'release' for scroll wheel */
1198                 return;
1199         else
1200                 strcpy(key, ":Release-X");
1201
1202         key[strlen(key) - 1] = '0' + be->detail;
1203         xd->last_event = time(NULL);
1204         call("Mouse-event", home, be->detail, NULL, key,
1205              press?1:2, NULL, mod,
1206              be->event_x, be->event_y);
1207 }
1208
1209 static void handle_motion(struct pane *home safe,
1210                           xcb_motion_notify_event_t *mne safe)
1211 {
1212         struct xcb_data *xd = home->data;
1213         xcb_query_pointer_cookie_t c;
1214         xcb_query_pointer_reply_t *qpr;
1215         int ret;
1216         int x = mne->event_x, y = mne->event_y;
1217
1218         if (xd->motion_blocked)
1219                 return;
1220         ret = call("Mouse-event", home, 0, NULL, ":Motion",
1221                    3, NULL, NULL, x, y);
1222         if (ret <= 0)
1223                 xd->motion_blocked = True;
1224
1225         /* This doesn't seem to be needed, but the spec says
1226          * I should do this when using POINTER_MOTION_HINT
1227          */
1228         c = xcb_query_pointer(xd->conn, xd->win);
1229         qpr = xcb_query_pointer_reply(xd->conn, c, NULL);
1230         free(qpr);
1231 }
1232
1233 static void handle_focus(struct pane *home safe, xcb_focus_in_event_t *fie safe)
1234 {
1235         struct xcb_data *xd = home->data;
1236         bool in = (fie->response_type & 0x7f) == XCB_FOCUS_IN;
1237         struct pane *p;
1238         struct mark *pt;
1239
1240         xd->in_focus = in;
1241         p = pane_leaf(home);
1242         pt = call_ret(mark, "doc:point", p);
1243         if (pt)
1244                 call("view:changed", p, 0, pt);
1245         if (in)
1246                 call("pane:refocus", home);
1247 }
1248
1249 static bool select_xkb_events_for_device(xcb_connection_t *conn,
1250                                          int32_t device_id)
1251 {
1252         xcb_generic_error_t *error;
1253         xcb_void_cookie_t cookie;
1254
1255         enum {
1256                 required_events =
1257                         (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
1258                          XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
1259                          XCB_XKB_EVENT_TYPE_STATE_NOTIFY),
1260
1261                 required_nkn_details =
1262                         (XCB_XKB_NKN_DETAIL_KEYCODES),
1263
1264                 required_map_parts =
1265                         (XCB_XKB_MAP_PART_KEY_TYPES |
1266                          XCB_XKB_MAP_PART_KEY_SYMS |
1267                          XCB_XKB_MAP_PART_MODIFIER_MAP |
1268                          XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
1269                          XCB_XKB_MAP_PART_KEY_ACTIONS |
1270                          XCB_XKB_MAP_PART_VIRTUAL_MODS |
1271                          XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP),
1272
1273                 required_state_details =
1274                         (XCB_XKB_STATE_PART_MODIFIER_BASE |
1275                          XCB_XKB_STATE_PART_MODIFIER_LATCH |
1276                          XCB_XKB_STATE_PART_MODIFIER_LOCK |
1277                          XCB_XKB_STATE_PART_GROUP_BASE |
1278                          XCB_XKB_STATE_PART_GROUP_LATCH |
1279                          XCB_XKB_STATE_PART_GROUP_LOCK),
1280         };
1281
1282         static const xcb_xkb_select_events_details_t details = {
1283                 .affectNewKeyboard = required_nkn_details,
1284                 .newKeyboardDetails = required_nkn_details,
1285                 .affectState = required_state_details,
1286                 .stateDetails = required_state_details,
1287         };
1288
1289         cookie = xcb_xkb_select_events_aux_checked(
1290                 conn,
1291                 device_id,
1292                 required_events,        /* affectWhich */
1293                 0,                      /* clear */
1294                 0,                      /* selectAll */
1295                 required_map_parts,     /* affectMap */
1296                 required_map_parts,     /* map */
1297                 &details);              /* details */
1298
1299         error = xcb_request_check(conn, cookie);
1300         if (error) {
1301                 free(error);
1302                 return False;
1303         }
1304
1305         return True;
1306 }
1307
1308 static bool update_keymap(struct xcb_data *xd safe)
1309 {
1310         struct xkb_keymap *new_keymap;
1311         struct xkb_state *new_state;
1312
1313         new_keymap = xkb_x11_keymap_new_from_device(xd->xkb, xd->conn,
1314                                                     xd->xkb_device_id,
1315                                                     XKB_KEYMAP_COMPILE_NO_FLAGS);
1316         if (!new_keymap)
1317                 return False;
1318
1319         new_state = xkb_x11_state_new_from_device(new_keymap, xd->conn,
1320                                                   xd->xkb_device_id);
1321         if (!new_state) {
1322                 xkb_keymap_unref(new_keymap);
1323                 return False;
1324         }
1325
1326         xkb_state_unref(xd->xkb_state);
1327         xkb_keymap_unref(xd->xkb_keymap);
1328         xd->xkb_keymap = new_keymap;
1329         xd->xkb_state = new_state;
1330         return True;
1331 }
1332
1333 static bool kbd_setup(struct xcb_data *xd safe)
1334 {
1335         int ret;
1336         const char *locale;
1337
1338         ret = xkb_x11_setup_xkb_extension(xd->conn,
1339                                           XKB_X11_MIN_MAJOR_XKB_VERSION,
1340                                           XKB_X11_MIN_MINOR_XKB_VERSION,
1341                                           XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
1342                                           NULL, NULL, &xd->first_xkb_event,
1343                                           NULL);
1344
1345         if (!ret)
1346                 return False;
1347         xd->xkb = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
1348         if (!xd->xkb)
1349                 return False;
1350         xd->xkb_device_id = xkb_x11_get_core_keyboard_device_id(xd->conn);
1351         if (xd->xkb_device_id == -1)
1352                 return False;
1353
1354         if (!update_keymap(xd))
1355                 return False;
1356
1357         if (!select_xkb_events_for_device(xd->conn, xd->xkb_device_id))
1358                 return False;
1359
1360         locale = setlocale(LC_CTYPE, NULL);
1361         xd->compose_table =
1362                 xkb_compose_table_new_from_locale(xd->xkb, locale,
1363                                                   XKB_COMPOSE_COMPILE_NO_FLAGS);
1364         if (xd->compose_table)
1365                 xd->compose_state =
1366                         xkb_compose_state_new(xd->compose_table,
1367                                               XKB_COMPOSE_STATE_NO_FLAGS);
1368         return True;
1369 }
1370
1371 static void kbd_free(struct xcb_data *xd safe)
1372 {
1373         if (xd->compose_table)
1374                 xkb_compose_table_unref(xd->compose_table);
1375         if (xd->xkb_keymap)
1376                 xkb_keymap_unref(xd->xkb_keymap);
1377         if (xd->xkb)
1378                 xkb_context_unref(xd->xkb);
1379 }
1380
1381 static struct {
1382         char *from safe, *to safe;
1383 } key_map[] = {
1384         { "Return",      ":Enter"},
1385         { "Tab",         ":Tab"},
1386         { "ISO_Left_Tab",":Tab"},
1387         { "Escape",      ":ESC"},
1388         { "Linefeed",    ":LF"},
1389         { "Down",        ":Down"},
1390         { "Up",          ":Up"},
1391         { "Left",        ":Left"},
1392         { "Right",       ":Right"},
1393         { "Home",        ":Home"},
1394         { "End",         ":End"},
1395         { "BackSpace",   ":Backspace"},
1396         { "Delete",      ":Del"},
1397         { "Insert",      ":Ins"},
1398         { "Next",        ":Prior"},
1399         { "Prior",       ":Next"},
1400         { "F1",          ":F1"},
1401         { "F2",          ":F2"},
1402         { "F3",          ":F3"},
1403         { "F4",          ":F4"},
1404         { "F5",          ":F5"},
1405         { "F6",          ":F6"},
1406         { "F7",          ":F7"},
1407         { "F8",          ":F8"},
1408         { "F9",          ":F9"},
1409         { "F10",         ":F11"},
1410         { "F11",         ":F11"},
1411         { "F12",         ":F12"},
1412 };
1413
1414 static void handle_key_press(struct pane *home safe,
1415                              xcb_key_press_event_t *kpe safe)
1416 {
1417         struct xcb_data                 *xd = home->data;
1418         xkb_keycode_t                   keycode = kpe->detail;
1419         xcb_keysym_t                    keysym;
1420         xkb_keysym_t                    sym;
1421         const xkb_keysym_t              *syms;
1422         int                             nsyms;
1423         enum xkb_compose_status         status;
1424         xkb_mod_index_t                 mod;
1425         char                            s[16];
1426         char                            key[16];
1427         char                            mods[32];
1428         bool                            shift=False, ctrl=False, alt=False;
1429
1430         xd->last_event = time(NULL);
1431
1432         keysym = xkb_state_key_get_one_sym(xd->xkb_state,
1433                                            keycode);
1434         if (xd->compose_state)
1435                 xkb_compose_state_feed(xd->compose_state, keysym);
1436         nsyms = xkb_state_key_get_syms(xd->xkb_state, keycode,
1437                                        &syms);
1438         if (nsyms <= 0)
1439                 return;
1440         status = XKB_COMPOSE_NOTHING;
1441         if (xd->compose_state)
1442                 status = xkb_compose_state_get_status(xd->compose_state);
1443         if (status == XKB_COMPOSE_COMPOSING ||
1444             status == XKB_COMPOSE_CANCELLED)
1445                 return;
1446
1447         for (mod = 0; mod < xkb_keymap_num_mods(xd->xkb_keymap); mod++) {
1448                 const char *n;
1449                 if (xkb_state_mod_index_is_active(
1450                             xd->xkb_state, mod,
1451                             XKB_STATE_MODS_EFFECTIVE) <= 0)
1452                         continue;
1453                 /* This does tells me "shift" is consumed for :C:S-l ...
1454                 if (xkb_state_mod_index_is_consumed2(
1455                             xd->xkb_state, keycode, mod,
1456                             XKB_CONSUMED_MODE_XKB))
1457                         continue;
1458                  */
1459                 n = xkb_keymap_mod_get_name(xd->xkb_keymap, mod);
1460                 if (n && strcmp(n, "Shift") == 0)
1461                         shift = True;
1462                 if (n && strcmp(n, "Control") == 0)
1463                         ctrl = True;
1464                 if (n && strcmp(n, "Mod1") == 0)
1465                         alt = True;
1466         }
1467
1468         if (status == XKB_COMPOSE_COMPOSED) {
1469                 sym = xkb_compose_state_get_one_sym(xd->compose_state);
1470                 syms = &sym;
1471                 nsyms = 1;
1472                 s[0] = '-';
1473                 xkb_compose_state_get_utf8(xd->compose_state,
1474                                            s+1, sizeof(s)-1);
1475                 key[0] = 0;
1476                 shift = False;
1477                 ctrl = False;
1478                 /* Mod1 can still apply to a composed char */
1479         } else if (nsyms == 1) {
1480                 unsigned int i;
1481                 sym = xkb_state_key_get_one_sym(xd->xkb_state, keycode);
1482                 syms = &sym;
1483                 s[0] = '-';
1484                 xkb_state_key_get_utf8(xd->xkb_state, keycode,
1485                                        s+1, sizeof(s)-1);
1486                 xkb_keysym_get_name(syms[0], key, sizeof(key));
1487                 for (i = 0; i < ARRAY_SIZE(key_map); i++) {
1488                         if (strcmp(key, key_map[i].from) == 0) {
1489                                 strcpy(s, key_map[i].to);
1490                                 break;
1491                         }
1492                 }
1493                 if (s[0] == '-' && s[1] >= ' ' && s[1] < 0x7f)
1494                         /* Shift is included */
1495                         shift = False;
1496                 if (s[0] == '-' && s[1] && (unsigned char)(s[1]) < ' ') {
1497                         ctrl = True;
1498                         s[1] += '@';
1499                         if (s[1] < 'A' || s[1] > 'Z')
1500                                 shift = False;
1501                 } else if (s[0] == '-' && !s[1] && strcmp(key, "space") == 0) {
1502                         /* 'nul' becomes "C- " (ctrl-space) */
1503                         ctrl = True;
1504                         s[1] = ' ';
1505                         s[2] = 0;
1506                 }
1507         }
1508
1509         if (xd->compose_state &&
1510             (status == XKB_COMPOSE_CANCELLED ||
1511              status == XKB_COMPOSE_COMPOSED))
1512                 xkb_compose_state_reset(xd->compose_state);
1513
1514         if (s[1]) {
1515                 mods[0] = 0;
1516                 if (alt)
1517                         strcat(mods, ":A");
1518                 if (ctrl)
1519                         strcat(mods, ":C");
1520                 if (shift)
1521                         strcat(mods, ":S");
1522                 strcat(mods, s);
1523                 call("Keystroke", home, 0, NULL, mods);
1524         }
1525 }
1526
1527 static void handle_xkb_event(struct pane *home safe,
1528                              xcb_generic_event_t *ev safe)
1529 {
1530         struct xcb_data *xd = home->data;
1531
1532         switch (ev->pad0) {
1533                 xcb_xkb_new_keyboard_notify_event_t     *nkne;
1534                 xcb_xkb_state_notify_event_t            *sne;
1535                 xcb_xkb_map_notify_event_t              *mne;
1536         case XCB_XKB_NEW_KEYBOARD_NOTIFY:
1537                 nkne = (void*)ev;
1538                 if (nkne->deviceID == xd->xkb_device_id &&
1539                     nkne->changed & XCB_XKB_NKN_DETAIL_KEYCODES)
1540                         update_keymap(xd);
1541                 break;
1542         case XCB_XKB_MAP_NOTIFY:
1543                 mne = (void*)ev;
1544                 if (mne->deviceID == xd->xkb_device_id)
1545                         update_keymap(xd);
1546                 break;
1547         case XCB_XKB_STATE_NOTIFY:
1548                 sne = (void*)ev;
1549                 if (sne->deviceID == xd->xkb_device_id)
1550                         xkb_state_update_mask(xd->xkb_state,
1551                                               sne->baseMods,
1552                                               sne->latchedMods,
1553                                               sne->lockedMods,
1554                                               sne->baseGroup,
1555                                               sne->latchedGroup,
1556                                               sne->lockedGroup);
1557                 break;
1558         }
1559 }
1560
1561 static void handle_configure(struct pane *home safe,
1562                              xcb_configure_notify_event_t *cne safe)
1563 {
1564         struct xcb_data *xd = home->data;
1565
1566         pane_resize(home, 0, 0, cne->width, cne->height);
1567         cairo_xcb_surface_set_size(xd->surface, cne->width, cne->height);
1568 }
1569
1570 static void handle_expose(struct pane *home safe,
1571                           xcb_expose_event_t *ee safe)
1572 {
1573         struct xcb_data *xd = home->data;
1574         cairo_rectangle_int_t r = {
1575                 .x = ee->x,
1576                 .y = ee->y,
1577                 .width = ee->width,
1578                 .height = ee->height,
1579         };
1580
1581         if (!xd->need_update)
1582                 xd->need_update = cairo_region_create();
1583         cairo_region_union_rectangle(xd->need_update, &r);
1584         if (ee->count == 0)
1585                 pane_damaged(home, DAMAGED_POSTORDER);
1586 }
1587
1588 static void handle_client_message(struct pane *home safe,
1589                                   xcb_client_message_event_t *cme safe)
1590 {
1591         struct xcb_data *xd = home->data;
1592
1593         if (cme->type == xd->atoms[a_WM_PROTOCOLS] &&
1594             cme->format == 32 &&
1595             cme->window == xd->win &&
1596             cme->data.data32[0] == xd->atoms[a_WM_DELETE_WINDOW]) {
1597                 call("Display:close", pane_leaf(home));
1598                 return;
1599         }
1600
1601         if (cme->type == xd->atoms[a_WM_PROTOCOLS] &&
1602             cme->format == 32 &&
1603             cme->window == xd->win &&
1604             cme->data.data32[0] == xd->atoms[a_NET_WM_PING]) {
1605                 cme->window = xd->screen->root;
1606                 xcb_send_event(xd->conn, 0, xd->screen->root,
1607                                XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
1608                                XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT,
1609                                (void*)cme);
1610                 return;
1611         }
1612         LOG("x11 %s got unexpected client message type=%d/%d win=%x data=%d",
1613             xd->display,
1614             cme->type, cme->format, cme->window, cme->data.data32[0]);
1615
1616 }
1617
1618 DEF_CMD(xcb_input)
1619 {
1620         struct xcb_data *xd = ci->home->data;
1621         xcb_generic_event_t *ev;
1622         int ret = 1;
1623
1624         wait_for(xd);
1625         if (ci->num < 0)
1626                 /* This is a poll - only return 1 on something happening */
1627                 ret = Efalse;
1628
1629         while ((ev = xcb_poll_for_event(xd->conn)) != NULL) {
1630                 ret = 1;
1631                 switch (ev->response_type & 0x7f) {
1632                 case XCB_KEY_PRESS:
1633                         time_start(TIME_KEY);
1634                         handle_key_press(ci->home, safe_cast (void*)ev);
1635                         time_stop(TIME_KEY);
1636                         break;
1637                 case XCB_KEY_RELEASE:
1638                         /* Ignore for now */
1639                         break;
1640                 case XCB_BUTTON_PRESS:
1641                 case XCB_BUTTON_RELEASE:
1642                         time_start(TIME_KEY);
1643                         handle_button(ci->home, (void*)ev);
1644                         time_stop(TIME_KEY);
1645                         break;
1646                 case XCB_MOTION_NOTIFY:
1647                         time_start(TIME_KEY);
1648                         handle_motion(ci->home, (void*)ev);
1649                         time_stop(TIME_KEY);
1650                         break;
1651                 case XCB_FOCUS_IN:
1652                 case XCB_FOCUS_OUT:
1653                         time_start(TIME_WINDOW);
1654                         handle_focus(ci->home, (void*)ev);
1655                         time_stop(TIME_WINDOW);
1656                         break;
1657                 case XCB_EXPOSE:
1658                         time_start(TIME_WINDOW);
1659                         handle_expose(ci->home, (void*)ev);
1660                         time_stop(TIME_WINDOW);
1661                         break;
1662                 case XCB_CONFIGURE_NOTIFY:
1663                         time_start(TIME_WINDOW);
1664                         handle_configure(ci->home, (void*)ev);
1665                         time_stop(TIME_WINDOW);
1666                         break;
1667                 case XCB_CLIENT_MESSAGE:
1668                         time_start(TIME_WINDOW);
1669                         handle_client_message(ci->home, (void*)ev);
1670                         time_stop(TIME_WINDOW);
1671                         break;
1672                 case XCB_REPARENT_NOTIFY:
1673                         /* Not interested */
1674                         break;
1675                 case XCB_MAP_NOTIFY:
1676                 case XCB_UNMAP_NOTIFY:
1677                 case XCB_MAPPING_NOTIFY:
1678                         /* FIXME what to do?? */
1679                         break;
1680                 case 0:
1681                         /* Don't know what this means, but I get a lot
1682                          * of them so I don't want to log that it was
1683                          * ignored.
1684                          */
1685                         break;
1686                 default:
1687                         if ((ev->response_type & 0x7f) ==
1688                             xd->first_xkb_event) {
1689                                 handle_xkb_event(ci->home, ev);
1690                                 break;
1691                         }
1692                         LOG("Ignored X11 event %d", ev->response_type);
1693                 }
1694                 xcb_flush(xd->conn);
1695         }
1696         if (xcb_connection_has_error(xd->conn)) {
1697                 call("Display:close", ci->home->parent);
1698                 pane_close(ci->home);
1699         }
1700         return ret;
1701 }
1702
1703 static void set_str_prop(struct xcb_data *xd safe,
1704                          enum my_atoms a, const char *str safe)
1705 {
1706         xcb_change_property(xd->conn,
1707                             XCB_PROP_MODE_REPLACE,
1708                             xd->win, xd->atoms[a], XCB_ATOM_STRING,
1709                             8, strlen(str), str);
1710 }
1711
1712 static void set_utf8_prop(struct xcb_data *xd safe,
1713                          enum my_atoms a, const char *str safe)
1714 {
1715         xcb_change_property(xd->conn,
1716                             XCB_PROP_MODE_REPLACE,
1717                             xd->win, xd->atoms[a],
1718                             xd->atoms[a_UTF8_STRING],
1719                             8, strlen(str), str);
1720 }
1721
1722 static void set_card32_property(struct xcb_data *xd safe,
1723                                 enum my_atoms a,
1724                                 const uint32_t *data, int cnt)
1725 {
1726         xcb_change_property(xd->conn,
1727                             XCB_PROP_MODE_REPLACE,
1728                             xd->win, xd->atoms[a],
1729                             XCB_ATOM_CARDINAL, 32,
1730                             cnt, data);
1731 }
1732
1733 static void set_atom_prop(struct xcb_data *xd safe,
1734                           enum my_atoms prop, enum my_atoms alist, ...)
1735 {
1736         uint32_t atoms[16];
1737         int anum = 0;
1738         va_list ap;
1739         enum my_atoms a;
1740
1741         atoms[anum++] = xd->atoms[alist];
1742         va_start(ap, alist);
1743         while ((a = va_arg(ap, enum my_atoms)) != a_NONE)
1744                 if (anum < 16)
1745                         atoms[anum++] = xd->atoms[a];
1746         va_end(ap);
1747         xcb_change_property(xd->conn,
1748                             XCB_PROP_MODE_REPLACE,
1749                             xd->win, xd->atoms[prop],
1750                             XCB_ATOM_ATOM,
1751                             32, anum, atoms);
1752 }
1753
1754 static void xcb_load_icon(struct pane *p safe,
1755                           struct xcb_data *xd safe,
1756                           char *file safe)
1757 {
1758         char *path;
1759         int h, w, n;
1760         unsigned int *data;
1761         MagickBooleanType status;
1762         MagickWand *wd;
1763         uint32_t fmt[2];
1764
1765         path = call_ret(str, "xdg-find-edlib-file", p, 0, NULL,
1766                         file, 0, NULL, "data");
1767         if (!path)
1768                 return;
1769
1770         wd = NewMagickWand();
1771         status = MagickReadImage(wd, path);
1772         free(path);
1773         if (status == MagickFalse)
1774                 goto done;
1775
1776         h = MagickGetImageHeight(wd);
1777         w = MagickGetImageWidth(wd);
1778         n = 2 + w*h;
1779         data = malloc(sizeof(data[0]) * n);
1780         if (!data)
1781                 goto done;
1782         data[0] = w;
1783         data[1] = h;
1784         /* Need host-endian ARGB data */
1785         fmt[0] = ('A'<<24) | ('R' << 16) | ('G' << 8) | ('B' << 0);
1786         fmt[1] = 0;
1787         MagickExportImagePixels(wd, 0, 0, w, h, (char*)fmt,
1788                                 CharPixel, data+2);
1789         set_card32_property(xd, a_NET_WM_ICON, data, n);
1790         free(data);
1791 done:
1792         DestroyMagickWand(wd);
1793         return;
1794 }
1795
1796 static struct pane *xcb_display_init(const char *d safe,
1797                                      const char *disp_auth,
1798                                      struct pane *focus safe)
1799 {
1800         struct xcb_data *xd;
1801         struct pane *p;
1802         xcb_connection_t *conn;
1803         xcb_intern_atom_cookie_t cookies[NR_ATOMS];
1804         xcb_screen_iterator_t iter;
1805         xcb_depth_iterator_t di;
1806         char scale[20];
1807         char hostname[128];
1808         uint32_t valwin[2];
1809         int screen = 0;
1810         int i;
1811         PangoLayout *layout;
1812         PangoRectangle log;
1813         cairo_t *cairo;
1814         cairo_surface_t *surface;
1815         PangoFontDescription *fd;
1816         // FIXME SCALE from environ?? or pango_cairo_context_set_resolution dpi
1817         // 254 * width_in_pixels / width_in_millimeters / 10
1818
1819         conn = safe_cast xcb_connect_auth(d, disp_auth, &screen);
1820         if (xcb_connection_has_error(conn))
1821                 return NULL;
1822
1823         p = pane_register(pane_root(focus), 1, &xcb_handle.c);
1824         if (!p)
1825                 return NULL;
1826         xd = p->data;
1827
1828         xd->motion_blocked = True;
1829         xd->in_focus = True;
1830
1831         xd->conn = conn;
1832         xd->display = strdup(d);
1833         if (disp_auth)
1834                 xd->disp_auth = strdup(disp_auth);
1835         xd->setup = safe_cast xcb_get_setup(conn);
1836         iter = xcb_setup_roots_iterator(xd->setup);
1837         for (i = 0; i < screen; i++)
1838                 xcb_screen_next(&iter);
1839         xd->screen = safe_cast iter.data;
1840
1841         di = xcb_screen_allowed_depths_iterator(xd->screen);
1842         while (di.data && di.data->depth < 24)
1843                 xcb_depth_next(&di);
1844         //?? look for class = TrueColor??
1845         xd->visual = xcb_depth_visuals(di.data);
1846
1847         for (i = 0; i < NR_ATOMS; i++) {
1848                 const char *n = atom_names[i];
1849                 if (!n)
1850                         continue;
1851                 cookies[i] = xcb_intern_atom(conn, 0, strlen(n), n);
1852         }
1853
1854         xd->win = xcb_generate_id(conn);
1855         valwin[0] = xd->screen->white_pixel;
1856         valwin[1] = (XCB_EVENT_MASK_KEY_PRESS |
1857                      XCB_EVENT_MASK_KEY_RELEASE |
1858                      XCB_EVENT_MASK_BUTTON_PRESS |
1859                      XCB_EVENT_MASK_BUTTON_RELEASE |
1860                      // XCB_EVENT_MASK_ENTER_WINDOW |
1861                      // XCB_EVENT_MASK_LEAVE_WINDOW |
1862                      XCB_EVENT_MASK_FOCUS_CHANGE |
1863                      XCB_EVENT_MASK_STRUCTURE_NOTIFY |
1864                      XCB_EVENT_MASK_EXPOSURE |
1865                      XCB_EVENT_MASK_BUTTON_MOTION |
1866                      XCB_EVENT_MASK_POINTER_MOTION_HINT |
1867                      0);
1868
1869         xcb_create_window(conn, XCB_COPY_FROM_PARENT, xd->win,
1870                           xd->screen->root,
1871                           0, 0,
1872                           100, 100,
1873                           0, XCB_WINDOW_CLASS_INPUT_OUTPUT,
1874                           xd->screen->root_visual,
1875                           XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK,
1876                           valwin);
1877         xcb_flush(conn);
1878         kbd_setup(xd);
1879
1880         surface = cairo_xcb_surface_create(
1881                 conn, xd->win, xd->visual, 100, 100);
1882         if (!surface)
1883                 goto abort;
1884         xd->surface = surface;
1885         cairo = safe_cast cairo_create(xd->surface);
1886         if (cairo_status(cairo) != CAIRO_STATUS_SUCCESS)
1887                 goto abort;
1888         xd->cairo = cairo;
1889         fd = pango_font_description_new();
1890         if (!fd)
1891                 goto abort;
1892         xd->fd = fd;
1893         pango_font_description_set_family(xd->fd, "monospace");
1894         pango_font_description_set_size(xd->fd, 12 * PANGO_SCALE);
1895
1896         layout = pango_cairo_create_layout(xd->cairo);
1897         pango_layout_set_font_description(layout, fd);
1898         pango_layout_set_text(layout, "M", 1);
1899         pango_layout_get_pixel_extents(layout, NULL, &log);
1900         g_object_unref(layout);
1901         xd->lineheight = log.height;
1902         xd->charwidth = log.width;
1903
1904         valwin[0] = xd->charwidth * 80;
1905         valwin[1] = xd->lineheight * 26;
1906         xcb_configure_window(conn, xd->win,
1907                              XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT,
1908                              valwin);
1909         cairo_xcb_surface_set_size(xd->surface, valwin[0], valwin[1]);
1910
1911         /* Now resolve all those cookies */
1912         for (i = 0; i < NR_ATOMS; i++) {
1913                 xcb_intern_atom_reply_t *r;
1914                 r = xcb_intern_atom_reply(conn, cookies[i], NULL);
1915                 if (!r)
1916                         goto abort;
1917                 xd->atoms[i] = r->atom;
1918                 free(r);
1919         }
1920
1921         /* FIXME set:
1922          *
1923          * WM_PROTOCOLS _NET_WM_SYN_REQUEST??
1924          * WM_NORMAL_HINTS WM_HINTS
1925          * WM_CLIENT_MACHINE
1926          */
1927         set_str_prop(xd, a_WM_NAME, "EdLib");
1928         set_utf8_prop(xd, a_NET_WM_NAME, "EdLib");
1929         set_str_prop(xd, a_WM_ICON_NAME, "EdLib");
1930         set_utf8_prop(xd, a_NET_WM_ICON_NAME, "EdLib");
1931         gethostname(hostname, sizeof(hostname));
1932         set_str_prop(xd, a_WM_CLIENT_MACHINE, hostname);
1933         set_atom_prop(xd, a_WM_PROTOCOLS, a_WM_DELETE_WINDOW, a_NET_WM_PING, 0);
1934
1935         /* Configure passive grabs - shift, lock, and control only */
1936         xcb_grab_button(xd->conn, 0, xd->win,
1937                         XCB_EVENT_MASK_BUTTON_PRESS |
1938                         XCB_EVENT_MASK_BUTTON_RELEASE |
1939                         XCB_EVENT_MASK_BUTTON_MOTION,
1940                         XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
1941                         XCB_WINDOW_NONE, XCB_CURSOR_NONE,
1942                         XCB_BUTTON_INDEX_ANY,
1943                         XCB_MOD_MASK_SHIFT |
1944                         XCB_MOD_MASK_LOCK |
1945                         XCB_MOD_MASK_CONTROL);
1946
1947         xcb_load_icon(focus, xd, "{COMM}-icon.png");
1948         xcb_map_window(conn, xd->win);
1949         xcb_flush(conn);
1950         pane_resize(p, 0, 0, xd->charwidth*80, xd->lineheight*26);
1951         call_comm("event:read", p, &xcb_input, xcb_get_file_descriptor(conn));
1952         call_comm("event:poll", p, &xcb_input);
1953         attr_set_str(&p->attrs, "DISPLAY", d);
1954         attr_set_str(&p->attrs, "XAUTHORITY", disp_auth);
1955         snprintf(scale, sizeof(scale), "%dx%d", xd->charwidth, xd->lineheight);
1956         attr_set_str(&p->attrs, "scale:M", scale);
1957         xd->last_event = time(NULL);
1958         call("editor:request:all-displays", p);
1959         p = call_ret(pane, "editor:activate-display", p);
1960         return p;
1961 abort:
1962         kbd_free(xd);
1963         cairo_destroy(xd->cairo);
1964         cairo_surface_destroy(xd->surface);
1965         xcb_disconnect(conn);
1966         free(xd->display);
1967         free(xd->disp_auth);
1968         return NULL;
1969 }
1970
1971 DEF_CMD(xcb_new_display)
1972 {
1973         struct pane *p;
1974         const char *d = ci->str;
1975         const char *disp_auth = ci->str2;
1976
1977         if (!d)
1978                 d = pane_attr_get(ci->focus, "DISPLAY");
1979         if (!disp_auth)
1980                 disp_auth = pane_attr_get(ci->focus, "XAUTHORITY");
1981         if (!disp_auth)
1982                 disp_auth = getenv("XAUTHORITY");
1983
1984         if (!d)
1985                 return Enoarg;
1986         p = xcb_display_init(d, disp_auth, ci->focus);
1987         if (p)
1988                 home_call_ret(pane, ci->focus, "doc:attach-view", p, 1);
1989         if (p)
1990                 comm_call(ci->comm2, "cb", p);
1991         return 1;
1992 }
1993
1994 void edlib_init(struct pane *ed safe)
1995 {
1996         call_comm("global-set-command", ed, &xcb_new_display, 0, NULL,
1997                   "attach-display-x11");
1998         call_comm("global-set-command", ed, &xcb_new_display, 0, NULL,
1999                   "interactive-cmd-x11window");
2000
2001         xcb_map = key_alloc();
2002
2003         key_add(xcb_map, "Display:close", &xcb_close_display);
2004         key_add_prefix(xcb_map, "Display:set:", &xcb_set_attr);
2005         key_add(xcb_map, "Display:external-viewer", &xcb_external_viewer);
2006         key_add(xcb_map, "Display:fullscreen", &xcb_fullscreen);
2007         key_add(xcb_map, "Display:new", &xcb_new_display);
2008
2009         key_add(xcb_map, "Close", &xcb_close);
2010         key_add(xcb_map, "Draw:clear", &xcb_clear);
2011         key_add(xcb_map, "Draw:text-size", &xcb_text_size);
2012         key_add(xcb_map, "Draw:text", &xcb_draw_text);
2013         key_add(xcb_map, "Draw:image", &xcb_draw_image);
2014         key_add(xcb_map, "Draw:image-size", &xcb_image_size);
2015         key_add(xcb_map, "Refresh:size", &xcb_refresh_size);
2016         key_add(xcb_map, "Refresh:postorder", &xcb_refresh_post);
2017         key_add(xcb_map, "all-displays", &xcb_notify_display);
2018         key_add(xcb_map, "Notify:Close", &xcb_pane_close);
2019 }