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