compositor: Check if surface creation failed in weston_compositor_fade.
[profile/ivi/weston.git] / src / compositor.c
1 /*
2  * Copyright © 2010-2011 Intel Corporation
3  * Copyright © 2008-2011 Kristian Høgsberg
4  * Copyright © 2012 Collabora, Ltd.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and
7  * its documentation for any purpose is hereby granted without fee, provided
8  * that the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of the copyright holders not be used in
11  * advertising or publicity pertaining to distribution of the software
12  * without specific, written prior permission.  The copyright holders make
13  * no representations about the suitability of this software for any
14  * purpose.  It is provided "as is" without express or implied warranty.
15  *
16  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
18  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
19  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
20  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
21  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23  */
24
25 #define _GNU_SOURCE
26
27 #include "config.h"
28
29 #include <fcntl.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdint.h>
34 #include <limits.h>
35 #include <stdarg.h>
36 #include <assert.h>
37 #include <sys/ioctl.h>
38 #include <sys/mman.h>
39 #include <sys/wait.h>
40 #include <sys/socket.h>
41 #include <sys/utsname.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44 #include <math.h>
45 #include <linux/input.h>
46 #include <dlfcn.h>
47 #include <signal.h>
48 #include <setjmp.h>
49 #include <sys/time.h>
50 #include <time.h>
51
52 #include <wayland-server.h>
53 #include "compositor.h"
54 #include "../shared/os-compatibility.h"
55 #include "git-version.h"
56
57 static struct wl_list child_process_list;
58 static struct weston_compositor *segv_compositor;
59
60 static int
61 sigchld_handler(int signal_number, void *data)
62 {
63         struct weston_process *p;
64         int status;
65         pid_t pid;
66
67         pid = waitpid(-1, &status, WNOHANG);
68         if (!pid)
69                 return 1;
70
71         wl_list_for_each(p, &child_process_list, link) {
72                 if (p->pid == pid)
73                         break;
74         }
75
76         if (&p->link == &child_process_list) {
77                 weston_log("unknown child process exited\n");
78                 return 1;
79         }
80
81         wl_list_remove(&p->link);
82         p->cleanup(p, status);
83
84         return 1;
85 }
86
87 WL_EXPORT int
88 weston_output_switch_mode(struct weston_output *output, struct weston_mode *mode)
89 {
90         if (!output->switch_mode)
91                 return -1;
92
93         return output->switch_mode(output, mode);
94 }
95
96 WL_EXPORT void
97 weston_watch_process(struct weston_process *process)
98 {
99         wl_list_insert(&child_process_list, &process->link);
100 }
101
102 static void
103 child_client_exec(int sockfd, const char *path)
104 {
105         int clientfd;
106         char s[32];
107         sigset_t allsigs;
108
109         /* do not give our signal mask to the new process */
110         sigfillset(&allsigs);
111         sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
112
113         /* Launch clients as the user. */
114         seteuid(getuid());
115
116         /* SOCK_CLOEXEC closes both ends, so we dup the fd to get a
117          * non-CLOEXEC fd to pass through exec. */
118         clientfd = dup(sockfd);
119         if (clientfd == -1) {
120                 weston_log("compositor: dup failed: %m\n");
121                 return;
122         }
123
124         snprintf(s, sizeof s, "%d", clientfd);
125         setenv("WAYLAND_SOCKET", s, 1);
126
127         if (execl(path, path, NULL) < 0)
128                 weston_log("compositor: executing '%s' failed: %m\n",
129                         path);
130 }
131
132 WL_EXPORT struct wl_client *
133 weston_client_launch(struct weston_compositor *compositor,
134                      struct weston_process *proc,
135                      const char *path,
136                      weston_process_cleanup_func_t cleanup)
137 {
138         int sv[2];
139         pid_t pid;
140         struct wl_client *client;
141
142         weston_log("launching '%s'\n", path);
143
144         if (os_socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
145                 weston_log("weston_client_launch: "
146                         "socketpair failed while launching '%s': %m\n",
147                         path);
148                 return NULL;
149         }
150
151         pid = fork();
152         if (pid == -1) {
153                 close(sv[0]);
154                 close(sv[1]);
155                 weston_log("weston_client_launch: "
156                         "fork failed while launching '%s': %m\n", path);
157                 return NULL;
158         }
159
160         if (pid == 0) {
161                 child_client_exec(sv[1], path);
162                 exit(-1);
163         }
164
165         close(sv[1]);
166
167         client = wl_client_create(compositor->wl_display, sv[0]);
168         if (!client) {
169                 close(sv[0]);
170                 weston_log("weston_client_launch: "
171                         "wl_client_create failed while launching '%s'.\n",
172                         path);
173                 return NULL;
174         }
175
176         proc->pid = pid;
177         proc->cleanup = cleanup;
178         weston_watch_process(proc);
179
180         return client;
181 }
182
183 static void
184 surface_handle_buffer_destroy(struct wl_listener *listener, void *data)
185 {
186         struct weston_surface *es =
187                 container_of(listener, struct weston_surface, 
188                              buffer_destroy_listener);
189
190         if (es->buffer && wl_buffer_is_shm(es->buffer))
191                 es->compositor->renderer->flush_damage(es);
192
193         es->buffer = NULL;
194 }
195
196 static void
197 surface_handle_pending_buffer_destroy(struct wl_listener *listener, void *data)
198 {
199         struct weston_surface *surface =
200                 container_of(listener, struct weston_surface,
201                              pending.buffer_destroy_listener);
202
203         surface->pending.buffer = NULL;
204 }
205
206 static void
207 empty_region(pixman_region32_t *region)
208 {
209         pixman_region32_fini(region);
210         pixman_region32_init(region);
211 }
212
213 static void
214 region_init_infinite(pixman_region32_t *region)
215 {
216         pixman_region32_init_rect(region, INT32_MIN, INT32_MIN,
217                                   UINT32_MAX, UINT32_MAX);
218 }
219
220 WL_EXPORT struct weston_surface *
221 weston_surface_create(struct weston_compositor *compositor)
222 {
223         struct weston_surface *surface;
224
225         surface = calloc(1, sizeof *surface);
226         if (surface == NULL)
227                 return NULL;
228
229         wl_signal_init(&surface->surface.resource.destroy_signal);
230
231         wl_list_init(&surface->link);
232         wl_list_init(&surface->layer_link);
233
234         surface->surface.resource.client = NULL;
235
236         surface->compositor = compositor;
237         surface->alpha = 1.0;
238         surface->pitch = 1;
239
240         surface->num_textures = 0;
241         surface->num_images = 0;
242
243         surface->buffer = NULL;
244         surface->output = NULL;
245         surface->plane = &compositor->primary_plane;
246
247         pixman_region32_init(&surface->damage);
248         pixman_region32_init(&surface->opaque);
249         pixman_region32_init(&surface->clip);
250         region_init_infinite(&surface->input);
251         pixman_region32_init(&surface->transform.opaque);
252         wl_list_init(&surface->frame_callback_list);
253
254         surface->buffer_destroy_listener.notify =
255                 surface_handle_buffer_destroy;
256
257         wl_list_init(&surface->geometry.transformation_list);
258         wl_list_insert(&surface->geometry.transformation_list,
259                        &surface->transform.position.link);
260         weston_matrix_init(&surface->transform.position.matrix);
261         pixman_region32_init(&surface->transform.boundingbox);
262         surface->geometry.dirty = 1;
263
264         surface->pending.buffer_destroy_listener.notify =
265                 surface_handle_pending_buffer_destroy;
266         pixman_region32_init(&surface->pending.damage);
267         pixman_region32_init(&surface->pending.opaque);
268         region_init_infinite(&surface->pending.input);
269         wl_list_init(&surface->pending.frame_callback_list);
270
271         return surface;
272 }
273
274 WL_EXPORT void
275 weston_surface_set_color(struct weston_surface *surface,
276                  float red, float green, float blue, float alpha)
277 {
278         surface->color[0] = red;
279         surface->color[1] = green;
280         surface->color[2] = blue;
281         surface->color[3] = alpha;
282         surface->shader = &surface->compositor->solid_shader;
283 }
284
285 WL_EXPORT void
286 weston_surface_to_global_float(struct weston_surface *surface,
287                                float sx, float sy, float *x, float *y)
288 {
289         if (surface->transform.enabled) {
290                 struct weston_vector v = { { sx, sy, 0.0f, 1.0f } };
291
292                 weston_matrix_transform(&surface->transform.matrix, &v);
293
294                 if (fabsf(v.f[3]) < 1e-6) {
295                         weston_log("warning: numerical instability in "
296                                 "weston_surface_to_global(), divisor = %g\n",
297                                 v.f[3]);
298                         *x = 0;
299                         *y = 0;
300                         return;
301                 }
302
303                 *x = v.f[0] / v.f[3];
304                 *y = v.f[1] / v.f[3];
305         } else {
306                 *x = sx + surface->geometry.x;
307                 *y = sy + surface->geometry.y;
308         }
309 }
310
311 WL_EXPORT void
312 weston_surface_move_to_plane(struct weston_surface *surface,
313                              struct weston_plane *plane)
314 {
315         if (surface->plane == plane)
316                 return;
317
318         weston_surface_damage_below(surface);
319         surface->plane = plane;
320         weston_surface_damage(surface);
321 }
322
323 WL_EXPORT void
324 weston_surface_damage_below(struct weston_surface *surface)
325 {
326         pixman_region32_t damage;
327
328         pixman_region32_init(&damage);
329         pixman_region32_subtract(&damage, &surface->transform.boundingbox,
330                                  &surface->clip);
331         pixman_region32_union(&surface->plane->damage,
332                               &surface->plane->damage, &damage);
333         pixman_region32_fini(&damage);
334 }
335
336 static struct wl_resource *
337 find_resource_for_client(struct wl_list *list, struct wl_client *client)
338 {
339         struct wl_resource *r;
340
341         wl_list_for_each(r, list, link) {
342                 if (r->client == client)
343                         return r;
344         }
345
346         return NULL;
347 }
348
349 static void
350 weston_surface_update_output_mask(struct weston_surface *es, uint32_t mask)
351 {
352         uint32_t different = es->output_mask ^ mask;
353         uint32_t entered = mask & different;
354         uint32_t left = es->output_mask & different;
355         struct weston_output *output;
356         struct wl_resource *resource = NULL;
357         struct wl_client *client = es->surface.resource.client;
358
359         es->output_mask = mask;
360         if (es->surface.resource.client == NULL)
361                 return;
362         if (different == 0)
363                 return;
364
365         wl_list_for_each(output, &es->compositor->output_list, link) {
366                 if (1 << output->id & different)
367                         resource =
368                                 find_resource_for_client(&output->resource_list,
369                                                          client);
370                 if (resource == NULL)
371                         continue;
372                 if (1 << output->id & entered)
373                         wl_surface_send_enter(&es->surface.resource, resource);
374                 if (1 << output->id & left)
375                         wl_surface_send_leave(&es->surface.resource, resource);
376         }
377 }
378
379 static void
380 weston_surface_assign_output(struct weston_surface *es)
381 {
382         struct weston_compositor *ec = es->compositor;
383         struct weston_output *output, *new_output;
384         pixman_region32_t region;
385         uint32_t max, area, mask;
386         pixman_box32_t *e;
387
388         new_output = NULL;
389         max = 0;
390         mask = 0;
391         pixman_region32_init(&region);
392         wl_list_for_each(output, &ec->output_list, link) {
393                 pixman_region32_intersect(&region, &es->transform.boundingbox,
394                                           &output->region);
395
396                 e = pixman_region32_extents(&region);
397                 area = (e->x2 - e->x1) * (e->y2 - e->y1);
398
399                 if (area > 0)
400                         mask |= 1 << output->id;
401
402                 if (area >= max) {
403                         new_output = output;
404                         max = area;
405                 }
406         }
407         pixman_region32_fini(&region);
408
409         es->output = new_output;
410         weston_surface_update_output_mask(es, mask);
411 }
412
413 static void
414 surface_compute_bbox(struct weston_surface *surface, int32_t sx, int32_t sy,
415                      int32_t width, int32_t height,
416                      pixman_region32_t *bbox)
417 {
418         float min_x = HUGE_VALF,  min_y = HUGE_VALF;
419         float max_x = -HUGE_VALF, max_y = -HUGE_VALF;
420         int32_t s[4][2] = {
421                 { sx,         sy },
422                 { sx,         sy + height },
423                 { sx + width, sy },
424                 { sx + width, sy + height }
425         };
426         float int_x, int_y;
427         int i;
428
429         if (width == 0 || height == 0) {
430                 /* avoid rounding empty bbox to 1x1 */
431                 pixman_region32_init(bbox);
432                 return;
433         }
434
435         for (i = 0; i < 4; ++i) {
436                 float x, y;
437                 weston_surface_to_global_float(surface,
438                                                s[i][0], s[i][1], &x, &y);
439                 if (x < min_x)
440                         min_x = x;
441                 if (x > max_x)
442                         max_x = x;
443                 if (y < min_y)
444                         min_y = y;
445                 if (y > max_y)
446                         max_y = y;
447         }
448
449         int_x = floorf(min_x);
450         int_y = floorf(min_y);
451         pixman_region32_init_rect(bbox, int_x, int_y,
452                                   ceilf(max_x) - int_x, ceilf(max_y) - int_y);
453 }
454
455 static void
456 weston_surface_update_transform_disable(struct weston_surface *surface)
457 {
458         surface->transform.enabled = 0;
459
460         /* round off fractions when not transformed */
461         surface->geometry.x = roundf(surface->geometry.x);
462         surface->geometry.y = roundf(surface->geometry.y);
463
464         pixman_region32_init_rect(&surface->transform.boundingbox,
465                                   surface->geometry.x,
466                                   surface->geometry.y,
467                                   surface->geometry.width,
468                                   surface->geometry.height);
469
470         if (surface->alpha == 1.0) {
471                 pixman_region32_copy(&surface->transform.opaque,
472                                      &surface->opaque);
473                 pixman_region32_translate(&surface->transform.opaque,
474                                           surface->geometry.x,
475                                           surface->geometry.y);
476         }
477 }
478
479 static int
480 weston_surface_update_transform_enable(struct weston_surface *surface)
481 {
482         struct weston_matrix *matrix = &surface->transform.matrix;
483         struct weston_matrix *inverse = &surface->transform.inverse;
484         struct weston_transform *tform;
485
486         surface->transform.enabled = 1;
487
488         /* Otherwise identity matrix, but with x and y translation. */
489         surface->transform.position.matrix.d[12] = surface->geometry.x;
490         surface->transform.position.matrix.d[13] = surface->geometry.y;
491
492         weston_matrix_init(matrix);
493         wl_list_for_each(tform, &surface->geometry.transformation_list, link)
494                 weston_matrix_multiply(matrix, &tform->matrix);
495
496         if (weston_matrix_invert(inverse, matrix) < 0) {
497                 /* Oops, bad total transformation, not invertible */
498                 weston_log("error: weston_surface %p"
499                         " transformation not invertible.\n", surface);
500                 return -1;
501         }
502
503         surface_compute_bbox(surface, 0, 0, surface->geometry.width,
504                              surface->geometry.height,
505                              &surface->transform.boundingbox);
506
507         return 0;
508 }
509
510 WL_EXPORT void
511 weston_surface_update_transform(struct weston_surface *surface)
512 {
513         if (!surface->geometry.dirty)
514                 return;
515
516         surface->geometry.dirty = 0;
517
518         weston_surface_damage_below(surface);
519
520         pixman_region32_fini(&surface->transform.boundingbox);
521         pixman_region32_fini(&surface->transform.opaque);
522         pixman_region32_init(&surface->transform.opaque);
523
524         /* transform.position is always in transformation_list */
525         if (surface->geometry.transformation_list.next ==
526             &surface->transform.position.link &&
527             surface->geometry.transformation_list.prev ==
528             &surface->transform.position.link) {
529                 weston_surface_update_transform_disable(surface);
530         } else {
531                 if (weston_surface_update_transform_enable(surface) < 0)
532                         weston_surface_update_transform_disable(surface);
533         }
534
535         weston_surface_damage_below(surface);
536
537         weston_surface_assign_output(surface);
538 }
539
540 WL_EXPORT void
541 weston_surface_to_global_fixed(struct weston_surface *surface,
542                                wl_fixed_t sx, wl_fixed_t sy,
543                                wl_fixed_t *x, wl_fixed_t *y)
544 {
545         float xf, yf;
546
547         weston_surface_to_global_float(surface,
548                                        wl_fixed_to_double(sx),
549                                        wl_fixed_to_double(sy),
550                                        &xf, &yf);
551         *x = wl_fixed_from_double(xf);
552         *y = wl_fixed_from_double(yf);
553 }
554
555 WL_EXPORT void
556 weston_surface_from_global_float(struct weston_surface *surface,
557                                  float x, float y, float *sx, float *sy)
558 {
559         if (surface->transform.enabled) {
560                 struct weston_vector v = { { x, y, 0.0f, 1.0f } };
561
562                 weston_matrix_transform(&surface->transform.inverse, &v);
563
564                 if (fabsf(v.f[3]) < 1e-6) {
565                         weston_log("warning: numerical instability in "
566                                 "weston_surface_from_global(), divisor = %g\n",
567                                 v.f[3]);
568                         *sx = 0;
569                         *sy = 0;
570                         return;
571                 }
572
573                 *sx = v.f[0] / v.f[3];
574                 *sy = v.f[1] / v.f[3];
575         } else {
576                 *sx = x - surface->geometry.x;
577                 *sy = y - surface->geometry.y;
578         }
579 }
580
581 WL_EXPORT void
582 weston_surface_from_global_fixed(struct weston_surface *surface,
583                                  wl_fixed_t x, wl_fixed_t y,
584                                  wl_fixed_t *sx, wl_fixed_t *sy)
585 {
586         float sxf, syf;
587
588         weston_surface_from_global_float(surface,
589                                          wl_fixed_to_double(x),
590                                          wl_fixed_to_double(y),
591                                          &sxf, &syf);
592         *sx = wl_fixed_from_double(sxf);
593         *sy = wl_fixed_from_double(syf);
594 }
595
596 WL_EXPORT void
597 weston_surface_from_global(struct weston_surface *surface,
598                            int32_t x, int32_t y, int32_t *sx, int32_t *sy)
599 {
600         float sxf, syf;
601
602         weston_surface_from_global_float(surface, x, y, &sxf, &syf);
603         *sx = floorf(sxf);
604         *sy = floorf(syf);
605 }
606
607 WL_EXPORT void
608 weston_surface_schedule_repaint(struct weston_surface *surface)
609 {
610         struct weston_output *output;
611
612         wl_list_for_each(output, &surface->compositor->output_list, link)
613                 if (surface->output_mask & (1 << output->id))
614                         weston_output_schedule_repaint(output);
615 }
616
617 WL_EXPORT void
618 weston_surface_damage(struct weston_surface *surface)
619 {
620         pixman_region32_union_rect(&surface->damage, &surface->damage,
621                                    0, 0, surface->geometry.width,
622                                    surface->geometry.height);
623
624         weston_surface_schedule_repaint(surface);
625 }
626
627 WL_EXPORT void
628 weston_surface_configure(struct weston_surface *surface,
629                          float x, float y, int width, int height)
630 {
631         surface->geometry.x = x;
632         surface->geometry.y = y;
633         surface->geometry.width = width;
634         surface->geometry.height = height;
635         surface->geometry.dirty = 1;
636 }
637
638 WL_EXPORT void
639 weston_surface_set_position(struct weston_surface *surface,
640                             float x, float y)
641 {
642         surface->geometry.x = x;
643         surface->geometry.y = y;
644         surface->geometry.dirty = 1;
645 }
646
647 WL_EXPORT int
648 weston_surface_is_mapped(struct weston_surface *surface)
649 {
650         if (surface->output)
651                 return 1;
652         else
653                 return 0;
654 }
655
656 WL_EXPORT uint32_t
657 weston_compositor_get_time(void)
658 {
659        struct timeval tv;
660
661        gettimeofday(&tv, NULL);
662
663        return tv.tv_sec * 1000 + tv.tv_usec / 1000;
664 }
665
666 static struct weston_surface *
667 weston_compositor_pick_surface(struct weston_compositor *compositor,
668                                wl_fixed_t x, wl_fixed_t y,
669                                wl_fixed_t *sx, wl_fixed_t *sy)
670 {
671         struct weston_surface *surface;
672
673         wl_list_for_each(surface, &compositor->surface_list, link) {
674                 weston_surface_from_global_fixed(surface, x, y, sx, sy);
675                 if (pixman_region32_contains_point(&surface->input,
676                                                    wl_fixed_to_int(*sx),
677                                                    wl_fixed_to_int(*sy),
678                                                    NULL))
679                         return surface;
680         }
681
682         return NULL;
683 }
684
685 static void
686 weston_device_repick(struct weston_seat *seat)
687 {
688         const struct wl_pointer_grab_interface *interface;
689         struct weston_surface *surface, *focus;
690         struct wl_pointer *pointer = seat->seat.pointer;
691
692         if (!pointer)
693                 return;
694
695         surface = weston_compositor_pick_surface(seat->compositor,
696                                                  pointer->x,
697                                                  pointer->y,
698                                                  &pointer->current_x,
699                                                  &pointer->current_y);
700
701         if (&surface->surface != pointer->current) {
702                 interface = pointer->grab->interface;
703                 pointer->current = &surface->surface;
704                 interface->focus(pointer->grab, &surface->surface,
705                                  pointer->current_x,
706                                  pointer->current_y);
707         }
708
709         focus = (struct weston_surface *) pointer->grab->focus;
710         if (focus)
711                 weston_surface_from_global_fixed(focus,
712                                                  pointer->x,
713                                                  pointer->y,
714                                                  &pointer->grab->x,
715                                                  &pointer->grab->y);
716 }
717
718 static void
719 weston_compositor_repick(struct weston_compositor *compositor)
720 {
721         struct weston_seat *seat;
722
723         if (!compositor->focus)
724                 return;
725
726         wl_list_for_each(seat, &compositor->seat_list, link)
727                 weston_device_repick(seat);
728 }
729
730 WL_EXPORT void
731 weston_surface_unmap(struct weston_surface *surface)
732 {
733         struct weston_seat *seat;
734
735         weston_surface_damage_below(surface);
736         surface->output = NULL;
737         wl_list_remove(&surface->layer_link);
738
739         wl_list_for_each(seat, &surface->compositor->seat_list, link) {
740                 if (seat->seat.keyboard &&
741                     seat->seat.keyboard->focus == &surface->surface)
742                         wl_keyboard_set_focus(seat->seat.keyboard, NULL);
743                 if (seat->seat.pointer &&
744                     seat->seat.pointer->focus == &surface->surface)
745                         wl_pointer_set_focus(seat->seat.pointer,
746                                              NULL,
747                                              wl_fixed_from_int(0),
748                                              wl_fixed_from_int(0));
749         }
750
751         weston_surface_schedule_repaint(surface);
752 }
753
754 struct weston_frame_callback {
755         struct wl_resource resource;
756         struct wl_list link;
757 };
758
759 static void
760 destroy_surface(struct wl_resource *resource)
761 {
762         struct weston_surface *surface =
763                 container_of(resource,
764                              struct weston_surface, surface.resource);
765         struct weston_compositor *compositor = surface->compositor;
766         struct weston_frame_callback *cb, *next;
767
768         if (weston_surface_is_mapped(surface))
769                 weston_surface_unmap(surface);
770
771         wl_list_for_each_safe(cb, next,
772                               &surface->pending.frame_callback_list, link)
773                 wl_resource_destroy(&cb->resource);
774
775         pixman_region32_fini(&surface->pending.input);
776         pixman_region32_fini(&surface->pending.opaque);
777         pixman_region32_fini(&surface->pending.damage);
778
779         if (surface->pending.buffer)
780                 wl_list_remove(&surface->pending.buffer_destroy_listener.link);
781
782         if (surface->buffer)
783                 wl_list_remove(&surface->buffer_destroy_listener.link);
784
785         compositor->renderer->destroy_surface(surface);
786
787         pixman_region32_fini(&surface->transform.boundingbox);
788         pixman_region32_fini(&surface->damage);
789         pixman_region32_fini(&surface->opaque);
790         pixman_region32_fini(&surface->clip);
791         pixman_region32_fini(&surface->input);
792
793         wl_list_for_each_safe(cb, next, &surface->frame_callback_list, link)
794                 wl_resource_destroy(&cb->resource);
795
796         free(surface);
797 }
798
799 WL_EXPORT void
800 weston_surface_destroy(struct weston_surface *surface)
801 {
802         /* Not a valid way to destroy a client surface */
803         assert(surface->surface.resource.client == NULL);
804
805         wl_signal_emit(&surface->surface.resource.destroy_signal,
806                        &surface->surface.resource);
807         destroy_surface(&surface->surface.resource);
808 }
809
810 static void
811 weston_surface_attach(struct weston_surface *surface, struct wl_buffer *buffer)
812 {
813         if (surface->buffer) {
814                 weston_buffer_post_release(surface->buffer);
815                 wl_list_remove(&surface->buffer_destroy_listener.link);
816         }
817
818         if (buffer) {
819                 buffer->busy_count++;
820                 wl_signal_add(&buffer->resource.destroy_signal,
821                               &surface->buffer_destroy_listener);
822         } else {
823                 if (weston_surface_is_mapped(surface))
824                         weston_surface_unmap(surface);
825         }
826
827         surface->compositor->renderer->attach(surface, buffer);
828         surface->buffer = buffer;
829 }
830
831 WL_EXPORT void
832 weston_surface_restack(struct weston_surface *surface, struct wl_list *below)
833 {
834         wl_list_remove(&surface->layer_link);
835         wl_list_insert(below, &surface->layer_link);
836         weston_surface_damage_below(surface);
837         weston_surface_damage(surface);
838 }
839
840 WL_EXPORT void
841 weston_compositor_damage_all(struct weston_compositor *compositor)
842 {
843         struct weston_output *output;
844
845         wl_list_for_each(output, &compositor->output_list, link)
846                 weston_output_damage(output);
847 }
848
849 WL_EXPORT void
850 weston_buffer_post_release(struct wl_buffer *buffer)
851 {
852         if (--buffer->busy_count > 0)
853                 return;
854
855         assert(buffer->resource.client != NULL);
856         wl_resource_queue_event(&buffer->resource, WL_BUFFER_RELEASE);
857 }
858
859 WL_EXPORT void
860 weston_output_damage(struct weston_output *output)
861 {
862         struct weston_compositor *compositor = output->compositor;
863
864         pixman_region32_union(&compositor->primary_plane.damage,
865                               &compositor->primary_plane.damage,
866                               &output->region);
867         weston_output_schedule_repaint(output);
868 }
869
870 static void
871 fade_frame(struct weston_animation *animation,
872            struct weston_output *output, uint32_t msecs)
873 {
874         struct weston_compositor *compositor =
875                 container_of(animation,
876                              struct weston_compositor, fade.animation);
877         struct weston_surface *surface;
878
879         if (animation->frame_counter <= 1)
880                 compositor->fade.spring.timestamp = msecs;
881
882         surface = compositor->fade.surface;
883         weston_spring_update(&compositor->fade.spring, msecs);
884         weston_surface_set_color(surface, 0.0, 0.0, 0.0,
885                                  compositor->fade.spring.current);
886         weston_surface_damage(surface);
887
888         if (weston_spring_done(&compositor->fade.spring)) {
889                 compositor->fade.spring.current =
890                         compositor->fade.spring.target;
891                 wl_list_remove(&animation->link);
892                 wl_list_init(&animation->link);
893
894                 if (compositor->fade.spring.current < 0.001) {
895                         destroy_surface(&surface->surface.resource);
896                         compositor->fade.surface = NULL;
897                 } else if (compositor->fade.spring.current > 0.999) {
898                         compositor->state = WESTON_COMPOSITOR_SLEEPING;
899                         wl_signal_emit(&compositor->lock_signal, compositor);
900                 }
901         }
902 }
903
904 static void
905 surface_accumulate_damage(struct weston_surface *surface,
906                           pixman_region32_t *opaque)
907 {
908         if (surface->buffer && wl_buffer_is_shm(surface->buffer))
909                 surface->compositor->renderer->flush_damage(surface);
910
911         if (surface->transform.enabled) {
912                 pixman_box32_t *extents;
913
914                 extents = pixman_region32_extents(&surface->damage);
915                 surface_compute_bbox(surface, extents->x1, extents->y1,
916                                      extents->x2 - extents->x1,
917                                      extents->y2 - extents->y1,
918                                      &surface->damage);
919                 pixman_region32_translate(&surface->damage,
920                                           -surface->plane->x,
921                                           -surface->plane->y);
922         } else {
923                 pixman_region32_translate(&surface->damage,
924                                           surface->geometry.x - surface->plane->x,
925                                           surface->geometry.y - surface->plane->y);
926         }
927
928         pixman_region32_union(&surface->plane->damage,
929                               &surface->plane->damage, &surface->damage);
930         empty_region(&surface->damage);
931         pixman_region32_copy(&surface->clip, opaque);
932         pixman_region32_union(opaque, opaque, &surface->transform.opaque);
933 }
934
935 static void
936 weston_output_repaint(struct weston_output *output, uint32_t msecs)
937 {
938         struct weston_compositor *ec = output->compositor;
939         struct weston_surface *es;
940         struct weston_layer *layer;
941         struct weston_animation *animation, *next;
942         struct weston_frame_callback *cb, *cnext;
943         struct wl_list frame_callback_list;
944         pixman_region32_t opaque, output_damage;
945
946         weston_compositor_update_drag_surfaces(ec);
947
948         /* Rebuild the surface list and update surface transforms up front. */
949         wl_list_init(&ec->surface_list);
950         wl_list_init(&frame_callback_list);
951         wl_list_for_each(layer, &ec->layer_list, link) {
952                 wl_list_for_each(es, &layer->surface_list, layer_link) {
953                         weston_surface_update_transform(es);
954                         wl_list_insert(ec->surface_list.prev, &es->link);
955                         if (es->output == output) {
956                                 wl_list_insert_list(&frame_callback_list,
957                                                     &es->frame_callback_list);
958                                 wl_list_init(&es->frame_callback_list);
959                         }
960                 }
961         }
962
963         if (output->assign_planes && !output->disable_planes)
964                 output->assign_planes(output);
965         else
966                 wl_list_for_each(es, &ec->surface_list, link)
967                         weston_surface_move_to_plane(es, &ec->primary_plane);
968
969         pixman_region32_init(&opaque);
970
971         wl_list_for_each(es, &ec->surface_list, link)
972                 surface_accumulate_damage(es, &opaque);
973
974         pixman_region32_fini(&opaque);
975
976         pixman_region32_init(&output_damage);
977         pixman_region32_intersect(&output_damage,
978                                   &ec->primary_plane.damage, &output->region);
979         pixman_region32_subtract(&ec->primary_plane.damage,
980                                  &ec->primary_plane.damage, &output->region);
981
982         if (output->dirty)
983                 weston_output_update_matrix(output);
984
985         output->repaint(output, &output_damage);
986
987         pixman_region32_fini(&output_damage);
988
989         output->repaint_needed = 0;
990
991         weston_compositor_repick(ec);
992         wl_event_loop_dispatch(ec->input_loop, 0);
993
994         wl_list_for_each_safe(cb, cnext, &frame_callback_list, link) {
995                 wl_callback_send_done(&cb->resource, msecs);
996                 wl_resource_destroy(&cb->resource);
997         }
998
999         wl_list_for_each_safe(animation, next, &output->animation_list, link) {
1000                 animation->frame_counter++;
1001                 animation->frame(animation, output, msecs);
1002         }
1003 }
1004
1005 static int
1006 weston_compositor_read_input(int fd, uint32_t mask, void *data)
1007 {
1008         struct weston_compositor *compositor = data;
1009
1010         wl_event_loop_dispatch(compositor->input_loop, 0);
1011
1012         return 1;
1013 }
1014
1015 WL_EXPORT void
1016 weston_output_finish_frame(struct weston_output *output, uint32_t msecs)
1017 {
1018         struct weston_compositor *compositor = output->compositor;
1019         struct wl_event_loop *loop =
1020                 wl_display_get_event_loop(compositor->wl_display);
1021         int fd;
1022
1023         output->frame_time = msecs;
1024         if (output->repaint_needed) {
1025                 weston_output_repaint(output, msecs);
1026                 return;
1027         }
1028
1029         output->repaint_scheduled = 0;
1030         if (compositor->input_loop_source)
1031                 return;
1032
1033         fd = wl_event_loop_get_fd(compositor->input_loop);
1034         compositor->input_loop_source =
1035                 wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
1036                                      weston_compositor_read_input, compositor);
1037 }
1038
1039 static void
1040 idle_repaint(void *data)
1041 {
1042         struct weston_output *output = data;
1043
1044         weston_output_finish_frame(output, weston_compositor_get_time());
1045 }
1046
1047 WL_EXPORT void
1048 weston_layer_init(struct weston_layer *layer, struct wl_list *below)
1049 {
1050         wl_list_init(&layer->surface_list);
1051         if (below != NULL)
1052                 wl_list_insert(below, &layer->link);
1053 }
1054
1055 WL_EXPORT void
1056 weston_output_schedule_repaint(struct weston_output *output)
1057 {
1058         struct weston_compositor *compositor = output->compositor;
1059         struct wl_event_loop *loop;
1060
1061         if (compositor->state == WESTON_COMPOSITOR_SLEEPING)
1062                 return;
1063
1064         loop = wl_display_get_event_loop(compositor->wl_display);
1065         output->repaint_needed = 1;
1066         if (output->repaint_scheduled)
1067                 return;
1068
1069         wl_event_loop_add_idle(loop, idle_repaint, output);
1070         output->repaint_scheduled = 1;
1071
1072         if (compositor->input_loop_source) {
1073                 wl_event_source_remove(compositor->input_loop_source);
1074                 compositor->input_loop_source = NULL;
1075         }
1076 }
1077
1078 WL_EXPORT void
1079 weston_compositor_schedule_repaint(struct weston_compositor *compositor)
1080 {
1081         struct weston_output *output;
1082
1083         wl_list_for_each(output, &compositor->output_list, link)
1084                 weston_output_schedule_repaint(output);
1085 }
1086
1087 WL_EXPORT void
1088 weston_compositor_fade(struct weston_compositor *compositor, float tint)
1089 {
1090         struct weston_output *output;
1091         struct weston_surface *surface;
1092
1093         output = container_of(compositor->output_list.next,
1094                              struct weston_output, link);
1095
1096         compositor->fade.spring.target = tint;
1097         if (weston_spring_done(&compositor->fade.spring))
1098                 return;
1099
1100         if (compositor->fade.surface == NULL) {
1101                 surface = weston_surface_create(compositor);
1102                 if (!surface)
1103                         return;
1104
1105                 weston_surface_configure(surface, 0, 0, 8192, 8192);
1106                 weston_surface_set_color(surface, 0.0, 0.0, 0.0, 0.0);
1107                 wl_list_insert(&compositor->fade_layer.surface_list,
1108                                &surface->layer_link);
1109                 weston_surface_update_transform(surface);
1110                 compositor->fade.surface = surface;
1111                 pixman_region32_init(&surface->input);
1112         }
1113
1114         weston_surface_damage(compositor->fade.surface);
1115         if (wl_list_empty(&compositor->fade.animation.link)) {
1116                 compositor->fade.animation.frame_counter = 0;
1117                 wl_list_insert(output->animation_list.prev,
1118                                &compositor->fade.animation.link);
1119         }
1120 }
1121
1122 static void
1123 surface_destroy(struct wl_client *client, struct wl_resource *resource)
1124 {
1125         wl_resource_destroy(resource);
1126 }
1127
1128 static void
1129 surface_attach(struct wl_client *client,
1130                struct wl_resource *resource,
1131                struct wl_resource *buffer_resource, int32_t sx, int32_t sy)
1132 {
1133         struct weston_surface *surface = resource->data;
1134         struct wl_buffer *buffer = NULL;
1135
1136         if (buffer_resource)
1137                 buffer = buffer_resource->data;
1138
1139         if (surface->pending.buffer)
1140                 wl_list_remove(&surface->pending.buffer_destroy_listener.link);
1141
1142         surface->pending.sx = sx;
1143         surface->pending.sy = sy;
1144         surface->pending.buffer = buffer;
1145         if (buffer) {
1146                 wl_signal_add(&buffer->resource.destroy_signal,
1147                               &surface->pending.buffer_destroy_listener);
1148                 surface->pending.remove_contents = 0;
1149         } else {
1150                 surface->pending.remove_contents = 1;
1151         }
1152 }
1153
1154 static void
1155 surface_damage(struct wl_client *client,
1156                struct wl_resource *resource,
1157                int32_t x, int32_t y, int32_t width, int32_t height)
1158 {
1159         struct weston_surface *surface = resource->data;
1160
1161         pixman_region32_union_rect(&surface->pending.damage,
1162                                    &surface->pending.damage,
1163                                    x, y, width, height);
1164 }
1165
1166 static void
1167 destroy_frame_callback(struct wl_resource *resource)
1168 {
1169         struct weston_frame_callback *cb = resource->data;
1170
1171         wl_list_remove(&cb->link);
1172         free(cb);
1173 }
1174
1175 static void
1176 surface_frame(struct wl_client *client,
1177               struct wl_resource *resource, uint32_t callback)
1178 {
1179         struct weston_frame_callback *cb;
1180         struct weston_surface *surface = resource->data;
1181
1182         cb = malloc(sizeof *cb);
1183         if (cb == NULL) {
1184                 wl_resource_post_no_memory(resource);
1185                 return;
1186         }
1187
1188         cb->resource.object.interface = &wl_callback_interface;
1189         cb->resource.object.id = callback;
1190         cb->resource.destroy = destroy_frame_callback;
1191         cb->resource.client = client;
1192         cb->resource.data = cb;
1193
1194         wl_client_add_resource(client, &cb->resource);
1195         wl_list_insert(surface->pending.frame_callback_list.prev, &cb->link);
1196 }
1197
1198 static void
1199 surface_set_opaque_region(struct wl_client *client,
1200                           struct wl_resource *resource,
1201                           struct wl_resource *region_resource)
1202 {
1203         struct weston_surface *surface = resource->data;
1204         struct weston_region *region;
1205
1206         if (region_resource) {
1207                 region = region_resource->data;
1208                 pixman_region32_copy(&surface->pending.opaque,
1209                                      &region->region);
1210         } else {
1211                 empty_region(&surface->pending.opaque);
1212         }
1213 }
1214
1215 static void
1216 surface_set_input_region(struct wl_client *client,
1217                          struct wl_resource *resource,
1218                          struct wl_resource *region_resource)
1219 {
1220         struct weston_surface *surface = resource->data;
1221         struct weston_region *region;
1222
1223         if (region_resource) {
1224                 region = region_resource->data;
1225                 pixman_region32_copy(&surface->pending.input,
1226                                      &region->region);
1227         } else {
1228                 pixman_region32_fini(&surface->pending.input);
1229                 region_init_infinite(&surface->pending.input);
1230         }
1231 }
1232
1233 static void
1234 surface_commit(struct wl_client *client, struct wl_resource *resource)
1235 {
1236         struct weston_surface *surface = resource->data;
1237
1238         /* wl_surface.attach */
1239         if (surface->pending.buffer || surface->pending.remove_contents)
1240                 weston_surface_attach(surface, surface->pending.buffer);
1241
1242         if (surface->buffer && surface->configure)
1243                 surface->configure(surface, surface->pending.sx,
1244                                    surface->pending.sy);
1245
1246         /* wl_surface.damage */
1247         pixman_region32_union(&surface->damage, &surface->damage,
1248                               &surface->pending.damage);
1249         empty_region(&surface->pending.damage);
1250
1251         /* wl_surface.set_opaque_region */
1252         pixman_region32_fini(&surface->opaque);
1253         pixman_region32_init_rect(&surface->opaque, 0, 0,
1254                                   surface->geometry.width,
1255                                   surface->geometry.height);
1256         pixman_region32_intersect(&surface->opaque,
1257                                   &surface->opaque, &surface->pending.opaque);
1258         surface->geometry.dirty = 1;
1259
1260         /* wl_surface.set_input_region */
1261         pixman_region32_fini(&surface->input);
1262         pixman_region32_init_rect(&surface->input, 0, 0,
1263                                   surface->geometry.width,
1264                                   surface->geometry.height);
1265         pixman_region32_intersect(&surface->input,
1266                                   &surface->input, &surface->pending.input);
1267
1268         /* wl_surface.frame */
1269         wl_list_insert_list(&surface->frame_callback_list,
1270                             &surface->pending.frame_callback_list);
1271         wl_list_init(&surface->pending.frame_callback_list);
1272
1273         weston_surface_schedule_repaint(surface);
1274 }
1275
1276 static const struct wl_surface_interface surface_interface = {
1277         surface_destroy,
1278         surface_attach,
1279         surface_damage,
1280         surface_frame,
1281         surface_set_opaque_region,
1282         surface_set_input_region,
1283         surface_commit
1284 };
1285
1286 static void
1287 compositor_create_surface(struct wl_client *client,
1288                           struct wl_resource *resource, uint32_t id)
1289 {
1290         struct weston_compositor *ec = resource->data;
1291         struct weston_surface *surface;
1292
1293         surface = weston_surface_create(ec);
1294         if (surface == NULL) {
1295                 wl_resource_post_no_memory(resource);
1296                 return;
1297         }
1298
1299         surface->surface.resource.destroy = destroy_surface;
1300
1301         surface->surface.resource.object.id = id;
1302         surface->surface.resource.object.interface = &wl_surface_interface;
1303         surface->surface.resource.object.implementation =
1304                 (void (**)(void)) &surface_interface;
1305         surface->surface.resource.data = surface;
1306
1307         wl_client_add_resource(client, &surface->surface.resource);
1308 }
1309
1310 static void
1311 destroy_region(struct wl_resource *resource)
1312 {
1313         struct weston_region *region =
1314                 container_of(resource, struct weston_region, resource);
1315
1316         pixman_region32_fini(&region->region);
1317         free(region);
1318 }
1319
1320 static void
1321 region_destroy(struct wl_client *client, struct wl_resource *resource)
1322 {
1323         wl_resource_destroy(resource);
1324 }
1325
1326 static void
1327 region_add(struct wl_client *client, struct wl_resource *resource,
1328            int32_t x, int32_t y, int32_t width, int32_t height)
1329 {
1330         struct weston_region *region = resource->data;
1331
1332         pixman_region32_union_rect(&region->region, &region->region,
1333                                    x, y, width, height);
1334 }
1335
1336 static void
1337 region_subtract(struct wl_client *client, struct wl_resource *resource,
1338                 int32_t x, int32_t y, int32_t width, int32_t height)
1339 {
1340         struct weston_region *region = resource->data;
1341         pixman_region32_t rect;
1342
1343         pixman_region32_init_rect(&rect, x, y, width, height);
1344         pixman_region32_subtract(&region->region, &region->region, &rect);
1345         pixman_region32_fini(&rect);
1346 }
1347
1348 static const struct wl_region_interface region_interface = {
1349         region_destroy,
1350         region_add,
1351         region_subtract
1352 };
1353
1354 static void
1355 compositor_create_region(struct wl_client *client,
1356                          struct wl_resource *resource, uint32_t id)
1357 {
1358         struct weston_region *region;
1359
1360         region = malloc(sizeof *region);
1361         if (region == NULL) {
1362                 wl_resource_post_no_memory(resource);
1363                 return;
1364         }
1365
1366         region->resource.destroy = destroy_region;
1367
1368         region->resource.object.id = id;
1369         region->resource.object.interface = &wl_region_interface;
1370         region->resource.object.implementation =
1371                 (void (**)(void)) &region_interface;
1372         region->resource.data = region;
1373
1374         pixman_region32_init(&region->region);
1375
1376         wl_client_add_resource(client, &region->resource);
1377 }
1378
1379 static const struct wl_compositor_interface compositor_interface = {
1380         compositor_create_surface,
1381         compositor_create_region
1382 };
1383
1384 WL_EXPORT void
1385 weston_compositor_wake(struct weston_compositor *compositor)
1386 {
1387         compositor->state = WESTON_COMPOSITOR_ACTIVE;
1388         weston_compositor_fade(compositor, 0.0);
1389
1390         wl_event_source_timer_update(compositor->idle_source,
1391                                      compositor->idle_time * 1000);
1392 }
1393
1394 static void
1395 weston_compositor_dpms_on(struct weston_compositor *compositor)
1396 {
1397         struct weston_output *output;
1398
1399         wl_list_for_each(output, &compositor->output_list, link)
1400                 if (output->set_dpms)
1401                         output->set_dpms(output, WESTON_DPMS_ON);
1402 }
1403
1404 WL_EXPORT void
1405 weston_compositor_activity(struct weston_compositor *compositor)
1406 {
1407         if (compositor->state == WESTON_COMPOSITOR_ACTIVE) {
1408                 weston_compositor_wake(compositor);
1409         } else {
1410                 weston_compositor_dpms_on(compositor);
1411                 wl_signal_emit(&compositor->unlock_signal, compositor);
1412         }
1413 }
1414
1415 static void
1416 weston_compositor_idle_inhibit(struct weston_compositor *compositor)
1417 {
1418         weston_compositor_activity(compositor);
1419         compositor->idle_inhibit++;
1420 }
1421
1422 static void
1423 weston_compositor_idle_release(struct weston_compositor *compositor)
1424 {
1425         compositor->idle_inhibit--;
1426         weston_compositor_activity(compositor);
1427 }
1428
1429 static int
1430 idle_handler(void *data)
1431 {
1432         struct weston_compositor *compositor = data;
1433
1434         if (compositor->idle_inhibit)
1435                 return 1;
1436
1437         weston_compositor_fade(compositor, 1.0);
1438
1439         return 1;
1440 }
1441
1442 WL_EXPORT void
1443 weston_plane_init(struct weston_plane *plane, int32_t x, int32_t y)
1444 {
1445         pixman_region32_init(&plane->damage);
1446         plane->x = x;
1447         plane->y = y;
1448 }
1449
1450 WL_EXPORT void
1451 weston_plane_release(struct weston_plane *plane)
1452 {
1453         pixman_region32_fini(&plane->damage);
1454 }
1455
1456 static  void
1457 weston_seat_update_drag_surface(struct weston_seat *seat, int dx, int dy);
1458
1459 static void
1460 clip_pointer_motion(struct weston_seat *seat, wl_fixed_t *fx, wl_fixed_t *fy)
1461 {
1462         struct weston_compositor *ec = seat->compositor;
1463         struct weston_output *output, *prev = NULL;
1464         int x, y, old_x, old_y, valid = 0;
1465
1466         x = wl_fixed_to_int(*fx);
1467         y = wl_fixed_to_int(*fy);
1468         old_x = wl_fixed_to_int(seat->seat.pointer->x);
1469         old_y = wl_fixed_to_int(seat->seat.pointer->y);
1470
1471         wl_list_for_each(output, &ec->output_list, link) {
1472                 if (pixman_region32_contains_point(&output->region,
1473                                                    x, y, NULL))
1474                         valid = 1;
1475                 if (pixman_region32_contains_point(&output->region,
1476                                                    old_x, old_y, NULL))
1477                         prev = output;
1478         }
1479
1480         if (!valid) {
1481                 if (x < prev->x)
1482                         *fx = wl_fixed_from_int(prev->x);
1483                 else if (x >= prev->x + prev->width)
1484                         *fx = wl_fixed_from_int(prev->x +
1485                                                 prev->width - 1);
1486                 if (y < prev->y)
1487                         *fy = wl_fixed_from_int(prev->y);
1488                 else if (y >= prev->y + prev->current->height)
1489                         *fy = wl_fixed_from_int(prev->y +
1490                                                 prev->height - 1);
1491         }
1492 }
1493
1494 WL_EXPORT void
1495 notify_motion(struct weston_seat *seat, uint32_t time, wl_fixed_t x, wl_fixed_t y)
1496 {
1497         const struct wl_pointer_grab_interface *interface;
1498         struct weston_compositor *ec = seat->compositor;
1499         struct weston_output *output;
1500         struct wl_pointer *pointer = seat->seat.pointer;
1501         int32_t ix, iy;
1502
1503         weston_compositor_activity(ec);
1504
1505         clip_pointer_motion(seat, &x, &y);
1506
1507         weston_seat_update_drag_surface(seat, x - pointer->x, y - pointer->y);
1508
1509         pointer->x = x;
1510         pointer->y = y;
1511
1512         ix = wl_fixed_to_int(x);
1513         iy = wl_fixed_to_int(y);
1514
1515         wl_list_for_each(output, &ec->output_list, link)
1516                 if (output->zoom.active &&
1517                     pixman_region32_contains_point(&output->region,
1518                                                    ix, iy, NULL))
1519                         weston_output_update_zoom(output, ZOOM_FOCUS_POINTER);
1520
1521         weston_device_repick(seat);
1522         interface = pointer->grab->interface;
1523         interface->motion(pointer->grab, time,
1524                           pointer->grab->x, pointer->grab->y);
1525
1526         if (seat->sprite) {
1527                 weston_surface_set_position(seat->sprite,
1528                                             ix - seat->hotspot_x,
1529                                             iy - seat->hotspot_y);
1530                 weston_surface_schedule_repaint(seat->sprite);
1531         }
1532 }
1533
1534 WL_EXPORT void
1535 weston_surface_activate(struct weston_surface *surface,
1536                         struct weston_seat *seat)
1537 {
1538         struct weston_compositor *compositor = seat->compositor;
1539
1540         if (seat->seat.keyboard) {
1541                 wl_keyboard_set_focus(seat->seat.keyboard, &surface->surface);
1542                 wl_data_device_set_keyboard_focus(&seat->seat);
1543         }
1544
1545         wl_signal_emit(&compositor->activate_signal, surface);
1546 }
1547
1548 WL_EXPORT void
1549 notify_button(struct weston_seat *seat, uint32_t time, int32_t button,
1550               enum wl_pointer_button_state state)
1551 {
1552         struct weston_compositor *compositor = seat->compositor;
1553         struct wl_pointer *pointer = seat->seat.pointer;
1554         struct weston_surface *focus =
1555                 (struct weston_surface *) pointer->focus;
1556         uint32_t serial = wl_display_next_serial(compositor->wl_display);
1557
1558         if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
1559                 if (compositor->ping_handler && focus)
1560                         compositor->ping_handler(focus, serial);
1561                 weston_compositor_idle_inhibit(compositor);
1562                 if (pointer->button_count == 0) {
1563                         pointer->grab_button = button;
1564                         pointer->grab_time = time;
1565                         pointer->grab_x = pointer->x;
1566                         pointer->grab_y = pointer->y;
1567                 }
1568                 pointer->button_count++;
1569         } else {
1570                 weston_compositor_idle_release(compositor);
1571                 pointer->button_count--;
1572         }
1573
1574         weston_compositor_run_button_binding(compositor, seat, time, button,
1575                                              state);
1576
1577         pointer->grab->interface->button(pointer->grab, time, button, state);
1578
1579         if (pointer->button_count == 1)
1580                 pointer->grab_serial =
1581                         wl_display_get_serial(compositor->wl_display);
1582 }
1583
1584 WL_EXPORT void
1585 notify_axis(struct weston_seat *seat, uint32_t time, uint32_t axis,
1586             wl_fixed_t value)
1587 {
1588         struct weston_compositor *compositor = seat->compositor;
1589         struct wl_pointer *pointer = seat->seat.pointer;
1590         struct weston_surface *focus =
1591                 (struct weston_surface *) pointer->focus;
1592         uint32_t serial = wl_display_next_serial(compositor->wl_display);
1593
1594         if (compositor->ping_handler && focus)
1595                 compositor->ping_handler(focus, serial);
1596
1597         weston_compositor_activity(compositor);
1598
1599         if (value)
1600                 weston_compositor_run_axis_binding(compositor, seat,
1601                                                    time, axis, value);
1602         else
1603                 return;
1604
1605         if (pointer->focus_resource)
1606                 wl_pointer_send_axis(pointer->focus_resource, time, axis,
1607                                      value);
1608 }
1609
1610 WL_EXPORT void
1611 notify_modifiers(struct weston_seat *seat, uint32_t serial)
1612 {
1613         struct wl_keyboard *keyboard = &seat->keyboard;
1614         struct wl_keyboard_grab *grab = keyboard->grab;
1615         uint32_t mods_depressed, mods_latched, mods_locked, group;
1616         uint32_t mods_lookup;
1617         enum weston_led leds = 0;
1618         int changed = 0;
1619
1620         /* Serialize and update our internal state, checking to see if it's
1621          * different to the previous state. */
1622         mods_depressed = xkb_state_serialize_mods(seat->xkb_state.state,
1623                                                   XKB_STATE_DEPRESSED);
1624         mods_latched = xkb_state_serialize_mods(seat->xkb_state.state,
1625                                                 XKB_STATE_LATCHED);
1626         mods_locked = xkb_state_serialize_mods(seat->xkb_state.state,
1627                                                XKB_STATE_LOCKED);
1628         group = xkb_state_serialize_group(seat->xkb_state.state,
1629                                           XKB_STATE_EFFECTIVE);
1630
1631         if (mods_depressed != seat->seat.keyboard->modifiers.mods_depressed ||
1632             mods_latched != seat->seat.keyboard->modifiers.mods_latched ||
1633             mods_locked != seat->seat.keyboard->modifiers.mods_locked ||
1634             group != seat->seat.keyboard->modifiers.group)
1635                 changed = 1;
1636
1637         seat->seat.keyboard->modifiers.mods_depressed = mods_depressed;
1638         seat->seat.keyboard->modifiers.mods_latched = mods_latched;
1639         seat->seat.keyboard->modifiers.mods_locked = mods_locked;
1640         seat->seat.keyboard->modifiers.group = group;
1641
1642         /* And update the modifier_state for bindings. */
1643         mods_lookup = mods_depressed | mods_latched;
1644         seat->modifier_state = 0;
1645         if (mods_lookup & (1 << seat->xkb_info.ctrl_mod))
1646                 seat->modifier_state |= MODIFIER_CTRL;
1647         if (mods_lookup & (1 << seat->xkb_info.alt_mod))
1648                 seat->modifier_state |= MODIFIER_ALT;
1649         if (mods_lookup & (1 << seat->xkb_info.super_mod))
1650                 seat->modifier_state |= MODIFIER_SUPER;
1651         if (mods_lookup & (1 << seat->xkb_info.shift_mod))
1652                 seat->modifier_state |= MODIFIER_SHIFT;
1653
1654         /* Finally, notify the compositor that LEDs have changed. */
1655         if (xkb_state_led_index_is_active(seat->xkb_state.state,
1656                                           seat->xkb_info.num_led))
1657                 leds |= LED_NUM_LOCK;
1658         if (xkb_state_led_index_is_active(seat->xkb_state.state,
1659                                           seat->xkb_info.caps_led))
1660                 leds |= LED_CAPS_LOCK;
1661         if (xkb_state_led_index_is_active(seat->xkb_state.state,
1662                                           seat->xkb_info.scroll_led))
1663                 leds |= LED_SCROLL_LOCK;
1664         if (leds != seat->xkb_state.leds && seat->led_update)
1665                 seat->led_update(seat, leds);
1666         seat->xkb_state.leds = leds;
1667
1668         if (changed) {
1669                 grab->interface->modifiers(grab,
1670                                            serial,
1671                                            keyboard->modifiers.mods_depressed,
1672                                            keyboard->modifiers.mods_latched,
1673                                            keyboard->modifiers.mods_locked,
1674                                            keyboard->modifiers.group);
1675         }
1676 }
1677
1678 static void
1679 update_modifier_state(struct weston_seat *seat, uint32_t serial, uint32_t key,
1680                       enum wl_keyboard_key_state state)
1681 {
1682         enum xkb_key_direction direction;
1683
1684         if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1685                 direction = XKB_KEY_DOWN;
1686         else
1687                 direction = XKB_KEY_UP;
1688
1689         /* Offset the keycode by 8, as the evdev XKB rules reflect X's
1690          * broken keycode system, which starts at 8. */
1691         xkb_state_update_key(seat->xkb_state.state, key + 8, direction);
1692
1693         notify_modifiers(seat, serial);
1694 }
1695
1696 WL_EXPORT void
1697 notify_key(struct weston_seat *seat, uint32_t time, uint32_t key,
1698            enum wl_keyboard_key_state state,
1699            enum weston_key_state_update update_state)
1700 {
1701         struct weston_compositor *compositor = seat->compositor;
1702         struct wl_keyboard *keyboard = seat->seat.keyboard;
1703         struct weston_surface *focus =
1704                 (struct weston_surface *) keyboard->focus;
1705         struct wl_keyboard_grab *grab = keyboard->grab;
1706         uint32_t serial = wl_display_next_serial(compositor->wl_display);
1707         uint32_t *k, *end;
1708
1709         if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
1710                 if (compositor->ping_handler && focus)
1711                         compositor->ping_handler(focus, serial);
1712
1713                 weston_compositor_idle_inhibit(compositor);
1714                 keyboard->grab_key = key;
1715                 keyboard->grab_time = time;
1716         } else {
1717                 weston_compositor_idle_release(compositor);
1718         }
1719
1720         end = keyboard->keys.data + keyboard->keys.size;
1721         for (k = keyboard->keys.data; k < end; k++) {
1722                 if (*k == key) {
1723                         /* Ignore server-generated repeats. */
1724                         if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1725                                 return;
1726                         *k = *--end;
1727                 }
1728         }
1729         keyboard->keys.size = (void *) end - keyboard->keys.data;
1730         if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
1731                 k = wl_array_add(&keyboard->keys, sizeof *k);
1732                 *k = key;
1733         }
1734
1735         if (grab == &keyboard->default_grab) {
1736                 weston_compositor_run_key_binding(compositor, seat, time, key,
1737                                                   state);
1738                 grab = keyboard->grab;
1739         }
1740
1741         grab->interface->key(grab, time, key, state);
1742
1743         if (update_state == STATE_UPDATE_AUTOMATIC) {
1744                 update_modifier_state(seat,
1745                                       wl_display_get_serial(compositor->wl_display),
1746                                       key,
1747                                       state);
1748         }
1749 }
1750
1751 WL_EXPORT void
1752 notify_pointer_focus(struct weston_seat *seat, struct weston_output *output,
1753                      wl_fixed_t x, wl_fixed_t y)
1754 {
1755         struct weston_compositor *compositor = seat->compositor;
1756         struct wl_pointer *pointer = seat->seat.pointer;
1757
1758         if (output) {
1759                 weston_seat_update_drag_surface(seat,
1760                                                 x - pointer->x,
1761                                                 y - pointer->y);
1762
1763                 pointer->x = x;
1764                 pointer->y = y;
1765                 compositor->focus = 1;
1766                 weston_compositor_repick(compositor);
1767         } else {
1768                 compositor->focus = 0;
1769                 /* FIXME: We should call wl_pointer_set_focus(seat,
1770                  * NULL) here, but somehow that breaks re-entry... */
1771         }
1772 }
1773
1774 static void
1775 destroy_device_saved_kbd_focus(struct wl_listener *listener, void *data)
1776 {
1777         struct weston_seat *ws;
1778
1779         ws = container_of(listener, struct weston_seat,
1780                           saved_kbd_focus_listener);
1781
1782         ws->saved_kbd_focus = NULL;
1783 }
1784
1785 WL_EXPORT void
1786 notify_keyboard_focus_in(struct weston_seat *seat, struct wl_array *keys,
1787                          enum weston_key_state_update update_state)
1788 {
1789         struct weston_compositor *compositor = seat->compositor;
1790         struct wl_keyboard *keyboard = seat->seat.keyboard;
1791         struct wl_surface *surface;
1792         uint32_t *k, serial;
1793
1794         serial = wl_display_next_serial(compositor->wl_display);
1795         wl_array_copy(&keyboard->keys, keys);
1796         wl_array_for_each(k, &keyboard->keys) {
1797                 weston_compositor_idle_inhibit(compositor);
1798                 if (update_state == STATE_UPDATE_AUTOMATIC)
1799                         update_modifier_state(seat, serial, *k,
1800                                               WL_KEYBOARD_KEY_STATE_PRESSED);
1801         }
1802
1803         /* Run key bindings after we've updated the state. */
1804         wl_array_for_each(k, &keyboard->keys) {
1805                 weston_compositor_run_key_binding(compositor, seat, 0, *k,
1806                                                   WL_KEYBOARD_KEY_STATE_PRESSED);
1807         }
1808
1809         surface = seat->saved_kbd_focus;
1810
1811         if (surface) {
1812                 wl_list_remove(&seat->saved_kbd_focus_listener.link);
1813                 wl_keyboard_set_focus(keyboard, surface);
1814                 seat->saved_kbd_focus = NULL;
1815         }
1816 }
1817
1818 WL_EXPORT void
1819 notify_keyboard_focus_out(struct weston_seat *seat)
1820 {
1821         struct weston_compositor *compositor = seat->compositor;
1822         struct wl_keyboard *keyboard = seat->seat.keyboard;
1823         uint32_t *k, serial;
1824
1825         serial = wl_display_next_serial(compositor->wl_display);
1826         wl_array_for_each(k, &keyboard->keys) {
1827                 weston_compositor_idle_release(compositor);
1828                 update_modifier_state(seat, serial, *k,
1829                                       WL_KEYBOARD_KEY_STATE_RELEASED);
1830         }
1831
1832         seat->modifier_state = 0;
1833
1834         if (keyboard->focus) {
1835                 seat->saved_kbd_focus = keyboard->focus;
1836                 seat->saved_kbd_focus_listener.notify =
1837                         destroy_device_saved_kbd_focus;
1838                 wl_signal_add(&keyboard->focus->resource.destroy_signal,
1839                               &seat->saved_kbd_focus_listener);
1840         }
1841
1842         wl_keyboard_set_focus(keyboard, NULL);
1843         /* FIXME: We really need keyboard grab cancel here to
1844          * let the grab shut down properly.  As it is we leak
1845          * the grab data. */
1846         wl_keyboard_end_grab(keyboard);
1847 }
1848
1849 static void
1850 touch_set_focus(struct weston_seat *ws, struct wl_surface *surface)
1851 {
1852         struct wl_seat *seat = &ws->seat;
1853         struct wl_resource *resource;
1854
1855         if (seat->touch->focus == surface)
1856                 return;
1857
1858         if (seat->touch->focus_resource)
1859                 wl_list_remove(&seat->touch->focus_listener.link);
1860         seat->touch->focus = NULL;
1861         seat->touch->focus_resource = NULL;
1862
1863         if (surface) {
1864                 resource =
1865                         find_resource_for_client(&seat->touch->resource_list,
1866                                                  surface->resource.client);
1867                 if (!resource) {
1868                         weston_log("couldn't find resource\n");
1869                         return;
1870                 }
1871
1872                 seat->touch->focus = surface;
1873                 seat->touch->focus_resource = resource;
1874                 wl_signal_add(&resource->destroy_signal,
1875                               &seat->touch->focus_listener);
1876         }
1877 }
1878
1879 /**
1880  * notify_touch - emulates button touches and notifies surfaces accordingly.
1881  *
1882  * It assumes always the correct cycle sequence until it gets here: touch_down
1883  * → touch_update → ... → touch_update → touch_end. The driver is responsible
1884  * for sending along such order.
1885  *
1886  */
1887 WL_EXPORT void
1888 notify_touch(struct weston_seat *seat, uint32_t time, int touch_id,
1889              wl_fixed_t x, wl_fixed_t y, int touch_type)
1890 {
1891         struct weston_compositor *ec = seat->compositor;
1892         struct wl_touch *touch = seat->seat.touch;
1893         struct wl_touch_grab *grab = touch->grab;
1894         struct weston_surface *es;
1895         wl_fixed_t sx, sy;
1896
1897         /* Update grab's global coordinates. */
1898         touch->grab_x = x;
1899         touch->grab_y = y;
1900
1901         switch (touch_type) {
1902         case WL_TOUCH_DOWN:
1903                 weston_compositor_idle_inhibit(ec);
1904
1905                 seat->num_tp++;
1906
1907                 /* the first finger down picks the surface, and all further go
1908                  * to that surface for the remainder of the touch session i.e.
1909                  * until all touch points are up again. */
1910                 if (seat->num_tp == 1) {
1911                         es = weston_compositor_pick_surface(ec, x, y, &sx, &sy);
1912                         touch_set_focus(seat, &es->surface);
1913                 } else if (touch->focus) {
1914                         es = (struct weston_surface *) touch->focus;
1915                         weston_surface_from_global_fixed(es, x, y, &sx, &sy);
1916                 }
1917
1918                 grab->interface->down(grab, time, touch_id, sx, sy);
1919                 break;
1920         case WL_TOUCH_MOTION:
1921                 es = (struct weston_surface *) touch->focus;
1922                 if (!es)
1923                         break;
1924
1925                 weston_surface_from_global_fixed(es, x, y, &sx, &sy);
1926                 grab->interface->motion(grab, time, touch_id, sx, sy);
1927                 break;
1928         case WL_TOUCH_UP:
1929                 weston_compositor_idle_release(ec);
1930                 seat->num_tp--;
1931
1932                 grab->interface->up(grab, time, touch_id);
1933                 if (seat->num_tp == 0)
1934                         touch_set_focus(seat, NULL);
1935                 break;
1936         }
1937 }
1938
1939 static void
1940 pointer_handle_sprite_destroy(struct wl_listener *listener, void *data)
1941 {
1942         struct weston_seat *seat = container_of(listener, struct weston_seat,
1943                                                 sprite_destroy_listener);
1944
1945         seat->sprite = NULL;
1946 }
1947
1948 static void
1949 pointer_cursor_surface_configure(struct weston_surface *es,
1950                                  int32_t dx, int32_t dy)
1951 {
1952         struct weston_seat *seat = es->private;
1953         int x, y;
1954
1955         assert(es == seat->sprite);
1956
1957         seat->hotspot_x -= dx;
1958         seat->hotspot_y -= dy;
1959
1960         x = wl_fixed_to_int(seat->seat.pointer->x) - seat->hotspot_x;
1961         y = wl_fixed_to_int(seat->seat.pointer->y) - seat->hotspot_y;
1962
1963         weston_surface_configure(seat->sprite, x, y,
1964                                  es->buffer->width, es->buffer->height);
1965
1966         empty_region(&es->pending.input);
1967
1968         if (!weston_surface_is_mapped(es)) {
1969                 wl_list_insert(&es->compositor->cursor_layer.surface_list,
1970                                &es->layer_link);
1971                 weston_surface_update_transform(es);
1972         }
1973 }
1974
1975 static void
1976 pointer_unmap_sprite(struct weston_seat *seat)
1977 {
1978         if (weston_surface_is_mapped(seat->sprite))
1979                 weston_surface_unmap(seat->sprite);
1980
1981         wl_list_remove(&seat->sprite_destroy_listener.link);
1982         seat->sprite->configure = NULL;
1983         seat->sprite->private = NULL;
1984         seat->sprite = NULL;
1985 }
1986
1987 static void
1988 pointer_set_cursor(struct wl_client *client, struct wl_resource *resource,
1989                    uint32_t serial, struct wl_resource *surface_resource,
1990                    int32_t x, int32_t y)
1991 {
1992         struct weston_seat *seat = resource->data;
1993         struct weston_surface *surface = NULL;
1994
1995         if (surface_resource)
1996                 surface = surface_resource->data;
1997
1998         if (seat->seat.pointer->focus == NULL)
1999                 return;
2000         if (seat->seat.pointer->focus->resource.client != client)
2001                 return;
2002         if (seat->seat.pointer->focus_serial - serial > UINT32_MAX / 2)
2003                 return;
2004
2005         if (surface && surface != seat->sprite) {
2006                 if (surface->configure) {
2007                         wl_resource_post_error(&surface->surface.resource,
2008                                                WL_DISPLAY_ERROR_INVALID_OBJECT,
2009                                                "surface->configure already "
2010                                                "set");
2011                         return;
2012                 }
2013         }
2014
2015         if (seat->sprite)
2016                 pointer_unmap_sprite(seat);
2017
2018         if (!surface)
2019                 return;
2020
2021         wl_signal_add(&surface->surface.resource.destroy_signal,
2022                       &seat->sprite_destroy_listener);
2023
2024         surface->configure = pointer_cursor_surface_configure;
2025         surface->private = seat;
2026         seat->sprite = surface;
2027         seat->hotspot_x = x;
2028         seat->hotspot_y = y;
2029
2030         if (surface->buffer)
2031                 pointer_cursor_surface_configure(surface, 0, 0);
2032 }
2033
2034 static const struct wl_pointer_interface pointer_interface = {
2035         pointer_set_cursor
2036 };
2037
2038 static void
2039 handle_drag_surface_destroy(struct wl_listener *listener, void *data)
2040 {
2041         struct weston_seat *seat;
2042
2043         seat = container_of(listener, struct weston_seat,
2044                             drag_surface_destroy_listener);
2045
2046         seat->drag_surface = NULL;
2047 }
2048
2049 static void unbind_resource(struct wl_resource *resource)
2050 {
2051         wl_list_remove(&resource->link);
2052         free(resource);
2053 }
2054
2055 static void
2056 seat_get_pointer(struct wl_client *client, struct wl_resource *resource,
2057                  uint32_t id)
2058 {
2059         struct weston_seat *seat = resource->data;
2060         struct wl_resource *cr;
2061
2062         if (!seat->seat.pointer)
2063                 return;
2064
2065         cr = wl_client_add_object(client, &wl_pointer_interface,
2066                                   &pointer_interface, id, seat);
2067         wl_list_insert(&seat->seat.pointer->resource_list, &cr->link);
2068         cr->destroy = unbind_resource;
2069
2070         if (seat->seat.pointer->focus &&
2071             seat->seat.pointer->focus->resource.client == client) {
2072                 struct weston_surface *surface;
2073                 wl_fixed_t sx, sy;
2074
2075                 surface = (struct weston_surface *) seat->seat.pointer->focus;
2076                 weston_surface_from_global_fixed(surface,
2077                                                  seat->seat.pointer->x,
2078                                                  seat->seat.pointer->y,
2079                                                  &sx,
2080                                                  &sy);
2081                 wl_pointer_set_focus(seat->seat.pointer,
2082                                      seat->seat.pointer->focus,
2083                                      sx,
2084                                      sy);
2085         }
2086 }
2087
2088 static void
2089 seat_get_keyboard(struct wl_client *client, struct wl_resource *resource,
2090                   uint32_t id)
2091 {
2092         struct weston_seat *seat = resource->data;
2093         struct wl_resource *cr;
2094
2095         if (!seat->seat.keyboard)
2096                 return;
2097
2098         cr = wl_client_add_object(client, &wl_keyboard_interface, NULL, id,
2099                                   seat);
2100         wl_list_insert(&seat->seat.keyboard->resource_list, &cr->link);
2101         cr->destroy = unbind_resource;
2102
2103         wl_keyboard_send_keymap(cr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
2104                                 seat->xkb_info.keymap_fd,
2105                                 seat->xkb_info.keymap_size);
2106
2107         if (seat->seat.keyboard->focus &&
2108             seat->seat.keyboard->focus->resource.client == client) {
2109                 wl_keyboard_set_focus(seat->seat.keyboard,
2110                                       seat->seat.keyboard->focus);
2111         }
2112 }
2113
2114 static void
2115 seat_get_touch(struct wl_client *client, struct wl_resource *resource,
2116                uint32_t id)
2117 {
2118         struct weston_seat *seat = resource->data;
2119         struct wl_resource *cr;
2120
2121         if (!seat->seat.touch)
2122                 return;
2123
2124         cr = wl_client_add_object(client, &wl_touch_interface, NULL, id, seat);
2125         wl_list_insert(&seat->seat.touch->resource_list, &cr->link);
2126         cr->destroy = unbind_resource;
2127 }
2128
2129 static const struct wl_seat_interface seat_interface = {
2130         seat_get_pointer,
2131         seat_get_keyboard,
2132         seat_get_touch,
2133 };
2134
2135 static void
2136 bind_seat(struct wl_client *client, void *data, uint32_t version, uint32_t id)
2137 {
2138         struct wl_seat *seat = data;
2139         struct wl_resource *resource;
2140         enum wl_seat_capability caps = 0;
2141
2142         resource = wl_client_add_object(client, &wl_seat_interface,
2143                                         &seat_interface, id, data);
2144         wl_list_insert(&seat->base_resource_list, &resource->link);
2145         resource->destroy = unbind_resource;
2146
2147         if (seat->pointer)
2148                 caps |= WL_SEAT_CAPABILITY_POINTER;
2149         if (seat->keyboard)
2150                 caps |= WL_SEAT_CAPABILITY_KEYBOARD;
2151         if (seat->touch)
2152                 caps |= WL_SEAT_CAPABILITY_TOUCH;
2153
2154         wl_seat_send_capabilities(resource, caps);
2155 }
2156
2157 static void
2158 device_handle_new_drag_icon(struct wl_listener *listener, void *data)
2159 {
2160         struct weston_seat *seat;
2161
2162         seat = container_of(listener, struct weston_seat,
2163                             new_drag_icon_listener);
2164
2165         weston_seat_update_drag_surface(seat, 0, 0);
2166 }
2167
2168 static void weston_compositor_xkb_init(struct weston_compositor *ec,
2169                                        struct xkb_rule_names *names)
2170 {
2171         if (ec->xkb_context == NULL) {
2172                 ec->xkb_context = xkb_context_new(0);
2173                 if (ec->xkb_context == NULL) {
2174                         weston_log("failed to create XKB context\n");
2175                         exit(1);
2176                 }
2177         }
2178
2179         if (names)
2180                 ec->xkb_names = *names;
2181         if (!ec->xkb_names.rules)
2182                 ec->xkb_names.rules = strdup("evdev");
2183         if (!ec->xkb_names.model)
2184                 ec->xkb_names.model = strdup("pc105");
2185         if (!ec->xkb_names.layout)
2186                 ec->xkb_names.layout = strdup("us");
2187 }
2188
2189 static void xkb_info_destroy(struct weston_xkb_info *xkb_info)
2190 {
2191         if (xkb_info->keymap)
2192                 xkb_map_unref(xkb_info->keymap);
2193
2194         if (xkb_info->keymap_area)
2195                 munmap(xkb_info->keymap_area, xkb_info->keymap_size);
2196         if (xkb_info->keymap_fd >= 0)
2197                 close(xkb_info->keymap_fd);
2198 }
2199
2200 static void weston_compositor_xkb_destroy(struct weston_compositor *ec)
2201 {
2202         free((char *) ec->xkb_names.rules);
2203         free((char *) ec->xkb_names.model);
2204         free((char *) ec->xkb_names.layout);
2205         free((char *) ec->xkb_names.variant);
2206         free((char *) ec->xkb_names.options);
2207
2208         xkb_info_destroy(&ec->xkb_info);
2209         xkb_context_unref(ec->xkb_context);
2210 }
2211
2212 static void
2213 weston_xkb_info_new_keymap(struct weston_xkb_info *xkb_info)
2214 {
2215         char *keymap_str;
2216
2217         xkb_info->shift_mod = xkb_map_mod_get_index(xkb_info->keymap,
2218                                                     XKB_MOD_NAME_SHIFT);
2219         xkb_info->caps_mod = xkb_map_mod_get_index(xkb_info->keymap,
2220                                                    XKB_MOD_NAME_CAPS);
2221         xkb_info->ctrl_mod = xkb_map_mod_get_index(xkb_info->keymap,
2222                                                    XKB_MOD_NAME_CTRL);
2223         xkb_info->alt_mod = xkb_map_mod_get_index(xkb_info->keymap,
2224                                                   XKB_MOD_NAME_ALT);
2225         xkb_info->mod2_mod = xkb_map_mod_get_index(xkb_info->keymap, "Mod2");
2226         xkb_info->mod3_mod = xkb_map_mod_get_index(xkb_info->keymap, "Mod3");
2227         xkb_info->super_mod = xkb_map_mod_get_index(xkb_info->keymap,
2228                                                     XKB_MOD_NAME_LOGO);
2229         xkb_info->mod5_mod = xkb_map_mod_get_index(xkb_info->keymap, "Mod5");
2230
2231         xkb_info->num_led = xkb_map_led_get_index(xkb_info->keymap,
2232                                                   XKB_LED_NAME_NUM);
2233         xkb_info->caps_led = xkb_map_led_get_index(xkb_info->keymap,
2234                                                    XKB_LED_NAME_CAPS);
2235         xkb_info->scroll_led = xkb_map_led_get_index(xkb_info->keymap,
2236                                                      XKB_LED_NAME_SCROLL);
2237
2238         keymap_str = xkb_map_get_as_string(xkb_info->keymap);
2239         if (keymap_str == NULL) {
2240                 weston_log("failed to get string version of keymap\n");
2241                 exit(EXIT_FAILURE);
2242         }
2243         xkb_info->keymap_size = strlen(keymap_str) + 1;
2244
2245         xkb_info->keymap_fd = os_create_anonymous_file(xkb_info->keymap_size);
2246         if (xkb_info->keymap_fd < 0) {
2247                 weston_log("creating a keymap file for %lu bytes failed: %m\n",
2248                         (unsigned long) xkb_info->keymap_size);
2249                 goto err_keymap_str;
2250         }
2251
2252         xkb_info->keymap_area = mmap(NULL, xkb_info->keymap_size,
2253                                      PROT_READ | PROT_WRITE,
2254                                      MAP_SHARED, xkb_info->keymap_fd, 0);
2255         if (xkb_info->keymap_area == MAP_FAILED) {
2256                 weston_log("failed to mmap() %lu bytes\n",
2257                         (unsigned long) xkb_info->keymap_size);
2258                 goto err_dev_zero;
2259         }
2260         strcpy(xkb_info->keymap_area, keymap_str);
2261         free(keymap_str);
2262
2263         return;
2264
2265 err_dev_zero:
2266         close(xkb_info->keymap_fd);
2267         xkb_info->keymap_fd = -1;
2268 err_keymap_str:
2269         free(keymap_str);
2270         exit(EXIT_FAILURE);
2271 }
2272
2273 static void
2274 weston_compositor_build_global_keymap(struct weston_compositor *ec)
2275 {
2276         if (ec->xkb_info.keymap != NULL)
2277                 return;
2278
2279         ec->xkb_info.keymap = xkb_map_new_from_names(ec->xkb_context,
2280                                                      &ec->xkb_names,
2281                                                      0);
2282         if (ec->xkb_info.keymap == NULL) {
2283                 weston_log("failed to compile global XKB keymap\n");
2284                 weston_log("  tried rules %s, model %s, layout %s, variant %s, "
2285                         "options %s",
2286                         ec->xkb_names.rules, ec->xkb_names.model,
2287                         ec->xkb_names.layout, ec->xkb_names.variant,
2288                         ec->xkb_names.options);
2289                 exit(1);
2290         }
2291
2292         weston_xkb_info_new_keymap(&ec->xkb_info);
2293 }
2294
2295 WL_EXPORT void
2296 weston_seat_init_keyboard(struct weston_seat *seat, struct xkb_keymap *keymap)
2297 {
2298         if (seat->has_keyboard)
2299                 return;
2300
2301         if (keymap != NULL) {
2302                 seat->xkb_info.keymap = xkb_map_ref(keymap);
2303                 weston_xkb_info_new_keymap(&seat->xkb_info);
2304         }
2305         else {
2306                 weston_compositor_build_global_keymap(seat->compositor);
2307                 seat->xkb_info = seat->compositor->xkb_info;
2308                 seat->xkb_info.keymap = xkb_map_ref(seat->xkb_info.keymap);
2309         }
2310
2311         seat->xkb_state.state = xkb_state_new(seat->xkb_info.keymap);
2312         if (seat->xkb_state.state == NULL) {
2313                 weston_log("failed to initialise XKB state\n");
2314                 exit(1);
2315         }
2316
2317         seat->xkb_state.leds = 0;
2318
2319         wl_keyboard_init(&seat->keyboard);
2320         wl_seat_set_keyboard(&seat->seat, &seat->keyboard);
2321
2322         seat->has_keyboard = 1;
2323 }
2324
2325 WL_EXPORT void
2326 weston_seat_init_pointer(struct weston_seat *seat)
2327 {
2328         if (seat->has_pointer)
2329                 return;
2330
2331         wl_pointer_init(&seat->pointer);
2332         wl_seat_set_pointer(&seat->seat, &seat->pointer);
2333
2334         seat->has_pointer = 1;
2335 }
2336
2337 WL_EXPORT void
2338 weston_seat_init_touch(struct weston_seat *seat)
2339 {
2340         if (seat->has_touch)
2341                 return;
2342
2343         wl_touch_init(&seat->touch);
2344         wl_seat_set_touch(&seat->seat, &seat->touch);
2345
2346         seat->has_touch = 1;
2347 }
2348
2349 WL_EXPORT void
2350 weston_seat_init(struct weston_seat *seat, struct weston_compositor *ec)
2351 {
2352         wl_seat_init(&seat->seat);
2353         seat->has_pointer = 0;
2354         seat->has_keyboard = 0;
2355         seat->has_touch = 0;
2356
2357         wl_display_add_global(ec->wl_display, &wl_seat_interface, seat,
2358                               bind_seat);
2359
2360         seat->sprite = NULL;
2361         seat->sprite_destroy_listener.notify = pointer_handle_sprite_destroy;
2362
2363         seat->compositor = ec;
2364         seat->hotspot_x = 16;
2365         seat->hotspot_y = 16;
2366         seat->modifier_state = 0;
2367         seat->num_tp = 0;
2368
2369         seat->drag_surface_destroy_listener.notify =
2370                 handle_drag_surface_destroy;
2371
2372         wl_list_insert(ec->seat_list.prev, &seat->link);
2373
2374         seat->new_drag_icon_listener.notify = device_handle_new_drag_icon;
2375         wl_signal_add(&seat->seat.drag_icon_signal,
2376                       &seat->new_drag_icon_listener);
2377
2378         clipboard_create(seat);
2379         input_method_create(ec, seat);
2380 }
2381
2382 WL_EXPORT void
2383 weston_seat_release(struct weston_seat *seat)
2384 {
2385         wl_list_remove(&seat->link);
2386         /* The global object is destroyed at wl_display_destroy() time. */
2387
2388         if (seat->sprite)
2389                 pointer_unmap_sprite(seat);
2390
2391         if (seat->xkb_state.state != NULL)
2392                 xkb_state_unref(seat->xkb_state.state);
2393         xkb_info_destroy(&seat->xkb_info);
2394
2395         wl_seat_release(&seat->seat);
2396 }
2397
2398 static void
2399 drag_surface_configure(struct weston_surface *es, int32_t sx, int32_t sy)
2400 {
2401         empty_region(&es->pending.input);
2402
2403         weston_surface_configure(es,
2404                                  es->geometry.x + sx, es->geometry.y + sy,
2405                                  es->buffer->width, es->buffer->height);
2406 }
2407
2408 static int
2409 device_setup_new_drag_surface(struct weston_seat *ws,
2410                               struct weston_surface *surface)
2411 {
2412         struct wl_seat *seat = &ws->seat;
2413
2414         if (surface->configure) {
2415                 wl_resource_post_error(&surface->surface.resource,
2416                                        WL_DISPLAY_ERROR_INVALID_OBJECT,
2417                                        "surface->configure already set");
2418                 return 0;
2419         }
2420
2421         ws->drag_surface = surface;
2422
2423         weston_surface_set_position(ws->drag_surface,
2424                                     wl_fixed_to_double(seat->pointer->x),
2425                                     wl_fixed_to_double(seat->pointer->y));
2426
2427         surface->configure = drag_surface_configure;
2428
2429         wl_signal_add(&surface->surface.resource.destroy_signal,
2430                        &ws->drag_surface_destroy_listener);
2431
2432         return 1;
2433 }
2434
2435 static void
2436 device_release_drag_surface(struct weston_seat *seat)
2437 {
2438         if (weston_surface_is_mapped(seat->drag_surface))
2439                 weston_surface_unmap(seat->drag_surface);
2440
2441         seat->drag_surface->configure = NULL;
2442         empty_region(&seat->drag_surface->pending.input);
2443         wl_list_remove(&seat->drag_surface_destroy_listener.link);
2444         seat->drag_surface = NULL;
2445 }
2446
2447 static void
2448 device_map_drag_surface(struct weston_seat *seat)
2449 {
2450         struct wl_list *list;
2451
2452         if (weston_surface_is_mapped(seat->drag_surface) ||
2453             !seat->drag_surface->buffer)
2454                 return;
2455
2456         if (seat->sprite && weston_surface_is_mapped(seat->sprite))
2457                 list = &seat->sprite->layer_link;
2458         else
2459                 list = &seat->compositor->cursor_layer.surface_list;
2460
2461         wl_list_insert(list, &seat->drag_surface->layer_link);
2462         weston_surface_update_transform(seat->drag_surface);
2463         empty_region(&seat->drag_surface->input);
2464 }
2465
2466 static  void
2467 weston_seat_update_drag_surface(struct weston_seat *seat,
2468                                 int dx, int dy)
2469 {
2470         int surface_changed = 0;
2471
2472         if (!seat->drag_surface && !seat->seat.drag_surface)
2473                 return;
2474
2475         if (seat->drag_surface && seat->seat.drag_surface &&
2476             (&seat->drag_surface->surface.resource !=
2477              &seat->seat.drag_surface->resource))
2478                 /* between calls to this funcion we got a new drag_surface */
2479                 surface_changed = 1;
2480
2481         if (!seat->seat.drag_surface || surface_changed) {
2482                 device_release_drag_surface(seat);
2483                 if (!surface_changed)
2484                         return;
2485         }
2486
2487         if (!seat->drag_surface || surface_changed) {
2488                 struct weston_surface *surface = (struct weston_surface *)
2489                         seat->seat.drag_surface;
2490                 if (!device_setup_new_drag_surface(seat, surface))
2491                         return;
2492         }
2493
2494         /* the client may not have attached a buffer to the drag surface
2495          * when we setup it up, so check if map is needed on every update */
2496         device_map_drag_surface(seat);
2497
2498         if (!dx && !dy)
2499                 return;
2500
2501         weston_surface_set_position(seat->drag_surface,
2502                                     seat->drag_surface->geometry.x + wl_fixed_to_double(dx),
2503                                     seat->drag_surface->geometry.y + wl_fixed_to_double(dy));
2504 }
2505
2506 WL_EXPORT void
2507 weston_compositor_update_drag_surfaces(struct weston_compositor *compositor)
2508 {
2509         struct weston_seat *seat;
2510
2511         wl_list_for_each(seat, &compositor->seat_list, link)
2512                 weston_seat_update_drag_surface(seat, 0, 0);
2513 }
2514
2515 static void
2516 bind_output(struct wl_client *client,
2517             void *data, uint32_t version, uint32_t id)
2518 {
2519         struct weston_output *output = data;
2520         struct weston_mode *mode;
2521         struct wl_resource *resource;
2522
2523         resource = wl_client_add_object(client,
2524                                         &wl_output_interface, NULL, id, data);
2525
2526         wl_list_insert(&output->resource_list, &resource->link);
2527         resource->destroy = unbind_resource;
2528
2529         wl_output_send_geometry(resource,
2530                                 output->x,
2531                                 output->y,
2532                                 output->mm_width,
2533                                 output->mm_height,
2534                                 output->subpixel,
2535                                 output->make, output->model,
2536                                 output->transform);
2537
2538         wl_list_for_each (mode, &output->mode_list, link) {
2539                 wl_output_send_mode(resource,
2540                                     mode->flags,
2541                                     mode->width,
2542                                     mode->height,
2543                                     mode->refresh);
2544         }
2545 }
2546
2547 WL_EXPORT void
2548 weston_output_destroy(struct weston_output *output)
2549 {
2550         struct weston_compositor *c = output->compositor;
2551         int i;
2552
2553         pixman_region32_fini(&output->region);
2554
2555         for (i = 0; i < 2; i++)
2556                 pixman_region32_fini(&output->buffer_damage[i]);
2557
2558         output->compositor->output_id_pool &= ~(1 << output->id);
2559
2560         wl_display_remove_global(c->wl_display, output->global);
2561 }
2562
2563 static void
2564 weston_output_compute_transform(struct weston_output *output)
2565 {
2566         struct weston_matrix transform;
2567         int flip;
2568
2569         weston_matrix_init(&transform);
2570
2571         switch(output->transform) {
2572         case WL_OUTPUT_TRANSFORM_FLIPPED:
2573         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
2574         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
2575         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
2576                 flip = -1;
2577                 break;
2578         default:
2579                 flip = 1;
2580                 break;
2581         }
2582
2583         switch(output->transform) {
2584         case WL_OUTPUT_TRANSFORM_NORMAL:
2585         case WL_OUTPUT_TRANSFORM_FLIPPED:
2586                 transform.d[0] = flip;
2587                 transform.d[1] = 0;
2588                 transform.d[4] = 0;
2589                 transform.d[5] = 1;
2590                 break;
2591         case WL_OUTPUT_TRANSFORM_90:
2592         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
2593                 transform.d[0] = 0;
2594                 transform.d[1] = -flip;
2595                 transform.d[4] = 1;
2596                 transform.d[5] = 0;
2597                 break;
2598         case WL_OUTPUT_TRANSFORM_180:
2599         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
2600                 transform.d[0] = -flip;
2601                 transform.d[1] = 0;
2602                 transform.d[4] = 0;
2603                 transform.d[5] = -1;
2604                 break;
2605         case WL_OUTPUT_TRANSFORM_270:
2606         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
2607                 transform.d[0] = 0;
2608                 transform.d[1] = flip;
2609                 transform.d[4] = -1;
2610                 transform.d[5] = 0;
2611                 break;
2612         default:
2613                 break;
2614         }
2615
2616         weston_matrix_multiply(&output->matrix, &transform);
2617 }
2618
2619 WL_EXPORT void
2620 weston_output_update_matrix(struct weston_output *output)
2621 {
2622         float magnification;
2623         struct weston_matrix camera;
2624         struct weston_matrix modelview;
2625
2626         weston_matrix_init(&output->matrix);
2627         weston_matrix_translate(&output->matrix,
2628                                 -(output->x + (output->border.right + output->width - output->border.left) / 2.0),
2629                                 -(output->y + (output->border.bottom + output->height - output->border.top) / 2.0), 0);
2630
2631         weston_matrix_scale(&output->matrix,
2632                             2.0 / (output->width + output->border.left + output->border.right),
2633                             -2.0 / (output->height + output->border.top + output->border.bottom), 1);
2634
2635         weston_output_compute_transform(output);
2636
2637         if (output->zoom.active) {
2638                 magnification = 1 / (1 - output->zoom.spring_z.current);
2639                 weston_matrix_init(&camera);
2640                 weston_matrix_init(&modelview);
2641                 weston_output_update_zoom(output, output->zoom.type);
2642                 weston_matrix_translate(&camera, output->zoom.trans_x,
2643                                         -output->zoom.trans_y, 0);
2644                 weston_matrix_invert(&modelview, &camera);
2645                 weston_matrix_scale(&modelview, magnification, magnification, 1.0);
2646                 weston_matrix_multiply(&output->matrix, &modelview);
2647         }
2648
2649         output->dirty = 0;
2650 }
2651
2652 static void
2653 weston_output_transform_init(struct weston_output *output, uint32_t transform)
2654 {
2655         output->transform = transform;
2656
2657         switch (transform) {
2658         case WL_OUTPUT_TRANSFORM_90:
2659         case WL_OUTPUT_TRANSFORM_270:
2660         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
2661         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
2662                 /* Swap width and height */
2663                 output->width = output->current->height;
2664                 output->height = output->current->width;
2665                 break;
2666         case WL_OUTPUT_TRANSFORM_NORMAL:
2667         case WL_OUTPUT_TRANSFORM_180:
2668         case WL_OUTPUT_TRANSFORM_FLIPPED:
2669         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
2670                 output->width = output->current->width;
2671                 output->height = output->current->height;
2672                 break;
2673         default:
2674                 break;
2675         }
2676 }
2677
2678 WL_EXPORT void
2679 weston_output_move(struct weston_output *output, int x, int y)
2680 {
2681         int i;
2682
2683         output->x = x;
2684         output->y = y;
2685
2686         output->current_buffer = 0;
2687         for (i = 0; i < 2; i++)
2688                 pixman_region32_init(&output->buffer_damage[i]);
2689
2690         pixman_region32_init_rect(&output->region, x, y,
2691                                   output->width,
2692                                   output->height);
2693 }
2694
2695 WL_EXPORT void
2696 weston_output_init(struct weston_output *output, struct weston_compositor *c,
2697                    int x, int y, int width, int height, uint32_t transform)
2698 {
2699         output->compositor = c;
2700         output->x = x;
2701         output->y = y;
2702         output->border.top = 0;
2703         output->border.bottom = 0;
2704         output->border.left = 0;
2705         output->border.right = 0;
2706         output->mm_width = width;
2707         output->mm_height = height;
2708         output->dirty = 1;
2709
2710         if (transform != WL_OUTPUT_TRANSFORM_NORMAL)
2711                 output->disable_planes++;
2712
2713         weston_output_transform_init(output, transform);
2714         weston_output_init_zoom(output);
2715
2716         weston_output_move(output, x, y);
2717         weston_output_damage(output);
2718
2719         wl_signal_init(&output->frame_signal);
2720         wl_list_init(&output->animation_list);
2721         wl_list_init(&output->resource_list);
2722
2723         output->id = ffs(~output->compositor->output_id_pool) - 1;
2724         output->compositor->output_id_pool |= 1 << output->id;
2725
2726         output->global =
2727                 wl_display_add_global(c->wl_display, &wl_output_interface,
2728                                       output, bind_output);
2729 }
2730
2731 static void
2732 compositor_bind(struct wl_client *client,
2733                 void *data, uint32_t version, uint32_t id)
2734 {
2735         struct weston_compositor *compositor = data;
2736
2737         wl_client_add_object(client, &wl_compositor_interface,
2738                              &compositor_interface, id, compositor);
2739 }
2740
2741 static void
2742 log_uname(void)
2743 {
2744         struct utsname usys;
2745
2746         uname(&usys);
2747
2748         weston_log("OS: %s, %s, %s, %s\n", usys.sysname, usys.release,
2749                                                 usys.version, usys.machine);
2750 }
2751
2752 WL_EXPORT int
2753 weston_compositor_init(struct weston_compositor *ec,
2754                        struct wl_display *display,
2755                        int argc,
2756                        char *argv[],
2757                        const char *config_file)
2758 {
2759         struct wl_event_loop *loop;
2760         struct xkb_rule_names xkb_names;
2761         const struct config_key keyboard_config_keys[] = {
2762                 { "keymap_rules", CONFIG_KEY_STRING, &xkb_names.rules },
2763                 { "keymap_model", CONFIG_KEY_STRING, &xkb_names.model },
2764                 { "keymap_layout", CONFIG_KEY_STRING, &xkb_names.layout },
2765                 { "keymap_variant", CONFIG_KEY_STRING, &xkb_names.variant },
2766                 { "keymap_options", CONFIG_KEY_STRING, &xkb_names.options },
2767         };
2768         const struct config_section cs[] = {
2769                 { "keyboard",
2770                   keyboard_config_keys, ARRAY_LENGTH(keyboard_config_keys) },
2771         };
2772
2773         memset(&xkb_names, 0, sizeof(xkb_names));
2774         parse_config_file(config_file, cs, ARRAY_LENGTH(cs), ec);
2775
2776         ec->wl_display = display;
2777         wl_signal_init(&ec->destroy_signal);
2778         wl_signal_init(&ec->activate_signal);
2779         wl_signal_init(&ec->kill_signal);
2780         wl_signal_init(&ec->lock_signal);
2781         wl_signal_init(&ec->unlock_signal);
2782         wl_signal_init(&ec->show_input_panel_signal);
2783         wl_signal_init(&ec->hide_input_panel_signal);
2784         ec->launcher_sock = weston_environment_get_fd("WESTON_LAUNCHER_SOCK");
2785
2786         ec->output_id_pool = 0;
2787
2788         if (!wl_display_add_global(display, &wl_compositor_interface,
2789                                    ec, compositor_bind))
2790                 return -1;
2791
2792         wl_list_init(&ec->surface_list);
2793         wl_list_init(&ec->layer_list);
2794         wl_list_init(&ec->seat_list);
2795         wl_list_init(&ec->output_list);
2796         wl_list_init(&ec->key_binding_list);
2797         wl_list_init(&ec->button_binding_list);
2798         wl_list_init(&ec->axis_binding_list);
2799         wl_list_init(&ec->fade.animation.link);
2800
2801         weston_plane_init(&ec->primary_plane, 0, 0);
2802
2803         weston_compositor_xkb_init(ec, &xkb_names);
2804
2805         ec->ping_handler = NULL;
2806
2807         screenshooter_create(ec);
2808         text_cursor_position_notifier_create(ec);
2809         text_model_factory_create(ec);
2810
2811         wl_data_device_manager_init(ec->wl_display);
2812
2813         wl_display_init_shm(display);
2814
2815         loop = wl_display_get_event_loop(ec->wl_display);
2816         ec->idle_source = wl_event_loop_add_timer(loop, idle_handler, ec);
2817         wl_event_source_timer_update(ec->idle_source, ec->idle_time * 1000);
2818
2819         ec->input_loop = wl_event_loop_create();
2820
2821         weston_spring_init(&ec->fade.spring, 30.0, 1.0, 1.0);
2822         ec->fade.animation.frame = fade_frame;
2823
2824         weston_layer_init(&ec->fade_layer, &ec->layer_list);
2825         weston_layer_init(&ec->cursor_layer, &ec->fade_layer.link);
2826
2827         weston_compositor_schedule_repaint(ec);
2828
2829         return 0;
2830 }
2831
2832 WL_EXPORT void
2833 weston_compositor_shutdown(struct weston_compositor *ec)
2834 {
2835         struct weston_output *output, *next;
2836
2837         wl_event_source_remove(ec->idle_source);
2838         if (ec->input_loop_source)
2839                 wl_event_source_remove(ec->input_loop_source);
2840
2841         /* Destroy all outputs associated with this compositor */
2842         wl_list_for_each_safe(output, next, &ec->output_list, link)
2843                 output->destroy(output);
2844
2845         weston_binding_list_destroy_all(&ec->key_binding_list);
2846         weston_binding_list_destroy_all(&ec->button_binding_list);
2847         weston_binding_list_destroy_all(&ec->axis_binding_list);
2848
2849         weston_plane_release(&ec->primary_plane);
2850
2851         wl_array_release(&ec->vertices);
2852         wl_array_release(&ec->indices);
2853         wl_array_release(&ec->vtxcnt);
2854
2855         wl_event_loop_destroy(ec->input_loop);
2856 }
2857
2858 static int on_term_signal(int signal_number, void *data)
2859 {
2860         struct wl_display *display = data;
2861
2862         weston_log("caught signal %d\n", signal_number);
2863         wl_display_terminate(display);
2864
2865         return 1;
2866 }
2867
2868 static void
2869 on_segv_signal(int s, siginfo_t *siginfo, void *context)
2870 {
2871         void *buffer[32];
2872         int i, count;
2873         Dl_info info;
2874
2875         /* This SIGSEGV handler will do a best-effort backtrace, and
2876          * then call the backend restore function, which will switch
2877          * back to the vt we launched from or ungrab X etc and then
2878          * raise SIGTRAP.  If we run weston under gdb from X or a
2879          * different vt, and tell gdb "handle SIGSEGV nostop", this
2880          * will allow weston to switch back to gdb on crash and then
2881          * gdb will catch the crash with SIGTRAP. */
2882
2883         weston_log("caught segv\n");
2884
2885         count = backtrace(buffer, ARRAY_LENGTH(buffer));
2886         for (i = 0; i < count; i++) {
2887                 dladdr(buffer[i], &info);
2888                 weston_log("  [%016lx]  %s  (%s)\n",
2889                         (long) buffer[i],
2890                         info.dli_sname ? info.dli_sname : "--",
2891                         info.dli_fname);
2892         }
2893
2894         segv_compositor->restore(segv_compositor);
2895
2896         raise(SIGTRAP);
2897 }
2898
2899
2900 static void *
2901 load_module(const char *name, const char *entrypoint)
2902 {
2903         char path[PATH_MAX];
2904         void *module, *init;
2905
2906         if (name[0] != '/')
2907                 snprintf(path, sizeof path, "%s/%s", MODULEDIR, name);
2908         else
2909                 snprintf(path, sizeof path, "%s", name);
2910
2911         module = dlopen(path, RTLD_NOW | RTLD_NOLOAD);
2912         if (module) {
2913                 weston_log("Module '%s' already loaded\n", path);
2914                 dlclose(module);
2915                 return NULL;
2916         }
2917
2918         weston_log("Loading module '%s'\n", path);
2919         module = dlopen(path, RTLD_NOW);
2920         if (!module) {
2921                 weston_log("Failed to load module: %s\n", dlerror());
2922                 return NULL;
2923         }
2924
2925         init = dlsym(module, entrypoint);
2926         if (!init) {
2927                 weston_log("Failed to lookup init function: %s\n", dlerror());
2928                 return NULL;
2929         }
2930
2931         return init;
2932 }
2933
2934 static int
2935 load_modules(struct weston_compositor *ec, const char *modules)
2936 {
2937         const char *p, *end;
2938         char buffer[256];
2939         int (*module_init)(struct weston_compositor *ec);
2940
2941         if (modules == NULL)
2942                 return 0;
2943
2944         p = modules;
2945         while (*p) {
2946                 end = strchrnul(p, ',');
2947                 snprintf(buffer, sizeof buffer, "%.*s", (int) (end - p), p);
2948                 module_init = load_module(buffer, "module_init");
2949                 if (module_init)
2950                         module_init(ec);
2951                 p = end;
2952                 while (*p == ',')
2953                         p++;
2954
2955         }
2956
2957         return 0;
2958 }
2959
2960 static const char xdg_error_message[] =
2961         "fatal: environment variable XDG_RUNTIME_DIR is not set.\n";
2962
2963 static const char xdg_wrong_message[] =
2964         "fatal: environment variable XDG_RUNTIME_DIR\n"
2965         "is set to \"%s\", which is not a directory.\n";
2966
2967 static const char xdg_wrong_mode_message[] =
2968         "warning: XDG_RUNTIME_DIR \"%s\" is not configured\n"
2969         "correctly.  Unix access mode must be 0700 but is %o,\n"
2970         "and XDG_RUNTIME_DIR must be owned by the user, but is\n"
2971         "owned by UID %d.\n";
2972
2973 static const char xdg_detail_message[] =
2974         "Refer to your distribution on how to get it, or\n"
2975         "http://www.freedesktop.org/wiki/Specifications/basedir-spec\n"
2976         "on how to implement it.\n";
2977
2978 static void
2979 verify_xdg_runtime_dir(void)
2980 {
2981         char *dir = getenv("XDG_RUNTIME_DIR");
2982         struct stat s;
2983
2984         if (!dir) {
2985                 weston_log(xdg_error_message);
2986                 weston_log_continue(xdg_detail_message);
2987                 exit(EXIT_FAILURE);
2988         }
2989
2990         if (stat(dir, &s) || !S_ISDIR(s.st_mode)) {
2991                 weston_log(xdg_wrong_message, dir);
2992                 weston_log_continue(xdg_detail_message);
2993                 exit(EXIT_FAILURE);
2994         }
2995
2996         if ((s.st_mode & 0777) != 0700 || s.st_uid != getuid()) {
2997                 weston_log(xdg_wrong_mode_message,
2998                            dir, s.st_mode & 0777, s.st_uid);
2999                 weston_log_continue(xdg_detail_message);
3000         }
3001 }
3002
3003 static int
3004 usage(int error_code)
3005 {
3006         fprintf(stderr,
3007                 "Usage: weston [OPTIONS]\n\n"
3008                 "This is weston version " VERSION ", the Wayland reference compositor.\n"
3009                 "Weston supports multiple backends, and depending on which backend is in use\n"
3010                 "different options will be accepted.\n\n"
3011
3012
3013                 "Core options:\n\n"
3014                 "  -B, --backend=MODULE\tBackend module, one of drm-backend.so,\n"
3015                 "\t\t\t\tx11-backend.so or wayland-backend.so\n"
3016                 "  -S, --socket=NAME\tName of socket to listen on\n"
3017                 "  -i, --idle-time=SECS\tIdle time in seconds\n"
3018                 "  --modules\t\tLoad the comma-separated list of modules\n"
3019                 "  --log==FILE\t\tLog to the given file\n"
3020                 "  -h, --help\t\tThis help message\n\n");
3021
3022         fprintf(stderr,
3023                 "Options for drm-backend.so:\n\n"
3024                 "  --connector=ID\tBring up only this connector\n"
3025                 "  --seat=SEAT\t\tThe seat that weston should run on\n"
3026                 "  --tty=TTY\t\tThe tty to use\n"
3027                 "  --current-mode\tPrefer current KMS mode over EDID preferred mode\n\n");
3028
3029         fprintf(stderr,
3030                 "Options for x11-backend.so:\n\n"
3031                 "  --width=WIDTH\t\tWidth of X window\n"
3032                 "  --height=HEIGHT\tHeight of X window\n"
3033                 "  --fullscreen\t\tRun in fullscreen mode\n"
3034                 "  --output-count=COUNT\tCreate multiple outputs\n"
3035                 "  --no-input\t\tDont create input devices\n\n");
3036
3037         fprintf(stderr,
3038                 "Options for wayland-backend.so:\n\n"
3039                 "  --width=WIDTH\t\tWidth of Wayland surface\n"
3040                 "  --height=HEIGHT\tHeight of Wayland surface\n"
3041                 "  --display=DISPLAY\tWayland display to connect to\n\n");
3042
3043         exit(error_code);
3044 }
3045
3046 int main(int argc, char *argv[])
3047 {
3048         int ret = EXIT_SUCCESS;
3049         struct wl_display *display;
3050         struct weston_compositor *ec;
3051         struct wl_event_source *signals[4];
3052         struct wl_event_loop *loop;
3053         struct sigaction segv_action;
3054         struct weston_compositor
3055                 *(*backend_init)(struct wl_display *display,
3056                                  int argc, char *argv[], const char *config_file);
3057         int i;
3058         char *backend = NULL;
3059         const char *modules = "desktop-shell.so", *option_modules = NULL;
3060         char *log = NULL;
3061         int32_t idle_time = 300;
3062         int32_t help = 0;
3063         char *socket_name = "wayland-0";
3064         char *config_file;
3065
3066         const struct config_key core_config_keys[] = {
3067                 { "modules", CONFIG_KEY_STRING, &modules },
3068         };
3069
3070         const struct config_section cs[] = {
3071                 { "core",
3072                   core_config_keys, ARRAY_LENGTH(core_config_keys) },
3073         };
3074
3075         const struct weston_option core_options[] = {
3076                 { WESTON_OPTION_STRING, "backend", 'B', &backend },
3077                 { WESTON_OPTION_STRING, "socket", 'S', &socket_name },
3078                 { WESTON_OPTION_INTEGER, "idle-time", 'i', &idle_time },
3079                 { WESTON_OPTION_STRING, "modules", 0, &option_modules },
3080                 { WESTON_OPTION_STRING, "log", 0, &log },
3081                 { WESTON_OPTION_BOOLEAN, "help", 'h', &help },
3082         };
3083
3084         argc = parse_options(core_options,
3085                              ARRAY_LENGTH(core_options), argc, argv);
3086
3087         if (help)
3088                 usage(EXIT_SUCCESS);
3089
3090         weston_log_file_open(log);
3091         
3092         weston_log("%s\n"
3093                    STAMP_SPACE "%s\n"
3094                    STAMP_SPACE "Bug reports to: %s\n"
3095                    STAMP_SPACE "Build: %s\n",
3096                    PACKAGE_STRING, PACKAGE_URL, PACKAGE_BUGREPORT,
3097                    BUILD_ID);
3098         log_uname();
3099
3100         verify_xdg_runtime_dir();
3101
3102         display = wl_display_create();
3103
3104         loop = wl_display_get_event_loop(display);
3105         signals[0] = wl_event_loop_add_signal(loop, SIGTERM, on_term_signal,
3106                                               display);
3107         signals[1] = wl_event_loop_add_signal(loop, SIGINT, on_term_signal,
3108                                               display);
3109         signals[2] = wl_event_loop_add_signal(loop, SIGQUIT, on_term_signal,
3110                                               display);
3111
3112         wl_list_init(&child_process_list);
3113         signals[3] = wl_event_loop_add_signal(loop, SIGCHLD, sigchld_handler,
3114                                               NULL);
3115
3116         if (!backend) {
3117                 if (getenv("WAYLAND_DISPLAY"))
3118                         backend = "wayland-backend.so";
3119                 else if (getenv("DISPLAY"))
3120                         backend = "x11-backend.so";
3121                 else
3122                         backend = "drm-backend.so";
3123         }
3124
3125         config_file = config_file_path("weston.ini");
3126         parse_config_file(config_file, cs, ARRAY_LENGTH(cs), NULL);
3127
3128         backend_init = load_module(backend, "backend_init");
3129         if (!backend_init)
3130                 exit(EXIT_FAILURE);
3131
3132         ec = backend_init(display, argc, argv, config_file);
3133         if (ec == NULL) {
3134                 weston_log("fatal: failed to create compositor\n");
3135                 exit(EXIT_FAILURE);
3136         }
3137
3138         segv_action.sa_flags = SA_SIGINFO | SA_RESETHAND;
3139         segv_action.sa_sigaction = on_segv_signal;
3140         sigemptyset(&segv_action.sa_mask);
3141         sigaction(SIGSEGV, &segv_action, NULL);
3142         segv_compositor = ec;
3143
3144         for (i = 1; argv[i]; i++)
3145                 weston_log("fatal: unhandled option: %s\n", argv[i]);
3146         if (argv[1]) {
3147                 ret = EXIT_FAILURE;
3148                 goto out;
3149         }
3150
3151         free(config_file);
3152
3153         ec->option_idle_time = idle_time;
3154         ec->idle_time = idle_time;
3155
3156         setenv("WAYLAND_DISPLAY", socket_name, 1);
3157
3158         if (load_modules(ec, modules) < 0)
3159                 goto out;
3160         if (load_modules(ec, option_modules) < 0)
3161                 goto out;
3162
3163         if (wl_display_add_socket(display, socket_name)) {
3164                 weston_log("fatal: failed to add socket: %m\n");
3165                 ret = EXIT_FAILURE;
3166                 goto out;
3167         }
3168
3169         weston_compositor_dpms_on(ec);
3170         weston_compositor_wake(ec);
3171
3172         wl_display_run(display);
3173
3174  out:
3175         /* prevent further rendering while shutting down */
3176         ec->state = WESTON_COMPOSITOR_SLEEPING;
3177
3178         wl_signal_emit(&ec->destroy_signal, ec);
3179
3180         for (i = ARRAY_LENGTH(signals); i;)
3181                 wl_event_source_remove(signals[--i]);
3182
3183         weston_compositor_xkb_destroy(ec);
3184
3185         ec->destroy(ec);
3186         wl_display_destroy(display);
3187
3188         weston_log_file_close();
3189
3190         return ret;
3191 }