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