xwm: Handle WM_TRANSIENT_FOR
[profile/ivi/weston-ivi-shell.git] / xwayland / window-manager.c
1 /*
2  * Copyright © 2011 Intel Corporation
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and
5  * its documentation for any purpose is hereby granted without fee, provided
6  * that the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation, and that the name of the copyright holders not be used in
9  * advertising or publicity pertaining to distribution of the software
10  * without specific, written prior permission.  The copyright holders make
11  * no representations about the suitability of this software for any
12  * purpose.  It is provided "as is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
15  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
16  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
17  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
18  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
19  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <signal.h>
34 #include <X11/Xcursor/Xcursor.h>
35 #include <linux/input.h>
36
37 #include "xwayland.h"
38
39 #include "cairo-util.h"
40 #include "compositor.h"
41 #include "xserver-server-protocol.h"
42 #include "hash.h"
43
44 struct wm_size_hints {
45         uint32_t flags;
46         int32_t x, y;
47         int32_t width, height;  /* should set so old wm's don't mess up */
48         int32_t min_width, min_height;
49         int32_t max_width, max_height;
50         int32_t width_inc, height_inc;
51         struct {
52                 int32_t x;
53                 int32_t y;
54         } min_aspect, max_aspect;
55         int32_t base_width, base_height;
56         int32_t win_gravity;
57 };
58
59 #define USPosition      (1L << 0)
60 #define USSize          (1L << 1)
61 #define PPosition       (1L << 2)
62 #define PSize           (1L << 3)
63 #define PMinSize        (1L << 4)
64 #define PMaxSize        (1L << 5)
65 #define PResizeInc      (1L << 6)
66 #define PAspect         (1L << 7)
67 #define PBaseSize       (1L << 8)
68 #define PWinGravity     (1L << 9)
69
70 struct motif_wm_hints {
71         uint32_t flags;
72         uint32_t functions;
73         uint32_t decorations;
74         int32_t input_mode;
75         uint32_t status;
76 };
77
78 #define MWM_HINTS_FUNCTIONS     (1L << 0)
79 #define MWM_HINTS_DECORATIONS   (1L << 1)
80 #define MWM_HINTS_INPUT_MODE    (1L << 2)
81 #define MWM_HINTS_STATUS        (1L << 3)
82
83 #define MWM_FUNC_ALL            (1L << 0)
84 #define MWM_FUNC_RESIZE         (1L << 1)
85 #define MWM_FUNC_MOVE           (1L << 2)
86 #define MWM_FUNC_MINIMIZE       (1L << 3)
87 #define MWM_FUNC_MAXIMIZE       (1L << 4)
88 #define MWM_FUNC_CLOSE          (1L << 5)
89
90 #define MWM_DECOR_ALL           (1L << 0)
91 #define MWM_DECOR_BORDER        (1L << 1)
92 #define MWM_DECOR_RESIZEH       (1L << 2)
93 #define MWM_DECOR_TITLE         (1L << 3)
94 #define MWM_DECOR_MENU          (1L << 4)
95 #define MWM_DECOR_MINIMIZE      (1L << 5)
96 #define MWM_DECOR_MAXIMIZE      (1L << 6)
97
98 #define MWM_INPUT_MODELESS 0
99 #define MWM_INPUT_PRIMARY_APPLICATION_MODAL 1
100 #define MWM_INPUT_SYSTEM_MODAL 2
101 #define MWM_INPUT_FULL_APPLICATION_MODAL 3
102 #define MWM_INPUT_APPLICATION_MODAL MWM_INPUT_PRIMARY_APPLICATION_MODAL
103
104 #define MWM_TEAROFF_WINDOW      (1L<<0)
105
106 #define _NET_WM_MOVERESIZE_SIZE_TOPLEFT      0
107 #define _NET_WM_MOVERESIZE_SIZE_TOP          1
108 #define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT     2
109 #define _NET_WM_MOVERESIZE_SIZE_RIGHT        3
110 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT  4
111 #define _NET_WM_MOVERESIZE_SIZE_BOTTOM       5
112 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT   6
113 #define _NET_WM_MOVERESIZE_SIZE_LEFT         7
114 #define _NET_WM_MOVERESIZE_MOVE              8   /* movement only */
115 #define _NET_WM_MOVERESIZE_SIZE_KEYBOARD     9   /* size via keyboard */
116 #define _NET_WM_MOVERESIZE_MOVE_KEYBOARD    10   /* move via keyboard */
117 #define _NET_WM_MOVERESIZE_CANCEL           11   /* cancel operation */
118
119 struct weston_wm_window {
120         struct weston_wm *wm;
121         xcb_window_t id;
122         xcb_window_t frame_id;
123         struct frame *frame;
124         cairo_surface_t *cairo_surface;
125         struct weston_surface *surface;
126         struct shell_surface *shsurf;
127         struct weston_view *view;
128         struct wl_listener surface_destroy_listener;
129         struct wl_event_source *repaint_source;
130         struct wl_event_source *configure_source;
131         int properties_dirty;
132         int pid;
133         char *machine;
134         char *class;
135         char *name;
136         struct weston_wm_window *transient_for;
137         uint32_t protocols;
138         xcb_atom_t type;
139         int width, height;
140         int x, y;
141         int saved_width, saved_height;
142         int decorate;
143         int override_redirect;
144         int fullscreen;
145         int has_alpha;
146         int delete_window;
147         struct wm_size_hints size_hints;
148         struct motif_wm_hints motif_hints;
149 };
150
151 static struct weston_wm_window *
152 get_wm_window(struct weston_surface *surface);
153
154 static void
155 weston_wm_window_schedule_repaint(struct weston_wm_window *window);
156
157 static int __attribute__ ((format (printf, 1, 2)))
158 wm_log(const char *fmt, ...)
159 {
160 #ifdef WM_DEBUG
161         int l;
162         va_list argp;
163
164         va_start(argp, fmt);
165         l = weston_vlog(fmt, argp);
166         va_end(argp);
167
168         return l;
169 #else
170         return 0;
171 #endif
172 }
173
174 static int __attribute__ ((format (printf, 1, 2)))
175 wm_log_continue(const char *fmt, ...)
176 {
177 #ifdef WM_DEBUG
178         int l;
179         va_list argp;
180
181         va_start(argp, fmt);
182         l = weston_vlog_continue(fmt, argp);
183         va_end(argp);
184
185         return l;
186 #else
187         return 0;
188 #endif
189 }
190
191
192 const char *
193 get_atom_name(xcb_connection_t *c, xcb_atom_t atom)
194 {
195         xcb_get_atom_name_cookie_t cookie;
196         xcb_get_atom_name_reply_t *reply;
197         xcb_generic_error_t *e;
198         static char buffer[64];
199
200         if (atom == XCB_ATOM_NONE)
201                 return "None";
202
203         cookie = xcb_get_atom_name (c, atom);
204         reply = xcb_get_atom_name_reply (c, cookie, &e);
205
206         if(reply) {
207                 snprintf(buffer, sizeof buffer, "%.*s",
208                          xcb_get_atom_name_name_length (reply),
209                          xcb_get_atom_name_name (reply));
210         } else {
211                 snprintf(buffer, sizeof buffer, "(atom %u)", atom);
212         }
213
214         free(reply);
215
216         return buffer;
217 }
218
219 static xcb_cursor_t
220 xcb_cursor_image_load_cursor(struct weston_wm *wm, const XcursorImage *img)
221 {
222         xcb_connection_t *c = wm->conn;
223         xcb_screen_iterator_t s = xcb_setup_roots_iterator(xcb_get_setup(c));
224         xcb_screen_t *screen = s.data;
225         xcb_gcontext_t gc;
226         xcb_pixmap_t pix;
227         xcb_render_picture_t pic;
228         xcb_cursor_t cursor;
229         int stride = img->width * 4;
230
231         pix = xcb_generate_id(c);
232         xcb_create_pixmap(c, 32, pix, screen->root, img->width, img->height);
233
234         pic = xcb_generate_id(c);
235         xcb_render_create_picture(c, pic, pix, wm->format_rgba.id, 0, 0);
236
237         gc = xcb_generate_id(c);
238         xcb_create_gc(c, gc, pix, 0, 0);
239
240         xcb_put_image(c, XCB_IMAGE_FORMAT_Z_PIXMAP, pix, gc,
241                       img->width, img->height, 0, 0, 0, 32,
242                       stride * img->height, (uint8_t *) img->pixels);
243         xcb_free_gc(c, gc);
244
245         cursor = xcb_generate_id(c);
246         xcb_render_create_cursor(c, cursor, pic, img->xhot, img->yhot);
247
248         xcb_render_free_picture(c, pic);
249         xcb_free_pixmap(c, pix);
250
251         return cursor;
252 }
253
254 static xcb_cursor_t
255 xcb_cursor_images_load_cursor(struct weston_wm *wm, const XcursorImages *images)
256 {
257         /* TODO: treat animated cursors as well */
258         if (images->nimage != 1)
259                 return -1;
260
261         return xcb_cursor_image_load_cursor(wm, images->images[0]);
262 }
263
264 static xcb_cursor_t
265 xcb_cursor_library_load_cursor(struct weston_wm *wm, const char *file)
266 {
267         xcb_cursor_t cursor;
268         XcursorImages *images;
269         char *v = NULL;
270         int size = 0;
271
272         if (!file)
273                 return 0;
274
275         v = getenv ("XCURSOR_SIZE");
276         if (v)
277                 size = atoi(v);
278
279         if (!size)
280                 size = 32;
281
282         images = XcursorLibraryLoadImages (file, NULL, size);
283         if (!images)
284                 return -1;
285
286         cursor = xcb_cursor_images_load_cursor (wm, images);
287         XcursorImagesDestroy (images);
288
289         return cursor;
290 }
291
292 void
293 dump_property(struct weston_wm *wm,
294               xcb_atom_t property, xcb_get_property_reply_t *reply)
295 {
296         int32_t *incr_value;
297         const char *text_value, *name;
298         xcb_atom_t *atom_value;
299         int width, len;
300         uint32_t i;
301
302         width = wm_log_continue("%s: ", get_atom_name(wm->conn, property));
303         if (reply == NULL) {
304                 wm_log_continue("(no reply)\n");
305                 return;
306         }
307
308         width += wm_log_continue("%s/%d, length %d (value_len %d): ",
309                                  get_atom_name(wm->conn, reply->type),
310                                  reply->format,
311                                  xcb_get_property_value_length(reply),
312                                  reply->value_len);
313
314         if (reply->type == wm->atom.incr) {
315                 incr_value = xcb_get_property_value(reply);
316                 wm_log_continue("%d\n", *incr_value);
317         } else if (reply->type == wm->atom.utf8_string ||
318               reply->type == wm->atom.string) {
319                 text_value = xcb_get_property_value(reply);
320                 if (reply->value_len > 40)
321                         len = 40;
322                 else
323                         len = reply->value_len;
324                 wm_log_continue("\"%.*s\"\n", len, text_value);
325         } else if (reply->type == XCB_ATOM_ATOM) {
326                 atom_value = xcb_get_property_value(reply);
327                 for (i = 0; i < reply->value_len; i++) {
328                         name = get_atom_name(wm->conn, atom_value[i]);
329                         if (width + strlen(name) + 2 > 78) {
330                                 wm_log_continue("\n    ");
331                                 width = 4;
332                         } else if (i > 0) {
333                                 width +=  wm_log_continue(", ");
334                         }
335
336                         width +=  wm_log_continue("%s", name);
337                 }
338                 wm_log_continue("\n");
339         } else {
340                 wm_log_continue("huh?\n");
341         }
342 }
343
344 static void
345 read_and_dump_property(struct weston_wm *wm,
346                        xcb_window_t window, xcb_atom_t property)
347 {
348         xcb_get_property_reply_t *reply;
349         xcb_get_property_cookie_t cookie;
350
351         cookie = xcb_get_property(wm->conn, 0, window,
352                                   property, XCB_ATOM_ANY, 0, 2048);
353         reply = xcb_get_property_reply(wm->conn, cookie, NULL);
354
355         dump_property(wm, property, reply);
356
357         free(reply);
358 }
359
360 /* We reuse some predefined, but otherwise useles atoms */
361 #define TYPE_WM_PROTOCOLS       XCB_ATOM_CUT_BUFFER0
362 #define TYPE_MOTIF_WM_HINTS     XCB_ATOM_CUT_BUFFER1
363 #define TYPE_NET_WM_STATE       XCB_ATOM_CUT_BUFFER2
364 #define TYPE_WM_NORMAL_HINTS    XCB_ATOM_CUT_BUFFER3
365
366 static void
367 weston_wm_window_read_properties(struct weston_wm_window *window)
368 {
369         struct weston_wm *wm = window->wm;
370         struct weston_shell_interface *shell_interface =
371                 &wm->server->compositor->shell_interface;
372
373 #define F(field) offsetof(struct weston_wm_window, field)
374         const struct {
375                 xcb_atom_t atom;
376                 xcb_atom_t type;
377                 int offset;
378         } props[] = {
379                 { XCB_ATOM_WM_CLASS, XCB_ATOM_STRING, F(class) },
380                 { XCB_ATOM_WM_NAME, XCB_ATOM_STRING, F(name) },
381                 { XCB_ATOM_WM_TRANSIENT_FOR, XCB_ATOM_WINDOW, F(transient_for) },
382                 { wm->atom.wm_protocols, TYPE_WM_PROTOCOLS, F(protocols) },
383                 { wm->atom.wm_normal_hints, TYPE_WM_NORMAL_HINTS, F(protocols) },
384                 { wm->atom.net_wm_state, TYPE_NET_WM_STATE },
385                 { wm->atom.net_wm_window_type, XCB_ATOM_ATOM, F(type) },
386                 { wm->atom.net_wm_name, XCB_ATOM_STRING, F(name) },
387                 { wm->atom.net_wm_pid, XCB_ATOM_CARDINAL, F(pid) },
388                 { wm->atom.motif_wm_hints, TYPE_MOTIF_WM_HINTS, 0 },
389                 { wm->atom.wm_client_machine, XCB_ATOM_WM_CLIENT_MACHINE, F(machine) },
390         };
391 #undef F
392
393         xcb_get_property_cookie_t cookie[ARRAY_LENGTH(props)];
394         xcb_get_property_reply_t *reply;
395         void *p;
396         uint32_t *xid;
397         xcb_atom_t *atom;
398         uint32_t i;
399
400         if (!window->properties_dirty)
401                 return;
402         window->properties_dirty = 0;
403
404         for (i = 0; i < ARRAY_LENGTH(props); i++)
405                 cookie[i] = xcb_get_property(wm->conn,
406                                              0, /* delete */
407                                              window->id,
408                                              props[i].atom,
409                                              XCB_ATOM_ANY, 0, 2048);
410
411         window->decorate = !window->override_redirect;
412         window->size_hints.flags = 0;
413         window->motif_hints.flags = 0;
414         window->delete_window = 0;
415
416         for (i = 0; i < ARRAY_LENGTH(props); i++)  {
417                 reply = xcb_get_property_reply(wm->conn, cookie[i], NULL);
418                 if (!reply)
419                         /* Bad window, typically */
420                         continue;
421                 if (reply->type == XCB_ATOM_NONE) {
422                         /* No such property */
423                         free(reply);
424                         continue;
425                 }
426
427                 p = ((char *) window + props[i].offset);
428
429                 switch (props[i].type) {
430                 case XCB_ATOM_WM_CLIENT_MACHINE:
431                 case XCB_ATOM_STRING:
432                         /* FIXME: We're using this for both string and
433                            utf8_string */
434                         if (*(char **) p)
435                                 free(*(char **) p);
436
437                         *(char **) p =
438                                 strndup(xcb_get_property_value(reply),
439                                         xcb_get_property_value_length(reply));
440                         break;
441                 case XCB_ATOM_WINDOW:
442                         xid = xcb_get_property_value(reply);
443                         *(struct weston_wm_window **) p =
444                                 hash_table_lookup(wm->window_hash, *xid);
445                         break;
446                 case XCB_ATOM_CARDINAL:
447                 case XCB_ATOM_ATOM:
448                         atom = xcb_get_property_value(reply);
449                         *(xcb_atom_t *) p = *atom;
450                         break;
451                 case TYPE_WM_PROTOCOLS:
452                         atom = xcb_get_property_value(reply);
453                         for (i = 0; i < reply->value_len; i++)
454                                 if (atom[i] == wm->atom.wm_delete_window)
455                                         window->delete_window = 1;
456                         break;
457
458                         break;
459                 case TYPE_WM_NORMAL_HINTS:
460                         memcpy(&window->size_hints,
461                                xcb_get_property_value(reply),
462                                sizeof window->size_hints);
463                         break;
464                 case TYPE_NET_WM_STATE:
465                         window->fullscreen = 0;
466                         atom = xcb_get_property_value(reply);
467                         for (i = 0; i < reply->value_len; i++)
468                                 if (atom[i] == wm->atom.net_wm_state_fullscreen)
469                                         window->fullscreen = 1;
470                         break;
471                 case TYPE_MOTIF_WM_HINTS:
472                         memcpy(&window->motif_hints,
473                                xcb_get_property_value(reply),
474                                sizeof window->motif_hints);
475                         if (window->motif_hints.flags & MWM_HINTS_DECORATIONS)
476                                 window->decorate =
477                                         window->motif_hints.decorations > 0;
478                         break;
479                 default:
480                         break;
481                 }
482                 free(reply);
483         }
484
485         if (window->shsurf && window->name)
486                 shell_interface->set_title(window->shsurf, window->name);
487         if (window->frame && window->name)
488                 frame_set_title(window->frame, window->name);
489 }
490
491 static void
492 weston_wm_window_get_frame_size(struct weston_wm_window *window,
493                                 int *width, int *height)
494 {
495         struct theme *t = window->wm->theme;
496
497         if (window->fullscreen) {
498                 *width = window->width;
499                 *height = window->height;
500         } else if (window->decorate && window->frame) {
501                 *width = frame_width(window->frame);
502                 *height = frame_height(window->frame);
503         } else {
504                 *width = window->width + t->margin * 2;
505                 *height = window->height + t->margin * 2;
506         }
507 }
508
509 static void
510 weston_wm_window_get_child_position(struct weston_wm_window *window,
511                                     int *x, int *y)
512 {
513         struct theme *t = window->wm->theme;
514
515         if (window->fullscreen) {
516                 *x = 0;
517                 *y = 0;
518         } else if (window->decorate && window->frame) {
519                 frame_interior(window->frame, x, y, NULL, NULL);
520         } else {
521                 *x = t->margin;
522                 *y = t->margin;
523         }
524 }
525
526 static void
527 weston_wm_window_send_configure_notify(struct weston_wm_window *window)
528 {
529         xcb_configure_notify_event_t configure_notify;
530         struct weston_wm *wm = window->wm;
531         int x, y;
532
533         weston_wm_window_get_child_position(window, &x, &y);
534         configure_notify.response_type = XCB_CONFIGURE_NOTIFY;
535         configure_notify.pad0 = 0;
536         configure_notify.event = window->id;
537         configure_notify.window = window->id;
538         configure_notify.above_sibling = XCB_WINDOW_NONE;
539         configure_notify.x = x;
540         configure_notify.y = y;
541         configure_notify.width = window->width;
542         configure_notify.height = window->height;
543         configure_notify.border_width = 0;
544         configure_notify.override_redirect = 0;
545         configure_notify.pad1 = 0;
546
547         xcb_send_event(wm->conn, 0, window->id, 
548                        XCB_EVENT_MASK_STRUCTURE_NOTIFY,
549                        (char *) &configure_notify);
550 }
551
552 static void
553 weston_wm_handle_configure_request(struct weston_wm *wm, xcb_generic_event_t *event)
554 {
555         xcb_configure_request_event_t *configure_request = 
556                 (xcb_configure_request_event_t *) event;
557         struct weston_wm_window *window;
558         uint32_t mask, values[16];
559         int x, y, width, height, i = 0;
560
561         wm_log("XCB_CONFIGURE_REQUEST (window %d) %d,%d @ %dx%d\n",
562                configure_request->window,
563                configure_request->x, configure_request->y,
564                configure_request->width, configure_request->height);
565
566         window = hash_table_lookup(wm->window_hash, configure_request->window);
567
568         if (window->fullscreen) {
569                 weston_wm_window_send_configure_notify(window);
570                 return;
571         }
572
573         if (configure_request->value_mask & XCB_CONFIG_WINDOW_WIDTH)
574                 window->width = configure_request->width;
575         if (configure_request->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
576                 window->height = configure_request->height;
577
578         if (window->frame)
579                 frame_resize_inside(window->frame, window->width, window->height);
580
581         weston_wm_window_get_child_position(window, &x, &y);
582         values[i++] = x;
583         values[i++] = y;
584         values[i++] = window->width;
585         values[i++] = window->height;
586         values[i++] = 0;
587         mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
588                 XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
589                 XCB_CONFIG_WINDOW_BORDER_WIDTH;
590         if (configure_request->value_mask & XCB_CONFIG_WINDOW_SIBLING) {
591                 values[i++] = configure_request->sibling;
592                 mask |= XCB_CONFIG_WINDOW_SIBLING;
593         }
594         if (configure_request->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) {
595                 values[i++] = configure_request->stack_mode;
596                 mask |= XCB_CONFIG_WINDOW_STACK_MODE;
597         }
598
599         xcb_configure_window(wm->conn, window->id, mask, values);
600
601         weston_wm_window_get_frame_size(window, &width, &height);
602         values[0] = width;
603         values[1] = height;
604         mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
605         xcb_configure_window(wm->conn, window->frame_id, mask, values);
606
607         weston_wm_window_schedule_repaint(window);
608 }
609
610 static int
611 our_resource(struct weston_wm *wm, uint32_t id)
612 {
613         const xcb_setup_t *setup;
614
615         setup = xcb_get_setup(wm->conn);
616
617         return (id & ~setup->resource_id_mask) == setup->resource_id_base;
618 }
619
620 static void
621 weston_wm_handle_configure_notify(struct weston_wm *wm, xcb_generic_event_t *event)
622 {
623         xcb_configure_notify_event_t *configure_notify = 
624                 (xcb_configure_notify_event_t *) event;
625         struct weston_wm_window *window;
626
627         wm_log("XCB_CONFIGURE_NOTIFY (window %d) %d,%d @ %dx%d\n",
628                configure_notify->window,
629                configure_notify->x, configure_notify->y,
630                configure_notify->width, configure_notify->height);
631
632         window = hash_table_lookup(wm->window_hash, configure_notify->window);
633         window->x = configure_notify->x;
634         window->y = configure_notify->y;
635         if (window->override_redirect) {
636                 window->width = configure_notify->width;
637                 window->height = configure_notify->height;
638                 if (window->frame)
639                         frame_resize_inside(window->frame,
640                                             window->width, window->height);
641         }
642 }
643
644 static void
645 weston_wm_kill_client(struct wl_listener *listener, void *data)
646 {
647         struct weston_surface *surface = data;
648         struct weston_wm_window *window = get_wm_window(surface);
649         char name[1024];
650
651         if (!window)
652                 return;
653
654         gethostname(name, 1024);
655
656         /* this is only one heuristic to guess the PID of a client is valid,
657          * assuming it's compliant with icccm and ewmh. Non-compliants and
658          * remote applications of course fail. */
659         if (!strcmp(window->machine, name) && window->pid != 0)
660                 kill(window->pid, SIGKILL);
661 }
662
663 static void
664 weston_wm_window_activate(struct wl_listener *listener, void *data)
665 {
666         struct weston_surface *surface = data;
667         struct weston_wm_window *window = NULL;
668         struct weston_wm *wm =
669                 container_of(listener, struct weston_wm, activate_listener);
670         xcb_client_message_event_t client_message;
671
672         if (surface) {
673                 window = get_wm_window(surface);
674         }
675
676         if (window) {
677                 client_message.response_type = XCB_CLIENT_MESSAGE;
678                 client_message.format = 32;
679                 client_message.window = window->id;
680                 client_message.type = wm->atom.wm_protocols;
681                 client_message.data.data32[0] = wm->atom.wm_take_focus;
682                 client_message.data.data32[1] = XCB_TIME_CURRENT_TIME;
683
684                 xcb_send_event(wm->conn, 0, window->id, 
685                                XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT,
686                                (char *) &client_message);
687
688                 xcb_set_input_focus (wm->conn, XCB_INPUT_FOCUS_POINTER_ROOT,
689                                      window->id, XCB_TIME_CURRENT_TIME);
690         } else {
691                 xcb_set_input_focus (wm->conn,
692                                      XCB_INPUT_FOCUS_POINTER_ROOT,
693                                      XCB_NONE,
694                                      XCB_TIME_CURRENT_TIME);
695         }
696
697         if (wm->focus_window) {
698                 if (wm->focus_window->frame)
699                         frame_unset_flag(wm->focus_window->frame, FRAME_FLAG_ACTIVE);
700                 weston_wm_window_schedule_repaint(wm->focus_window);
701         }
702         wm->focus_window = window;
703         if (wm->focus_window) {
704                 if (wm->focus_window->frame)
705                         frame_set_flag(wm->focus_window->frame, FRAME_FLAG_ACTIVE);
706                 weston_wm_window_schedule_repaint(wm->focus_window);
707         }
708 }
709
710 static void
711 weston_wm_window_transform(struct wl_listener *listener, void *data)
712 {
713         struct weston_surface *surface = data;
714         struct weston_wm_window *window = get_wm_window(surface);
715         struct weston_wm *wm =
716                 container_of(listener, struct weston_wm, transform_listener);
717         uint32_t mask, values[2];
718
719         if (!window || !wm)
720                 return;
721
722         if (!window->view || !weston_view_is_mapped(window->view))
723                 return;
724
725         if (window->x != window->view->geometry.x ||
726             window->y != window->view->geometry.y) {
727                 values[0] = window->view->geometry.x;
728                 values[1] = window->view->geometry.y;
729                 mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y;
730
731                 xcb_configure_window(wm->conn, window->frame_id, mask, values);
732                 xcb_flush(wm->conn);
733         }
734 }
735
736 #define ICCCM_WITHDRAWN_STATE   0
737 #define ICCCM_NORMAL_STATE      1
738 #define ICCCM_ICONIC_STATE      3
739
740 static void
741 weston_wm_window_set_wm_state(struct weston_wm_window *window, int32_t state)
742 {
743         struct weston_wm *wm = window->wm;
744         uint32_t property[2];
745
746         property[0] = state;
747         property[1] = XCB_WINDOW_NONE;
748
749         xcb_change_property(wm->conn,
750                             XCB_PROP_MODE_REPLACE,
751                             window->id,
752                             wm->atom.wm_state,
753                             wm->atom.wm_state,
754                             32, /* format */
755                             2, property);
756 }
757
758 static void
759 weston_wm_window_set_net_wm_state(struct weston_wm_window *window)
760 {
761         struct weston_wm *wm = window->wm;
762         uint32_t property[1];
763         int i;
764
765         i = 0;
766         if (window->fullscreen)
767                 property[i++] = wm->atom.net_wm_state_fullscreen;
768
769         xcb_change_property(wm->conn,
770                             XCB_PROP_MODE_REPLACE,
771                             window->id,
772                             wm->atom.net_wm_state,
773                             XCB_ATOM_ATOM,
774                             32, /* format */
775                             i, property);
776 }
777
778 static void
779 weston_wm_window_create_frame(struct weston_wm_window *window)
780 {
781         struct weston_wm *wm = window->wm;
782         uint32_t values[3];
783         int x, y, width, height;
784
785         window->frame = frame_create(window->wm->theme,
786                                      window->width, window->height,
787                                      FRAME_BUTTON_CLOSE, window->name);
788         frame_resize_inside(window->frame, window->width, window->height);
789
790         weston_wm_window_get_frame_size(window, &width, &height);
791         weston_wm_window_get_child_position(window, &x, &y);
792
793         values[0] = wm->screen->black_pixel;
794         values[1] =
795                 XCB_EVENT_MASK_KEY_PRESS |
796                 XCB_EVENT_MASK_KEY_RELEASE |
797                 XCB_EVENT_MASK_BUTTON_PRESS |
798                 XCB_EVENT_MASK_BUTTON_RELEASE |
799                 XCB_EVENT_MASK_POINTER_MOTION |
800                 XCB_EVENT_MASK_ENTER_WINDOW |
801                 XCB_EVENT_MASK_LEAVE_WINDOW |
802                 XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
803                 XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
804         values[2] = wm->colormap;
805
806         window->frame_id = xcb_generate_id(wm->conn);
807         xcb_create_window(wm->conn,
808                           32,
809                           window->frame_id,
810                           wm->screen->root,
811                           0, 0,
812                           width, height,
813                           0,
814                           XCB_WINDOW_CLASS_INPUT_OUTPUT,
815                           wm->visual_id,
816                           XCB_CW_BORDER_PIXEL |
817                           XCB_CW_EVENT_MASK |
818                           XCB_CW_COLORMAP, values);
819
820         xcb_reparent_window(wm->conn, window->id, window->frame_id, x, y);
821
822         values[0] = 0;
823         xcb_configure_window(wm->conn, window->id,
824                              XCB_CONFIG_WINDOW_BORDER_WIDTH, values);
825
826         window->cairo_surface =
827                 cairo_xcb_surface_create_with_xrender_format(wm->conn,
828                                                              wm->screen,
829                                                              window->frame_id,
830                                                              &wm->format_rgba,
831                                                              width, height);
832
833         hash_table_insert(wm->window_hash, window->frame_id, window);
834 }
835
836 static void
837 weston_wm_handle_map_request(struct weston_wm *wm, xcb_generic_event_t *event)
838 {
839         xcb_map_request_event_t *map_request =
840                 (xcb_map_request_event_t *) event;
841         struct weston_wm_window *window;
842
843         if (our_resource(wm, map_request->window)) {
844                 wm_log("XCB_MAP_REQUEST (window %d, ours)\n",
845                        map_request->window);
846                 return;
847         }
848
849         window = hash_table_lookup(wm->window_hash, map_request->window);
850
851         weston_wm_window_read_properties(window);
852
853         if (window->frame_id == XCB_WINDOW_NONE)
854                 weston_wm_window_create_frame(window);
855
856         wm_log("XCB_MAP_REQUEST (window %d, %p, frame %d)\n",
857                window->id, window, window->frame_id);
858
859         weston_wm_window_set_wm_state(window, ICCCM_NORMAL_STATE);
860         weston_wm_window_set_net_wm_state(window);
861
862         xcb_map_window(wm->conn, map_request->window);
863         xcb_map_window(wm->conn, window->frame_id);
864 }
865
866 static void
867 weston_wm_handle_map_notify(struct weston_wm *wm, xcb_generic_event_t *event)
868 {
869         xcb_map_notify_event_t *map_notify = (xcb_map_notify_event_t *) event;
870
871         if (our_resource(wm, map_notify->window)) {
872                 wm_log("XCB_MAP_NOTIFY (window %d, ours)\n",
873                        map_notify->window);
874                         return;
875         }
876
877         wm_log("XCB_MAP_NOTIFY (window %d)\n", map_notify->window);
878 }
879
880 static void
881 weston_wm_handle_unmap_notify(struct weston_wm *wm, xcb_generic_event_t *event)
882 {
883         xcb_unmap_notify_event_t *unmap_notify =
884                 (xcb_unmap_notify_event_t *) event;
885         struct weston_wm_window *window;
886
887         wm_log("XCB_UNMAP_NOTIFY (window %d, event %d%s)\n",
888                unmap_notify->window,
889                unmap_notify->event,
890                our_resource(wm, unmap_notify->window) ? ", ours" : "");
891
892         if (our_resource(wm, unmap_notify->window))
893                 return;
894
895         if (unmap_notify->response_type & SEND_EVENT_MASK)
896                 /* We just ignore the ICCCM 4.1.4 synthetic unmap notify
897                  * as it may come in after we've destroyed the window. */
898                 return;
899
900         window = hash_table_lookup(wm->window_hash, unmap_notify->window);
901         if (wm->focus_window == window)
902                 wm->focus_window = NULL;
903         if (window->surface)
904                 wl_list_remove(&window->surface_destroy_listener.link);
905         window->surface = NULL;
906         window->shsurf = NULL;
907         window->view = NULL;
908         xcb_unmap_window(wm->conn, window->frame_id);
909 }
910
911 static void
912 weston_wm_window_draw_decoration(void *data)
913 {
914         struct weston_wm_window *window = data;
915         struct weston_wm *wm = window->wm;
916         struct theme *t = wm->theme;
917         cairo_t *cr;
918         int x, y, width, height;
919         int32_t input_x, input_y, input_w, input_h;
920
921         uint32_t flags = 0;
922
923         weston_wm_window_read_properties(window);
924
925         window->repaint_source = NULL;
926
927         weston_wm_window_get_frame_size(window, &width, &height);
928         weston_wm_window_get_child_position(window, &x, &y);
929
930         cairo_xcb_surface_set_size(window->cairo_surface, width, height);
931         cr = cairo_create(window->cairo_surface);
932
933         if (window->fullscreen) {
934                 /* nothing */
935         } else if (window->decorate) {
936                 if (wm->focus_window == window)
937                         flags |= THEME_FRAME_ACTIVE;
938
939                 frame_repaint(window->frame, cr);
940         } else {
941                 cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
942                 cairo_set_source_rgba(cr, 0, 0, 0, 0);
943                 cairo_paint(cr);
944
945                 cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
946                 cairo_set_source_rgba(cr, 0, 0, 0, 0.45);
947                 tile_mask(cr, t->shadow, 2, 2, width + 8, height + 8, 64, 64);
948         }
949
950         cairo_destroy(cr);
951
952         if (window->surface) {
953                 pixman_region32_fini(&window->surface->pending.opaque);
954                 if(window->has_alpha) {
955                         pixman_region32_init(&window->surface->pending.opaque);
956                 } else {
957                         /* We leave an extra pixel around the X window area to
958                          * make sure we don't sample from the undefined alpha
959                          * channel when filtering. */
960                         pixman_region32_init_rect(&window->surface->pending.opaque, 
961                                                   x - 1, y - 1,
962                                                   window->width + 2,
963                                                   window->height + 2);
964                 }
965                 if (window->view)
966                         weston_view_geometry_dirty(window->view);
967
968                 pixman_region32_fini(&window->surface->pending.input);
969
970                 if (window->fullscreen) {
971                         input_x = 0;
972                         input_y = 0;
973                         input_w = window->width;
974                         input_h = window->height;
975                 } else if (window->decorate) {
976                         frame_input_rect(window->frame, &input_x, &input_y,
977                                          &input_w, &input_h);
978                 }
979
980                 pixman_region32_init_rect(&window->surface->pending.input,
981                                           input_x, input_y, input_w, input_h);
982         }
983 }
984
985 static void
986 weston_wm_window_schedule_repaint(struct weston_wm_window *window)
987 {
988         struct weston_wm *wm = window->wm;
989         int width, height;
990
991         if (window->frame_id == XCB_WINDOW_NONE) {
992                 if (window->surface != NULL) {
993                         weston_wm_window_get_frame_size(window, &width, &height);
994                         pixman_region32_fini(&window->surface->pending.opaque);
995                         if(window->has_alpha) {
996                                 pixman_region32_init(&window->surface->pending.opaque);
997                         } else {
998                                 pixman_region32_init_rect(&window->surface->pending.opaque, 0, 0,
999                                                           width, height);
1000                         }
1001                         if (window->view)
1002                                 weston_view_geometry_dirty(window->view);
1003                 }
1004                 return;
1005         }
1006
1007         if (window->repaint_source)
1008                 return;
1009
1010         window->repaint_source =
1011                 wl_event_loop_add_idle(wm->server->loop,
1012                                        weston_wm_window_draw_decoration,
1013                                        window);
1014 }
1015
1016 static void
1017 weston_wm_handle_property_notify(struct weston_wm *wm, xcb_generic_event_t *event)
1018 {
1019         xcb_property_notify_event_t *property_notify =
1020                 (xcb_property_notify_event_t *) event;
1021         struct weston_wm_window *window;
1022
1023         window = hash_table_lookup(wm->window_hash, property_notify->window);
1024         if (!window)
1025                 return;
1026
1027         window->properties_dirty = 1;
1028
1029         wm_log("XCB_PROPERTY_NOTIFY: window %d, ", property_notify->window);
1030         if (property_notify->state == XCB_PROPERTY_DELETE)
1031                 wm_log("deleted\n");
1032         else
1033                 read_and_dump_property(wm, property_notify->window,
1034                                        property_notify->atom);
1035
1036         if (property_notify->atom == wm->atom.net_wm_name ||
1037             property_notify->atom == XCB_ATOM_WM_NAME)
1038                 weston_wm_window_schedule_repaint(window);
1039 }
1040
1041 static void
1042 weston_wm_window_create(struct weston_wm *wm,
1043                         xcb_window_t id, int width, int height, int x, int y, int override)
1044 {
1045         struct weston_wm_window *window;
1046         uint32_t values[1];
1047         xcb_get_geometry_cookie_t geometry_cookie;
1048         xcb_get_geometry_reply_t *geometry_reply;
1049
1050         window = zalloc(sizeof *window);
1051         if (window == NULL) {
1052                 wm_log("failed to allocate window\n");
1053                 return;
1054         }
1055
1056         geometry_cookie = xcb_get_geometry(wm->conn, id);
1057
1058         values[0] = XCB_EVENT_MASK_PROPERTY_CHANGE;
1059         xcb_change_window_attributes(wm->conn, id, XCB_CW_EVENT_MASK, values);
1060
1061         window->wm = wm;
1062         window->id = id;
1063         window->properties_dirty = 1;
1064         window->override_redirect = override;
1065         window->width = width;
1066         window->height = height;
1067         window->x = x;
1068         window->y = y;
1069
1070         geometry_reply = xcb_get_geometry_reply(wm->conn, geometry_cookie, NULL);
1071         /* technically we should use XRender and check the visual format's
1072         alpha_mask, but checking depth is simpler and works in all known cases */
1073         if(geometry_reply != NULL)
1074                 window->has_alpha = geometry_reply->depth == 32;
1075         free(geometry_reply);
1076
1077         hash_table_insert(wm->window_hash, id, window);
1078 }
1079
1080 static void
1081 weston_wm_window_destroy(struct weston_wm_window *window)
1082 {
1083         struct weston_wm *wm = window->wm;
1084
1085         if (window->repaint_source)
1086                 wl_event_source_remove(window->repaint_source);
1087         if (window->cairo_surface)
1088                 cairo_surface_destroy(window->cairo_surface);
1089
1090         if (window->frame_id) {
1091                 xcb_reparent_window(wm->conn, window->id, wm->wm_window, 0, 0);
1092                 xcb_destroy_window(wm->conn, window->frame_id);
1093                 weston_wm_window_set_wm_state(window, ICCCM_WITHDRAWN_STATE);
1094                 hash_table_remove(wm->window_hash, window->frame_id);
1095                 window->frame_id = XCB_WINDOW_NONE;
1096         }
1097
1098         hash_table_remove(window->wm->window_hash, window->id);
1099         free(window);
1100 }
1101
1102 static void
1103 weston_wm_handle_create_notify(struct weston_wm *wm, xcb_generic_event_t *event)
1104 {
1105         xcb_create_notify_event_t *create_notify =
1106                 (xcb_create_notify_event_t *) event;
1107
1108         wm_log("XCB_CREATE_NOTIFY (window %d, width %d, height %d%s%s)\n",
1109                create_notify->window,
1110                create_notify->width, create_notify->height,
1111                create_notify->override_redirect ? ", override" : "",
1112                our_resource(wm, create_notify->window) ? ", ours" : "");
1113
1114         if (our_resource(wm, create_notify->window))
1115                 return;
1116
1117         weston_wm_window_create(wm, create_notify->window,
1118                                 create_notify->width, create_notify->height,
1119                                 create_notify->x, create_notify->y,
1120                                 create_notify->override_redirect);
1121 }
1122
1123 static void
1124 weston_wm_handle_destroy_notify(struct weston_wm *wm, xcb_generic_event_t *event)
1125 {
1126         xcb_destroy_notify_event_t *destroy_notify =
1127                 (xcb_destroy_notify_event_t *) event;
1128         struct weston_wm_window *window;
1129
1130         wm_log("XCB_DESTROY_NOTIFY, win %d, event %d%s\n",
1131                destroy_notify->window,
1132                destroy_notify->event,
1133                our_resource(wm, destroy_notify->window) ? ", ours" : "");
1134
1135         if (our_resource(wm, destroy_notify->window))
1136                 return;
1137
1138         window = hash_table_lookup(wm->window_hash, destroy_notify->window);
1139         weston_wm_window_destroy(window);
1140 }
1141
1142 static void
1143 weston_wm_handle_reparent_notify(struct weston_wm *wm, xcb_generic_event_t *event)
1144 {
1145         xcb_reparent_notify_event_t *reparent_notify =
1146                 (xcb_reparent_notify_event_t *) event;
1147         struct weston_wm_window *window;
1148
1149         wm_log("XCB_REPARENT_NOTIFY (window %d, parent %d, event %d)\n",
1150                reparent_notify->window,
1151                reparent_notify->parent,
1152                reparent_notify->event);
1153
1154         if (reparent_notify->parent == wm->screen->root) {
1155                 weston_wm_window_create(wm, reparent_notify->window, 10, 10,
1156                                         reparent_notify->x, reparent_notify->y,
1157                                         reparent_notify->override_redirect);
1158         } else if (!our_resource(wm, reparent_notify->parent)) {
1159                 window = hash_table_lookup(wm->window_hash,
1160                                            reparent_notify->window);
1161                 weston_wm_window_destroy(window);
1162         }
1163 }
1164
1165 struct weston_seat *
1166 weston_wm_pick_seat(struct weston_wm *wm)
1167 {
1168         return container_of(wm->server->compositor->seat_list.next,
1169                             struct weston_seat, link);
1170 }
1171
1172 static void
1173 weston_wm_window_handle_moveresize(struct weston_wm_window *window,
1174                                    xcb_client_message_event_t *client_message)
1175 {
1176         static const int map[] = {
1177                 THEME_LOCATION_RESIZING_TOP_LEFT,
1178                 THEME_LOCATION_RESIZING_TOP,
1179                 THEME_LOCATION_RESIZING_TOP_RIGHT,
1180                 THEME_LOCATION_RESIZING_RIGHT,
1181                 THEME_LOCATION_RESIZING_BOTTOM_RIGHT,
1182                 THEME_LOCATION_RESIZING_BOTTOM,
1183                 THEME_LOCATION_RESIZING_BOTTOM_LEFT,
1184                 THEME_LOCATION_RESIZING_LEFT
1185         };
1186
1187         struct weston_wm *wm = window->wm;
1188         struct weston_seat *seat = weston_wm_pick_seat(wm);
1189         int detail;
1190         struct weston_shell_interface *shell_interface =
1191                 &wm->server->compositor->shell_interface;
1192
1193         if (seat->pointer->button_count != 1 || !window->view
1194             || seat->pointer->focus != window->view)
1195                 return;
1196
1197         detail = client_message->data.data32[2];
1198         switch (detail) {
1199         case _NET_WM_MOVERESIZE_MOVE:
1200                 shell_interface->move(window->shsurf, seat);
1201                 break;
1202         case _NET_WM_MOVERESIZE_SIZE_TOPLEFT:
1203         case _NET_WM_MOVERESIZE_SIZE_TOP:
1204         case _NET_WM_MOVERESIZE_SIZE_TOPRIGHT:
1205         case _NET_WM_MOVERESIZE_SIZE_RIGHT:
1206         case _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT:
1207         case _NET_WM_MOVERESIZE_SIZE_BOTTOM:
1208         case _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT:
1209         case _NET_WM_MOVERESIZE_SIZE_LEFT:
1210                 shell_interface->resize(window->shsurf, seat, map[detail]);
1211                 break;
1212         case _NET_WM_MOVERESIZE_CANCEL:
1213                 break;
1214         }
1215 }
1216
1217 #define _NET_WM_STATE_REMOVE    0
1218 #define _NET_WM_STATE_ADD       1
1219 #define _NET_WM_STATE_TOGGLE    2
1220
1221 static int
1222 update_state(int action, int *state)
1223 {
1224         int new_state, changed;
1225
1226         switch (action) {
1227         case _NET_WM_STATE_REMOVE:
1228                 new_state = 0;
1229                 break;
1230         case _NET_WM_STATE_ADD:
1231                 new_state = 1;
1232                 break;
1233         case _NET_WM_STATE_TOGGLE:
1234                 new_state = !*state;
1235                 break;
1236         default:
1237                 return 0;
1238         }
1239
1240         changed = (*state != new_state);
1241         *state = new_state;
1242
1243         return changed;
1244 }
1245
1246 static void
1247 weston_wm_window_configure(void *data);
1248
1249 static void
1250 weston_wm_window_handle_state(struct weston_wm_window *window,
1251                               xcb_client_message_event_t *client_message)
1252 {
1253         struct weston_wm *wm = window->wm;
1254         struct weston_shell_interface *shell_interface =
1255                 &wm->server->compositor->shell_interface;
1256         uint32_t action, property;
1257
1258         action = client_message->data.data32[0];
1259         property = client_message->data.data32[1];
1260
1261         if (property == wm->atom.net_wm_state_fullscreen &&
1262             update_state(action, &window->fullscreen)) {
1263                 weston_wm_window_set_net_wm_state(window);
1264                 if (window->fullscreen) {
1265                         window->saved_width = window->width;
1266                         window->saved_height = window->height;
1267
1268                         if (window->shsurf)
1269                                 shell_interface->set_fullscreen(window->shsurf,
1270                                                                 WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT,
1271                                                                 0, NULL);
1272                 } else {
1273                         shell_interface->set_toplevel(window->shsurf);
1274                         window->width = window->saved_width;
1275                         window->height = window->saved_height;
1276                         if (window->frame)
1277                                 frame_resize_inside(window->frame,
1278                                                     window->width,
1279                                                     window->height);
1280                         weston_wm_window_configure(window);
1281                 }
1282         }
1283 }
1284
1285 static void
1286 weston_wm_handle_client_message(struct weston_wm *wm,
1287                                 xcb_generic_event_t *event)
1288 {
1289         xcb_client_message_event_t *client_message =
1290                 (xcb_client_message_event_t *) event;
1291         struct weston_wm_window *window;
1292
1293         window = hash_table_lookup(wm->window_hash, client_message->window);
1294
1295         wm_log("XCB_CLIENT_MESSAGE (%s %d %d %d %d %d win %d)\n",
1296                get_atom_name(wm->conn, client_message->type),
1297                client_message->data.data32[0],
1298                client_message->data.data32[1],
1299                client_message->data.data32[2],
1300                client_message->data.data32[3],
1301                client_message->data.data32[4],
1302                client_message->window);
1303
1304         if (client_message->type == wm->atom.net_wm_moveresize)
1305                 weston_wm_window_handle_moveresize(window, client_message);
1306         else if (client_message->type == wm->atom.net_wm_state)
1307                 weston_wm_window_handle_state(window, client_message);
1308 }
1309
1310 enum cursor_type {
1311         XWM_CURSOR_TOP,
1312         XWM_CURSOR_BOTTOM,
1313         XWM_CURSOR_LEFT,
1314         XWM_CURSOR_RIGHT,
1315         XWM_CURSOR_TOP_LEFT,
1316         XWM_CURSOR_TOP_RIGHT,
1317         XWM_CURSOR_BOTTOM_LEFT,
1318         XWM_CURSOR_BOTTOM_RIGHT,
1319         XWM_CURSOR_LEFT_PTR,
1320 };
1321
1322 /*
1323  * The following correspondences between file names and cursors was copied
1324  * from: https://bugs.kde.org/attachment.cgi?id=67313
1325  */
1326
1327 static const char *bottom_left_corners[] = {
1328         "bottom_left_corner",
1329         "sw-resize",
1330         "size_bdiag"
1331 };
1332
1333 static const char *bottom_right_corners[] = {
1334         "bottom_right_corner",
1335         "se-resize",
1336         "size_fdiag"
1337 };
1338
1339 static const char *bottom_sides[] = {
1340         "bottom_side",
1341         "s-resize",
1342         "size_ver"
1343 };
1344
1345 static const char *left_ptrs[] = {
1346         "left_ptr",
1347         "default",
1348         "top_left_arrow",
1349         "left-arrow"
1350 };
1351
1352 static const char *left_sides[] = {
1353         "left_side",
1354         "w-resize",
1355         "size_hor"
1356 };
1357
1358 static const char *right_sides[] = {
1359         "right_side",
1360         "e-resize",
1361         "size_hor"
1362 };
1363
1364 static const char *top_left_corners[] = {
1365         "top_left_corner",
1366         "nw-resize",
1367         "size_fdiag"
1368 };
1369
1370 static const char *top_right_corners[] = {
1371         "top_right_corner",
1372         "ne-resize",
1373         "size_bdiag"
1374 };
1375
1376 static const char *top_sides[] = {
1377         "top_side",
1378         "n-resize",
1379         "size_ver"
1380 };
1381
1382 struct cursor_alternatives {
1383         const char **names;
1384         size_t count;
1385 };
1386
1387 static const struct cursor_alternatives cursors[] = {
1388         {top_sides, ARRAY_LENGTH(top_sides)},
1389         {bottom_sides, ARRAY_LENGTH(bottom_sides)},
1390         {left_sides, ARRAY_LENGTH(left_sides)},
1391         {right_sides, ARRAY_LENGTH(right_sides)},
1392         {top_left_corners, ARRAY_LENGTH(top_left_corners)},
1393         {top_right_corners, ARRAY_LENGTH(top_right_corners)},
1394         {bottom_left_corners, ARRAY_LENGTH(bottom_left_corners)},
1395         {bottom_right_corners, ARRAY_LENGTH(bottom_right_corners)},
1396         {left_ptrs, ARRAY_LENGTH(left_ptrs)},
1397 };
1398
1399 static void
1400 weston_wm_create_cursors(struct weston_wm *wm)
1401 {
1402         const char *name;
1403         int i, count = ARRAY_LENGTH(cursors);
1404         size_t j;
1405
1406         wm->cursors = malloc(count * sizeof(xcb_cursor_t));
1407         for (i = 0; i < count; i++) {
1408                 for (j = 0; j < cursors[i].count; j++) {
1409                         name = cursors[i].names[j];
1410                         wm->cursors[i] =
1411                                 xcb_cursor_library_load_cursor(wm, name);
1412                         if (wm->cursors[i] != (xcb_cursor_t)-1)
1413                                 break;
1414                 }
1415         }
1416
1417         wm->last_cursor = -1;
1418 }
1419
1420 static void
1421 weston_wm_destroy_cursors(struct weston_wm *wm)
1422 {
1423         uint8_t i;
1424
1425         for (i = 0; i < ARRAY_LENGTH(cursors); i++)
1426                 xcb_free_cursor(wm->conn, wm->cursors[i]);
1427
1428         free(wm->cursors);
1429 }
1430
1431 static int
1432 get_cursor_for_location(enum theme_location location)
1433 {
1434         // int location = theme_get_location(t, x, y, width, height, 0);
1435
1436         switch (location) {
1437                 case THEME_LOCATION_RESIZING_TOP:
1438                         return XWM_CURSOR_TOP;
1439                 case THEME_LOCATION_RESIZING_BOTTOM:
1440                         return XWM_CURSOR_BOTTOM;
1441                 case THEME_LOCATION_RESIZING_LEFT:
1442                         return XWM_CURSOR_LEFT;
1443                 case THEME_LOCATION_RESIZING_RIGHT:
1444                         return XWM_CURSOR_RIGHT;
1445                 case THEME_LOCATION_RESIZING_TOP_LEFT:
1446                         return XWM_CURSOR_TOP_LEFT;
1447                 case THEME_LOCATION_RESIZING_TOP_RIGHT:
1448                         return XWM_CURSOR_TOP_RIGHT;
1449                 case THEME_LOCATION_RESIZING_BOTTOM_LEFT:
1450                         return XWM_CURSOR_BOTTOM_LEFT;
1451                 case THEME_LOCATION_RESIZING_BOTTOM_RIGHT:
1452                         return XWM_CURSOR_BOTTOM_RIGHT;
1453                 case THEME_LOCATION_EXTERIOR:
1454                 case THEME_LOCATION_TITLEBAR:
1455                 default:
1456                         return XWM_CURSOR_LEFT_PTR;
1457         }
1458 }
1459
1460 static void
1461 weston_wm_window_set_cursor(struct weston_wm *wm, xcb_window_t window_id,
1462                             int cursor)
1463 {
1464         uint32_t cursor_value_list;
1465
1466         if (wm->last_cursor == cursor)
1467                 return;
1468
1469         wm->last_cursor = cursor;
1470
1471         cursor_value_list = wm->cursors[cursor];
1472         xcb_change_window_attributes (wm->conn, window_id,
1473                                       XCB_CW_CURSOR, &cursor_value_list);
1474         xcb_flush(wm->conn);
1475 }
1476
1477 static void
1478 weston_wm_window_close(struct weston_wm_window *window, xcb_timestamp_t time)
1479 {
1480         xcb_client_message_event_t client_message;
1481
1482         if (window->delete_window) {
1483                 client_message.response_type = XCB_CLIENT_MESSAGE;
1484                 client_message.format = 32;
1485                 client_message.window = window->id;
1486                 client_message.type = window->wm->atom.wm_protocols;
1487                 client_message.data.data32[0] =
1488                         window->wm->atom.wm_delete_window;
1489                 client_message.data.data32[1] = time;
1490
1491                 xcb_send_event(window->wm->conn, 0, window->id,
1492                                XCB_EVENT_MASK_NO_EVENT,
1493                                (char *) &client_message);
1494         } else {
1495                 xcb_kill_client(window->wm->conn, window->id);
1496         }
1497 }
1498
1499 static void
1500 weston_wm_handle_button(struct weston_wm *wm, xcb_generic_event_t *event)
1501 {
1502         xcb_button_press_event_t *button = (xcb_button_press_event_t *) event;
1503         struct weston_shell_interface *shell_interface =
1504                 &wm->server->compositor->shell_interface;
1505         struct weston_seat *seat = weston_wm_pick_seat(wm);
1506         struct weston_wm_window *window;
1507         enum theme_location location;
1508         enum frame_button_state button_state;
1509         uint32_t button_id;
1510
1511         wm_log("XCB_BUTTON_%s (detail %d)\n",
1512                button->response_type == XCB_BUTTON_PRESS ?
1513                "PRESS" : "RELEASE", button->detail);
1514
1515         window = hash_table_lookup(wm->window_hash, button->event);
1516         if (!window || !window->decorate)
1517                 return;
1518
1519         if (button->detail != 1 && button->detail != 2)
1520                 return;
1521
1522         button_state = button->response_type == XCB_BUTTON_PRESS ?
1523                 FRAME_BUTTON_PRESSED : FRAME_BUTTON_RELEASED;
1524         button_id = button->detail == 1 ? BTN_LEFT : BTN_RIGHT;
1525
1526         location = frame_pointer_button(window->frame, NULL,
1527                                         button_id, button_state);
1528         if (frame_status(window->frame) & FRAME_STATUS_REPAINT)
1529                 weston_wm_window_schedule_repaint(window);
1530
1531         if (frame_status(window->frame) & FRAME_STATUS_MOVE) {
1532                 shell_interface->move(window->shsurf, seat);
1533                 frame_status_clear(window->frame, FRAME_STATUS_MOVE);
1534         }
1535
1536         if (frame_status(window->frame) & FRAME_STATUS_RESIZE) {
1537                 shell_interface->resize(window->shsurf, seat, location);
1538                 frame_status_clear(window->frame, FRAME_STATUS_RESIZE);
1539         }
1540
1541         if (frame_status(window->frame) & FRAME_STATUS_CLOSE) {
1542                 weston_wm_window_close(window, button->time);
1543                 frame_status_clear(window->frame, FRAME_STATUS_CLOSE);
1544         }
1545 }
1546
1547 static void
1548 weston_wm_handle_motion(struct weston_wm *wm, xcb_generic_event_t *event)
1549 {
1550         xcb_motion_notify_event_t *motion = (xcb_motion_notify_event_t *) event;
1551         struct weston_wm_window *window;
1552         enum theme_location location;
1553         int cursor;
1554
1555         window = hash_table_lookup(wm->window_hash, motion->event);
1556         if (!window || !window->decorate)
1557                 return;
1558
1559         location = frame_pointer_motion(window->frame, NULL,
1560                                         motion->event_x, motion->event_y);
1561         if (frame_status(window->frame) & FRAME_STATUS_REPAINT)
1562                 weston_wm_window_schedule_repaint(window);
1563
1564         cursor = get_cursor_for_location(location);
1565         weston_wm_window_set_cursor(wm, window->frame_id, cursor);
1566 }
1567
1568 static void
1569 weston_wm_handle_enter(struct weston_wm *wm, xcb_generic_event_t *event)
1570 {
1571         xcb_enter_notify_event_t *enter = (xcb_enter_notify_event_t *) event;
1572         struct weston_wm_window *window;
1573         enum theme_location location;
1574         int cursor;
1575
1576         window = hash_table_lookup(wm->window_hash, enter->event);
1577         if (!window || !window->decorate)
1578                 return;
1579
1580         location = frame_pointer_enter(window->frame, NULL,
1581                                        enter->event_x, enter->event_y);
1582         if (frame_status(window->frame) & FRAME_STATUS_REPAINT)
1583                 weston_wm_window_schedule_repaint(window);
1584
1585         cursor = get_cursor_for_location(location);
1586         weston_wm_window_set_cursor(wm, window->frame_id, cursor);
1587 }
1588
1589 static void
1590 weston_wm_handle_leave(struct weston_wm *wm, xcb_generic_event_t *event)
1591 {
1592         xcb_leave_notify_event_t *leave = (xcb_leave_notify_event_t *) event;
1593         struct weston_wm_window *window;
1594
1595         window = hash_table_lookup(wm->window_hash, leave->event);
1596         if (!window || !window->decorate)
1597                 return;
1598
1599         frame_pointer_leave(window->frame, NULL);
1600         if (frame_status(window->frame) & FRAME_STATUS_REPAINT)
1601                 weston_wm_window_schedule_repaint(window);
1602
1603         weston_wm_window_set_cursor(wm, window->frame_id, XWM_CURSOR_LEFT_PTR);
1604 }
1605
1606 static int
1607 weston_wm_handle_event(int fd, uint32_t mask, void *data)
1608 {
1609         struct weston_wm *wm = data;
1610         xcb_generic_event_t *event;
1611         int count = 0;
1612
1613         while (event = xcb_poll_for_event(wm->conn), event != NULL) {
1614                 if (weston_wm_handle_selection_event(wm, event)) {
1615                         free(event);
1616                         count++;
1617                         continue;
1618                 }
1619
1620                 if (weston_wm_handle_dnd_event(wm, event)) {
1621                         free(event);
1622                         count++;
1623                         continue;
1624                 }
1625
1626                 switch (EVENT_TYPE(event)) {
1627                 case XCB_BUTTON_PRESS:
1628                 case XCB_BUTTON_RELEASE:
1629                         weston_wm_handle_button(wm, event);
1630                         break;
1631                 case XCB_ENTER_NOTIFY:
1632                         weston_wm_handle_enter(wm, event);
1633                         break;
1634                 case XCB_LEAVE_NOTIFY:
1635                         weston_wm_handle_leave(wm, event);
1636                         break;
1637                 case XCB_MOTION_NOTIFY:
1638                         weston_wm_handle_motion(wm, event);
1639                         break;
1640                 case XCB_CREATE_NOTIFY:
1641                         weston_wm_handle_create_notify(wm, event);
1642                         break;
1643                 case XCB_MAP_REQUEST:
1644                         weston_wm_handle_map_request(wm, event);
1645                         break;
1646                 case XCB_MAP_NOTIFY:
1647                         weston_wm_handle_map_notify(wm, event);
1648                         break;
1649                 case XCB_UNMAP_NOTIFY:
1650                         weston_wm_handle_unmap_notify(wm, event);
1651                         break;
1652                 case XCB_REPARENT_NOTIFY:
1653                         weston_wm_handle_reparent_notify(wm, event);
1654                         break;
1655                 case XCB_CONFIGURE_REQUEST:
1656                         weston_wm_handle_configure_request(wm, event);
1657                         break;
1658                 case XCB_CONFIGURE_NOTIFY:
1659                         weston_wm_handle_configure_notify(wm, event);
1660                         break;
1661                 case XCB_DESTROY_NOTIFY:
1662                         weston_wm_handle_destroy_notify(wm, event);
1663                         break;
1664                 case XCB_MAPPING_NOTIFY:
1665                         wm_log("XCB_MAPPING_NOTIFY\n");
1666                         break;
1667                 case XCB_PROPERTY_NOTIFY:
1668                         weston_wm_handle_property_notify(wm, event);
1669                         break;
1670                 case XCB_CLIENT_MESSAGE:
1671                         weston_wm_handle_client_message(wm, event);
1672                         break;
1673                 }
1674
1675                 free(event);
1676                 count++;
1677         }
1678
1679         xcb_flush(wm->conn);
1680
1681         return count;
1682 }
1683
1684 static void
1685 weston_wm_get_visual_and_colormap(struct weston_wm *wm)
1686 {
1687         xcb_depth_iterator_t d_iter;
1688         xcb_visualtype_iterator_t vt_iter;
1689         xcb_visualtype_t *visualtype;
1690
1691         d_iter = xcb_screen_allowed_depths_iterator(wm->screen);
1692         visualtype = NULL;
1693         while (d_iter.rem > 0) {
1694                 if (d_iter.data->depth == 32) {
1695                         vt_iter = xcb_depth_visuals_iterator(d_iter.data);
1696                         visualtype = vt_iter.data;
1697                         break;
1698                 }
1699
1700                 xcb_depth_next(&d_iter);
1701         }
1702
1703         if (visualtype == NULL) {
1704                 weston_log("no 32 bit visualtype\n");
1705                 return;
1706         }
1707
1708         wm->visual_id = visualtype->visual_id;
1709         wm->colormap = xcb_generate_id(wm->conn);
1710         xcb_create_colormap(wm->conn, XCB_COLORMAP_ALLOC_NONE,
1711                             wm->colormap, wm->screen->root, wm->visual_id);
1712 }
1713
1714 static void
1715 weston_wm_get_resources(struct weston_wm *wm)
1716 {
1717
1718 #define F(field) offsetof(struct weston_wm, field)
1719
1720         static const struct { const char *name; int offset; } atoms[] = {
1721                 { "WM_PROTOCOLS",       F(atom.wm_protocols) },
1722                 { "WM_NORMAL_HINTS",    F(atom.wm_normal_hints) },
1723                 { "WM_TAKE_FOCUS",      F(atom.wm_take_focus) },
1724                 { "WM_DELETE_WINDOW",   F(atom.wm_delete_window) },
1725                 { "WM_STATE",           F(atom.wm_state) },
1726                 { "WM_S0",              F(atom.wm_s0) },
1727                 { "WM_CLIENT_MACHINE",  F(atom.wm_client_machine) },
1728                 { "_NET_WM_CM_S0",      F(atom.net_wm_cm_s0) },
1729                 { "_NET_WM_NAME",       F(atom.net_wm_name) },
1730                 { "_NET_WM_PID",        F(atom.net_wm_pid) },
1731                 { "_NET_WM_ICON",       F(atom.net_wm_icon) },
1732                 { "_NET_WM_STATE",      F(atom.net_wm_state) },
1733                 { "_NET_WM_STATE_FULLSCREEN", F(atom.net_wm_state_fullscreen) },
1734                 { "_NET_WM_USER_TIME", F(atom.net_wm_user_time) },
1735                 { "_NET_WM_ICON_NAME", F(atom.net_wm_icon_name) },
1736                 { "_NET_WM_WINDOW_TYPE", F(atom.net_wm_window_type) },
1737
1738                 { "_NET_WM_WINDOW_TYPE_DESKTOP", F(atom.net_wm_window_type_desktop) },
1739                 { "_NET_WM_WINDOW_TYPE_DOCK", F(atom.net_wm_window_type_dock) },
1740                 { "_NET_WM_WINDOW_TYPE_TOOLBAR", F(atom.net_wm_window_type_toolbar) },
1741                 { "_NET_WM_WINDOW_TYPE_MENU", F(atom.net_wm_window_type_menu) },
1742                 { "_NET_WM_WINDOW_TYPE_UTILITY", F(atom.net_wm_window_type_utility) },
1743                 { "_NET_WM_WINDOW_TYPE_SPLASH", F(atom.net_wm_window_type_splash) },
1744                 { "_NET_WM_WINDOW_TYPE_DIALOG", F(atom.net_wm_window_type_dialog) },
1745                 { "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", F(atom.net_wm_window_type_dropdown) },
1746                 { "_NET_WM_WINDOW_TYPE_POPUP_MENU", F(atom.net_wm_window_type_popup) },
1747                 { "_NET_WM_WINDOW_TYPE_TOOLTIP", F(atom.net_wm_window_type_tooltip) },
1748                 { "_NET_WM_WINDOW_TYPE_NOTIFICATION", F(atom.net_wm_window_type_notification) },
1749                 { "_NET_WM_WINDOW_TYPE_COMBO", F(atom.net_wm_window_type_combo) },
1750                 { "_NET_WM_WINDOW_TYPE_DND", F(atom.net_wm_window_type_dnd) },
1751                 { "_NET_WM_WINDOW_TYPE_NORMAL", F(atom.net_wm_window_type_normal) },
1752
1753                 { "_NET_WM_MOVERESIZE", F(atom.net_wm_moveresize) },
1754                 { "_NET_SUPPORTING_WM_CHECK",
1755                                         F(atom.net_supporting_wm_check) },
1756                 { "_NET_SUPPORTED",     F(atom.net_supported) },
1757                 { "_MOTIF_WM_HINTS",    F(atom.motif_wm_hints) },
1758                 { "CLIPBOARD",          F(atom.clipboard) },
1759                 { "CLIPBOARD_MANAGER",  F(atom.clipboard_manager) },
1760                 { "TARGETS",            F(atom.targets) },
1761                 { "UTF8_STRING",        F(atom.utf8_string) },
1762                 { "_WL_SELECTION",      F(atom.wl_selection) },
1763                 { "INCR",               F(atom.incr) },
1764                 { "TIMESTAMP",          F(atom.timestamp) },
1765                 { "MULTIPLE",           F(atom.multiple) },
1766                 { "UTF8_STRING" ,       F(atom.utf8_string) },
1767                 { "COMPOUND_TEXT",      F(atom.compound_text) },
1768                 { "TEXT",               F(atom.text) },
1769                 { "STRING",             F(atom.string) },
1770                 { "text/plain;charset=utf-8",   F(atom.text_plain_utf8) },
1771                 { "text/plain",         F(atom.text_plain) },
1772                 { "XdndSelection",      F(atom.xdnd_selection) },
1773                 { "XdndAware",          F(atom.xdnd_aware) },
1774                 { "XdndEnter",          F(atom.xdnd_enter) },
1775                 { "XdndLeave",          F(atom.xdnd_leave) },
1776                 { "XdndDrop",           F(atom.xdnd_drop) },
1777                 { "XdndStatus",         F(atom.xdnd_status) },
1778                 { "XdndFinished",       F(atom.xdnd_finished) },
1779                 { "XdndTypeList",       F(atom.xdnd_type_list) },
1780                 { "XdndActionCopy",     F(atom.xdnd_action_copy) }
1781         };
1782 #undef F
1783
1784         xcb_xfixes_query_version_cookie_t xfixes_cookie;
1785         xcb_xfixes_query_version_reply_t *xfixes_reply;
1786         xcb_intern_atom_cookie_t cookies[ARRAY_LENGTH(atoms)];
1787         xcb_intern_atom_reply_t *reply;
1788         xcb_render_query_pict_formats_reply_t *formats_reply;
1789         xcb_render_query_pict_formats_cookie_t formats_cookie;
1790         xcb_render_pictforminfo_t *formats;
1791         uint32_t i;
1792
1793         xcb_prefetch_extension_data (wm->conn, &xcb_xfixes_id);
1794         xcb_prefetch_extension_data (wm->conn, &xcb_composite_id);
1795
1796         formats_cookie = xcb_render_query_pict_formats(wm->conn);
1797
1798         for (i = 0; i < ARRAY_LENGTH(atoms); i++)
1799                 cookies[i] = xcb_intern_atom (wm->conn, 0,
1800                                               strlen(atoms[i].name),
1801                                               atoms[i].name);
1802
1803         for (i = 0; i < ARRAY_LENGTH(atoms); i++) {
1804                 reply = xcb_intern_atom_reply (wm->conn, cookies[i], NULL);
1805                 *(xcb_atom_t *) ((char *) wm + atoms[i].offset) = reply->atom;
1806                 free(reply);
1807         }
1808
1809         wm->xfixes = xcb_get_extension_data(wm->conn, &xcb_xfixes_id);
1810         if (!wm->xfixes || !wm->xfixes->present)
1811                 weston_log("xfixes not available\n");
1812
1813         xfixes_cookie = xcb_xfixes_query_version(wm->conn,
1814                                                  XCB_XFIXES_MAJOR_VERSION,
1815                                                  XCB_XFIXES_MINOR_VERSION);
1816         xfixes_reply = xcb_xfixes_query_version_reply(wm->conn,
1817                                                       xfixes_cookie, NULL);
1818
1819         weston_log("xfixes version: %d.%d\n",
1820                xfixes_reply->major_version, xfixes_reply->minor_version);
1821
1822         free(xfixes_reply);
1823
1824         formats_reply = xcb_render_query_pict_formats_reply(wm->conn,
1825                                                             formats_cookie, 0);
1826         if (formats_reply == NULL)
1827                 return;
1828
1829         formats = xcb_render_query_pict_formats_formats(formats_reply);
1830         for (i = 0; i < formats_reply->num_formats; i++) {
1831                 if (formats[i].direct.red_mask != 0xff &&
1832                     formats[i].direct.red_shift != 16)
1833                         continue;
1834                 if (formats[i].type == XCB_RENDER_PICT_TYPE_DIRECT &&
1835                     formats[i].depth == 24)
1836                         wm->format_rgb = formats[i];
1837                 if (formats[i].type == XCB_RENDER_PICT_TYPE_DIRECT &&
1838                     formats[i].depth == 32 &&
1839                     formats[i].direct.alpha_mask == 0xff &&
1840                     formats[i].direct.alpha_shift == 24)
1841                         wm->format_rgba = formats[i];
1842         }
1843
1844         free(formats_reply);
1845 }
1846
1847 static void
1848 weston_wm_create_wm_window(struct weston_wm *wm)
1849 {
1850         static const char name[] = "Weston WM";
1851
1852         wm->wm_window = xcb_generate_id(wm->conn);
1853         xcb_create_window(wm->conn,
1854                           XCB_COPY_FROM_PARENT,
1855                           wm->wm_window,
1856                           wm->screen->root,
1857                           0, 0,
1858                           10, 10,
1859                           0,
1860                           XCB_WINDOW_CLASS_INPUT_OUTPUT,
1861                           wm->screen->root_visual,
1862                           0, NULL);
1863
1864         xcb_change_property(wm->conn,
1865                             XCB_PROP_MODE_REPLACE,
1866                             wm->wm_window,
1867                             wm->atom.net_supporting_wm_check,
1868                             XCB_ATOM_WINDOW,
1869                             32, /* format */
1870                             1, &wm->wm_window);
1871
1872         xcb_change_property(wm->conn,
1873                             XCB_PROP_MODE_REPLACE,
1874                             wm->wm_window,
1875                             wm->atom.net_wm_name,
1876                             wm->atom.utf8_string,
1877                             8, /* format */
1878                             strlen(name), name);
1879
1880         xcb_change_property(wm->conn,
1881                             XCB_PROP_MODE_REPLACE,
1882                             wm->screen->root,
1883                             wm->atom.net_supporting_wm_check,
1884                             XCB_ATOM_WINDOW,
1885                             32, /* format */
1886                             1, &wm->wm_window);
1887
1888         /* Claim the WM_S0 selection even though we don't suport
1889          * the --replace functionality. */
1890         xcb_set_selection_owner(wm->conn,
1891                                 wm->wm_window,
1892                                 wm->atom.wm_s0,
1893                                 XCB_TIME_CURRENT_TIME);
1894
1895         xcb_set_selection_owner(wm->conn,
1896                                 wm->wm_window,
1897                                 wm->atom.net_wm_cm_s0,
1898                                 XCB_TIME_CURRENT_TIME);
1899 }
1900
1901 struct weston_wm *
1902 weston_wm_create(struct weston_xserver *wxs)
1903 {
1904         struct weston_wm *wm;
1905         struct wl_event_loop *loop;
1906         xcb_screen_iterator_t s;
1907         uint32_t values[1];
1908         int sv[2];
1909         xcb_atom_t supported[3];
1910
1911         wm = zalloc(sizeof *wm);
1912         if (wm == NULL)
1913                 return NULL;
1914
1915         wm->server = wxs;
1916         wm->window_hash = hash_table_create();
1917         if (wm->window_hash == NULL) {
1918                 free(wm);
1919                 return NULL;
1920         }
1921
1922         if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) < 0) {
1923                 weston_log("socketpair failed\n");
1924                 hash_table_destroy(wm->window_hash);
1925                 free(wm);
1926                 return NULL;
1927         }
1928
1929         xserver_send_client(wxs->resource, sv[1]);
1930         wl_client_flush(wl_resource_get_client(wxs->resource));
1931         close(sv[1]);
1932         
1933         /* xcb_connect_to_fd takes ownership of the fd. */
1934         wm->conn = xcb_connect_to_fd(sv[0], NULL);
1935         if (xcb_connection_has_error(wm->conn)) {
1936                 weston_log("xcb_connect_to_fd failed\n");
1937                 close(sv[0]);
1938                 hash_table_destroy(wm->window_hash);
1939                 free(wm);
1940                 return NULL;
1941         }
1942
1943         s = xcb_setup_roots_iterator(xcb_get_setup(wm->conn));
1944         wm->screen = s.data;
1945
1946         loop = wl_display_get_event_loop(wxs->wl_display);
1947         wm->source =
1948                 wl_event_loop_add_fd(loop, sv[0],
1949                                      WL_EVENT_READABLE,
1950                                      weston_wm_handle_event, wm);
1951         wl_event_source_check(wm->source);
1952
1953         weston_wm_get_resources(wm);
1954         weston_wm_get_visual_and_colormap(wm);
1955
1956         values[0] =
1957                 XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
1958                 XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
1959                 XCB_EVENT_MASK_PROPERTY_CHANGE;
1960         xcb_change_window_attributes(wm->conn, wm->screen->root,
1961                                      XCB_CW_EVENT_MASK, values);
1962
1963         xcb_composite_redirect_subwindows(wm->conn, wm->screen->root,
1964                                           XCB_COMPOSITE_REDIRECT_MANUAL);
1965
1966         wm->theme = theme_create();
1967
1968         weston_wm_create_wm_window(wm);
1969
1970         supported[0] = wm->atom.net_wm_moveresize;
1971         supported[1] = wm->atom.net_wm_state;
1972         supported[2] = wm->atom.net_wm_state_fullscreen;
1973         xcb_change_property(wm->conn,
1974                             XCB_PROP_MODE_REPLACE,
1975                             wm->screen->root,
1976                             wm->atom.net_supported,
1977                             XCB_ATOM_ATOM,
1978                             32, /* format */
1979                             ARRAY_LENGTH(supported), supported);
1980
1981         weston_wm_selection_init(wm);
1982
1983         weston_wm_dnd_init(wm);
1984
1985         xcb_flush(wm->conn);
1986
1987         wm->activate_listener.notify = weston_wm_window_activate;
1988         wl_signal_add(&wxs->compositor->activate_signal,
1989                       &wm->activate_listener);
1990         wm->transform_listener.notify = weston_wm_window_transform;
1991         wl_signal_add(&wxs->compositor->transform_signal,
1992                       &wm->transform_listener);
1993         wm->kill_listener.notify = weston_wm_kill_client;
1994         wl_signal_add(&wxs->compositor->kill_signal,
1995                       &wm->kill_listener);
1996
1997         weston_wm_create_cursors(wm);
1998         weston_wm_window_set_cursor(wm, wm->screen->root, XWM_CURSOR_LEFT_PTR);
1999
2000         weston_log("created wm\n");
2001
2002         return wm;
2003 }
2004
2005 void
2006 weston_wm_destroy(struct weston_wm *wm)
2007 {
2008         /* FIXME: Free windows in hash. */
2009         hash_table_destroy(wm->window_hash);
2010         weston_wm_destroy_cursors(wm);
2011         xcb_disconnect(wm->conn);
2012         wl_event_source_remove(wm->source);
2013         wl_list_remove(&wm->selection_listener.link);
2014         wl_list_remove(&wm->activate_listener.link);
2015         wl_list_remove(&wm->kill_listener.link);
2016         wl_list_remove(&wm->transform_listener.link);
2017
2018         free(wm);
2019 }
2020
2021 static void
2022 surface_destroy(struct wl_listener *listener, void *data)
2023 {
2024         struct weston_wm_window *window =
2025                 container_of(listener,
2026                              struct weston_wm_window, surface_destroy_listener);
2027
2028         wm_log("surface for xid %d destroyed\n", window->id);
2029
2030         /* This should have been freed by the shell.
2031        Don't try to use it later. */
2032         window->shsurf = NULL;
2033         window->surface = NULL;
2034         window->view = NULL;
2035 }
2036
2037 static struct weston_wm_window *
2038 get_wm_window(struct weston_surface *surface)
2039 {
2040         struct wl_listener *listener;
2041
2042         listener = wl_signal_get(&surface->destroy_signal, surface_destroy);
2043         if (listener)
2044                 return container_of(listener, struct weston_wm_window,
2045                                     surface_destroy_listener);
2046
2047         return NULL;
2048 }
2049
2050 static void
2051 weston_wm_window_configure(void *data)
2052 {
2053         struct weston_wm_window *window = data;
2054         struct weston_wm *wm = window->wm;
2055         uint32_t values[4];
2056         int x, y, width, height;
2057
2058         weston_wm_window_get_child_position(window, &x, &y);
2059         values[0] = x;
2060         values[1] = y;
2061         values[2] = window->width;
2062         values[3] = window->height;
2063         xcb_configure_window(wm->conn,
2064                              window->id,
2065                              XCB_CONFIG_WINDOW_X |
2066                              XCB_CONFIG_WINDOW_Y |
2067                              XCB_CONFIG_WINDOW_WIDTH |
2068                              XCB_CONFIG_WINDOW_HEIGHT,
2069                              values);
2070
2071         weston_wm_window_get_frame_size(window, &width, &height);
2072         values[0] = width;
2073         values[1] = height;
2074         xcb_configure_window(wm->conn,
2075                              window->frame_id,
2076                              XCB_CONFIG_WINDOW_WIDTH |
2077                              XCB_CONFIG_WINDOW_HEIGHT,
2078                              values);
2079
2080         window->configure_source = NULL;
2081
2082         weston_wm_window_schedule_repaint(window);
2083 }
2084
2085 static void
2086 send_configure(struct weston_surface *surface,
2087                uint32_t edges, int32_t width, int32_t height)
2088 {
2089         struct weston_wm_window *window = get_wm_window(surface);
2090         struct weston_wm *wm = window->wm;
2091         struct theme *t = window->wm->theme;
2092         int vborder, hborder;
2093
2094         if (window->fullscreen) {
2095                 hborder = 0;
2096                 vborder = 0;
2097         } else if (window->decorate) {
2098                 hborder = 2 * (t->margin + t->width);
2099                 vborder = 2 * t->margin + t->titlebar_height + t->width;
2100         } else {
2101                 hborder = 2 * t->margin;
2102                 vborder = 2 * t->margin;
2103         }
2104
2105         if (width > hborder)
2106                 window->width = width - hborder;
2107         else
2108                 window->width = 1;
2109
2110         if (height > vborder)
2111                 window->height = height - vborder;
2112         else
2113                 window->height = 1;
2114
2115         if (window->frame)
2116                 frame_resize_inside(window->frame, window->width, window->height);
2117
2118         if (window->configure_source)
2119                 return;
2120
2121         window->configure_source =
2122                 wl_event_loop_add_idle(wm->server->loop,
2123                                        weston_wm_window_configure, window);
2124 }
2125
2126 static const struct weston_shell_client shell_client = {
2127         send_configure
2128 };
2129
2130 static int
2131 legacy_fullscreen(struct weston_wm *wm,
2132                   struct weston_wm_window *window,
2133                   struct weston_output **output_ret)
2134 {
2135         struct weston_compositor *compositor = wm->server->compositor;
2136         struct weston_output *output;
2137         uint32_t minmax = PMinSize | PMaxSize;
2138         int matching_size;
2139
2140         /* Heuristics for detecting legacy fullscreen windows... */
2141
2142         wl_list_for_each(output, &compositor->output_list, link) {
2143                 if (output->x == window->x &&
2144                     output->y == window->y &&
2145                     output->width == window->width &&
2146                     output->height == window->height &&
2147                     window->override_redirect) {
2148                         *output_ret = output;
2149                         return 1;
2150                 }
2151
2152                 matching_size = 0;
2153                 if ((window->size_hints.flags & (USSize |PSize)) &&
2154                     window->size_hints.width == output->width &&
2155                     window->size_hints.height == output->height)
2156                         matching_size = 1;
2157                 if ((window->size_hints.flags & minmax) == minmax &&
2158                     window->size_hints.min_width == output->width &&
2159                     window->size_hints.min_height == output->height &&
2160                     window->size_hints.max_width == output->width &&
2161                     window->size_hints.max_height == output->height)
2162                         matching_size = 1;
2163
2164                 if (matching_size && !window->decorate &&
2165                     (window->size_hints.flags & (USPosition | PPosition)) &&
2166                     window->size_hints.x == output->x &&
2167                     window->size_hints.y == output->y) {
2168                         *output_ret = output;
2169                         return 1;
2170                 }
2171         }
2172
2173         return 0;
2174 }
2175 static void
2176 xserver_map_shell_surface(struct weston_wm *wm,
2177                           struct weston_wm_window *window)
2178 {
2179         struct weston_shell_interface *shell_interface =
2180                 &wm->server->compositor->shell_interface;
2181         struct weston_output *output;
2182         struct weston_wm_window *parent;
2183
2184         if (!shell_interface->create_shell_surface)
2185                 return;
2186
2187         if (!shell_interface->get_primary_view)
2188                 return;
2189
2190         window->shsurf = 
2191                 shell_interface->create_shell_surface(shell_interface->shell,
2192                                                       window->surface,
2193                                                       &shell_client);
2194         window->view = shell_interface->get_primary_view(shell_interface->shell,
2195                                                          window->shsurf);
2196
2197         if (window->name)
2198                 shell_interface->set_title(window->shsurf, window->name);
2199
2200         if (window->fullscreen) {
2201                 window->saved_width = window->width;
2202                 window->saved_height = window->height;
2203                 shell_interface->set_fullscreen(window->shsurf,
2204                                                 WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT,
2205                                                 0, NULL);
2206                 return;
2207         } else if (legacy_fullscreen(wm, window, &output)) {
2208                 window->fullscreen = 1;
2209                 shell_interface->set_fullscreen(window->shsurf,
2210                                                 WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT,
2211                                                 0, output);
2212         } else if (window->override_redirect) {
2213                 shell_interface->set_xwayland(window->shsurf,
2214                                               window->x,
2215                                               window->y,
2216                                               WL_SHELL_SURFACE_TRANSIENT_INACTIVE);
2217         } else if (window->transient_for) {
2218                 parent = window->transient_for;
2219                 shell_interface->set_transient(window->shsurf,
2220                                                parent->surface,
2221                                                parent->x - window->x,
2222                                                parent->y - window->y, 0);
2223         } else {
2224                 shell_interface->set_toplevel(window->shsurf);
2225         }
2226 }
2227
2228 static void
2229 xserver_set_window_id(struct wl_client *client, struct wl_resource *resource,
2230                       struct wl_resource *surface_resource, uint32_t id)
2231 {
2232         struct weston_xserver *wxs = wl_resource_get_user_data(resource);
2233         struct weston_wm *wm = wxs->wm;
2234         struct weston_surface *surface =
2235                 wl_resource_get_user_data(surface_resource);
2236         struct weston_wm_window *window;
2237
2238         if (client != wxs->client)
2239                 return;
2240
2241         window = hash_table_lookup(wm->window_hash, id);
2242         if (window == NULL) {
2243                 weston_log("set_window_id for unknown window %d\n", id);
2244                 return;
2245         }
2246
2247         wm_log("set_window_id %d for surface %p\n", id, surface);
2248
2249         weston_wm_window_read_properties(window);
2250
2251         /* A weston_wm_window may have many different surfaces assigned
2252          * throughout its life, so we must make sure to remove the listener
2253          * from the old surface signal list. */
2254         if (window->surface)
2255                 wl_list_remove(&window->surface_destroy_listener.link);
2256
2257         window->surface = (struct weston_surface *) surface;
2258         window->surface_destroy_listener.notify = surface_destroy;
2259         wl_signal_add(&surface->destroy_signal,
2260                       &window->surface_destroy_listener);
2261
2262         weston_wm_window_schedule_repaint(window);
2263         xserver_map_shell_surface(wm, window);
2264 }
2265
2266 const struct xserver_interface xserver_implementation = {
2267         xserver_set_window_id
2268 };