toytoolkit: Don't draw shadows for maximized windows.
[profile/ivi/weston.git] / src / compositor-x11.c
1 /*
2  * Copyright © 2008-2011 Kristian Høgsberg
3  * Copyright © 2010-2011 Intel Corporation
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and
6  * its documentation for any purpose is hereby granted without fee, provided
7  * that the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation, and that the name of the copyright holders not be used in
10  * advertising or publicity pertaining to distribution of the software
11  * without specific, written prior permission.  The copyright holders make
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied warranty.
14  *
15  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
16  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
19  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
20  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <stddef.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <errno.h>
34 #include <sys/time.h>
35 #include <linux/input.h>
36
37 #include <xcb/xcb.h>
38 #ifdef HAVE_XCB_XKB
39 #include <xcb/xkb.h>
40 #endif
41
42 #include <X11/Xlib.h>
43 #include <X11/Xlib-xcb.h>
44
45 #include <xkbcommon/xkbcommon.h>
46
47 #include <GLES2/gl2.h>
48 #include <EGL/egl.h>
49
50 #include "compositor.h"
51 #include "../shared/config-parser.h"
52
53 static char *output_name;
54 static char *output_mode;
55 static char *output_transform;
56 static int option_width;
57 static int option_height;
58 static int option_count;
59 static struct wl_list configured_output_list;
60
61 struct x11_configured_output {
62         char *name;
63         int width, height;
64         uint32_t transform;
65         struct wl_list link;
66 };
67
68 struct x11_compositor {
69         struct weston_compositor         base;
70
71         Display                 *dpy;
72         xcb_connection_t        *conn;
73         xcb_screen_t            *screen;
74         xcb_cursor_t             null_cursor;
75         struct wl_array          keys;
76         struct wl_event_source  *xcb_source;
77         struct xkb_keymap       *xkb_keymap;
78         unsigned int             has_xkb;
79         uint8_t                  xkb_event_base;
80
81         /* We could map multi-pointer X to multiple wayland seats, but
82          * for now we only support core X input. */
83         struct weston_seat       core_seat;
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_wm_icon;
93                 xcb_atom_t               net_wm_state;
94                 xcb_atom_t               net_wm_state_fullscreen;
95                 xcb_atom_t               string;
96                 xcb_atom_t               utf8_string;
97                 xcb_atom_t               cardinal;
98                 xcb_atom_t               xkb_names;
99         } atom;
100 };
101
102 struct x11_output {
103         struct weston_output    base;
104
105         xcb_window_t            window;
106         struct weston_mode      mode;
107         struct wl_event_source *finish_frame_timer;
108 };
109
110 static struct xkb_keymap *
111 x11_compositor_get_keymap(struct x11_compositor *c)
112 {
113         xcb_get_property_cookie_t cookie;
114         xcb_get_property_reply_t *reply;
115         xcb_generic_error_t *error;
116         struct xkb_rule_names names;
117         struct xkb_keymap *ret;
118         const char *value_all, *value_part;
119         int length_all, length_part;
120
121         memset(&names, 0, sizeof(names));
122
123         cookie = xcb_get_property(c->conn, 0, c->screen->root,
124                                   c->atom.xkb_names, c->atom.string, 0, 1024);
125         reply = xcb_get_property_reply(c->conn, cookie, &error);
126         if (reply == NULL)
127                 return NULL;
128
129         value_all = xcb_get_property_value(reply);
130         length_all = xcb_get_property_value_length(reply);
131         value_part = value_all;
132
133 #define copy_prop_value(to) \
134         length_part = strlen(value_part); \
135         if (value_part + length_part < (value_all + length_all) && \
136             length_part > 0) \
137                 names.to = value_part; \
138         value_part += length_part + 1;
139
140         copy_prop_value(rules);
141         copy_prop_value(model);
142         copy_prop_value(layout);
143         copy_prop_value(variant);
144         copy_prop_value(options);
145 #undef copy_prop_value
146
147         ret = xkb_map_new_from_names(c->base.xkb_context, &names, 0);
148
149         free(reply);
150         return ret;
151 }
152
153 static void
154 x11_compositor_setup_xkb(struct x11_compositor *c)
155 {
156 #ifndef HAVE_XCB_XKB
157         weston_log("XCB-XKB not available during build\n");
158         c->has_xkb = 0;
159         c->xkb_event_base = 0;
160         return;
161 #else
162         const xcb_query_extension_reply_t *ext;
163         xcb_generic_error_t *error;
164         xcb_void_cookie_t select;
165         xcb_xkb_per_client_flags_cookie_t pcf;
166         xcb_xkb_per_client_flags_reply_t *pcf_reply;
167
168         c->has_xkb = 0;
169         c->xkb_event_base = 0;
170
171         ext = xcb_get_extension_data(c->conn, &xcb_xkb_id);
172         if (!ext) {
173                 weston_log("XKB extension not available on host X11 server\n");
174                 return;
175         }
176         c->xkb_event_base = ext->first_event;
177
178         select = xcb_xkb_select_events(c->conn,
179                                        XCB_XKB_ID_USE_CORE_KBD,
180                                        XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
181                                        0,
182                                        XCB_XKB_EVENT_TYPE_STATE_NOTIFY,
183                                        0,
184                                        0,
185                                        NULL);
186         error = xcb_request_check(c->conn, select);
187         if (error) {
188                 weston_log("error: failed to select for XKB state events\n");
189                 return;
190         }
191
192         pcf = xcb_xkb_per_client_flags(c->conn,
193                                        XCB_XKB_ID_USE_CORE_KBD,
194                                        XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT,
195                                        XCB_XKB_PER_CLIENT_FLAG_DETECTABLE_AUTO_REPEAT,
196                                        0,
197                                        0,
198                                        0);
199         pcf_reply = xcb_xkb_per_client_flags_reply(c->conn, pcf, &error);
200         free(pcf_reply);
201         if (error) {
202                 weston_log("failed to set XKB per-client flags, not using "
203                            "detectable repeat\n");
204                 return;
205         }
206
207         c->has_xkb = 1;
208 #endif
209 }
210
211 static int
212 x11_input_create(struct x11_compositor *c, int no_input)
213 {
214         struct xkb_keymap *keymap;
215
216         weston_seat_init(&c->core_seat, &c->base);
217
218         if (no_input)
219                 return 0;
220
221         weston_seat_init_pointer(&c->core_seat);
222
223         x11_compositor_setup_xkb(c);
224
225         keymap = x11_compositor_get_keymap(c);
226         weston_seat_init_keyboard(&c->core_seat, keymap);
227         if (keymap)
228                 xkb_map_unref(keymap);
229
230         return 0;
231 }
232
233 static void
234 x11_input_destroy(struct x11_compositor *compositor)
235 {
236         weston_seat_release(&compositor->core_seat);
237 }
238
239 static int
240 x11_compositor_init_egl(struct x11_compositor *c)
241 {
242         EGLint major, minor;
243         EGLint n;
244         EGLint config_attribs[] = {
245                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
246                 EGL_RED_SIZE, 1,
247                 EGL_GREEN_SIZE, 1,
248                 EGL_BLUE_SIZE, 1,
249                 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
250                 EGL_NONE
251         };
252
253         c->base.egl_display = eglGetDisplay(c->dpy);
254         if (c->base.egl_display == NULL) {
255                 weston_log("failed to create display\n");
256                 return -1;
257         }
258
259         if (!eglInitialize(c->base.egl_display, &major, &minor)) {
260                 weston_log("failed to initialize display\n");
261                 return -1;
262         }
263
264         if (!eglChooseConfig(c->base.egl_display, config_attribs,
265                              &c->base.egl_config, 1, &n) || n == 0) {
266                 weston_log("failed to choose config: %d\n", n);
267                 return -1;
268         }
269
270         return 0;
271 }
272
273 static void
274 x11_compositor_fini_egl(struct x11_compositor *compositor)
275 {
276         gles2_renderer_destroy(&compositor->base);
277
278         eglMakeCurrent(compositor->base.egl_display,
279                        EGL_NO_SURFACE, EGL_NO_SURFACE,
280                        EGL_NO_CONTEXT);
281
282         eglTerminate(compositor->base.egl_display);
283         eglReleaseThread();
284 }
285
286 static void
287 x11_output_repaint(struct weston_output *output_base,
288                    pixman_region32_t *damage)
289 {
290         struct x11_output *output = (struct x11_output *)output_base;
291         struct weston_compositor *ec = output->base.compositor;
292
293         ec->renderer->repaint_output(output_base, damage);
294
295         wl_event_source_timer_update(output->finish_frame_timer, 10);
296 }
297
298 static int
299 finish_frame_handler(void *data)
300 {
301         struct x11_output *output = data;
302         uint32_t msec;
303         struct timeval tv;
304         
305         gettimeofday(&tv, NULL);
306         msec = tv.tv_sec * 1000 + tv.tv_usec / 1000;
307         weston_output_finish_frame(&output->base, msec);
308
309         return 1;
310 }
311
312 static void
313 x11_output_destroy(struct weston_output *output_base)
314 {
315         struct x11_output *output = (struct x11_output *)output_base;
316         struct x11_compositor *compositor =
317                 (struct x11_compositor *)output->base.compositor;
318
319         wl_list_remove(&output->base.link);
320         wl_event_source_remove(output->finish_frame_timer);
321
322         eglDestroySurface(compositor->base.egl_display,
323                           output->base.egl_surface);
324
325         xcb_destroy_window(compositor->conn, output->window);
326
327         weston_output_destroy(&output->base);
328
329         free(output);
330 }
331
332 static void
333 x11_output_set_wm_protocols(struct x11_output *output)
334 {
335         xcb_atom_t list[1];
336         struct x11_compositor *c =
337                 (struct x11_compositor *) output->base.compositor;
338
339         list[0] = c->atom.wm_delete_window;
340         xcb_change_property (c->conn, 
341                              XCB_PROP_MODE_REPLACE,
342                              output->window,
343                              c->atom.wm_protocols,
344                              XCB_ATOM_ATOM,
345                              32,
346                              ARRAY_LENGTH(list),
347                              list);
348 }
349
350 static void
351 x11_output_change_state(struct x11_output *output, int add, xcb_atom_t state)
352 {
353         xcb_client_message_event_t event;
354         struct x11_compositor *c =
355                 (struct x11_compositor *) output->base.compositor;
356         xcb_screen_iterator_t iter;
357
358 #define _NET_WM_STATE_REMOVE        0    /* remove/unset property */
359 #define _NET_WM_STATE_ADD           1    /* add/set property */
360 #define _NET_WM_STATE_TOGGLE        2    /* toggle property  */  
361
362         memset(&event, 0, sizeof event);
363         event.response_type = XCB_CLIENT_MESSAGE;
364         event.format = 32;
365         event.window = output->window;
366         event.type = c->atom.net_wm_state;
367
368         event.data.data32[0] = add ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
369         event.data.data32[1] = state;
370         event.data.data32[2] = 0;
371         event.data.data32[3] = 0;
372         event.data.data32[4] = 0;
373
374         iter = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
375         xcb_send_event(c->conn, 0, iter.data->root,
376                        XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
377                        XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT,
378                        (void *) &event);
379 }
380
381
382 struct wm_normal_hints {
383         uint32_t flags;
384         uint32_t pad[4];
385         int32_t min_width, min_height;
386         int32_t max_width, max_height;
387         int32_t width_inc, height_inc;
388         int32_t min_aspect_x, min_aspect_y;
389         int32_t max_aspect_x, max_aspect_y;
390         int32_t base_width, base_height;
391         int32_t win_gravity;
392 };
393
394 #define WM_NORMAL_HINTS_MIN_SIZE        16
395 #define WM_NORMAL_HINTS_MAX_SIZE        32
396
397 static void
398 x11_output_set_icon(struct x11_compositor *c,
399                     struct x11_output *output, const char *filename)
400 {
401         uint32_t *icon;
402         int32_t width, height;
403         pixman_image_t *image;
404
405         image = load_image(filename);
406         if (!image)
407                 return;
408         width = pixman_image_get_width(image);
409         height = pixman_image_get_height(image);
410         icon = malloc(width * height * 4 + 8);
411         if (!icon) {
412                 pixman_image_unref(image);
413                 return;
414         }
415
416         icon[0] = width;
417         icon[1] = height;
418         memcpy(icon + 2, pixman_image_get_data(image), width * height * 4);
419         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
420                             c->atom.net_wm_icon, c->atom.cardinal, 32,
421                             width * height + 2, icon);
422         free(icon);
423         pixman_image_unref(image);
424 }
425
426 static struct x11_output *
427 x11_compositor_create_output(struct x11_compositor *c, int x, int y,
428                              int width, int height, int fullscreen,
429                              int no_input, char *configured_name,
430                              uint32_t transform)
431 {
432         static const char name[] = "Weston Compositor";
433         static const char class[] = "weston-1\0Weston Compositor";
434         char title[32];
435         struct x11_output *output;
436         xcb_screen_iterator_t iter;
437         struct wm_normal_hints normal_hints;
438         struct wl_event_loop *loop;
439         uint32_t mask = XCB_CW_EVENT_MASK | XCB_CW_CURSOR;
440         uint32_t values[2] = {
441                 XCB_EVENT_MASK_EXPOSURE |
442                 XCB_EVENT_MASK_STRUCTURE_NOTIFY,
443                 0
444         };
445
446         if (configured_name)
447                 sprintf(title, "%s - %s", name, configured_name);
448         else
449                 strcpy(title, name);
450
451         if (!no_input)
452                 values[0] |=
453                         XCB_EVENT_MASK_KEY_PRESS |
454                         XCB_EVENT_MASK_KEY_RELEASE |
455                         XCB_EVENT_MASK_BUTTON_PRESS |
456                         XCB_EVENT_MASK_BUTTON_RELEASE |
457                         XCB_EVENT_MASK_POINTER_MOTION |
458                         XCB_EVENT_MASK_ENTER_WINDOW |
459                         XCB_EVENT_MASK_LEAVE_WINDOW |
460                         XCB_EVENT_MASK_KEYMAP_STATE |
461                         XCB_EVENT_MASK_FOCUS_CHANGE;
462
463         output = malloc(sizeof *output);
464         if (output == NULL)
465                 return NULL;
466
467         memset(output, 0, sizeof *output);
468
469         output->mode.flags =
470                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
471         output->mode.width = width;
472         output->mode.height = height;
473         output->mode.refresh = 60000;
474         wl_list_init(&output->base.mode_list);
475         wl_list_insert(&output->base.mode_list, &output->mode.link);
476
477         output->base.current = &output->mode;
478         output->base.make = "xwayland";
479         output->base.model = "none";
480         weston_output_init(&output->base, &c->base,
481                            x, y, width, height, transform);
482
483         values[1] = c->null_cursor;
484         output->window = xcb_generate_id(c->conn);
485         iter = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
486         xcb_create_window(c->conn,
487                           XCB_COPY_FROM_PARENT,
488                           output->window,
489                           iter.data->root,
490                           0, 0,
491                           width, height,
492                           0,
493                           XCB_WINDOW_CLASS_INPUT_OUTPUT,
494                           iter.data->root_visual,
495                           mask, values);
496
497         /* Don't resize me. */
498         memset(&normal_hints, 0, sizeof normal_hints);
499         normal_hints.flags =
500                 WM_NORMAL_HINTS_MAX_SIZE | WM_NORMAL_HINTS_MIN_SIZE;
501         normal_hints.min_width = width;
502         normal_hints.min_height = height;
503         normal_hints.max_width = width;
504         normal_hints.max_height = height;
505         xcb_change_property (c->conn, XCB_PROP_MODE_REPLACE, output->window,
506                              c->atom.wm_normal_hints,
507                              c->atom.wm_size_hints, 32,
508                              sizeof normal_hints / 4,
509                              (uint8_t *) &normal_hints);
510
511         /* Set window name.  Don't bother with non-EWMH WMs. */
512         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
513                             c->atom.net_wm_name, c->atom.utf8_string, 8,
514                             strlen(title), title);
515         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
516                             c->atom.wm_class, c->atom.string, 8,
517                             sizeof class, class);
518
519         x11_output_set_icon(c, output, DATADIR "/weston/wayland.png");
520
521         xcb_map_window(c->conn, output->window);
522
523         x11_output_set_wm_protocols(output);
524
525         if (fullscreen)
526                 x11_output_change_state(output, 1,
527                                         c->atom.net_wm_state_fullscreen);
528
529         output->base.egl_surface = 
530                 eglCreateWindowSurface(c->base.egl_display, c->base.egl_config,
531                                        output->window, NULL);
532         if (!output->base.egl_surface) {
533                 weston_log("failed to create window surface\n");
534                 return NULL;
535         }
536
537         loop = wl_display_get_event_loop(c->base.wl_display);
538         output->finish_frame_timer =
539                 wl_event_loop_add_timer(loop, finish_frame_handler, output);
540
541         output->base.origin = output->base.current;
542         output->base.repaint = x11_output_repaint;
543         output->base.destroy = x11_output_destroy;
544         output->base.assign_planes = NULL;
545         output->base.set_backlight = NULL;
546         output->base.set_dpms = NULL;
547         output->base.switch_mode = NULL;
548
549         wl_list_insert(c->base.output_list.prev, &output->base.link);
550
551         weston_log("x11 output %dx%d, window id %d\n",
552                    width, height, output->window);
553
554         return output;
555 }
556
557 static struct x11_output *
558 x11_compositor_find_output(struct x11_compositor *c, xcb_window_t window)
559 {
560         struct x11_output *output;
561
562         wl_list_for_each(output, &c->base.output_list, base.link) {
563                 if (output->window == window)
564                         return output;
565         }
566
567         return NULL;
568 }
569
570 static uint32_t
571 get_xkb_mod_mask(struct x11_compositor *c, uint32_t in)
572 {
573         struct weston_xkb_info *info = &c->core_seat.xkb_info;
574         uint32_t ret = 0;
575
576         if ((in & ShiftMask) && info->shift_mod != XKB_MOD_INVALID)
577                 ret |= (1 << info->shift_mod);
578         if ((in & LockMask) && info->caps_mod != XKB_MOD_INVALID)
579                 ret |= (1 << info->caps_mod);
580         if ((in & ControlMask) && info->ctrl_mod != XKB_MOD_INVALID)
581                 ret |= (1 << info->ctrl_mod);
582         if ((in & Mod1Mask) && info->alt_mod != XKB_MOD_INVALID)
583                 ret |= (1 << info->alt_mod);
584         if ((in & Mod2Mask) && info->mod2_mod != XKB_MOD_INVALID)
585                 ret |= (1 << info->mod2_mod);
586         if ((in & Mod3Mask) && info->mod3_mod != XKB_MOD_INVALID)
587                 ret |= (1 << info->mod3_mod);
588         if ((in & Mod4Mask) && info->super_mod != XKB_MOD_INVALID)
589                 ret |= (1 << info->super_mod);
590         if ((in & Mod5Mask) && info->mod5_mod != XKB_MOD_INVALID)
591                 ret |= (1 << info->mod5_mod);
592
593         return ret;
594 }
595
596 #ifdef HAVE_XCB_XKB
597 static void
598 update_xkb_state(struct x11_compositor *c, xcb_xkb_state_notify_event_t *state)
599 {
600         xkb_state_update_mask(c->core_seat.xkb_state.state,
601                               get_xkb_mod_mask(c, state->baseMods),
602                               get_xkb_mod_mask(c, state->latchedMods),
603                               get_xkb_mod_mask(c, state->lockedMods),
604                               0,
605                               0,
606                               state->group);
607
608         notify_modifiers(&c->core_seat,
609                          wl_display_next_serial(c->base.wl_display));
610 }
611 #endif
612
613 /**
614  * This is monumentally unpleasant.  If we don't have XCB-XKB bindings,
615  * the best we can do (given that XCB also lacks XI2 support), is to take
616  * the state from the core key events.  Unfortunately that only gives us
617  * the effective (i.e. union of depressed/latched/locked) state, and we
618  * need the granularity.
619  *
620  * So we still update the state with every key event we see, but also use
621  * the state field from X11 events as a mask so we don't get any stuck
622  * modifiers.
623  */
624 static void
625 update_xkb_state_from_core(struct x11_compositor *c, uint16_t x11_mask)
626 {
627         uint32_t mask = get_xkb_mod_mask(c, x11_mask);
628         struct wl_keyboard *keyboard = &c->core_seat.keyboard;
629
630         xkb_state_update_mask(c->core_seat.xkb_state.state,
631                               keyboard->modifiers.mods_depressed & mask,
632                               keyboard->modifiers.mods_latched & mask,
633                               keyboard->modifiers.mods_locked & mask,
634                               0,
635                               0,
636                               (x11_mask >> 13) & 3);
637         notify_modifiers(&c->core_seat,
638                          wl_display_next_serial(c->base.wl_display));
639 }
640
641 static void
642 x11_compositor_deliver_button_event(struct x11_compositor *c,
643                                     xcb_generic_event_t *event, int state)
644 {
645         xcb_button_press_event_t *button_event =
646                 (xcb_button_press_event_t *) event;
647         uint32_t button;
648
649         if (!c->has_xkb)
650                 update_xkb_state_from_core(c, button_event->state);
651
652         switch (button_event->detail) {
653         default:
654                 button = button_event->detail + BTN_LEFT - 1;
655                 break;
656         case 2:
657                 button = BTN_MIDDLE;
658                 break;
659         case 3:
660                 button = BTN_RIGHT;
661                 break;
662         case 4:
663                 if (state)
664                         notify_axis(&c->core_seat,
665                                       weston_compositor_get_time(),
666                                       WL_POINTER_AXIS_VERTICAL_SCROLL,
667                                       wl_fixed_from_int(1));
668                 return;
669         case 5:
670                 if (state)
671                         notify_axis(&c->core_seat,
672                                       weston_compositor_get_time(),
673                                       WL_POINTER_AXIS_VERTICAL_SCROLL,
674                                       wl_fixed_from_int(-1));
675                 return;
676         case 6:
677                 if (state)
678                         notify_axis(&c->core_seat,
679                                       weston_compositor_get_time(),
680                                       WL_POINTER_AXIS_HORIZONTAL_SCROLL,
681                                       wl_fixed_from_int(1));
682                 return;
683         case 7:
684                 if (state)
685                         notify_axis(&c->core_seat,
686                                       weston_compositor_get_time(),
687                                       WL_POINTER_AXIS_HORIZONTAL_SCROLL,
688                                       wl_fixed_from_int(-1));
689                 return;
690         }
691
692         notify_button(&c->core_seat,
693                       weston_compositor_get_time(), button,
694                       state ? WL_POINTER_BUTTON_STATE_PRESSED :
695                               WL_POINTER_BUTTON_STATE_RELEASED);
696 }
697
698 static void
699 x11_output_transform_coordinate(struct x11_output *x11_output,
700                                                 wl_fixed_t *x, wl_fixed_t *y)
701 {
702         struct weston_output *output = &x11_output->base;
703         wl_fixed_t tx, ty;
704         wl_fixed_t width = wl_fixed_from_int(output->width - 1);
705         wl_fixed_t height = wl_fixed_from_int(output->height - 1);
706
707         switch(output->transform) {
708         case WL_OUTPUT_TRANSFORM_NORMAL:
709         default:
710                 tx = *x;
711                 ty = *y;
712                 break;
713         case WL_OUTPUT_TRANSFORM_90:
714                 tx = *y;
715                 ty = height - *x;
716                 break;
717         case WL_OUTPUT_TRANSFORM_180:
718                 tx = width - *x;
719                 ty = height - *y;
720                 break;
721         case WL_OUTPUT_TRANSFORM_270:
722                 tx = width - *y;
723                 ty = *x;
724                 break;
725         case WL_OUTPUT_TRANSFORM_FLIPPED:
726                 tx = width - *x;
727                 ty = *y;
728                 break;
729         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
730                 tx = width - *y;
731                 ty = height - *x;
732                 break;
733         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
734                 tx = *x;
735                 ty = height - *y;
736                 break;
737         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
738                 tx = *y;
739                 ty = *x;
740                 break;
741         }
742
743         tx += wl_fixed_from_int(output->x);
744         ty += wl_fixed_from_int(output->y);
745
746         *x = tx;
747         *y = ty;
748 }
749
750 static void
751 x11_compositor_deliver_motion_event(struct x11_compositor *c,
752                                         xcb_generic_event_t *event)
753 {
754         struct x11_output *output;
755         wl_fixed_t x, y;
756         xcb_motion_notify_event_t *motion_notify =
757                         (xcb_motion_notify_event_t *) event;
758
759         if (!c->has_xkb)
760                 update_xkb_state_from_core(c, motion_notify->state);
761         output = x11_compositor_find_output(c, motion_notify->event);
762         x = wl_fixed_from_int(motion_notify->event_x);
763         y = wl_fixed_from_int(motion_notify->event_y);
764         x11_output_transform_coordinate(output, &x, &y);
765
766         notify_motion(&c->core_seat, weston_compositor_get_time(), x, y);
767 }
768
769 static void
770 x11_compositor_deliver_enter_event(struct x11_compositor *c,
771                                         xcb_generic_event_t *event)
772 {
773         struct x11_output *output;
774         wl_fixed_t x, y;
775
776         xcb_enter_notify_event_t *enter_notify =
777                         (xcb_enter_notify_event_t *) event;
778         if (enter_notify->state >= Button1Mask)
779                 return;
780         if (!c->has_xkb)
781                 update_xkb_state_from_core(c, enter_notify->state);
782         output = x11_compositor_find_output(c, enter_notify->event);
783         x = wl_fixed_from_int(enter_notify->event_x);
784         y = wl_fixed_from_int(enter_notify->event_y);
785         x11_output_transform_coordinate(output, &x, &y);
786
787         notify_pointer_focus(&c->core_seat, &output->base, x, y);
788 }
789
790 static int
791 x11_compositor_next_event(struct x11_compositor *c,
792                           xcb_generic_event_t **event, uint32_t mask)
793 {
794         if (mask & WL_EVENT_READABLE) {
795                 *event = xcb_poll_for_event(c->conn);
796         } else {
797 #ifdef HAVE_XCB_POLL_FOR_QUEUED_EVENT
798                 *event = xcb_poll_for_queued_event(c->conn);
799 #else
800                 *event = xcb_poll_for_event(c->conn);
801 #endif
802         }
803
804         return *event != NULL;
805 }
806
807 static int
808 x11_compositor_handle_event(int fd, uint32_t mask, void *data)
809 {
810         struct x11_compositor *c = data;
811         struct x11_output *output;
812         xcb_generic_event_t *event, *prev;
813         xcb_client_message_event_t *client_message;
814         xcb_enter_notify_event_t *enter_notify;
815         xcb_key_press_event_t *key_press, *key_release;
816         xcb_keymap_notify_event_t *keymap_notify;
817         xcb_focus_in_event_t *focus_in;
818         xcb_expose_event_t *expose;
819         xcb_atom_t atom;
820         uint32_t *k;
821         uint32_t i, set;
822         int count;
823
824         prev = NULL;
825         count = 0;
826         while (x11_compositor_next_event(c, &event, mask)) {
827                 switch (prev ? prev->response_type & ~0x80 : 0x80) {
828                 case XCB_KEY_RELEASE:
829                         /* Suppress key repeat events; this is only used if we
830                          * don't have XCB XKB support. */
831                         key_release = (xcb_key_press_event_t *) prev;
832                         key_press = (xcb_key_press_event_t *) event;
833                         if ((event->response_type & ~0x80) == XCB_KEY_PRESS &&
834                             key_release->time == key_press->time &&
835                             key_release->detail == key_press->detail) {
836                                 /* Don't deliver the held key release
837                                  * event or the new key press event. */
838                                 free(event);
839                                 free(prev);
840                                 prev = NULL;
841                                 continue;
842                         } else {
843                                 /* Deliver the held key release now
844                                  * and fall through and handle the new
845                                  * event below. */
846                                 update_xkb_state_from_core(c, key_release->state);
847                                 notify_key(&c->core_seat,
848                                            weston_compositor_get_time(),
849                                            key_release->detail - 8,
850                                            WL_KEYBOARD_KEY_STATE_RELEASED,
851                                            STATE_UPDATE_AUTOMATIC);
852                                 free(prev);
853                                 prev = NULL;
854                                 break;
855                         }
856
857                 case XCB_FOCUS_IN:
858                         /* assert event is keymap_notify */
859                         focus_in = (xcb_focus_in_event_t *) prev;
860                         keymap_notify = (xcb_keymap_notify_event_t *) event;
861                         c->keys.size = 0;
862                         for (i = 0; i < ARRAY_LENGTH(keymap_notify->keys) * 8; i++) {
863                                 set = keymap_notify->keys[i >> 3] &
864                                         (1 << (i & 7));
865                                 if (set) {
866                                         k = wl_array_add(&c->keys, sizeof *k);
867                                         *k = i;
868                                 }
869                         }
870
871                         output = x11_compositor_find_output(c, focus_in->event);
872                         /* Unfortunately the state only comes with the enter
873                          * event, rather than with the focus event.  I'm not
874                          * sure of the exact semantics around it and whether
875                          * we can ensure that we get both? */
876                         notify_keyboard_focus_in(&c->core_seat, &c->keys,
877                                                  STATE_UPDATE_AUTOMATIC);
878
879                         free(prev);
880                         prev = NULL;
881                         break;
882
883                 default:
884                         /* No previous event held */
885                         break;
886                 }
887
888                 switch (event->response_type & ~0x80) {
889                 case XCB_KEY_PRESS:
890                         key_press = (xcb_key_press_event_t *) event;
891                         if (!c->has_xkb)
892                                 update_xkb_state_from_core(c, key_press->state);
893                         notify_key(&c->core_seat,
894                                    weston_compositor_get_time(),
895                                    key_press->detail - 8,
896                                    WL_KEYBOARD_KEY_STATE_PRESSED,
897                                    c->has_xkb ? STATE_UPDATE_NONE :
898                                                 STATE_UPDATE_AUTOMATIC);
899                         break;
900                 case XCB_KEY_RELEASE:
901                         /* If we don't have XKB, we need to use the lame
902                          * autorepeat detection above. */
903                         if (!c->has_xkb) {
904                                 prev = event;
905                                 break;
906                         }
907                         key_release = (xcb_key_press_event_t *) event;
908                         notify_key(&c->core_seat,
909                                    weston_compositor_get_time(),
910                                    key_release->detail - 8,
911                                    WL_KEYBOARD_KEY_STATE_RELEASED,
912                                    STATE_UPDATE_NONE);
913                         break;
914                 case XCB_BUTTON_PRESS:
915                         x11_compositor_deliver_button_event(c, event, 1);
916                         break;
917                 case XCB_BUTTON_RELEASE:
918                         x11_compositor_deliver_button_event(c, event, 0);
919                         break;
920                 case XCB_MOTION_NOTIFY:
921                         x11_compositor_deliver_motion_event(c, event);
922                         break;
923
924                 case XCB_EXPOSE:
925                         expose = (xcb_expose_event_t *) event;
926                         output = x11_compositor_find_output(c, expose->window);
927                         weston_output_schedule_repaint(&output->base);
928                         break;
929
930                 case XCB_ENTER_NOTIFY:
931                         x11_compositor_deliver_enter_event(c, event);
932                         break;
933
934                 case XCB_LEAVE_NOTIFY:
935                         enter_notify = (xcb_enter_notify_event_t *) event;
936                         if (enter_notify->state >= Button1Mask)
937                                 break;
938                         if (!c->has_xkb)
939                                 update_xkb_state_from_core(c, enter_notify->state);
940                         output = x11_compositor_find_output(c, enter_notify->event);
941                         notify_pointer_focus(&c->core_seat, NULL, 0, 0);
942                         break;
943
944                 case XCB_CLIENT_MESSAGE:
945                         client_message = (xcb_client_message_event_t *) event;
946                         atom = client_message->data.data32[0];
947                         if (atom == c->atom.wm_delete_window)
948                                 wl_display_terminate(c->base.wl_display);
949                         break;
950
951                 case XCB_FOCUS_IN:
952                         focus_in = (xcb_focus_in_event_t *) event;
953                         if (focus_in->mode == XCB_NOTIFY_MODE_WHILE_GRABBED)
954                                 break;
955
956                         prev = event;
957                         break;
958
959                 case XCB_FOCUS_OUT:
960                         focus_in = (xcb_focus_in_event_t *) event;
961                         if (focus_in->mode == XCB_NOTIFY_MODE_WHILE_GRABBED ||
962                             focus_in->mode == XCB_NOTIFY_MODE_UNGRAB)
963                                 break;
964                         notify_keyboard_focus_out(&c->core_seat);
965                         break;
966
967                 default:
968                         break;
969                 }
970
971 #ifdef HAVE_XCB_XKB
972                 if (c->has_xkb &&
973                     (event->response_type & ~0x80) == c->xkb_event_base) {
974                         xcb_xkb_state_notify_event_t *state =
975                                 (xcb_xkb_state_notify_event_t *) event;
976                         if (state->xkbType == XCB_XKB_STATE_NOTIFY)
977                                 update_xkb_state(c, state);
978                 }
979 #endif
980
981                 count++;
982                 if (prev != event)
983                         free (event);
984         }
985
986         switch (prev ? prev->response_type & ~0x80 : 0x80) {
987         case XCB_KEY_RELEASE:
988                 key_release = (xcb_key_press_event_t *) prev;
989                 update_xkb_state_from_core(c, key_release->state);
990                 notify_key(&c->core_seat,
991                            weston_compositor_get_time(),
992                            key_release->detail - 8,
993                            WL_KEYBOARD_KEY_STATE_RELEASED,
994                            STATE_UPDATE_AUTOMATIC);
995                 free(prev);
996                 prev = NULL;
997                 break;
998         default:
999                 break;
1000         }
1001
1002         return count;
1003 }
1004
1005 #define F(field) offsetof(struct x11_compositor, field)
1006
1007 static void
1008 x11_compositor_get_resources(struct x11_compositor *c)
1009 {
1010         static const struct { const char *name; int offset; } atoms[] = {
1011                 { "WM_PROTOCOLS",       F(atom.wm_protocols) },
1012                 { "WM_NORMAL_HINTS",    F(atom.wm_normal_hints) },
1013                 { "WM_SIZE_HINTS",      F(atom.wm_size_hints) },
1014                 { "WM_DELETE_WINDOW",   F(atom.wm_delete_window) },
1015                 { "WM_CLASS",           F(atom.wm_class) },
1016                 { "_NET_WM_NAME",       F(atom.net_wm_name) },
1017                 { "_NET_WM_ICON",       F(atom.net_wm_icon) },
1018                 { "_NET_WM_STATE",      F(atom.net_wm_state) },
1019                 { "_NET_WM_STATE_FULLSCREEN", F(atom.net_wm_state_fullscreen) },
1020                 { "STRING",             F(atom.string) },
1021                 { "UTF8_STRING",        F(atom.utf8_string) },
1022                 { "CARDINAL",           F(atom.cardinal) },
1023                 { "_XKB_RULES_NAMES",   F(atom.xkb_names) },
1024         };
1025
1026         xcb_intern_atom_cookie_t cookies[ARRAY_LENGTH(atoms)];
1027         xcb_intern_atom_reply_t *reply;
1028         xcb_pixmap_t pixmap;
1029         xcb_gc_t gc;
1030         unsigned int i;
1031         uint8_t data[] = { 0, 0, 0, 0 };
1032
1033         for (i = 0; i < ARRAY_LENGTH(atoms); i++)
1034                 cookies[i] = xcb_intern_atom (c->conn, 0,
1035                                               strlen(atoms[i].name),
1036                                               atoms[i].name);
1037
1038         for (i = 0; i < ARRAY_LENGTH(atoms); i++) {
1039                 reply = xcb_intern_atom_reply (c->conn, cookies[i], NULL);
1040                 *(xcb_atom_t *) ((char *) c + atoms[i].offset) = reply->atom;
1041                 free(reply);
1042         }
1043
1044         pixmap = xcb_generate_id(c->conn);
1045         gc = xcb_generate_id(c->conn);
1046         xcb_create_pixmap(c->conn, 1, pixmap, c->screen->root, 1, 1);
1047         xcb_create_gc(c->conn, gc, pixmap, 0, NULL);
1048         xcb_put_image(c->conn, XCB_IMAGE_FORMAT_XY_PIXMAP,
1049                       pixmap, gc, 1, 1, 0, 0, 0, 32, sizeof data, data);
1050         c->null_cursor = xcb_generate_id(c->conn);
1051         xcb_create_cursor (c->conn, c->null_cursor,
1052                            pixmap, pixmap, 0, 0, 0,  0, 0, 0,  1, 1);
1053         xcb_free_gc(c->conn, gc);
1054         xcb_free_pixmap(c->conn, pixmap);
1055 }
1056
1057 static void
1058 x11_restore(struct weston_compositor *ec)
1059 {
1060 }
1061
1062 static void
1063 x11_free_configured_output(struct x11_configured_output *output)
1064 {
1065         free(output->name);
1066         free(output);
1067 }
1068
1069 static void
1070 x11_destroy(struct weston_compositor *ec)
1071 {
1072         struct x11_compositor *compositor = (struct x11_compositor *)ec;
1073         struct x11_configured_output *o, *n;
1074
1075         wl_list_for_each_safe(o, n, &configured_output_list, link)
1076                 x11_free_configured_output(o);
1077
1078         wl_event_source_remove(compositor->xcb_source);
1079         x11_input_destroy(compositor);
1080
1081         weston_compositor_shutdown(ec); /* destroys outputs, too */
1082
1083         x11_compositor_fini_egl(compositor);
1084
1085         XCloseDisplay(compositor->dpy);
1086         free(ec);
1087 }
1088
1089 static struct weston_compositor *
1090 x11_compositor_create(struct wl_display *display,
1091                       int fullscreen,
1092                       int no_input,
1093                       int argc, char *argv[], const char *config_file)
1094 {
1095         struct x11_compositor *c;
1096         struct x11_configured_output *o;
1097         struct x11_output *output;
1098         xcb_screen_iterator_t s;
1099         int i, x = 0, output_count = 0;
1100         int width, height, count;
1101
1102         weston_log("initializing x11 backend\n");
1103
1104         c = malloc(sizeof *c);
1105         if (c == NULL)
1106                 return NULL;
1107
1108         memset(c, 0, sizeof *c);
1109
1110         if (weston_compositor_init(&c->base, display, argc, argv,
1111                                    config_file) < 0)
1112                 goto err_free;
1113
1114         c->dpy = XOpenDisplay(NULL);
1115         if (c->dpy == NULL)
1116                 goto err_free;
1117
1118         c->conn = XGetXCBConnection(c->dpy);
1119         XSetEventQueueOwner(c->dpy, XCBOwnsEventQueue);
1120
1121         if (xcb_connection_has_error(c->conn))
1122                 goto err_xdisplay;
1123
1124         s = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
1125         c->screen = s.data;
1126         wl_array_init(&c->keys);
1127
1128         x11_compositor_get_resources(c);
1129
1130         c->base.wl_display = display;
1131         if (x11_compositor_init_egl(c) < 0)
1132                 goto err_xdisplay;
1133
1134         c->base.destroy = x11_destroy;
1135         c->base.restore = x11_restore;
1136
1137         if (x11_input_create(c, no_input) < 0)
1138                 goto err_egl;
1139
1140         width = option_width ? option_width : 1024;
1141         height = option_height ? option_height : 640;
1142         count = option_count ? option_count : 1;
1143
1144         wl_list_for_each(o, &configured_output_list, link) {
1145                 output = x11_compositor_create_output(c, x, 0,
1146                                                       option_width ? width :
1147                                                       o->width,
1148                                                       option_height ? height :
1149                                                       o->height,
1150                                                       fullscreen, no_input,
1151                                                       o->name, o->transform);
1152                 if (output == NULL)
1153                         goto err_x11_input;
1154
1155                 x = pixman_region32_extents(&output->base.region)->x2;
1156
1157                 output_count++;
1158                 if (option_count && output_count >= option_count)
1159                         break;
1160         }
1161
1162         for (i = output_count; i < count; i++) {
1163                 output = x11_compositor_create_output(c, x, 0, width, height,
1164                                                       fullscreen, no_input, NULL,
1165                                                       WL_OUTPUT_TRANSFORM_NORMAL);
1166                 if (output == NULL)
1167                         goto err_x11_input;
1168                 x = pixman_region32_extents(&output->base.region)->x2;
1169         }
1170
1171         if (gles2_renderer_init(&c->base) < 0)
1172                 goto err_egl;
1173
1174         c->xcb_source =
1175                 wl_event_loop_add_fd(c->base.input_loop,
1176                                      xcb_get_file_descriptor(c->conn),
1177                                      WL_EVENT_READABLE,
1178                                      x11_compositor_handle_event, c);
1179         wl_event_source_check(c->xcb_source);
1180
1181         return &c->base;
1182
1183 err_x11_input:
1184         x11_input_destroy(c);
1185 err_egl:
1186         x11_compositor_fini_egl(c);
1187 err_xdisplay:
1188         XCloseDisplay(c->dpy);
1189 err_free:
1190         free(c);
1191         return NULL;
1192 }
1193
1194 static void
1195 x11_output_set_transform(struct x11_configured_output *output)
1196 {
1197         if (!output_transform) {
1198                 output->transform = WL_OUTPUT_TRANSFORM_NORMAL;
1199                 return;
1200         }
1201
1202         if (!strcmp(output_transform, "normal"))
1203                 output->transform = WL_OUTPUT_TRANSFORM_NORMAL;
1204         else if (!strcmp(output_transform, "90"))
1205                 output->transform = WL_OUTPUT_TRANSFORM_90;
1206         else if (!strcmp(output_transform, "180"))
1207                 output->transform = WL_OUTPUT_TRANSFORM_180;
1208         else if (!strcmp(output_transform, "270"))
1209                 output->transform = WL_OUTPUT_TRANSFORM_270;
1210         else if (!strcmp(output_transform, "flipped"))
1211                 output->transform = WL_OUTPUT_TRANSFORM_FLIPPED;
1212         else if (!strcmp(output_transform, "flipped-90"))
1213                 output->transform = WL_OUTPUT_TRANSFORM_FLIPPED_90;
1214         else if (!strcmp(output_transform, "flipped-180"))
1215                 output->transform = WL_OUTPUT_TRANSFORM_FLIPPED_180;
1216         else if (!strcmp(output_transform, "flipped-270"))
1217                 output->transform = WL_OUTPUT_TRANSFORM_FLIPPED_270;
1218         else {
1219                 weston_log("Invalid transform \"%s\" for output %s\n",
1220                                                 output_transform, output_name);
1221                 output->transform = WL_OUTPUT_TRANSFORM_NORMAL;
1222         }
1223 }
1224
1225 static void
1226 output_section_done(void *data)
1227 {
1228         struct x11_configured_output *output;
1229
1230         output = malloc(sizeof *output);
1231
1232         if (!output || !output_name || (output_name[0] != 'X') ||
1233                                 (!output_mode && !output_transform)) {
1234                 if (output_name)
1235                         free(output_name);
1236                 output_name = NULL;
1237                 goto err_free;
1238         }
1239
1240         output->name = output_name;
1241
1242         if (output_mode) {
1243                 if (sscanf(output_mode, "%dx%d", &output->width,
1244                                                 &output->height) != 2) {
1245                         weston_log("Invalid mode \"%s\" for output %s\n",
1246                                                         output_mode, output_name);
1247                         x11_free_configured_output(output);
1248                         goto err_free;
1249                 }
1250         } else {
1251                 output->width = 1024;
1252                 output->height = 640;
1253         }
1254
1255         x11_output_set_transform(output);
1256
1257         wl_list_insert(configured_output_list.prev, &output->link);
1258
1259 err_free:
1260         if (output_mode)
1261                 free(output_mode);
1262         if (output_transform)
1263                 free(output_transform);
1264         output_mode = NULL;
1265         output_transform = NULL;
1266 }
1267
1268 WL_EXPORT struct weston_compositor *
1269 backend_init(struct wl_display *display, int argc, char *argv[],
1270              const char *config_file)
1271 {
1272         int fullscreen = 0;
1273         int no_input = 0;
1274
1275         const struct weston_option x11_options[] = {
1276                 { WESTON_OPTION_INTEGER, "width", 0, &option_width },
1277                 { WESTON_OPTION_INTEGER, "height", 0, &option_height },
1278                 { WESTON_OPTION_BOOLEAN, "fullscreen", 0, &fullscreen },
1279                 { WESTON_OPTION_INTEGER, "output-count", 0, &option_count },
1280                 { WESTON_OPTION_BOOLEAN, "no-input", 0, &no_input },
1281         };
1282
1283         parse_options(x11_options, ARRAY_LENGTH(x11_options), argc, argv);
1284
1285         wl_list_init(&configured_output_list);
1286
1287         const struct config_key x11_config_keys[] = {
1288                 { "name", CONFIG_KEY_STRING, &output_name },
1289                 { "mode", CONFIG_KEY_STRING, &output_mode },
1290                 { "transform", CONFIG_KEY_STRING, &output_transform },
1291         };
1292
1293         const struct config_section config_section[] = {
1294                 { "output", x11_config_keys,
1295                 ARRAY_LENGTH(x11_config_keys), output_section_done },
1296         };
1297
1298         parse_config_file(config_file, config_section,
1299                                 ARRAY_LENGTH(config_section), NULL);
1300
1301         return x11_compositor_create(display,
1302                                      fullscreen,
1303                                      no_input,
1304                                      argc, argv, config_file);
1305 }