compositor: Parse config file in main(), only keep weston config object
[profile/ivi/weston-ivi-shell.git] / src / compositor-x11.c
1 /*
2  * Copyright © 2008-2011 Kristian Høgsberg
3  * Copyright © 2010-2011 Intel Corporation
4  * Copyright © 2013 Vasily Khoruzhick <anarsoul@gmail.com>
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and
7  * its documentation for any purpose is hereby granted without fee, provided
8  * that the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of the copyright holders not be used in
11  * advertising or publicity pertaining to distribution of the software
12  * without specific, written prior permission.  The copyright holders make
13  * no representations about the suitability of this software for any
14  * purpose.  It is provided "as is" without express or implied warranty.
15  *
16  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
18  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
19  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
20  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
21  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <assert.h>
30 #include <stddef.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <sys/time.h>
37 #include <sys/shm.h>
38 #include <linux/input.h>
39
40 #include <xcb/xcb.h>
41 #include <xcb/shm.h>
42 #ifdef HAVE_XCB_XKB
43 #include <xcb/xkb.h>
44 #endif
45
46 #include <X11/Xlib.h>
47 #include <X11/Xlib-xcb.h>
48
49 #include <xkbcommon/xkbcommon.h>
50
51 #include "compositor.h"
52 #include "gl-renderer.h"
53 #include "pixman-renderer.h"
54 #include "../shared/config-parser.h"
55 #include "../shared/image-loader.h"
56
57 #define DEFAULT_AXIS_STEP_DISTANCE wl_fixed_from_int(10)
58
59 static int option_width;
60 static int option_height;
61 static int option_count;
62
63 struct x11_compositor {
64         struct weston_compositor         base;
65
66         Display                 *dpy;
67         xcb_connection_t        *conn;
68         xcb_screen_t            *screen;
69         xcb_cursor_t             null_cursor;
70         struct wl_array          keys;
71         struct wl_event_source  *xcb_source;
72         struct xkb_keymap       *xkb_keymap;
73         unsigned int             has_xkb;
74         uint8_t                  xkb_event_base;
75         int                      use_pixman;
76
77         int                      has_net_wm_state_fullscreen;
78
79         /* We could map multi-pointer X to multiple wayland seats, but
80          * for now we only support core X input. */
81         struct weston_seat               core_seat;
82         wl_fixed_t                       prev_x;
83         wl_fixed_t                       prev_y;
84
85         struct {
86                 xcb_atom_t               wm_protocols;
87                 xcb_atom_t               wm_normal_hints;
88                 xcb_atom_t               wm_size_hints;
89                 xcb_atom_t               wm_delete_window;
90                 xcb_atom_t               wm_class;
91                 xcb_atom_t               net_wm_name;
92                 xcb_atom_t               net_supporting_wm_check;
93                 xcb_atom_t               net_supported;
94                 xcb_atom_t               net_wm_icon;
95                 xcb_atom_t               net_wm_state;
96                 xcb_atom_t               net_wm_state_fullscreen;
97                 xcb_atom_t               string;
98                 xcb_atom_t               utf8_string;
99                 xcb_atom_t               cardinal;
100                 xcb_atom_t               xkb_names;
101         } atom;
102 };
103
104 struct x11_output {
105         struct weston_output    base;
106
107         xcb_window_t            window;
108         struct weston_mode      mode;
109         struct wl_event_source *finish_frame_timer;
110
111         xcb_gc_t                gc;
112         xcb_shm_seg_t           segment;
113         pixman_image_t         *hw_surface;
114         int                     shm_id;
115         void                   *buf;
116         uint8_t                 depth;
117         uint32_t                scale;
118 };
119
120 static struct xkb_keymap *
121 x11_compositor_get_keymap(struct x11_compositor *c)
122 {
123         xcb_get_property_cookie_t cookie;
124         xcb_get_property_reply_t *reply;
125         struct xkb_rule_names names;
126         struct xkb_keymap *ret;
127         const char *value_all, *value_part;
128         int length_all, length_part;
129
130         memset(&names, 0, sizeof(names));
131
132         cookie = xcb_get_property(c->conn, 0, c->screen->root,
133                                   c->atom.xkb_names, c->atom.string, 0, 1024);
134         reply = xcb_get_property_reply(c->conn, cookie, NULL);
135         if (reply == NULL)
136                 return NULL;
137
138         value_all = xcb_get_property_value(reply);
139         length_all = xcb_get_property_value_length(reply);
140         value_part = value_all;
141
142 #define copy_prop_value(to) \
143         length_part = strlen(value_part); \
144         if (value_part + length_part < (value_all + length_all) && \
145             length_part > 0) \
146                 names.to = value_part; \
147         value_part += length_part + 1;
148
149         copy_prop_value(rules);
150         copy_prop_value(model);
151         copy_prop_value(layout);
152         copy_prop_value(variant);
153         copy_prop_value(options);
154 #undef copy_prop_value
155
156         ret = xkb_map_new_from_names(c->base.xkb_context, &names, 0);
157
158         free(reply);
159         return ret;
160 }
161
162 static uint32_t
163 get_xkb_mod_mask(struct x11_compositor *c, uint32_t in)
164 {
165         struct weston_xkb_info *info = &c->core_seat.xkb_info;
166         uint32_t ret = 0;
167
168         if ((in & ShiftMask) && info->shift_mod != XKB_MOD_INVALID)
169                 ret |= (1 << info->shift_mod);
170         if ((in & LockMask) && info->caps_mod != XKB_MOD_INVALID)
171                 ret |= (1 << info->caps_mod);
172         if ((in & ControlMask) && info->ctrl_mod != XKB_MOD_INVALID)
173                 ret |= (1 << info->ctrl_mod);
174         if ((in & Mod1Mask) && info->alt_mod != XKB_MOD_INVALID)
175                 ret |= (1 << info->alt_mod);
176         if ((in & Mod2Mask) && info->mod2_mod != XKB_MOD_INVALID)
177                 ret |= (1 << info->mod2_mod);
178         if ((in & Mod3Mask) && info->mod3_mod != XKB_MOD_INVALID)
179                 ret |= (1 << info->mod3_mod);
180         if ((in & Mod4Mask) && info->super_mod != XKB_MOD_INVALID)
181                 ret |= (1 << info->super_mod);
182         if ((in & Mod5Mask) && info->mod5_mod != XKB_MOD_INVALID)
183                 ret |= (1 << info->mod5_mod);
184
185         return ret;
186 }
187
188 static void
189 x11_compositor_setup_xkb(struct x11_compositor *c)
190 {
191 #ifndef HAVE_XCB_XKB
192         weston_log("XCB-XKB not available during build\n");
193         c->has_xkb = 0;
194         c->xkb_event_base = 0;
195         return;
196 #else
197         const xcb_query_extension_reply_t *ext;
198         xcb_generic_error_t *error;
199         xcb_void_cookie_t select;
200         xcb_xkb_use_extension_cookie_t use_ext;
201         xcb_xkb_use_extension_reply_t *use_ext_reply;
202         xcb_xkb_per_client_flags_cookie_t pcf;
203         xcb_xkb_per_client_flags_reply_t *pcf_reply;
204         xcb_xkb_get_state_cookie_t state;
205         xcb_xkb_get_state_reply_t *state_reply;
206
207         c->has_xkb = 0;
208         c->xkb_event_base = 0;
209
210         ext = xcb_get_extension_data(c->conn, &xcb_xkb_id);
211         if (!ext) {
212                 weston_log("XKB extension not available on host X11 server\n");
213                 return;
214         }
215         c->xkb_event_base = ext->first_event;
216
217         select = xcb_xkb_select_events_checked(c->conn,
218                                                XCB_XKB_ID_USE_CORE_KBD,
219                                                XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
220                                                0,
221                                                XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
222                                                0,
223                                                0,
224                                                NULL);
225         error = xcb_request_check(c->conn, select);
226         if (error) {
227                 weston_log("error: failed to select for XKB state events\n");
228                 free(error);
229                 return;
230         }
231
232         use_ext = xcb_xkb_use_extension(c->conn,
233                                         XCB_XKB_MAJOR_VERSION,
234                                         XCB_XKB_MINOR_VERSION);
235         use_ext_reply = xcb_xkb_use_extension_reply(c->conn, use_ext, NULL);
236         if (!use_ext_reply) {
237                 weston_log("couldn't start using XKB extension\n");
238                 return;
239         }
240
241         if (!use_ext_reply->supported) {
242                 weston_log("XKB extension version on the server is too old "
243                            "(want %d.%d, has %d.%d)\n",
244                            XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION,
245                            use_ext_reply->serverMajor, use_ext_reply->serverMinor);
246                 free(use_ext_reply);
247                 return;
248         }
249         free(use_ext_reply);
250
251         pcf = xcb_xkb_per_client_flags(c->conn,
252                                        XCB_XKB_ID_USE_CORE_KBD,
253                                        XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT,
254                                        XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT,
255                                        0,
256                                        0,
257                                        0);
258         pcf_reply = xcb_xkb_per_client_flags_reply(c->conn, pcf, NULL);
259         if (!pcf_reply ||
260             !(pcf_reply->value & XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT)) {
261                 weston_log("failed to set XKB per-client flags, not using "
262                            "detectable repeat\n");
263                 free(pcf_reply);
264                 return;
265         }
266         free(pcf_reply);
267
268         state = xcb_xkb_get_state(c->conn, XCB_XKB_ID_USE_CORE_KBD);
269         state_reply = xcb_xkb_get_state_reply(c->conn, state, NULL);
270         if (!state_reply) {
271                 weston_log("failed to get initial XKB state\n");
272                 return;
273         }
274
275         xkb_state_update_mask(c->core_seat.xkb_state.state,
276                               get_xkb_mod_mask(c, state_reply->baseMods),
277                               get_xkb_mod_mask(c, state_reply->latchedMods),
278                               get_xkb_mod_mask(c, state_reply->lockedMods),
279                               0,
280                               0,
281                               state_reply->group);
282
283         free(state_reply);
284
285         c->has_xkb = 1;
286 #endif
287 }
288
289 static int
290 x11_input_create(struct x11_compositor *c, int no_input)
291 {
292         struct xkb_keymap *keymap;
293
294         weston_seat_init(&c->core_seat, &c->base);
295
296         if (no_input)
297                 return 0;
298
299         weston_seat_init_pointer(&c->core_seat);
300
301         keymap = x11_compositor_get_keymap(c);
302         if (weston_seat_init_keyboard(&c->core_seat, keymap) < 0)
303                 return -1;
304         if (keymap)
305                 xkb_map_unref(keymap);
306
307         x11_compositor_setup_xkb(c);
308
309         return 0;
310 }
311
312 static void
313 x11_input_destroy(struct x11_compositor *compositor)
314 {
315         weston_seat_release(&compositor->core_seat);
316 }
317
318 static void
319 x11_output_start_repaint_loop(struct weston_output *output)
320 {
321         uint32_t msec;
322         struct timeval tv;
323
324         gettimeofday(&tv, NULL);
325         msec = tv.tv_sec * 1000 + tv.tv_usec / 1000;
326         weston_output_finish_frame(output, msec);
327 }
328
329 static void
330 x11_output_repaint_gl(struct weston_output *output_base,
331                       pixman_region32_t *damage)
332 {
333         struct x11_output *output = (struct x11_output *)output_base;
334         struct weston_compositor *ec = output->base.compositor;
335
336         ec->renderer->repaint_output(output_base, damage);
337
338         pixman_region32_subtract(&ec->primary_plane.damage,
339                                  &ec->primary_plane.damage, damage);
340
341         wl_event_source_timer_update(output->finish_frame_timer, 10);
342 }
343
344 static void
345 set_clip_for_output(struct weston_output *output_base, pixman_region32_t *region)
346 {
347         struct x11_output *output = (struct x11_output *)output_base;
348         struct weston_compositor *ec = output->base.compositor;
349         struct x11_compositor *c = (struct x11_compositor *)ec;
350         pixman_box32_t *rects;
351         xcb_rectangle_t *output_rects;
352         pixman_box32_t rect, transformed_rect;
353         xcb_void_cookie_t cookie;
354         int width, height, nrects, i;
355         xcb_generic_error_t *err;
356
357         rects = pixman_region32_rectangles(region, &nrects);
358         output_rects = calloc(nrects, sizeof(xcb_rectangle_t));
359
360         if (output_rects == NULL)
361                 return;
362
363         width = output_base->width;
364         height = output_base->height;
365
366         for (i = 0; i < nrects; i++) {
367                 rect = rects[i];
368                 rect.x1 -= output_base->x;
369                 rect.y1 -= output_base->y;
370                 rect.x2 -= output_base->x;
371                 rect.y2 -= output_base->y;
372
373                 switch (output_base->transform) {
374                 default:
375                 case WL_OUTPUT_TRANSFORM_NORMAL:
376                         transformed_rect.x1 = rect.x1;
377                         transformed_rect.y1 = rect.y1;
378                         transformed_rect.x2 = rect.x2;
379                         transformed_rect.y2 = rect.y2;
380                         break;
381                 case WL_OUTPUT_TRANSFORM_90:
382                         transformed_rect.x1 = height - rect.y2;
383                         transformed_rect.y1 = rect.x1;
384                         transformed_rect.x2 = height - rect.y1;
385                         transformed_rect.y2 = rect.x2;
386                         break;
387                 case WL_OUTPUT_TRANSFORM_180:
388                         transformed_rect.x1 = width - rect.x2;
389                         transformed_rect.y1 = height - rect.y2;
390                         transformed_rect.x2 = width - rect.x1;
391                         transformed_rect.y2 = height - rect.y1;
392                         break;
393                 case WL_OUTPUT_TRANSFORM_270:
394                         transformed_rect.x1 = rect.y1;
395                         transformed_rect.y1 = width - rect.x2;
396                         transformed_rect.x2 = rect.y2;
397                         transformed_rect.y2 = width - rect.x1;
398                         break;
399                 case WL_OUTPUT_TRANSFORM_FLIPPED:
400                         transformed_rect.x1 = width - rect.x2;
401                         transformed_rect.y1 = rect.y1;
402                         transformed_rect.x2 = width - rect.x1;
403                         transformed_rect.y2 = rect.y2;
404                         break;
405                 case WL_OUTPUT_TRANSFORM_FLIPPED_90:
406                         transformed_rect.x1 = height - rect.y2;
407                         transformed_rect.y1 = width - rect.x2;
408                         transformed_rect.x2 = height - rect.y1;
409                         transformed_rect.y2 = width - rect.x1;
410                         break;
411                 case WL_OUTPUT_TRANSFORM_FLIPPED_180:
412                         transformed_rect.x1 = rect.x1;
413                         transformed_rect.y1 = height - rect.y2;
414                         transformed_rect.x2 = rect.x2;
415                         transformed_rect.y2 = height - rect.y1;
416                         break;
417                 case WL_OUTPUT_TRANSFORM_FLIPPED_270:
418                         transformed_rect.x1 = rect.y1;
419                         transformed_rect.y1 = rect.x1;
420                         transformed_rect.x2 = rect.y2;
421                         transformed_rect.y2 = rect.x2;
422                         break;
423                 }
424
425                 transformed_rect.x1 *= output_base->scale;
426                 transformed_rect.y1 *= output_base->scale;
427                 transformed_rect.x2 *= output_base->scale;
428                 transformed_rect.y2 *= output_base->scale;
429
430                 output_rects[i].x = transformed_rect.x1;
431                 output_rects[i].y = transformed_rect.y1;
432                 output_rects[i].width = transformed_rect.x2 - transformed_rect.x1;
433                 output_rects[i].height = transformed_rect.y2 - transformed_rect.y1;
434         }
435
436         cookie = xcb_set_clip_rectangles_checked(c->conn, XCB_CLIP_ORDERING_UNSORTED,
437                                         output->gc,
438                                         0, 0, nrects,
439                                         output_rects);
440         err = xcb_request_check(c->conn, cookie);
441         if (err != NULL) {
442                 weston_log("Failed to set clip rects, err: %d\n", err->error_code);
443                 free(err);
444         }
445         free(output_rects);
446 }
447
448
449 static void
450 x11_output_repaint_shm(struct weston_output *output_base,
451                        pixman_region32_t *damage)
452 {
453         struct x11_output *output = (struct x11_output *)output_base;
454         struct weston_compositor *ec = output->base.compositor;
455         struct x11_compositor *c = (struct x11_compositor *)ec;
456         xcb_void_cookie_t cookie;
457         xcb_generic_error_t *err;
458
459         pixman_renderer_output_set_buffer(output_base, output->hw_surface);
460         ec->renderer->repaint_output(output_base, damage);
461
462         pixman_region32_subtract(&ec->primary_plane.damage,
463                                  &ec->primary_plane.damage, damage);
464         set_clip_for_output(output_base, damage);
465         cookie = xcb_shm_put_image_checked(c->conn, output->window, output->gc,
466                                         pixman_image_get_width(output->hw_surface),
467                                         pixman_image_get_height(output->hw_surface),
468                                         0, 0,
469                                         pixman_image_get_width(output->hw_surface),
470                                         pixman_image_get_height(output->hw_surface),
471                                         0, 0, output->depth, XCB_IMAGE_FORMAT_Z_PIXMAP,
472                                         0, output->segment, 0);
473         err = xcb_request_check(c->conn, cookie);
474         if (err != NULL) {
475                 weston_log("Failed to put shm image, err: %d\n", err->error_code);
476                 free(err);
477         }
478
479         wl_event_source_timer_update(output->finish_frame_timer, 10);
480 }
481
482 static int
483 finish_frame_handler(void *data)
484 {
485         struct x11_output *output = data;
486
487         x11_output_start_repaint_loop(&output->base);
488
489         return 1;
490 }
491
492 static void
493 x11_output_deinit_shm(struct x11_compositor *c, struct x11_output *output)
494 {
495         xcb_void_cookie_t cookie;
496         xcb_generic_error_t *err;
497         xcb_free_gc(c->conn, output->gc);
498
499         pixman_image_unref(output->hw_surface);
500         output->hw_surface = NULL;
501         cookie = xcb_shm_detach_checked(c->conn, output->segment);
502         err = xcb_request_check(c->conn, cookie);
503         if (err) {
504                 weston_log("xcb_shm_detach failed, error %d\n", err->error_code);
505                 free(err);
506         }
507         shmdt(output->buf);
508 }
509
510 static void
511 x11_output_destroy(struct weston_output *output_base)
512 {
513         struct x11_output *output = (struct x11_output *)output_base;
514         struct x11_compositor *compositor =
515                 (struct x11_compositor *)output->base.compositor;
516
517         wl_list_remove(&output->base.link);
518         wl_event_source_remove(output->finish_frame_timer);
519
520         if (compositor->use_pixman) {
521                 pixman_renderer_output_destroy(output_base);
522                 x11_output_deinit_shm(compositor, output);
523         } else
524                 gl_renderer_output_destroy(output_base);
525
526         xcb_destroy_window(compositor->conn, output->window);
527
528         weston_output_destroy(&output->base);
529
530         free(output);
531 }
532
533 static void
534 x11_output_set_wm_protocols(struct x11_compositor *c,
535                             struct x11_output *output)
536 {
537         xcb_atom_t list[1];
538
539         list[0] = c->atom.wm_delete_window;
540         xcb_change_property (c->conn, 
541                              XCB_PROP_MODE_REPLACE,
542                              output->window,
543                              c->atom.wm_protocols,
544                              XCB_ATOM_ATOM,
545                              32,
546                              ARRAY_LENGTH(list),
547                              list);
548 }
549
550 struct wm_normal_hints {
551         uint32_t flags;
552         uint32_t pad[4];
553         int32_t min_width, min_height;
554         int32_t max_width, max_height;
555         int32_t width_inc, height_inc;
556         int32_t min_aspect_x, min_aspect_y;
557         int32_t max_aspect_x, max_aspect_y;
558         int32_t base_width, base_height;
559         int32_t win_gravity;
560 };
561
562 #define WM_NORMAL_HINTS_MIN_SIZE        16
563 #define WM_NORMAL_HINTS_MAX_SIZE        32
564
565 static void
566 x11_output_set_icon(struct x11_compositor *c,
567                     struct x11_output *output, const char *filename)
568 {
569         uint32_t *icon;
570         int32_t width, height;
571         pixman_image_t *image;
572
573         image = load_image(filename);
574         if (!image)
575                 return;
576         width = pixman_image_get_width(image);
577         height = pixman_image_get_height(image);
578         icon = malloc(width * height * 4 + 8);
579         if (!icon) {
580                 pixman_image_unref(image);
581                 return;
582         }
583
584         icon[0] = width;
585         icon[1] = height;
586         memcpy(icon + 2, pixman_image_get_data(image), width * height * 4);
587         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
588                             c->atom.net_wm_icon, c->atom.cardinal, 32,
589                             width * height + 2, icon);
590         free(icon);
591         pixman_image_unref(image);
592 }
593
594 static void
595 x11_output_wait_for_map(struct x11_compositor *c, struct x11_output *output)
596 {
597         xcb_map_notify_event_t *map_notify;
598         xcb_configure_notify_event_t *configure_notify;
599         xcb_generic_event_t *event;
600         int mapped = 0, configured = 0;
601         uint8_t response_type;
602
603         /* This isn't the nicest way to do this.  Ideally, we could
604          * just go back to the main loop and once we get the configure
605          * notify, we add the output to the compositor.  While we do
606          * support output hotplug, we can't start up with no outputs.
607          * We could add the output and then resize once we get the
608          * configure notify, but we don't want to start up and
609          * immediately resize the output.
610          *
611          * Also, some window managers don't give us our final
612          * fullscreen size before map_notify, so if we don't get a
613          * configure_notify before map_notify, we just wait for the
614          * first one and hope that's our size. */
615
616         xcb_flush(c->conn);
617
618         while (!mapped || !configured) {
619                 event = xcb_wait_for_event(c->conn);
620                 response_type = event->response_type & ~0x80;
621
622                 switch (response_type) {
623                 case XCB_MAP_NOTIFY:
624                         map_notify = (xcb_map_notify_event_t *) event;
625                         if (map_notify->window == output->window)
626                                 mapped = 1;
627                         break;
628
629                 case XCB_CONFIGURE_NOTIFY:
630                         configure_notify =
631                                 (xcb_configure_notify_event_t *) event;
632
633
634                         if (configure_notify->width % output->scale != 0 ||
635                             configure_notify->height % output->scale != 0)
636                                 weston_log("Resolution is not a multiple of screen size, rounding\n");
637                         output->mode.width = configure_notify->width / output->scale;
638                         output->mode.height = configure_notify->height / output->scale;
639                         configured = 1;
640                         break;
641                 }
642         }
643 }
644
645 static xcb_visualtype_t *
646 find_visual_by_id(xcb_screen_t *screen,
647                    xcb_visualid_t id)
648 {
649         xcb_depth_iterator_t i;
650         xcb_visualtype_iterator_t j;
651         for (i = xcb_screen_allowed_depths_iterator(screen);
652              i.rem;
653              xcb_depth_next(&i)) {
654                 for (j = xcb_depth_visuals_iterator(i.data);
655                      j.rem;
656                      xcb_visualtype_next(&j)) {
657                         if (j.data->visual_id == id)
658                                 return j.data;
659                 }
660         }
661         return 0;
662 }
663
664 static uint8_t
665 get_depth_of_visual(xcb_screen_t *screen,
666                    xcb_visualid_t id)
667 {
668         xcb_depth_iterator_t i;
669         xcb_visualtype_iterator_t j;
670         for (i = xcb_screen_allowed_depths_iterator(screen);
671              i.rem;
672              xcb_depth_next(&i)) {
673                 for (j = xcb_depth_visuals_iterator(i.data);
674                      j.rem;
675                      xcb_visualtype_next(&j)) {
676                         if (j.data->visual_id == id)
677                                 return i.data->depth;
678                 }
679         }
680         return 0;
681 }
682
683 static int
684 x11_output_init_shm(struct x11_compositor *c, struct x11_output *output,
685         int width, int height)
686 {
687         xcb_screen_iterator_t iter;
688         xcb_visualtype_t *visual_type;
689         xcb_format_iterator_t fmt;
690         xcb_void_cookie_t cookie;
691         xcb_generic_error_t *err;
692         const xcb_query_extension_reply_t *ext;
693         int bitsperpixel = 0;
694         pixman_format_code_t pixman_format;
695
696         /* Check if SHM is available */
697         ext = xcb_get_extension_data(c->conn, &xcb_shm_id);
698         if (ext == NULL || !ext->present) {
699                 /* SHM is missing */
700                 weston_log("SHM extension is not available\n");
701                 errno = ENOENT;
702                 return -1;
703         }
704
705         iter = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
706         visual_type = find_visual_by_id(iter.data, iter.data->root_visual);
707         if (!visual_type) {
708                 weston_log("Failed to lookup visual for root window\n");
709                 errno = ENOENT;
710                 return -1;
711         }
712         weston_log("Found visual, bits per value: %d, red_mask: %.8x, green_mask: %.8x, blue_mask: %.8x\n",
713                 visual_type->bits_per_rgb_value,
714                 visual_type->red_mask,
715                 visual_type->green_mask,
716                 visual_type->blue_mask);
717         output->depth = get_depth_of_visual(iter.data, iter.data->root_visual);
718         weston_log("Visual depth is %d\n", output->depth);
719
720         for (fmt = xcb_setup_pixmap_formats_iterator(xcb_get_setup(c->conn));
721              fmt.rem;
722              xcb_format_next(&fmt)) {
723                 if (fmt.data->depth == output->depth) {
724                         bitsperpixel = fmt.data->bits_per_pixel;
725                         break;
726                 }
727         }
728         weston_log("Found format for depth %d, bpp: %d\n",
729                 output->depth, bitsperpixel);
730
731         if  (bitsperpixel == 32 &&
732              visual_type->red_mask == 0xff0000 &&
733              visual_type->green_mask == 0x00ff00 &&
734              visual_type->blue_mask == 0x0000ff) {
735                 weston_log("Will use x8r8g8b8 format for SHM surfaces\n");
736                 pixman_format = PIXMAN_x8r8g8b8;
737         } else {
738                 weston_log("Can't find appropriate format for SHM pixmap\n");
739                 errno = ENOTSUP;
740                 return -1;
741         }
742
743
744         /* Create SHM segment and attach it */
745         output->shm_id = shmget(IPC_PRIVATE, width * height * (bitsperpixel / 8), IPC_CREAT | S_IRWXU);
746         if (output->shm_id == -1) {
747                 weston_log("x11shm: failed to allocate SHM segment\n");
748                 return -1;
749         }
750         output->buf = shmat(output->shm_id, NULL, 0 /* read/write */);
751         if (-1 == (long)output->buf) {
752                 weston_log("x11shm: failed to attach SHM segment\n");
753                 return -1;
754         }
755         output->segment = xcb_generate_id(c->conn);
756         cookie = xcb_shm_attach_checked(c->conn, output->segment, output->shm_id, 1);
757         err = xcb_request_check(c->conn, cookie);
758         if (err) {
759                 weston_log("x11shm: xcb_shm_attach error %d\n", err->error_code);
760                 free(err);
761                 return -1;
762         }
763
764         shmctl(output->shm_id, IPC_RMID, NULL);
765
766         /* Now create pixman image */
767         output->hw_surface = pixman_image_create_bits(pixman_format, width, height, output->buf,
768                 width * (bitsperpixel / 8));
769
770         output->gc = xcb_generate_id(c->conn);
771         xcb_create_gc(c->conn, output->gc, output->window, 0, NULL);
772
773         return 0;
774 }
775
776 static struct x11_output *
777 x11_compositor_create_output(struct x11_compositor *c, int x, int y,
778                              int width, int height, int fullscreen,
779                              int no_input, char *configured_name,
780                              uint32_t transform, uint32_t scale)
781 {
782         static const char name[] = "Weston Compositor";
783         static const char class[] = "weston-1\0Weston Compositor";
784         char title[32];
785         struct x11_output *output;
786         xcb_screen_iterator_t iter;
787         struct wm_normal_hints normal_hints;
788         struct wl_event_loop *loop;
789         int output_width, output_height;
790         uint32_t mask = XCB_CW_EVENT_MASK | XCB_CW_CURSOR;
791         xcb_atom_t atom_list[1];
792         uint32_t values[2] = {
793                 XCB_EVENT_MASK_EXPOSURE |
794                 XCB_EVENT_MASK_STRUCTURE_NOTIFY,
795                 0
796         };
797
798         output_width = width * scale;
799         output_height = height * scale;
800
801         if (configured_name)
802                 sprintf(title, "%s - %s", name, configured_name);
803         else
804                 strcpy(title, name);
805
806         if (!no_input)
807                 values[0] |=
808                         XCB_EVENT_MASK_KEY_PRESS |
809                         XCB_EVENT_MASK_KEY_RELEASE |
810                         XCB_EVENT_MASK_BUTTON_PRESS |
811                         XCB_EVENT_MASK_BUTTON_RELEASE |
812                         XCB_EVENT_MASK_POINTER_MOTION |
813                         XCB_EVENT_MASK_ENTER_WINDOW |
814                         XCB_EVENT_MASK_LEAVE_WINDOW |
815                         XCB_EVENT_MASK_KEYMAP_STATE |
816                         XCB_EVENT_MASK_FOCUS_CHANGE;
817
818         output = malloc(sizeof *output);
819         if (output == NULL)
820                 return NULL;
821
822         memset(output, 0, sizeof *output);
823
824         output->mode.flags =
825                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
826         if (output->scale != 1)
827                 output->mode.flags |= WL_OUTPUT_MODE_SCALED;
828
829         output->mode.width = width;
830         output->mode.height = height;
831         output->mode.refresh = 60000;
832         output->scale = scale;
833         wl_list_init(&output->base.mode_list);
834         wl_list_insert(&output->base.mode_list, &output->mode.link);
835
836         values[1] = c->null_cursor;
837         output->window = xcb_generate_id(c->conn);
838         iter = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
839         xcb_create_window(c->conn,
840                           XCB_COPY_FROM_PARENT,
841                           output->window,
842                           iter.data->root,
843                           0, 0,
844                           output_width, output_height,
845                           0,
846                           XCB_WINDOW_CLASS_INPUT_OUTPUT,
847                           iter.data->root_visual,
848                           mask, values);
849
850         if (fullscreen) {
851                 atom_list[0] = c->atom.net_wm_state_fullscreen;
852                 xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE,
853                                     output->window,
854                                     c->atom.net_wm_state,
855                                     XCB_ATOM_ATOM, 32,
856                                     ARRAY_LENGTH(atom_list), atom_list);
857         } else {
858                 /* Don't resize me. */
859                 memset(&normal_hints, 0, sizeof normal_hints);
860                 normal_hints.flags =
861                         WM_NORMAL_HINTS_MAX_SIZE | WM_NORMAL_HINTS_MIN_SIZE;
862                 normal_hints.min_width = output_width;
863                 normal_hints.min_height = output_height;
864                 normal_hints.max_width = output_width;
865                 normal_hints.max_height = output_height;
866                 xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
867                                     c->atom.wm_normal_hints,
868                                     c->atom.wm_size_hints, 32,
869                                     sizeof normal_hints / 4,
870                                     (uint8_t *) &normal_hints);
871         }
872
873         /* Set window name.  Don't bother with non-EWMH WMs. */
874         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
875                             c->atom.net_wm_name, c->atom.utf8_string, 8,
876                             strlen(title), title);
877         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
878                             c->atom.wm_class, c->atom.string, 8,
879                             sizeof class, class);
880
881         x11_output_set_icon(c, output, DATADIR "/weston/wayland.png");
882
883         x11_output_set_wm_protocols(c, output);
884
885         xcb_map_window(c->conn, output->window);
886
887         if (fullscreen)
888                 x11_output_wait_for_map(c, output);
889
890         output->base.origin = output->base.current;
891         output->base.start_repaint_loop = x11_output_start_repaint_loop;
892         if (c->use_pixman)
893                 output->base.repaint = x11_output_repaint_shm;
894         else
895                 output->base.repaint = x11_output_repaint_gl;
896         output->base.destroy = x11_output_destroy;
897         output->base.assign_planes = NULL;
898         output->base.set_backlight = NULL;
899         output->base.set_dpms = NULL;
900         output->base.switch_mode = NULL;
901         output->base.current = &output->mode;
902         output->base.make = "xwayland";
903         output->base.model = "none";
904         weston_output_init(&output->base, &c->base,
905                            x, y, width, height, transform, scale);
906
907         if (c->use_pixman) {
908                 if (x11_output_init_shm(c, output, output_width, output_height) < 0)
909                         return NULL;
910                 if (pixman_renderer_output_create(&output->base) < 0) {
911                         x11_output_deinit_shm(c, output);
912                         return NULL;
913                 }
914         } else {
915                 if (gl_renderer_output_create(&output->base, (EGLNativeWindowType)output->window) < 0)
916                         return NULL;
917         }
918
919         loop = wl_display_get_event_loop(c->base.wl_display);
920         output->finish_frame_timer =
921                 wl_event_loop_add_timer(loop, finish_frame_handler, output);
922
923         wl_list_insert(c->base.output_list.prev, &output->base.link);
924
925         weston_log("x11 output %dx%d, window id %d\n",
926                    width, height, output->window);
927
928         return output;
929 }
930
931 static struct x11_output *
932 x11_compositor_find_output(struct x11_compositor *c, xcb_window_t window)
933 {
934         struct x11_output *output;
935
936         wl_list_for_each(output, &c->base.output_list, base.link) {
937                 if (output->window == window)
938                         return output;
939         }
940
941         return NULL;
942 }
943
944 #ifdef HAVE_XCB_XKB
945 static void
946 update_xkb_state(struct x11_compositor *c, xcb_xkb_state_notify_event_t *state)
947 {
948         xkb_state_update_mask(c->core_seat.xkb_state.state,
949                               get_xkb_mod_mask(c, state->baseMods),
950                               get_xkb_mod_mask(c, state->latchedMods),
951                               get_xkb_mod_mask(c, state->lockedMods),
952                               0,
953                               0,
954                               state->group);
955
956         notify_modifiers(&c->core_seat,
957                          wl_display_next_serial(c->base.wl_display));
958 }
959 #endif
960
961 /**
962  * This is monumentally unpleasant.  If we don't have XCB-XKB bindings,
963  * the best we can do (given that XCB also lacks XI2 support), is to take
964  * the state from the core key events.  Unfortunately that only gives us
965  * the effective (i.e. union of depressed/latched/locked) state, and we
966  * need the granularity.
967  *
968  * So we still update the state with every key event we see, but also use
969  * the state field from X11 events as a mask so we don't get any stuck
970  * modifiers.
971  */
972 static void
973 update_xkb_state_from_core(struct x11_compositor *c, uint16_t x11_mask)
974 {
975         uint32_t mask = get_xkb_mod_mask(c, x11_mask);
976         struct weston_keyboard *keyboard = c->core_seat.keyboard;
977
978         xkb_state_update_mask(c->core_seat.xkb_state.state,
979                               keyboard->modifiers.mods_depressed & mask,
980                               keyboard->modifiers.mods_latched & mask,
981                               keyboard->modifiers.mods_locked & mask,
982                               0,
983                               0,
984                               (x11_mask >> 13) & 3);
985         notify_modifiers(&c->core_seat,
986                          wl_display_next_serial(c->base.wl_display));
987 }
988
989 static void
990 x11_compositor_deliver_button_event(struct x11_compositor *c,
991                                     xcb_generic_event_t *event, int state)
992 {
993         xcb_button_press_event_t *button_event =
994                 (xcb_button_press_event_t *) event;
995         uint32_t button;
996         struct x11_output *output;
997
998         output = x11_compositor_find_output(c, button_event->event);
999
1000         if (state)
1001                 xcb_grab_pointer(c->conn, 0, output->window,
1002                                  XCB_EVENT_MASK_BUTTON_PRESS |
1003                                  XCB_EVENT_MASK_BUTTON_RELEASE |
1004                                  XCB_EVENT_MASK_POINTER_MOTION |
1005                                  XCB_EVENT_MASK_ENTER_WINDOW |
1006                                  XCB_EVENT_MASK_LEAVE_WINDOW,
1007                                  XCB_GRAB_MODE_ASYNC,
1008                                  XCB_GRAB_MODE_ASYNC,
1009                                  output->window, XCB_CURSOR_NONE,
1010                                  button_event->time);
1011         else
1012                 xcb_ungrab_pointer(c->conn, button_event->time);
1013
1014         if (!c->has_xkb)
1015                 update_xkb_state_from_core(c, button_event->state);
1016
1017         switch (button_event->detail) {
1018         default:
1019                 button = button_event->detail + BTN_LEFT - 1;
1020                 break;
1021         case 2:
1022                 button = BTN_MIDDLE;
1023                 break;
1024         case 3:
1025                 button = BTN_RIGHT;
1026                 break;
1027         case 4:
1028                 /* Axis are measured in pixels, but the xcb events are discrete
1029                  * steps. Therefore move the axis by some pixels every step. */
1030                 if (state)
1031                         notify_axis(&c->core_seat,
1032                                     weston_compositor_get_time(),
1033                                     WL_POINTER_AXIS_VERTICAL_SCROLL,
1034                                     -DEFAULT_AXIS_STEP_DISTANCE);
1035                 return;
1036         case 5:
1037                 if (state)
1038                         notify_axis(&c->core_seat,
1039                                     weston_compositor_get_time(),
1040                                     WL_POINTER_AXIS_VERTICAL_SCROLL,
1041                                     DEFAULT_AXIS_STEP_DISTANCE);
1042                 return;
1043         case 6:
1044                 if (state)
1045                         notify_axis(&c->core_seat,
1046                                     weston_compositor_get_time(),
1047                                     WL_POINTER_AXIS_HORIZONTAL_SCROLL,
1048                                     -DEFAULT_AXIS_STEP_DISTANCE);
1049                 return;
1050         case 7:
1051                 if (state)
1052                         notify_axis(&c->core_seat,
1053                                     weston_compositor_get_time(),
1054                                     WL_POINTER_AXIS_HORIZONTAL_SCROLL,
1055                                     DEFAULT_AXIS_STEP_DISTANCE);
1056                 return;
1057         }
1058
1059         notify_button(&c->core_seat,
1060                       weston_compositor_get_time(), button,
1061                       state ? WL_POINTER_BUTTON_STATE_PRESSED :
1062                               WL_POINTER_BUTTON_STATE_RELEASED);
1063 }
1064
1065 static void
1066 x11_output_transform_coordinate(struct x11_output *x11_output,
1067                                                 wl_fixed_t *x, wl_fixed_t *y)
1068 {
1069         struct weston_output *output = &x11_output->base;
1070         wl_fixed_t tx, ty;
1071         wl_fixed_t width = wl_fixed_from_int(output->width * output->scale - 1);
1072         wl_fixed_t height = wl_fixed_from_int(output->height * output->scale - 1);
1073
1074         switch(output->transform) {
1075         case WL_OUTPUT_TRANSFORM_NORMAL:
1076         default:
1077                 tx = *x;
1078                 ty = *y;
1079                 break;
1080         case WL_OUTPUT_TRANSFORM_90:
1081                 tx = *y;
1082                 ty = height - *x;
1083                 break;
1084         case WL_OUTPUT_TRANSFORM_180:
1085                 tx = width - *x;
1086                 ty = height - *y;
1087                 break;
1088         case WL_OUTPUT_TRANSFORM_270:
1089                 tx = width - *y;
1090                 ty = *x;
1091                 break;
1092         case WL_OUTPUT_TRANSFORM_FLIPPED:
1093                 tx = width - *x;
1094                 ty = *y;
1095                 break;
1096         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1097                 tx = width - *y;
1098                 ty = height - *x;
1099                 break;
1100         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
1101                 tx = *x;
1102                 ty = height - *y;
1103                 break;
1104         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1105                 tx = *y;
1106                 ty = *x;
1107                 break;
1108         }
1109
1110         tx /= output->scale;
1111         ty /= output->scale;
1112
1113         tx += wl_fixed_from_int(output->x);
1114         ty += wl_fixed_from_int(output->y);
1115
1116         *x = tx;
1117         *y = ty;
1118 }
1119
1120 static void
1121 x11_compositor_deliver_motion_event(struct x11_compositor *c,
1122                                         xcb_generic_event_t *event)
1123 {
1124         struct x11_output *output;
1125         wl_fixed_t x, y;
1126         xcb_motion_notify_event_t *motion_notify =
1127                         (xcb_motion_notify_event_t *) event;
1128
1129         if (!c->has_xkb)
1130                 update_xkb_state_from_core(c, motion_notify->state);
1131         output = x11_compositor_find_output(c, motion_notify->event);
1132         x = wl_fixed_from_int(motion_notify->event_x);
1133         y = wl_fixed_from_int(motion_notify->event_y);
1134         x11_output_transform_coordinate(output, &x, &y);
1135
1136         notify_motion(&c->core_seat, weston_compositor_get_time(),
1137                       x - c->prev_x, y - c->prev_y);
1138
1139         c->prev_x = x;
1140         c->prev_y = y;
1141 }
1142
1143 static void
1144 x11_compositor_deliver_enter_event(struct x11_compositor *c,
1145                                         xcb_generic_event_t *event)
1146 {
1147         struct x11_output *output;
1148         wl_fixed_t x, y;
1149
1150         xcb_enter_notify_event_t *enter_notify =
1151                         (xcb_enter_notify_event_t *) event;
1152         if (enter_notify->state >= Button1Mask)
1153                 return;
1154         if (!c->has_xkb)
1155                 update_xkb_state_from_core(c, enter_notify->state);
1156         output = x11_compositor_find_output(c, enter_notify->event);
1157         x = wl_fixed_from_int(enter_notify->event_x);
1158         y = wl_fixed_from_int(enter_notify->event_y);
1159         x11_output_transform_coordinate(output, &x, &y);
1160
1161         notify_pointer_focus(&c->core_seat, &output->base, x, y);
1162
1163         c->prev_x = x;
1164         c->prev_y = y;
1165 }
1166
1167 static int
1168 x11_compositor_next_event(struct x11_compositor *c,
1169                           xcb_generic_event_t **event, uint32_t mask)
1170 {
1171         if (mask & WL_EVENT_READABLE) {
1172                 *event = xcb_poll_for_event(c->conn);
1173         } else {
1174 #ifdef HAVE_XCB_POLL_FOR_QUEUED_EVENT
1175                 *event = xcb_poll_for_queued_event(c->conn);
1176 #else
1177                 *event = xcb_poll_for_event(c->conn);
1178 #endif
1179         }
1180
1181         return *event != NULL;
1182 }
1183
1184 static int
1185 x11_compositor_handle_event(int fd, uint32_t mask, void *data)
1186 {
1187         struct x11_compositor *c = data;
1188         struct x11_output *output;
1189         xcb_generic_event_t *event, *prev;
1190         xcb_client_message_event_t *client_message;
1191         xcb_enter_notify_event_t *enter_notify;
1192         xcb_key_press_event_t *key_press, *key_release;
1193         xcb_keymap_notify_event_t *keymap_notify;
1194         xcb_focus_in_event_t *focus_in;
1195         xcb_expose_event_t *expose;
1196         xcb_atom_t atom;
1197         uint32_t *k;
1198         uint32_t i, set;
1199         uint8_t response_type;
1200         int count;
1201
1202         prev = NULL;
1203         count = 0;
1204         while (x11_compositor_next_event(c, &event, mask)) {
1205                 response_type = event->response_type & ~0x80;
1206
1207                 switch (prev ? prev->response_type & ~0x80 : 0x80) {
1208                 case XCB_KEY_RELEASE:
1209                         /* Suppress key repeat events; this is only used if we
1210                          * don't have XCB XKB support. */
1211                         key_release = (xcb_key_press_event_t *) prev;
1212                         key_press = (xcb_key_press_event_t *) event;
1213                         if (response_type == XCB_KEY_PRESS &&
1214                             key_release->time == key_press->time &&
1215                             key_release->detail == key_press->detail) {
1216                                 /* Don't deliver the held key release
1217                                  * event or the new key press event. */
1218                                 free(event);
1219                                 free(prev);
1220                                 prev = NULL;
1221                                 continue;
1222                         } else {
1223                                 /* Deliver the held key release now
1224                                  * and fall through and handle the new
1225                                  * event below. */
1226                                 update_xkb_state_from_core(c, key_release->state);
1227                                 notify_key(&c->core_seat,
1228                                            weston_compositor_get_time(),
1229                                            key_release->detail - 8,
1230                                            WL_KEYBOARD_KEY_STATE_RELEASED,
1231                                            STATE_UPDATE_AUTOMATIC);
1232                                 free(prev);
1233                                 prev = NULL;
1234                                 break;
1235                         }
1236
1237                 case XCB_FOCUS_IN:
1238                         assert(response_type == XCB_KEYMAP_NOTIFY);
1239                         keymap_notify = (xcb_keymap_notify_event_t *) event;
1240                         c->keys.size = 0;
1241                         for (i = 0; i < ARRAY_LENGTH(keymap_notify->keys) * 8; i++) {
1242                                 set = keymap_notify->keys[i >> 3] &
1243                                         (1 << (i & 7));
1244                                 if (set) {
1245                                         k = wl_array_add(&c->keys, sizeof *k);
1246                                         *k = i;
1247                                 }
1248                         }
1249
1250                         /* Unfortunately the state only comes with the enter
1251                          * event, rather than with the focus event.  I'm not
1252                          * sure of the exact semantics around it and whether
1253                          * we can ensure that we get both? */
1254                         notify_keyboard_focus_in(&c->core_seat, &c->keys,
1255                                                  STATE_UPDATE_AUTOMATIC);
1256
1257                         free(prev);
1258                         prev = NULL;
1259                         break;
1260
1261                 default:
1262                         /* No previous event held */
1263                         break;
1264                 }
1265
1266                 switch (response_type) {
1267                 case XCB_KEY_PRESS:
1268                         key_press = (xcb_key_press_event_t *) event;
1269                         if (!c->has_xkb)
1270                                 update_xkb_state_from_core(c, key_press->state);
1271                         notify_key(&c->core_seat,
1272                                    weston_compositor_get_time(),
1273                                    key_press->detail - 8,
1274                                    WL_KEYBOARD_KEY_STATE_PRESSED,
1275                                    c->has_xkb ? STATE_UPDATE_NONE :
1276                                                 STATE_UPDATE_AUTOMATIC);
1277                         break;
1278                 case XCB_KEY_RELEASE:
1279                         /* If we don't have XKB, we need to use the lame
1280                          * autorepeat detection above. */
1281                         if (!c->has_xkb) {
1282                                 prev = event;
1283                                 break;
1284                         }
1285                         key_release = (xcb_key_press_event_t *) event;
1286                         notify_key(&c->core_seat,
1287                                    weston_compositor_get_time(),
1288                                    key_release->detail - 8,
1289                                    WL_KEYBOARD_KEY_STATE_RELEASED,
1290                                    STATE_UPDATE_NONE);
1291                         break;
1292                 case XCB_BUTTON_PRESS:
1293                         x11_compositor_deliver_button_event(c, event, 1);
1294                         break;
1295                 case XCB_BUTTON_RELEASE:
1296                         x11_compositor_deliver_button_event(c, event, 0);
1297                         break;
1298                 case XCB_MOTION_NOTIFY:
1299                         x11_compositor_deliver_motion_event(c, event);
1300                         break;
1301
1302                 case XCB_EXPOSE:
1303                         expose = (xcb_expose_event_t *) event;
1304                         output = x11_compositor_find_output(c, expose->window);
1305                         weston_output_schedule_repaint(&output->base);
1306                         break;
1307
1308                 case XCB_ENTER_NOTIFY:
1309                         x11_compositor_deliver_enter_event(c, event);
1310                         break;
1311
1312                 case XCB_LEAVE_NOTIFY:
1313                         enter_notify = (xcb_enter_notify_event_t *) event;
1314                         if (enter_notify->state >= Button1Mask)
1315                                 break;
1316                         if (!c->has_xkb)
1317                                 update_xkb_state_from_core(c, enter_notify->state);
1318                         notify_pointer_focus(&c->core_seat, NULL, 0, 0);
1319                         break;
1320
1321                 case XCB_CLIENT_MESSAGE:
1322                         client_message = (xcb_client_message_event_t *) event;
1323                         atom = client_message->data.data32[0];
1324                         if (atom == c->atom.wm_delete_window)
1325                                 wl_display_terminate(c->base.wl_display);
1326                         break;
1327
1328                 case XCB_FOCUS_IN:
1329                         focus_in = (xcb_focus_in_event_t *) event;
1330                         if (focus_in->mode == XCB_NOTIFY_MODE_WHILE_GRABBED)
1331                                 break;
1332
1333                         prev = event;
1334                         break;
1335
1336                 case XCB_FOCUS_OUT:
1337                         focus_in = (xcb_focus_in_event_t *) event;
1338                         if (focus_in->mode == XCB_NOTIFY_MODE_WHILE_GRABBED ||
1339                             focus_in->mode == XCB_NOTIFY_MODE_UNGRAB)
1340                                 break;
1341                         notify_keyboard_focus_out(&c->core_seat);
1342                         break;
1343
1344                 default:
1345                         break;
1346                 }
1347
1348 #ifdef HAVE_XCB_XKB
1349                 if (c->has_xkb &&
1350                     response_type == c->xkb_event_base) {
1351                         xcb_xkb_state_notify_event_t *state =
1352                                 (xcb_xkb_state_notify_event_t *) event;
1353                         if (state->xkbType == XCB_XKB_STATE_NOTIFY)
1354                                 update_xkb_state(c, state);
1355                 }
1356 #endif
1357
1358                 count++;
1359                 if (prev != event)
1360                         free (event);
1361         }
1362
1363         switch (prev ? prev->response_type & ~0x80 : 0x80) {
1364         case XCB_KEY_RELEASE:
1365                 key_release = (xcb_key_press_event_t *) prev;
1366                 update_xkb_state_from_core(c, key_release->state);
1367                 notify_key(&c->core_seat,
1368                            weston_compositor_get_time(),
1369                            key_release->detail - 8,
1370                            WL_KEYBOARD_KEY_STATE_RELEASED,
1371                            STATE_UPDATE_AUTOMATIC);
1372                 free(prev);
1373                 prev = NULL;
1374                 break;
1375         default:
1376                 break;
1377         }
1378
1379         return count;
1380 }
1381
1382 #define F(field) offsetof(struct x11_compositor, field)
1383
1384 static void
1385 x11_compositor_get_resources(struct x11_compositor *c)
1386 {
1387         static const struct { const char *name; int offset; } atoms[] = {
1388                 { "WM_PROTOCOLS",       F(atom.wm_protocols) },
1389                 { "WM_NORMAL_HINTS",    F(atom.wm_normal_hints) },
1390                 { "WM_SIZE_HINTS",      F(atom.wm_size_hints) },
1391                 { "WM_DELETE_WINDOW",   F(atom.wm_delete_window) },
1392                 { "WM_CLASS",           F(atom.wm_class) },
1393                 { "_NET_WM_NAME",       F(atom.net_wm_name) },
1394                 { "_NET_WM_ICON",       F(atom.net_wm_icon) },
1395                 { "_NET_WM_STATE",      F(atom.net_wm_state) },
1396                 { "_NET_WM_STATE_FULLSCREEN", F(atom.net_wm_state_fullscreen) },
1397                 { "_NET_SUPPORTING_WM_CHECK",
1398                                         F(atom.net_supporting_wm_check) },
1399                 { "_NET_SUPPORTED",     F(atom.net_supported) },
1400                 { "STRING",             F(atom.string) },
1401                 { "UTF8_STRING",        F(atom.utf8_string) },
1402                 { "CARDINAL",           F(atom.cardinal) },
1403                 { "_XKB_RULES_NAMES",   F(atom.xkb_names) },
1404         };
1405
1406         xcb_intern_atom_cookie_t cookies[ARRAY_LENGTH(atoms)];
1407         xcb_intern_atom_reply_t *reply;
1408         xcb_pixmap_t pixmap;
1409         xcb_gc_t gc;
1410         unsigned int i;
1411         uint8_t data[] = { 0, 0, 0, 0 };
1412
1413         for (i = 0; i < ARRAY_LENGTH(atoms); i++)
1414                 cookies[i] = xcb_intern_atom (c->conn, 0,
1415                                               strlen(atoms[i].name),
1416                                               atoms[i].name);
1417
1418         for (i = 0; i < ARRAY_LENGTH(atoms); i++) {
1419                 reply = xcb_intern_atom_reply (c->conn, cookies[i], NULL);
1420                 *(xcb_atom_t *) ((char *) c + atoms[i].offset) = reply->atom;
1421                 free(reply);
1422         }
1423
1424         pixmap = xcb_generate_id(c->conn);
1425         gc = xcb_generate_id(c->conn);
1426         xcb_create_pixmap(c->conn, 1, pixmap, c->screen->root, 1, 1);
1427         xcb_create_gc(c->conn, gc, pixmap, 0, NULL);
1428         xcb_put_image(c->conn, XCB_IMAGE_FORMAT_XY_PIXMAP,
1429                       pixmap, gc, 1, 1, 0, 0, 0, 32, sizeof data, data);
1430         c->null_cursor = xcb_generate_id(c->conn);
1431         xcb_create_cursor (c->conn, c->null_cursor,
1432                            pixmap, pixmap, 0, 0, 0,  0, 0, 0,  1, 1);
1433         xcb_free_gc(c->conn, gc);
1434         xcb_free_pixmap(c->conn, pixmap);
1435 }
1436
1437 static void
1438 x11_compositor_get_wm_info(struct x11_compositor *c)
1439 {
1440         xcb_get_property_cookie_t cookie;
1441         xcb_get_property_reply_t *reply;
1442         xcb_atom_t *atom;
1443         unsigned int i;
1444
1445         cookie = xcb_get_property(c->conn, 0, c->screen->root,
1446                                   c->atom.net_supported,
1447                                   XCB_ATOM_ATOM, 0, 1024);
1448         reply = xcb_get_property_reply(c->conn, cookie, NULL);
1449         if (reply == NULL)
1450                 return;
1451
1452         atom = (xcb_atom_t *) xcb_get_property_value(reply);
1453
1454         for (i = 0; i < reply->value_len; i++) {
1455                 if (atom[i] == c->atom.net_wm_state_fullscreen)
1456                         c->has_net_wm_state_fullscreen = 1;
1457         }
1458 }
1459
1460 static void
1461 x11_restore(struct weston_compositor *ec)
1462 {
1463 }
1464
1465 static void
1466 x11_destroy(struct weston_compositor *ec)
1467 {
1468         struct x11_compositor *compositor = (struct x11_compositor *)ec;
1469
1470         wl_event_source_remove(compositor->xcb_source);
1471         x11_input_destroy(compositor);
1472
1473         weston_compositor_shutdown(ec); /* destroys outputs, too */
1474
1475         ec->renderer->destroy(ec);
1476
1477         XCloseDisplay(compositor->dpy);
1478         free(ec);
1479 }
1480
1481 static uint32_t
1482 parse_transform(const char *transform, const char *output_name)
1483 {
1484         static const struct { const char *name; uint32_t token; } names[] = {
1485                 { "normal",     WL_OUTPUT_TRANSFORM_NORMAL },
1486                 { "90",         WL_OUTPUT_TRANSFORM_90 },
1487                 { "180",        WL_OUTPUT_TRANSFORM_180 },
1488                 { "270",        WL_OUTPUT_TRANSFORM_270 },
1489                 { "flipped",    WL_OUTPUT_TRANSFORM_FLIPPED },
1490                 { "flipped-90", WL_OUTPUT_TRANSFORM_FLIPPED_90 },
1491                 { "flipped-180", WL_OUTPUT_TRANSFORM_FLIPPED_180 },
1492                 { "flipped-270", WL_OUTPUT_TRANSFORM_FLIPPED_270 },
1493         };
1494         unsigned int i;
1495
1496         for (i = 0; i < ARRAY_LENGTH(names); i++)
1497                 if (strcmp(names[i].name, transform) == 0)
1498                         return names[i].token;
1499
1500         weston_log("Invalid transform \"%s\" for output %s\n",
1501                    transform, output_name);
1502
1503         return WL_OUTPUT_TRANSFORM_NORMAL;
1504 }
1505
1506 static struct weston_compositor *
1507 x11_compositor_create(struct wl_display *display,
1508                       int fullscreen,
1509                       int no_input,
1510                       int use_pixman,
1511                       int *argc, char *argv[],
1512                       struct weston_config *config)
1513 {
1514         struct x11_compositor *c;
1515         struct x11_output *output;
1516         struct weston_config_section *section;
1517         xcb_screen_iterator_t s;
1518         int i, x = 0, output_count = 0;
1519         int width, height, count, scale;
1520         const char *section_name;
1521         char *name, *t, *mode;
1522         uint32_t transform;
1523
1524         weston_log("initializing x11 backend\n");
1525
1526         c = malloc(sizeof *c);
1527         if (c == NULL)
1528                 return NULL;
1529
1530         memset(c, 0, sizeof *c);
1531
1532         if (weston_compositor_init(&c->base, display, argc, argv, config) < 0)
1533                 goto err_free;
1534
1535         c->dpy = XOpenDisplay(NULL);
1536         if (c->dpy == NULL)
1537                 goto err_free;
1538
1539         c->conn = XGetXCBConnection(c->dpy);
1540         XSetEventQueueOwner(c->dpy, XCBOwnsEventQueue);
1541
1542         if (xcb_connection_has_error(c->conn))
1543                 goto err_xdisplay;
1544
1545         s = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
1546         c->screen = s.data;
1547         wl_array_init(&c->keys);
1548
1549         x11_compositor_get_resources(c);
1550         x11_compositor_get_wm_info(c);
1551
1552         if (!c->has_net_wm_state_fullscreen && fullscreen) {
1553                 weston_log("Can not fullscreen without window manager support"
1554                            "(need _NET_WM_STATE_FULLSCREEN)\n");
1555                 fullscreen = 0;
1556         }
1557
1558         c->base.wl_display = display;
1559         c->use_pixman = use_pixman;
1560         if (c->use_pixman) {
1561                 if (pixman_renderer_init(&c->base) < 0)
1562                         goto err_xdisplay;
1563         }
1564         else {
1565                 if (gl_renderer_create(&c->base, (EGLNativeDisplayType)c->dpy, gl_renderer_opaque_attribs,
1566                                 NULL) < 0)
1567                         goto err_xdisplay;
1568         }
1569         weston_log("Using %s renderer\n", use_pixman ? "pixman" : "gl");
1570
1571         c->base.destroy = x11_destroy;
1572         c->base.restore = x11_restore;
1573
1574         if (x11_input_create(c, no_input) < 0)
1575                 goto err_renderer;
1576
1577         width = option_width ? option_width : 1024;
1578         height = option_height ? option_height : 640;
1579         count = option_count ? option_count : 1;
1580
1581         section = NULL;
1582         while (weston_config_next_section(c->base.config,
1583                                           &section, &section_name)) {
1584                 if (strcmp(section_name, "output") != 0)
1585                         continue;
1586                 weston_config_section_get_string(section, "name", &name, NULL);
1587                 if (name == NULL || name[0] != 'X')
1588                         continue;
1589
1590                 weston_config_section_get_string(section,
1591                                                  "mode", &mode, "1024x600");
1592                 if (sscanf(mode, "%dx%d", &width, &height) != 2) {
1593                         weston_log("Invalid mode \"%s\" for output %s\n",
1594                                    mode, name);
1595                         width = 1024;
1596                         height = 600;
1597                 }
1598                 free(mode);
1599
1600                 if (option_width)
1601                         width = option_width;
1602                 if (option_height)
1603                         height = option_height;
1604
1605                 weston_config_section_get_int(section, "scale", &scale, 1);
1606                 weston_config_section_get_string(section,
1607                                                  "transform", &t, "normal");
1608                 transform = parse_transform(t, name);
1609                 free(t);
1610
1611                 output = x11_compositor_create_output(c, x, 0,
1612                                                       width, height,
1613                                                       fullscreen, no_input,
1614                                                       name, transform, scale);
1615                 free(name);
1616                 if (output == NULL)
1617                         goto err_x11_input;
1618
1619                 x = pixman_region32_extents(&output->base.region)->x2;
1620
1621                 output_count++;
1622                 if (option_count && output_count >= option_count)
1623                         break;
1624         }
1625
1626         for (i = output_count; i < count; i++) {
1627                 output = x11_compositor_create_output(c, x, 0, width, height,
1628                                                       fullscreen, no_input, NULL,
1629                                                       WL_OUTPUT_TRANSFORM_NORMAL, 1);
1630                 if (output == NULL)
1631                         goto err_x11_input;
1632                 x = pixman_region32_extents(&output->base.region)->x2;
1633         }
1634
1635         c->xcb_source =
1636                 wl_event_loop_add_fd(c->base.input_loop,
1637                                      xcb_get_file_descriptor(c->conn),
1638                                      WL_EVENT_READABLE,
1639                                      x11_compositor_handle_event, c);
1640         wl_event_source_check(c->xcb_source);
1641
1642         return &c->base;
1643
1644 err_x11_input:
1645         x11_input_destroy(c);
1646 err_renderer:
1647         c->base.renderer->destroy(&c->base);
1648 err_xdisplay:
1649         XCloseDisplay(c->dpy);
1650 err_free:
1651         free(c);
1652         return NULL;
1653 }
1654
1655 WL_EXPORT struct weston_compositor *
1656 backend_init(struct wl_display *display, int *argc, char *argv[],
1657              struct weston_config *config)
1658 {
1659         int fullscreen = 0;
1660         int no_input = 0;
1661         int use_pixman = 0;
1662
1663         const struct weston_option x11_options[] = {
1664                 { WESTON_OPTION_INTEGER, "width", 0, &option_width },
1665                 { WESTON_OPTION_INTEGER, "height", 0, &option_height },
1666                 { WESTON_OPTION_BOOLEAN, "fullscreen", 'f', &fullscreen },
1667                 { WESTON_OPTION_INTEGER, "output-count", 0, &option_count },
1668                 { WESTON_OPTION_BOOLEAN, "no-input", 0, &no_input },
1669                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
1670         };
1671
1672         parse_options(x11_options, ARRAY_LENGTH(x11_options), argc, argv);
1673
1674         return x11_compositor_create(display,
1675                                      fullscreen,
1676                                      no_input,
1677                                      use_pixman,
1678                                      argc, argv, config);
1679 }