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