compositor: quick fix for sub-surface mapping
[profile/ivi/weston-ivi-shell.git] / src / compositor.c
1 /*
2  * Copyright © 2010-2011 Intel Corporation
3  * Copyright © 2008-2011 Kristian Høgsberg
4  * Copyright © 2012 Collabora, Ltd.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and
7  * its documentation for any purpose is hereby granted without fee, provided
8  * that the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of the copyright holders not be used in
11  * advertising or publicity pertaining to distribution of the software
12  * without specific, written prior permission.  The copyright holders make
13  * no representations about the suitability of this software for any
14  * purpose.  It is provided "as is" without express or implied warranty.
15  *
16  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
18  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
19  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
20  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
21  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23  */
24
25 #include "config.h"
26
27 #include <fcntl.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stdint.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <assert.h>
35 #include <sys/ioctl.h>
36 #include <sys/mman.h>
37 #include <sys/wait.h>
38 #include <sys/socket.h>
39 #include <sys/utsname.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <math.h>
43 #include <linux/input.h>
44 #include <dlfcn.h>
45 #include <signal.h>
46 #include <setjmp.h>
47 #include <sys/time.h>
48 #include <time.h>
49
50 #ifdef HAVE_LIBUNWIND
51 #define UNW_LOCAL_ONLY
52 #include <libunwind.h>
53 #endif
54
55 #include "compositor.h"
56 #include "scaler-server-protocol.h"
57 #include "../shared/os-compatibility.h"
58 #include "git-version.h"
59 #include "version.h"
60
61 static struct wl_list child_process_list;
62 static struct weston_compositor *segv_compositor;
63
64 static int
65 sigchld_handler(int signal_number, void *data)
66 {
67         struct weston_process *p;
68         int status;
69         pid_t pid;
70
71         pid = waitpid(-1, &status, WNOHANG);
72         if (!pid)
73                 return 1;
74
75         wl_list_for_each(p, &child_process_list, link) {
76                 if (p->pid == pid)
77                         break;
78         }
79
80         if (&p->link == &child_process_list) {
81                 weston_log("unknown child process exited\n");
82                 return 1;
83         }
84
85         wl_list_remove(&p->link);
86         p->cleanup(p, status);
87
88         return 1;
89 }
90
91 static void
92 weston_output_transform_scale_init(struct weston_output *output,
93                                    uint32_t transform, uint32_t scale);
94
95 static void
96 weston_compositor_build_view_list(struct weston_compositor *compositor);
97
98 WL_EXPORT int
99 weston_output_switch_mode(struct weston_output *output, struct weston_mode *mode,
100                 int32_t scale, enum weston_mode_switch_op op)
101 {
102         struct weston_seat *seat;
103         struct wl_resource *resource;
104         pixman_region32_t old_output_region;
105         int ret, notify_mode_changed, notify_scale_changed;
106         int temporary_mode, temporary_scale;
107
108         if (!output->switch_mode)
109                 return -1;
110
111         temporary_mode = (output->original_mode != 0);
112         temporary_scale = (output->current_scale != output->original_scale);
113         ret = 0;
114
115         notify_mode_changed = 0;
116         notify_scale_changed = 0;
117         switch(op) {
118         case WESTON_MODE_SWITCH_SET_NATIVE:
119                 output->native_mode = mode;
120                 if (!temporary_mode) {
121                         notify_mode_changed = 1;
122                         ret = output->switch_mode(output, mode);
123                         if (ret < 0)
124                                 return ret;
125                 }
126
127                 output->native_scale = scale;
128                 if(!temporary_scale)
129                         notify_scale_changed = 1;
130                 break;
131         case WESTON_MODE_SWITCH_SET_TEMPORARY:
132                 if (!temporary_mode)
133                         output->original_mode = output->native_mode;
134                 if (!temporary_scale)
135                         output->original_scale = output->native_scale;
136
137                 ret = output->switch_mode(output, mode);
138                 if (ret < 0)
139                         return ret;
140
141                 output->current_scale = scale;
142                 break;
143         case WESTON_MODE_SWITCH_RESTORE_NATIVE:
144                 if (!temporary_mode) {
145                         weston_log("already in the native mode\n");
146                         return -1;
147                 }
148
149                 notify_mode_changed = (output->original_mode != output->native_mode);
150
151                 ret = output->switch_mode(output, mode);
152                 if (ret < 0)
153                         return ret;
154
155                 if (output->original_scale != output->native_scale) {
156                         notify_scale_changed = 1;
157                         scale = output->native_scale;
158                         output->original_scale = scale;
159                 }
160                 output->original_mode = 0;
161
162                 output->current_scale = output->native_scale;
163                 break;
164         default:
165                 weston_log("unknown weston_switch_mode_op %d\n", op);
166                 break;
167         }
168
169         pixman_region32_init(&old_output_region);
170         pixman_region32_copy(&old_output_region, &output->region);
171
172         /* Update output region and transformation matrix */
173         weston_output_transform_scale_init(output, output->transform, output->current_scale);
174
175         pixman_region32_init(&output->previous_damage);
176         pixman_region32_init_rect(&output->region, output->x, output->y,
177                                   output->width, output->height);
178
179         weston_output_update_matrix(output);
180
181         /* If a pointer falls outside the outputs new geometry, move it to its
182          * lower-right corner */
183         wl_list_for_each(seat, &output->compositor->seat_list, link) {
184                 struct weston_pointer *pointer = seat->pointer;
185                 int32_t x, y;
186
187                 if (!pointer)
188                         continue;
189
190                 x = wl_fixed_to_int(pointer->x);
191                 y = wl_fixed_to_int(pointer->y);
192
193                 if (!pixman_region32_contains_point(&old_output_region,
194                                                     x, y, NULL) ||
195                     pixman_region32_contains_point(&output->region,
196                                                    x, y, NULL))
197                         continue;
198
199                 if (x >= output->x + output->width)
200                         x = output->x + output->width - 1;
201                 if (y >= output->y + output->height)
202                         y = output->y + output->height - 1;
203
204                 pointer->x = wl_fixed_from_int(x);
205                 pointer->y = wl_fixed_from_int(y);
206         }
207
208         pixman_region32_fini(&old_output_region);
209
210         /* notify clients of the changes */
211         if (notify_mode_changed || notify_scale_changed) {
212                 wl_resource_for_each(resource, &output->resource_list) {
213                         if(notify_mode_changed) {
214                                 wl_output_send_mode(resource,
215                                                 mode->flags | WL_OUTPUT_MODE_CURRENT,
216                                                 mode->width,
217                                                 mode->height,
218                                                 mode->refresh);
219                         }
220
221                         if (notify_scale_changed)
222                                 wl_output_send_scale(resource, scale);
223
224                         if (wl_resource_get_version(resource) >= 2)
225                                    wl_output_send_done(resource);
226                 }
227         }
228
229         return ret;
230 }
231
232 WL_EXPORT void
233 weston_watch_process(struct weston_process *process)
234 {
235         wl_list_insert(&child_process_list, &process->link);
236 }
237
238 static void
239 child_client_exec(int sockfd, const char *path)
240 {
241         int clientfd;
242         char s[32];
243         sigset_t allsigs;
244
245         /* do not give our signal mask to the new process */
246         sigfillset(&allsigs);
247         sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
248
249         /* Launch clients as the user. Do not lauch clients with wrong euid.*/
250         if (seteuid(getuid()) == -1) {
251                 weston_log("compositor: failed seteuid\n");
252                 return;
253         }
254
255         /* SOCK_CLOEXEC closes both ends, so we dup the fd to get a
256          * non-CLOEXEC fd to pass through exec. */
257         clientfd = dup(sockfd);
258         if (clientfd == -1) {
259                 weston_log("compositor: dup failed: %m\n");
260                 return;
261         }
262
263         snprintf(s, sizeof s, "%d", clientfd);
264         setenv("WAYLAND_SOCKET", s, 1);
265
266         if (execl(path, path, NULL) < 0)
267                 weston_log("compositor: executing '%s' failed: %m\n",
268                         path);
269 }
270
271 WL_EXPORT struct wl_client *
272 weston_client_launch(struct weston_compositor *compositor,
273                      struct weston_process *proc,
274                      const char *path,
275                      weston_process_cleanup_func_t cleanup)
276 {
277         int sv[2];
278         pid_t pid;
279         struct wl_client *client;
280
281         weston_log("launching '%s'\n", path);
282
283         if (os_socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
284                 weston_log("weston_client_launch: "
285                         "socketpair failed while launching '%s': %m\n",
286                         path);
287                 return NULL;
288         }
289
290         pid = fork();
291         if (pid == -1) {
292                 close(sv[0]);
293                 close(sv[1]);
294                 weston_log("weston_client_launch: "
295                         "fork failed while launching '%s': %m\n", path);
296                 return NULL;
297         }
298
299         if (pid == 0) {
300                 child_client_exec(sv[1], path);
301                 _exit(-1);
302         }
303
304         close(sv[1]);
305
306         client = wl_client_create(compositor->wl_display, sv[0]);
307         if (!client) {
308                 close(sv[0]);
309                 weston_log("weston_client_launch: "
310                         "wl_client_create failed while launching '%s'.\n",
311                         path);
312                 return NULL;
313         }
314
315         proc->pid = pid;
316         proc->cleanup = cleanup;
317         weston_watch_process(proc);
318
319         return client;
320 }
321
322 static void
323 region_init_infinite(pixman_region32_t *region)
324 {
325         pixman_region32_init_rect(region, INT32_MIN, INT32_MIN,
326                                   UINT32_MAX, UINT32_MAX);
327 }
328
329 static struct weston_subsurface *
330 weston_surface_to_subsurface(struct weston_surface *surface);
331
332 WL_EXPORT struct weston_view *
333 weston_view_create(struct weston_surface *surface)
334 {
335         struct weston_view *view;
336
337         view = calloc(1, sizeof *view);
338         if (view == NULL)
339                 return NULL;
340
341         view->surface = surface;
342
343         /* Assign to surface */
344         wl_list_insert(&surface->views, &view->surface_link);
345
346         wl_signal_init(&view->destroy_signal);
347         wl_list_init(&view->link);
348         wl_list_init(&view->layer_link.link);
349
350         view->plane = NULL;
351         view->layer_link.layer = NULL;
352         view->parent_view = NULL;
353
354         pixman_region32_init(&view->clip);
355         pixman_region32_init(&view->transform.masked_boundingbox);
356         pixman_region32_init(&view->transform.masked_opaque);
357
358         view->alpha = 1.0;
359         pixman_region32_init(&view->transform.opaque);
360
361         wl_list_init(&view->geometry.transformation_list);
362         wl_list_insert(&view->geometry.transformation_list,
363                        &view->transform.position.link);
364         weston_matrix_init(&view->transform.position.matrix);
365         wl_list_init(&view->geometry.child_list);
366         pixman_region32_init(&view->transform.boundingbox);
367         view->transform.dirty = 1;
368
369         view->output = NULL;
370
371         return view;
372 }
373
374 struct weston_frame_callback {
375         struct wl_resource *resource;
376         struct wl_list link;
377 };
378
379 static void
380 surface_state_handle_buffer_destroy(struct wl_listener *listener, void *data)
381 {
382         struct weston_surface_state *state =
383                 container_of(listener, struct weston_surface_state,
384                              buffer_destroy_listener);
385
386         state->buffer = NULL;
387 }
388
389 static void
390 weston_surface_state_init(struct weston_surface_state *state)
391 {
392         state->newly_attached = 0;
393         state->buffer = NULL;
394         state->buffer_destroy_listener.notify =
395                 surface_state_handle_buffer_destroy;
396         state->sx = 0;
397         state->sy = 0;
398
399         pixman_region32_init(&state->damage);
400         pixman_region32_init(&state->opaque);
401         region_init_infinite(&state->input);
402
403         wl_list_init(&state->frame_callback_list);
404
405         state->buffer_viewport.buffer.transform = WL_OUTPUT_TRANSFORM_NORMAL;
406         state->buffer_viewport.buffer.scale = 1;
407         state->buffer_viewport.buffer.src_width = wl_fixed_from_int(-1);
408         state->buffer_viewport.surface.width = -1;
409         state->buffer_viewport.changed = 0;
410 }
411
412 static void
413 weston_surface_state_fini(struct weston_surface_state *state)
414 {
415         struct weston_frame_callback *cb, *next;
416
417         wl_list_for_each_safe(cb, next,
418                               &state->frame_callback_list, link)
419                 wl_resource_destroy(cb->resource);
420
421         pixman_region32_fini(&state->input);
422         pixman_region32_fini(&state->opaque);
423         pixman_region32_fini(&state->damage);
424
425         if (state->buffer)
426                 wl_list_remove(&state->buffer_destroy_listener.link);
427         state->buffer = NULL;
428 }
429
430 static void
431 weston_surface_state_set_buffer(struct weston_surface_state *state,
432                                 struct weston_buffer *buffer)
433 {
434         if (state->buffer == buffer)
435                 return;
436
437         if (state->buffer)
438                 wl_list_remove(&state->buffer_destroy_listener.link);
439         state->buffer = buffer;
440         if (state->buffer)
441                 wl_signal_add(&state->buffer->destroy_signal,
442                               &state->buffer_destroy_listener);
443 }
444
445 WL_EXPORT struct weston_surface *
446 weston_surface_create(struct weston_compositor *compositor)
447 {
448         struct weston_surface *surface;
449
450         surface = calloc(1, sizeof *surface);
451         if (surface == NULL)
452                 return NULL;
453
454         wl_signal_init(&surface->destroy_signal);
455
456         surface->resource = NULL;
457
458         surface->compositor = compositor;
459         surface->ref_count = 1;
460
461         surface->buffer_viewport.buffer.transform = WL_OUTPUT_TRANSFORM_NORMAL;
462         surface->buffer_viewport.buffer.scale = 1;
463         surface->buffer_viewport.buffer.src_width = wl_fixed_from_int(-1);
464         surface->buffer_viewport.surface.width = -1;
465
466         weston_surface_state_init(&surface->pending);
467
468         surface->output = NULL;
469
470         surface->viewport_resource = NULL;
471
472         pixman_region32_init(&surface->damage);
473         pixman_region32_init(&surface->opaque);
474         region_init_infinite(&surface->input);
475
476         wl_list_init(&surface->views);
477
478         wl_list_init(&surface->frame_callback_list);
479
480         wl_list_init(&surface->subsurface_list);
481         wl_list_init(&surface->subsurface_list_pending);
482
483         return surface;
484 }
485
486 WL_EXPORT void
487 weston_surface_set_color(struct weston_surface *surface,
488                  float red, float green, float blue, float alpha)
489 {
490         surface->compositor->renderer->surface_set_color(surface, red, green, blue, alpha);
491 }
492
493 WL_EXPORT void
494 weston_view_to_global_float(struct weston_view *view,
495                             float sx, float sy, float *x, float *y)
496 {
497         if (view->transform.enabled) {
498                 struct weston_vector v = { { sx, sy, 0.0f, 1.0f } };
499
500                 weston_matrix_transform(&view->transform.matrix, &v);
501
502                 if (fabsf(v.f[3]) < 1e-6) {
503                         weston_log("warning: numerical instability in "
504                                 "%s(), divisor = %g\n", __func__,
505                                 v.f[3]);
506                         *x = 0;
507                         *y = 0;
508                         return;
509                 }
510
511                 *x = v.f[0] / v.f[3];
512                 *y = v.f[1] / v.f[3];
513         } else {
514                 *x = sx + view->geometry.x;
515                 *y = sy + view->geometry.y;
516         }
517 }
518
519 WL_EXPORT void
520 weston_transformed_coord(int width, int height,
521                          enum wl_output_transform transform,
522                          int32_t scale,
523                          float sx, float sy, float *bx, float *by)
524 {
525         switch (transform) {
526         case WL_OUTPUT_TRANSFORM_NORMAL:
527         default:
528                 *bx = sx;
529                 *by = sy;
530                 break;
531         case WL_OUTPUT_TRANSFORM_FLIPPED:
532                 *bx = width - sx;
533                 *by = sy;
534                 break;
535         case WL_OUTPUT_TRANSFORM_90:
536                 *bx = height - sy;
537                 *by = sx;
538                 break;
539         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
540                 *bx = height - sy;
541                 *by = width - sx;
542                 break;
543         case WL_OUTPUT_TRANSFORM_180:
544                 *bx = width - sx;
545                 *by = height - sy;
546                 break;
547         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
548                 *bx = sx;
549                 *by = height - sy;
550                 break;
551         case WL_OUTPUT_TRANSFORM_270:
552                 *bx = sy;
553                 *by = width - sx;
554                 break;
555         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
556                 *bx = sy;
557                 *by = sx;
558                 break;
559         }
560
561         *bx *= scale;
562         *by *= scale;
563 }
564
565 WL_EXPORT pixman_box32_t
566 weston_transformed_rect(int width, int height,
567                         enum wl_output_transform transform,
568                         int32_t scale,
569                         pixman_box32_t rect)
570 {
571         float x1, x2, y1, y2;
572
573         pixman_box32_t ret;
574
575         weston_transformed_coord(width, height, transform, scale,
576                                  rect.x1, rect.y1, &x1, &y1);
577         weston_transformed_coord(width, height, transform, scale,
578                                  rect.x2, rect.y2, &x2, &y2);
579
580         if (x1 <= x2) {
581                 ret.x1 = x1;
582                 ret.x2 = x2;
583         } else {
584                 ret.x1 = x2;
585                 ret.x2 = x1;
586         }
587
588         if (y1 <= y2) {
589                 ret.y1 = y1;
590                 ret.y2 = y2;
591         } else {
592                 ret.y1 = y2;
593                 ret.y2 = y1;
594         }
595
596         return ret;
597 }
598
599 WL_EXPORT void
600 weston_transformed_region(int width, int height,
601                           enum wl_output_transform transform,
602                           int32_t scale,
603                           pixman_region32_t *src, pixman_region32_t *dest)
604 {
605         pixman_box32_t *src_rects, *dest_rects;
606         int nrects, i;
607
608         if (transform == WL_OUTPUT_TRANSFORM_NORMAL && scale == 1) {
609                 if (src != dest)
610                         pixman_region32_copy(dest, src);
611                 return;
612         }
613
614         src_rects = pixman_region32_rectangles(src, &nrects);
615         dest_rects = malloc(nrects * sizeof(*dest_rects));
616         if (!dest_rects)
617                 return;
618
619         if (transform == WL_OUTPUT_TRANSFORM_NORMAL) {
620                 memcpy(dest_rects, src_rects, nrects * sizeof(*dest_rects));
621         } else {
622                 for (i = 0; i < nrects; i++) {
623                         switch (transform) {
624                         default:
625                         case WL_OUTPUT_TRANSFORM_NORMAL:
626                                 dest_rects[i].x1 = src_rects[i].x1;
627                                 dest_rects[i].y1 = src_rects[i].y1;
628                                 dest_rects[i].x2 = src_rects[i].x2;
629                                 dest_rects[i].y2 = src_rects[i].y2;
630                                 break;
631                         case WL_OUTPUT_TRANSFORM_90:
632                                 dest_rects[i].x1 = height - src_rects[i].y2;
633                                 dest_rects[i].y1 = src_rects[i].x1;
634                                 dest_rects[i].x2 = height - src_rects[i].y1;
635                                 dest_rects[i].y2 = src_rects[i].x2;
636                                 break;
637                         case WL_OUTPUT_TRANSFORM_180:
638                                 dest_rects[i].x1 = width - src_rects[i].x2;
639                                 dest_rects[i].y1 = height - src_rects[i].y2;
640                                 dest_rects[i].x2 = width - src_rects[i].x1;
641                                 dest_rects[i].y2 = height - src_rects[i].y1;
642                                 break;
643                         case WL_OUTPUT_TRANSFORM_270:
644                                 dest_rects[i].x1 = src_rects[i].y1;
645                                 dest_rects[i].y1 = width - src_rects[i].x2;
646                                 dest_rects[i].x2 = src_rects[i].y2;
647                                 dest_rects[i].y2 = width - src_rects[i].x1;
648                                 break;
649                         case WL_OUTPUT_TRANSFORM_FLIPPED:
650                                 dest_rects[i].x1 = width - src_rects[i].x2;
651                                 dest_rects[i].y1 = src_rects[i].y1;
652                                 dest_rects[i].x2 = width - src_rects[i].x1;
653                                 dest_rects[i].y2 = src_rects[i].y2;
654                                 break;
655                         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
656                                 dest_rects[i].x1 = height - src_rects[i].y2;
657                                 dest_rects[i].y1 = width - src_rects[i].x2;
658                                 dest_rects[i].x2 = height - src_rects[i].y1;
659                                 dest_rects[i].y2 = width - src_rects[i].x1;
660                                 break;
661                         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
662                                 dest_rects[i].x1 = src_rects[i].x1;
663                                 dest_rects[i].y1 = height - src_rects[i].y2;
664                                 dest_rects[i].x2 = src_rects[i].x2;
665                                 dest_rects[i].y2 = height - src_rects[i].y1;
666                                 break;
667                         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
668                                 dest_rects[i].x1 = src_rects[i].y1;
669                                 dest_rects[i].y1 = src_rects[i].x1;
670                                 dest_rects[i].x2 = src_rects[i].y2;
671                                 dest_rects[i].y2 = src_rects[i].x2;
672                                 break;
673                         }
674                 }
675         }
676
677         if (scale != 1) {
678                 for (i = 0; i < nrects; i++) {
679                         dest_rects[i].x1 *= scale;
680                         dest_rects[i].x2 *= scale;
681                         dest_rects[i].y1 *= scale;
682                         dest_rects[i].y2 *= scale;
683                 }
684         }
685
686         pixman_region32_clear(dest);
687         pixman_region32_init_rects(dest, dest_rects, nrects);
688         free(dest_rects);
689 }
690
691 static void
692 scaler_surface_to_buffer(struct weston_surface *surface,
693                          float sx, float sy, float *bx, float *by)
694 {
695         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
696         double src_width, src_height;
697         double src_x, src_y;
698
699         if (vp->buffer.src_width == wl_fixed_from_int(-1)) {
700                 if (vp->surface.width == -1) {
701                         *bx = sx;
702                         *by = sy;
703                         return;
704                 }
705
706                 src_x = 0.0;
707                 src_y = 0.0;
708                 src_width = surface->width_from_buffer;
709                 src_height = surface->height_from_buffer;
710         } else {
711                 src_x = wl_fixed_to_double(vp->buffer.src_x);
712                 src_y = wl_fixed_to_double(vp->buffer.src_y);
713                 src_width = wl_fixed_to_double(vp->buffer.src_width);
714                 src_height = wl_fixed_to_double(vp->buffer.src_height);
715         }
716
717         *bx = sx * src_width / surface->width + src_x;
718         *by = sy * src_height / surface->height + src_y;
719 }
720
721 WL_EXPORT void
722 weston_surface_to_buffer_float(struct weston_surface *surface,
723                                float sx, float sy, float *bx, float *by)
724 {
725         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
726
727         /* first transform coordinates if the scaler is set */
728         scaler_surface_to_buffer(surface, sx, sy, bx, by);
729
730         weston_transformed_coord(surface->width_from_buffer,
731                                  surface->height_from_buffer,
732                                  vp->buffer.transform, vp->buffer.scale,
733                                  *bx, *by, bx, by);
734 }
735
736 WL_EXPORT void
737 weston_surface_to_buffer(struct weston_surface *surface,
738                          int sx, int sy, int *bx, int *by)
739 {
740         float bxf, byf;
741
742         weston_surface_to_buffer_float(surface,
743                                        sx, sy, &bxf, &byf);
744
745         *bx = floorf(bxf);
746         *by = floorf(byf);
747 }
748
749 WL_EXPORT pixman_box32_t
750 weston_surface_to_buffer_rect(struct weston_surface *surface,
751                               pixman_box32_t rect)
752 {
753         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
754         float xf, yf;
755
756         /* first transform box coordinates if the scaler is set */
757         scaler_surface_to_buffer(surface, rect.x1, rect.y1, &xf, &yf);
758         rect.x1 = floorf(xf);
759         rect.y1 = floorf(yf);
760
761         scaler_surface_to_buffer(surface, rect.x2, rect.y2, &xf, &yf);
762         rect.x2 = floorf(xf);
763         rect.y2 = floorf(yf);
764
765         return weston_transformed_rect(surface->width_from_buffer,
766                                        surface->height_from_buffer,
767                                        vp->buffer.transform, vp->buffer.scale,
768                                        rect);
769 }
770
771 WL_EXPORT void
772 weston_view_move_to_plane(struct weston_view *view,
773                              struct weston_plane *plane)
774 {
775         if (view->plane == plane)
776                 return;
777
778         weston_view_damage_below(view);
779         view->plane = plane;
780         weston_surface_damage(view->surface);
781 }
782
783 WL_EXPORT void
784 weston_view_damage_below(struct weston_view *view)
785 {
786         pixman_region32_t damage;
787
788         pixman_region32_init(&damage);
789         pixman_region32_subtract(&damage, &view->transform.masked_boundingbox,
790                                  &view->clip);
791         if (view->plane)
792                 pixman_region32_union(&view->plane->damage,
793                                       &view->plane->damage, &damage);
794         pixman_region32_fini(&damage);
795         weston_view_schedule_repaint(view);
796 }
797
798 static void
799 weston_surface_update_output_mask(struct weston_surface *es, uint32_t mask)
800 {
801         uint32_t different = es->output_mask ^ mask;
802         uint32_t entered = mask & different;
803         uint32_t left = es->output_mask & different;
804         struct weston_output *output;
805         struct wl_resource *resource = NULL;
806         struct wl_client *client;
807
808         es->output_mask = mask;
809         if (es->resource == NULL)
810                 return;
811         if (different == 0)
812                 return;
813
814         client = wl_resource_get_client(es->resource);
815
816         wl_list_for_each(output, &es->compositor->output_list, link) {
817                 if (1 << output->id & different)
818                         resource =
819                                 wl_resource_find_for_client(&output->resource_list,
820                                                          client);
821                 if (resource == NULL)
822                         continue;
823                 if (1 << output->id & entered)
824                         wl_surface_send_enter(es->resource, resource);
825                 if (1 << output->id & left)
826                         wl_surface_send_leave(es->resource, resource);
827         }
828 }
829
830
831 static void
832 weston_surface_assign_output(struct weston_surface *es)
833 {
834         struct weston_output *new_output;
835         struct weston_view *view;
836         pixman_region32_t region;
837         uint32_t max, area, mask;
838         pixman_box32_t *e;
839
840         new_output = NULL;
841         max = 0;
842         mask = 0;
843         pixman_region32_init(&region);
844         wl_list_for_each(view, &es->views, surface_link) {
845                 if (!view->output)
846                         continue;
847
848                 pixman_region32_intersect(&region, &view->transform.boundingbox,
849                                           &view->output->region);
850
851                 e = pixman_region32_extents(&region);
852                 area = (e->x2 - e->x1) * (e->y2 - e->y1);
853
854                 mask |= view->output_mask;
855
856                 if (area >= max) {
857                         new_output = view->output;
858                         max = area;
859                 }
860         }
861         pixman_region32_fini(&region);
862
863         es->output = new_output;
864         weston_surface_update_output_mask(es, mask);
865 }
866
867 static void
868 weston_view_assign_output(struct weston_view *ev)
869 {
870         struct weston_compositor *ec = ev->surface->compositor;
871         struct weston_output *output, *new_output;
872         pixman_region32_t region;
873         uint32_t max, area, mask;
874         pixman_box32_t *e;
875
876         new_output = NULL;
877         max = 0;
878         mask = 0;
879         pixman_region32_init(&region);
880         wl_list_for_each(output, &ec->output_list, link) {
881                 pixman_region32_intersect(&region, &ev->transform.boundingbox,
882                                           &output->region);
883
884                 e = pixman_region32_extents(&region);
885                 area = (e->x2 - e->x1) * (e->y2 - e->y1);
886
887                 if (area > 0)
888                         mask |= 1 << output->id;
889
890                 if (area >= max) {
891                         new_output = output;
892                         max = area;
893                 }
894         }
895         pixman_region32_fini(&region);
896
897         ev->output = new_output;
898         ev->output_mask = mask;
899
900         weston_surface_assign_output(ev->surface);
901 }
902
903 static void
904 view_compute_bbox(struct weston_view *view, int32_t sx, int32_t sy,
905                   int32_t width, int32_t height,
906                   pixman_region32_t *bbox)
907 {
908         float min_x = HUGE_VALF,  min_y = HUGE_VALF;
909         float max_x = -HUGE_VALF, max_y = -HUGE_VALF;
910         int32_t s[4][2] = {
911                 { sx,         sy },
912                 { sx,         sy + height },
913                 { sx + width, sy },
914                 { sx + width, sy + height }
915         };
916         float int_x, int_y;
917         int i;
918
919         if (width == 0 || height == 0) {
920                 /* avoid rounding empty bbox to 1x1 */
921                 pixman_region32_init(bbox);
922                 return;
923         }
924
925         for (i = 0; i < 4; ++i) {
926                 float x, y;
927                 weston_view_to_global_float(view, s[i][0], s[i][1], &x, &y);
928                 if (x < min_x)
929                         min_x = x;
930                 if (x > max_x)
931                         max_x = x;
932                 if (y < min_y)
933                         min_y = y;
934                 if (y > max_y)
935                         max_y = y;
936         }
937
938         int_x = floorf(min_x);
939         int_y = floorf(min_y);
940         pixman_region32_init_rect(bbox, int_x, int_y,
941                                   ceilf(max_x) - int_x, ceilf(max_y) - int_y);
942 }
943
944 static void
945 weston_view_update_transform_disable(struct weston_view *view)
946 {
947         view->transform.enabled = 0;
948
949         /* round off fractions when not transformed */
950         view->geometry.x = roundf(view->geometry.x);
951         view->geometry.y = roundf(view->geometry.y);
952
953         /* Otherwise identity matrix, but with x and y translation. */
954         view->transform.position.matrix.type = WESTON_MATRIX_TRANSFORM_TRANSLATE;
955         view->transform.position.matrix.d[12] = view->geometry.x;
956         view->transform.position.matrix.d[13] = view->geometry.y;
957
958         view->transform.matrix = view->transform.position.matrix;
959
960         view->transform.inverse = view->transform.position.matrix;
961         view->transform.inverse.d[12] = -view->geometry.x;
962         view->transform.inverse.d[13] = -view->geometry.y;
963
964         pixman_region32_init_rect(&view->transform.boundingbox,
965                                   view->geometry.x,
966                                   view->geometry.y,
967                                   view->surface->width,
968                                   view->surface->height);
969
970         if (view->alpha == 1.0) {
971                 pixman_region32_copy(&view->transform.opaque,
972                                      &view->surface->opaque);
973                 pixman_region32_translate(&view->transform.opaque,
974                                           view->geometry.x,
975                                           view->geometry.y);
976         }
977 }
978
979 static int
980 weston_view_update_transform_enable(struct weston_view *view)
981 {
982         struct weston_view *parent = view->geometry.parent;
983         struct weston_matrix *matrix = &view->transform.matrix;
984         struct weston_matrix *inverse = &view->transform.inverse;
985         struct weston_transform *tform;
986
987         view->transform.enabled = 1;
988
989         /* Otherwise identity matrix, but with x and y translation. */
990         view->transform.position.matrix.type = WESTON_MATRIX_TRANSFORM_TRANSLATE;
991         view->transform.position.matrix.d[12] = view->geometry.x;
992         view->transform.position.matrix.d[13] = view->geometry.y;
993
994         weston_matrix_init(matrix);
995         wl_list_for_each(tform, &view->geometry.transformation_list, link)
996                 weston_matrix_multiply(matrix, &tform->matrix);
997
998         if (parent)
999                 weston_matrix_multiply(matrix, &parent->transform.matrix);
1000
1001         if (weston_matrix_invert(inverse, matrix) < 0) {
1002                 /* Oops, bad total transformation, not invertible */
1003                 weston_log("error: weston_view %p"
1004                         " transformation not invertible.\n", view);
1005                 return -1;
1006         }
1007
1008         view_compute_bbox(view, 0, 0,
1009                           view->surface->width, view->surface->height,
1010                           &view->transform.boundingbox);
1011
1012         return 0;
1013 }
1014
1015 static struct weston_layer *
1016 get_view_layer(struct weston_view *view)
1017 {
1018         if (view->parent_view)
1019                 return get_view_layer(view->parent_view);
1020         return view->layer_link.layer;
1021 }
1022
1023 WL_EXPORT void
1024 weston_view_update_transform(struct weston_view *view)
1025 {
1026         struct weston_view *parent = view->geometry.parent;
1027         struct weston_layer *layer;
1028         pixman_region32_t mask;
1029
1030         if (!view->transform.dirty)
1031                 return;
1032
1033         if (parent)
1034                 weston_view_update_transform(parent);
1035
1036         view->transform.dirty = 0;
1037
1038         weston_view_damage_below(view);
1039
1040         pixman_region32_fini(&view->transform.boundingbox);
1041         pixman_region32_fini(&view->transform.opaque);
1042         pixman_region32_init(&view->transform.opaque);
1043
1044         /* transform.position is always in transformation_list */
1045         if (view->geometry.transformation_list.next ==
1046             &view->transform.position.link &&
1047             view->geometry.transformation_list.prev ==
1048             &view->transform.position.link &&
1049             !parent) {
1050                 weston_view_update_transform_disable(view);
1051         } else {
1052                 if (weston_view_update_transform_enable(view) < 0)
1053                         weston_view_update_transform_disable(view);
1054         }
1055
1056         layer = get_view_layer(view);
1057         if (layer) {
1058                 pixman_region32_init_with_extents(&mask, &layer->mask);
1059                 pixman_region32_intersect(&view->transform.masked_boundingbox,
1060                                         &view->transform.boundingbox, &mask);
1061                 pixman_region32_intersect(&view->transform.masked_opaque,
1062                                         &view->transform.opaque, &mask);
1063                 pixman_region32_fini(&mask);
1064         }
1065
1066         weston_view_damage_below(view);
1067
1068         weston_view_assign_output(view);
1069
1070         wl_signal_emit(&view->surface->compositor->transform_signal,
1071                        view->surface);
1072 }
1073
1074 WL_EXPORT void
1075 weston_view_geometry_dirty(struct weston_view *view)
1076 {
1077         struct weston_view *child;
1078
1079         /*
1080          * The invariant: if view->geometry.dirty, then all views
1081          * in view->geometry.child_list have geometry.dirty too.
1082          * Corollary: if not parent->geometry.dirty, then all ancestors
1083          * are not dirty.
1084          */
1085
1086         if (view->transform.dirty)
1087                 return;
1088
1089         view->transform.dirty = 1;
1090
1091         wl_list_for_each(child, &view->geometry.child_list,
1092                          geometry.parent_link)
1093                 weston_view_geometry_dirty(child);
1094 }
1095
1096 WL_EXPORT void
1097 weston_view_to_global_fixed(struct weston_view *view,
1098                             wl_fixed_t vx, wl_fixed_t vy,
1099                             wl_fixed_t *x, wl_fixed_t *y)
1100 {
1101         float xf, yf;
1102
1103         weston_view_to_global_float(view,
1104                                     wl_fixed_to_double(vx),
1105                                     wl_fixed_to_double(vy),
1106                                     &xf, &yf);
1107         *x = wl_fixed_from_double(xf);
1108         *y = wl_fixed_from_double(yf);
1109 }
1110
1111 WL_EXPORT void
1112 weston_view_from_global_float(struct weston_view *view,
1113                               float x, float y, float *vx, float *vy)
1114 {
1115         if (view->transform.enabled) {
1116                 struct weston_vector v = { { x, y, 0.0f, 1.0f } };
1117
1118                 weston_matrix_transform(&view->transform.inverse, &v);
1119
1120                 if (fabsf(v.f[3]) < 1e-6) {
1121                         weston_log("warning: numerical instability in "
1122                                 "weston_view_from_global(), divisor = %g\n",
1123                                 v.f[3]);
1124                         *vx = 0;
1125                         *vy = 0;
1126                         return;
1127                 }
1128
1129                 *vx = v.f[0] / v.f[3];
1130                 *vy = v.f[1] / v.f[3];
1131         } else {
1132                 *vx = x - view->geometry.x;
1133                 *vy = y - view->geometry.y;
1134         }
1135 }
1136
1137 WL_EXPORT void
1138 weston_view_from_global_fixed(struct weston_view *view,
1139                               wl_fixed_t x, wl_fixed_t y,
1140                               wl_fixed_t *vx, wl_fixed_t *vy)
1141 {
1142         float vxf, vyf;
1143
1144         weston_view_from_global_float(view,
1145                                       wl_fixed_to_double(x),
1146                                       wl_fixed_to_double(y),
1147                                       &vxf, &vyf);
1148         *vx = wl_fixed_from_double(vxf);
1149         *vy = wl_fixed_from_double(vyf);
1150 }
1151
1152 WL_EXPORT void
1153 weston_view_from_global(struct weston_view *view,
1154                         int32_t x, int32_t y, int32_t *vx, int32_t *vy)
1155 {
1156         float vxf, vyf;
1157
1158         weston_view_from_global_float(view, x, y, &vxf, &vyf);
1159         *vx = floorf(vxf);
1160         *vy = floorf(vyf);
1161 }
1162
1163 WL_EXPORT void
1164 weston_surface_schedule_repaint(struct weston_surface *surface)
1165 {
1166         struct weston_output *output;
1167
1168         wl_list_for_each(output, &surface->compositor->output_list, link)
1169                 if (surface->output_mask & (1 << output->id))
1170                         weston_output_schedule_repaint(output);
1171 }
1172
1173 WL_EXPORT void
1174 weston_view_schedule_repaint(struct weston_view *view)
1175 {
1176         struct weston_output *output;
1177
1178         wl_list_for_each(output, &view->surface->compositor->output_list, link)
1179                 if (view->output_mask & (1 << output->id))
1180                         weston_output_schedule_repaint(output);
1181 }
1182
1183 WL_EXPORT void
1184 weston_surface_damage(struct weston_surface *surface)
1185 {
1186         pixman_region32_union_rect(&surface->damage, &surface->damage,
1187                                    0, 0, surface->width,
1188                                    surface->height);
1189
1190         weston_surface_schedule_repaint(surface);
1191 }
1192
1193 WL_EXPORT void
1194 weston_view_set_position(struct weston_view *view, float x, float y)
1195 {
1196         if (view->geometry.x == x && view->geometry.y == y)
1197                 return;
1198
1199         view->geometry.x = x;
1200         view->geometry.y = y;
1201         weston_view_geometry_dirty(view);
1202 }
1203
1204 static void
1205 transform_parent_handle_parent_destroy(struct wl_listener *listener,
1206                                        void *data)
1207 {
1208         struct weston_view *view =
1209                 container_of(listener, struct weston_view,
1210                              geometry.parent_destroy_listener);
1211
1212         weston_view_set_transform_parent(view, NULL);
1213 }
1214
1215 WL_EXPORT void
1216 weston_view_set_transform_parent(struct weston_view *view,
1217                                     struct weston_view *parent)
1218 {
1219         if (view->geometry.parent) {
1220                 wl_list_remove(&view->geometry.parent_destroy_listener.link);
1221                 wl_list_remove(&view->geometry.parent_link);
1222         }
1223
1224         view->geometry.parent = parent;
1225
1226         view->geometry.parent_destroy_listener.notify =
1227                 transform_parent_handle_parent_destroy;
1228         if (parent) {
1229                 wl_signal_add(&parent->destroy_signal,
1230                               &view->geometry.parent_destroy_listener);
1231                 wl_list_insert(&parent->geometry.child_list,
1232                                &view->geometry.parent_link);
1233         }
1234
1235         weston_view_geometry_dirty(view);
1236 }
1237
1238 WL_EXPORT int
1239 weston_view_is_mapped(struct weston_view *view)
1240 {
1241         if (view->output)
1242                 return 1;
1243         else
1244                 return 0;
1245 }
1246
1247 WL_EXPORT int
1248 weston_surface_is_mapped(struct weston_surface *surface)
1249 {
1250         if (surface->output)
1251                 return 1;
1252         else
1253                 return 0;
1254 }
1255
1256 static void
1257 surface_set_size(struct weston_surface *surface, int32_t width, int32_t height)
1258 {
1259         struct weston_view *view;
1260
1261         if (surface->width == width && surface->height == height)
1262                 return;
1263
1264         surface->width = width;
1265         surface->height = height;
1266
1267         wl_list_for_each(view, &surface->views, surface_link)
1268                 weston_view_geometry_dirty(view);
1269 }
1270
1271 WL_EXPORT void
1272 weston_surface_set_size(struct weston_surface *surface,
1273                         int32_t width, int32_t height)
1274 {
1275         assert(!surface->resource);
1276         surface_set_size(surface, width, height);
1277 }
1278
1279 static int
1280 fixed_round_up_to_int(wl_fixed_t f)
1281 {
1282         return wl_fixed_to_int(wl_fixed_from_int(1) - 1 + f);
1283 }
1284
1285 static void
1286 weston_surface_calculate_size_from_buffer(struct weston_surface *surface)
1287 {
1288         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
1289         int32_t width, height;
1290
1291         if (!surface->buffer_ref.buffer) {
1292                 surface->width_from_buffer = 0;
1293                 surface->height_from_buffer = 0;
1294                 return;
1295         }
1296
1297         switch (vp->buffer.transform) {
1298         case WL_OUTPUT_TRANSFORM_90:
1299         case WL_OUTPUT_TRANSFORM_270:
1300         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1301         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1302                 width = surface->buffer_ref.buffer->height / vp->buffer.scale;
1303                 height = surface->buffer_ref.buffer->width / vp->buffer.scale;
1304                 break;
1305         default:
1306                 width = surface->buffer_ref.buffer->width / vp->buffer.scale;
1307                 height = surface->buffer_ref.buffer->height / vp->buffer.scale;
1308                 break;
1309         }
1310
1311         surface->width_from_buffer = width;
1312         surface->height_from_buffer = height;
1313 }
1314
1315 static void
1316 weston_surface_update_size(struct weston_surface *surface)
1317 {
1318         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
1319         int32_t width, height;
1320
1321         width = surface->width_from_buffer;
1322         height = surface->height_from_buffer;
1323
1324         if (width != 0 && vp->surface.width != -1) {
1325                 surface_set_size(surface,
1326                                  vp->surface.width, vp->surface.height);
1327                 return;
1328         }
1329
1330         if (width != 0 && vp->buffer.src_width != wl_fixed_from_int(-1)) {
1331                 int32_t w = fixed_round_up_to_int(vp->buffer.src_width);
1332                 int32_t h = fixed_round_up_to_int(vp->buffer.src_height);
1333
1334                 surface_set_size(surface, w ?: 1, h ?: 1);
1335                 return;
1336         }
1337
1338         surface_set_size(surface, width, height);
1339 }
1340
1341 WL_EXPORT uint32_t
1342 weston_compositor_get_time(void)
1343 {
1344        struct timeval tv;
1345
1346        gettimeofday(&tv, NULL);
1347
1348        return tv.tv_sec * 1000 + tv.tv_usec / 1000;
1349 }
1350
1351 WL_EXPORT struct weston_view *
1352 weston_compositor_pick_view(struct weston_compositor *compositor,
1353                             wl_fixed_t x, wl_fixed_t y,
1354                             wl_fixed_t *vx, wl_fixed_t *vy)
1355 {
1356         struct weston_view *view;
1357         int ix = wl_fixed_to_int(x);
1358         int iy = wl_fixed_to_int(y);
1359
1360         wl_list_for_each(view, &compositor->view_list, link) {
1361                 weston_view_from_global_fixed(view, x, y, vx, vy);
1362                 if (pixman_region32_contains_point(
1363                         &view->transform.masked_boundingbox,
1364                                                    ix, iy, NULL) &&
1365                     pixman_region32_contains_point(&view->surface->input,
1366                                                    wl_fixed_to_int(*vx),
1367                                                    wl_fixed_to_int(*vy),
1368                                                    NULL))
1369                         return view;
1370         }
1371
1372         return NULL;
1373 }
1374
1375 static void
1376 weston_compositor_repick(struct weston_compositor *compositor)
1377 {
1378         struct weston_seat *seat;
1379
1380         if (!compositor->session_active)
1381                 return;
1382
1383         wl_list_for_each(seat, &compositor->seat_list, link)
1384                 weston_seat_repick(seat);
1385 }
1386
1387 WL_EXPORT void
1388 weston_view_unmap(struct weston_view *view)
1389 {
1390         struct weston_seat *seat;
1391
1392         if (!weston_view_is_mapped(view))
1393                 return;
1394
1395         weston_view_damage_below(view);
1396         view->output = NULL;
1397         view->plane = NULL;
1398         weston_layer_entry_remove(&view->layer_link);
1399         wl_list_remove(&view->link);
1400         wl_list_init(&view->link);
1401         view->output_mask = 0;
1402         weston_surface_assign_output(view->surface);
1403
1404         if (weston_surface_is_mapped(view->surface))
1405                 return;
1406
1407         wl_list_for_each(seat, &view->surface->compositor->seat_list, link) {
1408                 if (seat->keyboard && seat->keyboard->focus == view->surface)
1409                         weston_keyboard_set_focus(seat->keyboard, NULL);
1410                 if (seat->pointer && seat->pointer->focus == view)
1411                         weston_pointer_set_focus(seat->pointer,
1412                                                  NULL,
1413                                                  wl_fixed_from_int(0),
1414                                                  wl_fixed_from_int(0));
1415                 if (seat->touch && seat->touch->focus == view)
1416                         weston_touch_set_focus(seat, NULL);
1417         }
1418 }
1419
1420 WL_EXPORT void
1421 weston_surface_unmap(struct weston_surface *surface)
1422 {
1423         struct weston_view *view;
1424
1425         wl_list_for_each(view, &surface->views, surface_link)
1426                 weston_view_unmap(view);
1427         surface->output = NULL;
1428 }
1429
1430 static void
1431 weston_surface_reset_pending_buffer(struct weston_surface *surface)
1432 {
1433         weston_surface_state_set_buffer(&surface->pending, NULL);
1434         surface->pending.sx = 0;
1435         surface->pending.sy = 0;
1436         surface->pending.newly_attached = 0;
1437         surface->pending.buffer_viewport.changed = 0;
1438 }
1439
1440 WL_EXPORT void
1441 weston_view_destroy(struct weston_view *view)
1442 {
1443         wl_signal_emit(&view->destroy_signal, view);
1444
1445         assert(wl_list_empty(&view->geometry.child_list));
1446
1447         if (weston_view_is_mapped(view)) {
1448                 weston_view_unmap(view);
1449                 weston_compositor_build_view_list(view->surface->compositor);
1450         }
1451
1452         wl_list_remove(&view->link);
1453         weston_layer_entry_remove(&view->layer_link);
1454
1455         pixman_region32_fini(&view->clip);
1456         pixman_region32_fini(&view->transform.boundingbox);
1457         pixman_region32_fini(&view->transform.masked_boundingbox);
1458         pixman_region32_fini(&view->transform.masked_opaque);
1459
1460         weston_view_set_transform_parent(view, NULL);
1461
1462         wl_list_remove(&view->surface_link);
1463
1464         free(view);
1465 }
1466
1467 WL_EXPORT void
1468 weston_surface_destroy(struct weston_surface *surface)
1469 {
1470         struct weston_frame_callback *cb, *next;
1471         struct weston_view *ev, *nv;
1472
1473         if (--surface->ref_count > 0)
1474                 return;
1475
1476         wl_signal_emit(&surface->destroy_signal, &surface->resource);
1477
1478         assert(wl_list_empty(&surface->subsurface_list_pending));
1479         assert(wl_list_empty(&surface->subsurface_list));
1480
1481         wl_list_for_each_safe(ev, nv, &surface->views, surface_link)
1482                 weston_view_destroy(ev);
1483
1484         weston_surface_state_fini(&surface->pending);
1485
1486         weston_buffer_reference(&surface->buffer_ref, NULL);
1487
1488         pixman_region32_fini(&surface->damage);
1489         pixman_region32_fini(&surface->opaque);
1490         pixman_region32_fini(&surface->input);
1491
1492         wl_list_for_each_safe(cb, next, &surface->frame_callback_list, link)
1493                 wl_resource_destroy(cb->resource);
1494
1495         free(surface);
1496 }
1497
1498 static void
1499 destroy_surface(struct wl_resource *resource)
1500 {
1501         struct weston_surface *surface = wl_resource_get_user_data(resource);
1502
1503         /* Set the resource to NULL, since we don't want to leave a
1504          * dangling pointer if the surface was refcounted and survives
1505          * the weston_surface_destroy() call. */
1506         surface->resource = NULL;
1507         weston_surface_destroy(surface);
1508 }
1509
1510 static void
1511 weston_buffer_destroy_handler(struct wl_listener *listener, void *data)
1512 {
1513         struct weston_buffer *buffer =
1514                 container_of(listener, struct weston_buffer, destroy_listener);
1515
1516         wl_signal_emit(&buffer->destroy_signal, buffer);
1517         free(buffer);
1518 }
1519
1520 WL_EXPORT struct weston_buffer *
1521 weston_buffer_from_resource(struct wl_resource *resource)
1522 {
1523         struct weston_buffer *buffer;
1524         struct wl_listener *listener;
1525
1526         listener = wl_resource_get_destroy_listener(resource,
1527                                                     weston_buffer_destroy_handler);
1528
1529         if (listener)
1530                 return container_of(listener, struct weston_buffer,
1531                                     destroy_listener);
1532
1533         buffer = zalloc(sizeof *buffer);
1534         if (buffer == NULL)
1535                 return NULL;
1536
1537         buffer->resource = resource;
1538         wl_signal_init(&buffer->destroy_signal);
1539         buffer->destroy_listener.notify = weston_buffer_destroy_handler;
1540         buffer->y_inverted = 1;
1541         wl_resource_add_destroy_listener(resource, &buffer->destroy_listener);
1542
1543         return buffer;
1544 }
1545
1546 static void
1547 weston_buffer_reference_handle_destroy(struct wl_listener *listener,
1548                                        void *data)
1549 {
1550         struct weston_buffer_reference *ref =
1551                 container_of(listener, struct weston_buffer_reference,
1552                              destroy_listener);
1553
1554         assert((struct weston_buffer *)data == ref->buffer);
1555         ref->buffer = NULL;
1556 }
1557
1558 WL_EXPORT void
1559 weston_buffer_reference(struct weston_buffer_reference *ref,
1560                         struct weston_buffer *buffer)
1561 {
1562         if (ref->buffer && buffer != ref->buffer) {
1563                 ref->buffer->busy_count--;
1564                 if (ref->buffer->busy_count == 0) {
1565                         assert(wl_resource_get_client(ref->buffer->resource));
1566                         wl_resource_queue_event(ref->buffer->resource,
1567                                                 WL_BUFFER_RELEASE);
1568                 }
1569                 wl_list_remove(&ref->destroy_listener.link);
1570         }
1571
1572         if (buffer && buffer != ref->buffer) {
1573                 buffer->busy_count++;
1574                 wl_signal_add(&buffer->destroy_signal,
1575                               &ref->destroy_listener);
1576         }
1577
1578         ref->buffer = buffer;
1579         ref->destroy_listener.notify = weston_buffer_reference_handle_destroy;
1580 }
1581
1582 static void
1583 weston_surface_attach(struct weston_surface *surface,
1584                       struct weston_buffer *buffer)
1585 {
1586         weston_buffer_reference(&surface->buffer_ref, buffer);
1587
1588         if (!buffer) {
1589                 if (weston_surface_is_mapped(surface))
1590                         weston_surface_unmap(surface);
1591         }
1592
1593         surface->compositor->renderer->attach(surface, buffer);
1594
1595         weston_surface_calculate_size_from_buffer(surface);
1596 }
1597
1598 WL_EXPORT void
1599 weston_compositor_damage_all(struct weston_compositor *compositor)
1600 {
1601         struct weston_output *output;
1602
1603         wl_list_for_each(output, &compositor->output_list, link)
1604                 weston_output_damage(output);
1605 }
1606
1607 WL_EXPORT void
1608 weston_output_damage(struct weston_output *output)
1609 {
1610         struct weston_compositor *compositor = output->compositor;
1611
1612         pixman_region32_union(&compositor->primary_plane.damage,
1613                               &compositor->primary_plane.damage,
1614                               &output->region);
1615         weston_output_schedule_repaint(output);
1616 }
1617
1618 static void
1619 surface_flush_damage(struct weston_surface *surface)
1620 {
1621         if (surface->buffer_ref.buffer &&
1622             wl_shm_buffer_get(surface->buffer_ref.buffer->resource))
1623                 surface->compositor->renderer->flush_damage(surface);
1624
1625         pixman_region32_clear(&surface->damage);
1626 }
1627
1628 static void
1629 view_accumulate_damage(struct weston_view *view,
1630                        pixman_region32_t *opaque)
1631 {
1632         pixman_region32_t damage;
1633
1634         pixman_region32_init(&damage);
1635         if (view->transform.enabled) {
1636                 pixman_box32_t *extents;
1637
1638                 extents = pixman_region32_extents(&view->surface->damage);
1639                 view_compute_bbox(view, extents->x1, extents->y1,
1640                                   extents->x2 - extents->x1,
1641                                   extents->y2 - extents->y1,
1642                                   &damage);
1643                 pixman_region32_translate(&damage,
1644                                           -view->plane->x,
1645                                           -view->plane->y);
1646         } else {
1647                 pixman_region32_copy(&damage, &view->surface->damage);
1648                 pixman_region32_translate(&damage,
1649                                           view->geometry.x - view->plane->x,
1650                                           view->geometry.y - view->plane->y);
1651         }
1652
1653         pixman_region32_subtract(&damage, &damage, opaque);
1654         pixman_region32_union(&view->plane->damage,
1655                               &view->plane->damage, &damage);
1656         pixman_region32_fini(&damage);
1657         pixman_region32_copy(&view->clip, opaque);
1658         pixman_region32_union(opaque, opaque, &view->transform.masked_opaque);
1659 }
1660
1661 static void
1662 compositor_accumulate_damage(struct weston_compositor *ec)
1663 {
1664         struct weston_plane *plane;
1665         struct weston_view *ev;
1666         pixman_region32_t opaque, clip;
1667
1668         pixman_region32_init(&clip);
1669
1670         wl_list_for_each(plane, &ec->plane_list, link) {
1671                 pixman_region32_copy(&plane->clip, &clip);
1672
1673                 pixman_region32_init(&opaque);
1674
1675                 wl_list_for_each(ev, &ec->view_list, link) {
1676                         if (ev->plane != plane)
1677                                 continue;
1678
1679                         view_accumulate_damage(ev, &opaque);
1680                 }
1681
1682                 pixman_region32_union(&clip, &clip, &opaque);
1683                 pixman_region32_fini(&opaque);
1684         }
1685
1686         pixman_region32_fini(&clip);
1687
1688         wl_list_for_each(ev, &ec->view_list, link)
1689                 ev->surface->touched = 0;
1690
1691         wl_list_for_each(ev, &ec->view_list, link) {
1692                 if (ev->surface->touched)
1693                         continue;
1694                 ev->surface->touched = 1;
1695
1696                 surface_flush_damage(ev->surface);
1697
1698                 /* Both the renderer and the backend have seen the buffer
1699                  * by now. If renderer needs the buffer, it has its own
1700                  * reference set. If the backend wants to keep the buffer
1701                  * around for migrating the surface into a non-primary plane
1702                  * later, keep_buffer is true. Otherwise, drop the core
1703                  * reference now, and allow early buffer release. This enables
1704                  * clients to use single-buffering.
1705                  */
1706                 if (!ev->surface->keep_buffer)
1707                         weston_buffer_reference(&ev->surface->buffer_ref, NULL);
1708         }
1709 }
1710
1711 static void
1712 surface_stash_subsurface_views(struct weston_surface *surface)
1713 {
1714         struct weston_subsurface *sub;
1715
1716         wl_list_for_each(sub, &surface->subsurface_list, parent_link) {
1717                 if (sub->surface == surface)
1718                         continue;
1719
1720                 wl_list_insert_list(&sub->unused_views, &sub->surface->views);
1721                 wl_list_init(&sub->surface->views);
1722
1723                 surface_stash_subsurface_views(sub->surface);
1724         }
1725 }
1726
1727 static void
1728 surface_free_unused_subsurface_views(struct weston_surface *surface)
1729 {
1730         struct weston_subsurface *sub;
1731         struct weston_view *view, *nv;
1732
1733         wl_list_for_each(sub, &surface->subsurface_list, parent_link) {
1734                 if (sub->surface == surface)
1735                         continue;
1736
1737                 wl_list_for_each_safe(view, nv, &sub->unused_views, surface_link) {
1738                         weston_view_unmap (view);
1739                         weston_view_destroy(view);
1740                 }
1741
1742                 surface_free_unused_subsurface_views(sub->surface);
1743         }
1744 }
1745
1746 static void
1747 view_list_add_subsurface_view(struct weston_compositor *compositor,
1748                               struct weston_subsurface *sub,
1749                               struct weston_view *parent)
1750 {
1751         struct weston_subsurface *child;
1752         struct weston_view *view = NULL, *iv;
1753
1754         wl_list_for_each(iv, &sub->unused_views, surface_link) {
1755                 if (iv->geometry.parent == parent) {
1756                         view = iv;
1757                         break;
1758                 }
1759         }
1760
1761         if (view) {
1762                 /* Put it back in the surface's list of views */
1763                 wl_list_remove(&view->surface_link);
1764                 wl_list_insert(&sub->surface->views, &view->surface_link);
1765         } else {
1766                 view = weston_view_create(sub->surface);
1767                 weston_view_set_position(view,
1768                                          sub->position.x,
1769                                          sub->position.y);
1770                 weston_view_set_transform_parent(view, parent);
1771         }
1772
1773         view->parent_view = parent;
1774         weston_view_update_transform(view);
1775
1776         if (wl_list_empty(&sub->surface->subsurface_list)) {
1777                 wl_list_insert(compositor->view_list.prev, &view->link);
1778                 return;
1779         }
1780
1781         wl_list_for_each(child, &sub->surface->subsurface_list, parent_link) {
1782                 if (child->surface == sub->surface)
1783                         wl_list_insert(compositor->view_list.prev, &view->link);
1784                 else
1785                         view_list_add_subsurface_view(compositor, child, view);
1786         }
1787 }
1788
1789 static void
1790 view_list_add(struct weston_compositor *compositor,
1791               struct weston_view *view)
1792 {
1793         struct weston_subsurface *sub;
1794
1795         weston_view_update_transform(view);
1796
1797         if (wl_list_empty(&view->surface->subsurface_list)) {
1798                 wl_list_insert(compositor->view_list.prev, &view->link);
1799                 return;
1800         }
1801
1802         wl_list_for_each(sub, &view->surface->subsurface_list, parent_link) {
1803                 if (sub->surface == view->surface)
1804                         wl_list_insert(compositor->view_list.prev, &view->link);
1805                 else
1806                         view_list_add_subsurface_view(compositor, sub, view);
1807         }
1808 }
1809
1810 static void
1811 weston_compositor_build_view_list(struct weston_compositor *compositor)
1812 {
1813         struct weston_view *view;
1814         struct weston_layer *layer;
1815
1816         wl_list_for_each(layer, &compositor->layer_list, link)
1817                 wl_list_for_each(view, &layer->view_list.link, layer_link.link)
1818                         surface_stash_subsurface_views(view->surface);
1819
1820         wl_list_init(&compositor->view_list);
1821         wl_list_for_each(layer, &compositor->layer_list, link) {
1822                 wl_list_for_each(view, &layer->view_list.link, layer_link.link) {
1823                         view_list_add(compositor, view);
1824                 }
1825         }
1826
1827         wl_list_for_each(layer, &compositor->layer_list, link)
1828                 wl_list_for_each(view, &layer->view_list.link, layer_link.link)
1829                         surface_free_unused_subsurface_views(view->surface);
1830 }
1831
1832 static int
1833 weston_output_repaint(struct weston_output *output, uint32_t msecs)
1834 {
1835         struct weston_compositor *ec = output->compositor;
1836         struct weston_view *ev;
1837         struct weston_animation *animation, *next;
1838         struct weston_frame_callback *cb, *cnext;
1839         struct wl_list frame_callback_list;
1840         pixman_region32_t output_damage;
1841         int r;
1842
1843         if (output->destroying)
1844                 return 0;
1845
1846         /* Rebuild the surface list and update surface transforms up front. */
1847         weston_compositor_build_view_list(ec);
1848
1849         if (output->assign_planes && !output->disable_planes)
1850                 output->assign_planes(output);
1851         else
1852                 wl_list_for_each(ev, &ec->view_list, link)
1853                         weston_view_move_to_plane(ev, &ec->primary_plane);
1854
1855         wl_list_init(&frame_callback_list);
1856         wl_list_for_each(ev, &ec->view_list, link) {
1857                 /* Note: This operation is safe to do multiple times on the
1858                  * same surface.
1859                  */
1860                 if (ev->surface->output == output) {
1861                         wl_list_insert_list(&frame_callback_list,
1862                                             &ev->surface->frame_callback_list);
1863                         wl_list_init(&ev->surface->frame_callback_list);
1864                 }
1865         }
1866
1867         compositor_accumulate_damage(ec);
1868
1869         pixman_region32_init(&output_damage);
1870         pixman_region32_intersect(&output_damage,
1871                                   &ec->primary_plane.damage, &output->region);
1872         pixman_region32_subtract(&output_damage,
1873                                  &output_damage, &ec->primary_plane.clip);
1874
1875         if (output->dirty)
1876                 weston_output_update_matrix(output);
1877
1878         r = output->repaint(output, &output_damage);
1879
1880         pixman_region32_fini(&output_damage);
1881
1882         output->repaint_needed = 0;
1883
1884         weston_compositor_repick(ec);
1885         wl_event_loop_dispatch(ec->input_loop, 0);
1886
1887         wl_list_for_each_safe(cb, cnext, &frame_callback_list, link) {
1888                 wl_callback_send_done(cb->resource, msecs);
1889                 wl_resource_destroy(cb->resource);
1890         }
1891
1892         wl_list_for_each_safe(animation, next, &output->animation_list, link) {
1893                 animation->frame_counter++;
1894                 animation->frame(animation, output, msecs);
1895         }
1896
1897         return r;
1898 }
1899
1900 static int
1901 weston_compositor_read_input(int fd, uint32_t mask, void *data)
1902 {
1903         struct weston_compositor *compositor = data;
1904
1905         wl_event_loop_dispatch(compositor->input_loop, 0);
1906
1907         return 1;
1908 }
1909
1910 WL_EXPORT void
1911 weston_output_finish_frame(struct weston_output *output, uint32_t msecs)
1912 {
1913         struct weston_compositor *compositor = output->compositor;
1914         struct wl_event_loop *loop =
1915                 wl_display_get_event_loop(compositor->wl_display);
1916         int fd, r;
1917
1918         output->frame_time = msecs;
1919
1920         if (output->repaint_needed &&
1921             compositor->state != WESTON_COMPOSITOR_SLEEPING &&
1922             compositor->state != WESTON_COMPOSITOR_OFFSCREEN) {
1923                 r = weston_output_repaint(output, msecs);
1924                 if (!r)
1925                         return;
1926         }
1927
1928         output->repaint_scheduled = 0;
1929         if (compositor->input_loop_source)
1930                 return;
1931
1932         fd = wl_event_loop_get_fd(compositor->input_loop);
1933         compositor->input_loop_source =
1934                 wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
1935                                      weston_compositor_read_input, compositor);
1936 }
1937
1938 static void
1939 idle_repaint(void *data)
1940 {
1941         struct weston_output *output = data;
1942
1943         output->start_repaint_loop(output);
1944 }
1945
1946 WL_EXPORT void
1947 weston_layer_entry_insert(struct weston_layer_entry *list,
1948                           struct weston_layer_entry *entry)
1949 {
1950         wl_list_insert(&list->link, &entry->link);
1951         entry->layer = list->layer;
1952 }
1953
1954 WL_EXPORT void
1955 weston_layer_entry_remove(struct weston_layer_entry *entry)
1956 {
1957         wl_list_remove(&entry->link);
1958         wl_list_init(&entry->link);
1959         entry->layer = NULL;
1960 }
1961
1962 WL_EXPORT void
1963 weston_layer_init(struct weston_layer *layer, struct wl_list *below)
1964 {
1965         wl_list_init(&layer->view_list.link);
1966         layer->view_list.layer = layer;
1967         weston_layer_set_mask_infinite(layer);
1968         if (below != NULL)
1969                 wl_list_insert(below, &layer->link);
1970 }
1971
1972 WL_EXPORT void
1973 weston_layer_set_mask(struct weston_layer *layer,
1974                       int x, int y, int width, int height)
1975 {
1976         struct weston_view *view;
1977
1978         layer->mask.x1 = x;
1979         layer->mask.x2 = x + width;
1980         layer->mask.y1 = y;
1981         layer->mask.y2 = y + height;
1982
1983         wl_list_for_each(view, &layer->view_list.link, layer_link.link) {
1984                 weston_view_geometry_dirty(view);
1985         }
1986 }
1987
1988 WL_EXPORT void
1989 weston_layer_set_mask_infinite(struct weston_layer *layer)
1990 {
1991         weston_layer_set_mask(layer, INT32_MIN, INT32_MIN,
1992                                      UINT32_MAX, UINT32_MAX);
1993 }
1994
1995 WL_EXPORT void
1996 weston_output_schedule_repaint(struct weston_output *output)
1997 {
1998         struct weston_compositor *compositor = output->compositor;
1999         struct wl_event_loop *loop;
2000
2001         if (compositor->state == WESTON_COMPOSITOR_SLEEPING ||
2002             compositor->state == WESTON_COMPOSITOR_OFFSCREEN)
2003                 return;
2004
2005         loop = wl_display_get_event_loop(compositor->wl_display);
2006         output->repaint_needed = 1;
2007         if (output->repaint_scheduled)
2008                 return;
2009
2010         wl_event_loop_add_idle(loop, idle_repaint, output);
2011         output->repaint_scheduled = 1;
2012
2013         if (compositor->input_loop_source) {
2014                 wl_event_source_remove(compositor->input_loop_source);
2015                 compositor->input_loop_source = NULL;
2016         }
2017 }
2018
2019 WL_EXPORT void
2020 weston_compositor_schedule_repaint(struct weston_compositor *compositor)
2021 {
2022         struct weston_output *output;
2023
2024         wl_list_for_each(output, &compositor->output_list, link)
2025                 weston_output_schedule_repaint(output);
2026 }
2027
2028 static void
2029 surface_destroy(struct wl_client *client, struct wl_resource *resource)
2030 {
2031         wl_resource_destroy(resource);
2032 }
2033
2034 static void
2035 surface_attach(struct wl_client *client,
2036                struct wl_resource *resource,
2037                struct wl_resource *buffer_resource, int32_t sx, int32_t sy)
2038 {
2039         struct weston_surface *surface = wl_resource_get_user_data(resource);
2040         struct weston_buffer *buffer = NULL;
2041
2042         if (buffer_resource) {
2043                 buffer = weston_buffer_from_resource(buffer_resource);
2044                 if (buffer == NULL) {
2045                         wl_client_post_no_memory(client);
2046                         return;
2047                 }
2048         }
2049
2050         /* Attach, attach, without commit in between does not send
2051          * wl_buffer.release. */
2052         weston_surface_state_set_buffer(&surface->pending, buffer);
2053
2054         surface->pending.sx = sx;
2055         surface->pending.sy = sy;
2056         surface->pending.newly_attached = 1;
2057 }
2058
2059 static void
2060 surface_damage(struct wl_client *client,
2061                struct wl_resource *resource,
2062                int32_t x, int32_t y, int32_t width, int32_t height)
2063 {
2064         struct weston_surface *surface = wl_resource_get_user_data(resource);
2065
2066         pixman_region32_union_rect(&surface->pending.damage,
2067                                    &surface->pending.damage,
2068                                    x, y, width, height);
2069 }
2070
2071 static void
2072 destroy_frame_callback(struct wl_resource *resource)
2073 {
2074         struct weston_frame_callback *cb = wl_resource_get_user_data(resource);
2075
2076         wl_list_remove(&cb->link);
2077         free(cb);
2078 }
2079
2080 static void
2081 surface_frame(struct wl_client *client,
2082               struct wl_resource *resource, uint32_t callback)
2083 {
2084         struct weston_frame_callback *cb;
2085         struct weston_surface *surface = wl_resource_get_user_data(resource);
2086
2087         cb = malloc(sizeof *cb);
2088         if (cb == NULL) {
2089                 wl_resource_post_no_memory(resource);
2090                 return;
2091         }
2092
2093         cb->resource = wl_resource_create(client, &wl_callback_interface, 1,
2094                                           callback);
2095         if (cb->resource == NULL) {
2096                 free(cb);
2097                 wl_resource_post_no_memory(resource);
2098                 return;
2099         }
2100
2101         wl_resource_set_implementation(cb->resource, NULL, cb,
2102                                        destroy_frame_callback);
2103
2104         wl_list_insert(surface->pending.frame_callback_list.prev, &cb->link);
2105 }
2106
2107 static void
2108 surface_set_opaque_region(struct wl_client *client,
2109                           struct wl_resource *resource,
2110                           struct wl_resource *region_resource)
2111 {
2112         struct weston_surface *surface = wl_resource_get_user_data(resource);
2113         struct weston_region *region;
2114
2115         if (region_resource) {
2116                 region = wl_resource_get_user_data(region_resource);
2117                 pixman_region32_copy(&surface->pending.opaque,
2118                                      &region->region);
2119         } else {
2120                 pixman_region32_clear(&surface->pending.opaque);
2121         }
2122 }
2123
2124 static void
2125 surface_set_input_region(struct wl_client *client,
2126                          struct wl_resource *resource,
2127                          struct wl_resource *region_resource)
2128 {
2129         struct weston_surface *surface = wl_resource_get_user_data(resource);
2130         struct weston_region *region;
2131
2132         if (region_resource) {
2133                 region = wl_resource_get_user_data(region_resource);
2134                 pixman_region32_copy(&surface->pending.input,
2135                                      &region->region);
2136         } else {
2137                 pixman_region32_fini(&surface->pending.input);
2138                 region_init_infinite(&surface->pending.input);
2139         }
2140 }
2141
2142 static void
2143 weston_surface_commit_subsurface_order(struct weston_surface *surface)
2144 {
2145         struct weston_subsurface *sub;
2146
2147         wl_list_for_each_reverse(sub, &surface->subsurface_list_pending,
2148                                  parent_link_pending) {
2149                 wl_list_remove(&sub->parent_link);
2150                 wl_list_insert(&surface->subsurface_list, &sub->parent_link);
2151         }
2152 }
2153
2154 static void
2155 weston_surface_commit_state(struct weston_surface *surface,
2156                             struct weston_surface_state *state)
2157 {
2158         struct weston_view *view;
2159         pixman_region32_t opaque;
2160
2161         /* wl_surface.set_buffer_transform */
2162         /* wl_surface.set_buffer_scale */
2163         /* wl_viewport.set */
2164         surface->buffer_viewport = state->buffer_viewport;
2165
2166         /* wl_surface.attach */
2167         if (state->newly_attached)
2168                 weston_surface_attach(surface, state->buffer);
2169         weston_surface_state_set_buffer(state, NULL);
2170
2171         if (state->newly_attached || state->buffer_viewport.changed) {
2172                 weston_surface_update_size(surface);
2173                 if (surface->configure)
2174                         surface->configure(surface, state->sx, state->sy);
2175         }
2176
2177         state->sx = 0;
2178         state->sy = 0;
2179         state->newly_attached = 0;
2180         state->buffer_viewport.changed = 0;
2181
2182         /* wl_surface.damage */
2183         pixman_region32_union(&surface->damage, &surface->damage,
2184                               &state->damage);
2185         pixman_region32_intersect_rect(&surface->damage, &surface->damage,
2186                                        0, 0, surface->width, surface->height);
2187         pixman_region32_clear(&surface->pending.damage);
2188
2189         /* wl_surface.set_opaque_region */
2190         pixman_region32_init(&opaque);
2191         pixman_region32_intersect_rect(&opaque, &state->opaque,
2192                                        0, 0, surface->width, surface->height);
2193
2194         if (!pixman_region32_equal(&opaque, &surface->opaque)) {
2195                 pixman_region32_copy(&surface->opaque, &opaque);
2196                 wl_list_for_each(view, &surface->views, surface_link)
2197                         weston_view_geometry_dirty(view);
2198         }
2199
2200         pixman_region32_fini(&opaque);
2201
2202         /* wl_surface.set_input_region */
2203         pixman_region32_intersect_rect(&surface->input, &state->input,
2204                                        0, 0, surface->width, surface->height);
2205
2206         /* wl_surface.frame */
2207         wl_list_insert_list(&surface->frame_callback_list,
2208                             &state->frame_callback_list);
2209         wl_list_init(&state->frame_callback_list);
2210 }
2211
2212 static void
2213 weston_surface_commit(struct weston_surface *surface)
2214 {
2215         weston_surface_commit_state(surface, &surface->pending);
2216
2217         weston_surface_commit_subsurface_order(surface);
2218
2219         weston_surface_schedule_repaint(surface);
2220 }
2221
2222 static void
2223 weston_subsurface_commit(struct weston_subsurface *sub);
2224
2225 static void
2226 weston_subsurface_parent_commit(struct weston_subsurface *sub,
2227                                 int parent_is_synchronized);
2228
2229 static void
2230 surface_commit(struct wl_client *client, struct wl_resource *resource)
2231 {
2232         struct weston_surface *surface = wl_resource_get_user_data(resource);
2233         struct weston_subsurface *sub = weston_surface_to_subsurface(surface);
2234
2235         if (sub) {
2236                 weston_subsurface_commit(sub);
2237                 return;
2238         }
2239
2240         weston_surface_commit(surface);
2241
2242         wl_list_for_each(sub, &surface->subsurface_list, parent_link) {
2243                 if (sub->surface != surface)
2244                         weston_subsurface_parent_commit(sub, 0);
2245         }
2246 }
2247
2248 static void
2249 surface_set_buffer_transform(struct wl_client *client,
2250                              struct wl_resource *resource, int transform)
2251 {
2252         struct weston_surface *surface = wl_resource_get_user_data(resource);
2253
2254         /* if wl_output.transform grows more members this will need to be updated. */
2255         if (transform < 0 ||
2256             transform > WL_OUTPUT_TRANSFORM_FLIPPED_270) {
2257                 wl_resource_post_error(resource,
2258                         WL_SURFACE_ERROR_INVALID_TRANSFORM,
2259                         "buffer transform must be a valid transform "
2260                         "('%d' specified)", transform);
2261                 return;
2262         }
2263
2264         surface->pending.buffer_viewport.buffer.transform = transform;
2265         surface->pending.buffer_viewport.changed = 1;
2266 }
2267
2268 static void
2269 surface_set_buffer_scale(struct wl_client *client,
2270                          struct wl_resource *resource,
2271                          int32_t scale)
2272 {
2273         struct weston_surface *surface = wl_resource_get_user_data(resource);
2274
2275         if (scale < 1) {
2276                 wl_resource_post_error(resource,
2277                         WL_SURFACE_ERROR_INVALID_SCALE,
2278                         "buffer scale must be at least one "
2279                         "('%d' specified)", scale);
2280                 return;
2281         }
2282
2283         surface->pending.buffer_viewport.buffer.scale = scale;
2284         surface->pending.buffer_viewport.changed = 1;
2285 }
2286
2287 static const struct wl_surface_interface surface_interface = {
2288         surface_destroy,
2289         surface_attach,
2290         surface_damage,
2291         surface_frame,
2292         surface_set_opaque_region,
2293         surface_set_input_region,
2294         surface_commit,
2295         surface_set_buffer_transform,
2296         surface_set_buffer_scale
2297 };
2298
2299 static void
2300 compositor_create_surface(struct wl_client *client,
2301                           struct wl_resource *resource, uint32_t id)
2302 {
2303         struct weston_compositor *ec = wl_resource_get_user_data(resource);
2304         struct weston_surface *surface;
2305
2306         surface = weston_surface_create(ec);
2307         if (surface == NULL) {
2308                 wl_resource_post_no_memory(resource);
2309                 return;
2310         }
2311
2312         surface->resource =
2313                 wl_resource_create(client, &wl_surface_interface,
2314                                    wl_resource_get_version(resource), id);
2315         if (surface->resource == NULL) {
2316                 weston_surface_destroy(surface);
2317                 wl_resource_post_no_memory(resource);
2318                 return;
2319         }
2320         wl_resource_set_implementation(surface->resource, &surface_interface,
2321                                        surface, destroy_surface);
2322
2323         wl_signal_emit(&ec->create_surface_signal, surface);
2324 }
2325
2326 static void
2327 destroy_region(struct wl_resource *resource)
2328 {
2329         struct weston_region *region = wl_resource_get_user_data(resource);
2330
2331         pixman_region32_fini(&region->region);
2332         free(region);
2333 }
2334
2335 static void
2336 region_destroy(struct wl_client *client, struct wl_resource *resource)
2337 {
2338         wl_resource_destroy(resource);
2339 }
2340
2341 static void
2342 region_add(struct wl_client *client, struct wl_resource *resource,
2343            int32_t x, int32_t y, int32_t width, int32_t height)
2344 {
2345         struct weston_region *region = wl_resource_get_user_data(resource);
2346
2347         pixman_region32_union_rect(&region->region, &region->region,
2348                                    x, y, width, height);
2349 }
2350
2351 static void
2352 region_subtract(struct wl_client *client, struct wl_resource *resource,
2353                 int32_t x, int32_t y, int32_t width, int32_t height)
2354 {
2355         struct weston_region *region = wl_resource_get_user_data(resource);
2356         pixman_region32_t rect;
2357
2358         pixman_region32_init_rect(&rect, x, y, width, height);
2359         pixman_region32_subtract(&region->region, &region->region, &rect);
2360         pixman_region32_fini(&rect);
2361 }
2362
2363 static const struct wl_region_interface region_interface = {
2364         region_destroy,
2365         region_add,
2366         region_subtract
2367 };
2368
2369 static void
2370 compositor_create_region(struct wl_client *client,
2371                          struct wl_resource *resource, uint32_t id)
2372 {
2373         struct weston_region *region;
2374
2375         region = malloc(sizeof *region);
2376         if (region == NULL) {
2377                 wl_resource_post_no_memory(resource);
2378                 return;
2379         }
2380
2381         pixman_region32_init(&region->region);
2382
2383         region->resource =
2384                 wl_resource_create(client, &wl_region_interface, 1, id);
2385         if (region->resource == NULL) {
2386                 free(region);
2387                 wl_resource_post_no_memory(resource);
2388                 return;
2389         }
2390         wl_resource_set_implementation(region->resource, &region_interface,
2391                                        region, destroy_region);
2392 }
2393
2394 static const struct wl_compositor_interface compositor_interface = {
2395         compositor_create_surface,
2396         compositor_create_region
2397 };
2398
2399 static void
2400 weston_subsurface_commit_from_cache(struct weston_subsurface *sub)
2401 {
2402         struct weston_surface *surface = sub->surface;
2403
2404         weston_surface_commit_state(surface, &sub->cached);
2405         weston_buffer_reference(&sub->cached_buffer_ref, NULL);
2406
2407         weston_surface_commit_subsurface_order(surface);
2408
2409         weston_surface_schedule_repaint(surface);
2410
2411         sub->has_cached_data = 0;
2412 }
2413
2414 static void
2415 weston_subsurface_commit_to_cache(struct weston_subsurface *sub)
2416 {
2417         struct weston_surface *surface = sub->surface;
2418
2419         /*
2420          * If this commit would cause the surface to move by the
2421          * attach(dx, dy) parameters, the old damage region must be
2422          * translated to correspond to the new surface coordinate system
2423          * original_mode.
2424          */
2425         pixman_region32_translate(&sub->cached.damage,
2426                                   -surface->pending.sx, -surface->pending.sy);
2427         pixman_region32_union(&sub->cached.damage, &sub->cached.damage,
2428                               &surface->pending.damage);
2429         pixman_region32_clear(&surface->pending.damage);
2430
2431         if (surface->pending.newly_attached) {
2432                 sub->cached.newly_attached = 1;
2433                 weston_surface_state_set_buffer(&sub->cached,
2434                                                 surface->pending.buffer);
2435                 weston_buffer_reference(&sub->cached_buffer_ref,
2436                                         surface->pending.buffer);
2437         }
2438         sub->cached.sx += surface->pending.sx;
2439         sub->cached.sy += surface->pending.sy;
2440
2441         sub->cached.buffer_viewport.changed |=
2442                 surface->pending.buffer_viewport.changed;
2443         sub->cached.buffer_viewport.buffer =
2444                 surface->pending.buffer_viewport.buffer;
2445         sub->cached.buffer_viewport.surface =
2446                 surface->pending.buffer_viewport.surface;
2447
2448         weston_surface_reset_pending_buffer(surface);
2449
2450         pixman_region32_copy(&sub->cached.opaque, &surface->pending.opaque);
2451
2452         pixman_region32_copy(&sub->cached.input, &surface->pending.input);
2453
2454         wl_list_insert_list(&sub->cached.frame_callback_list,
2455                             &surface->pending.frame_callback_list);
2456         wl_list_init(&surface->pending.frame_callback_list);
2457
2458         sub->has_cached_data = 1;
2459 }
2460
2461 static int
2462 weston_subsurface_is_synchronized(struct weston_subsurface *sub)
2463 {
2464         while (sub) {
2465                 if (sub->synchronized)
2466                         return 1;
2467
2468                 if (!sub->parent)
2469                         return 0;
2470
2471                 sub = weston_surface_to_subsurface(sub->parent);
2472         }
2473
2474         return 0;
2475 }
2476
2477 static void
2478 weston_subsurface_commit(struct weston_subsurface *sub)
2479 {
2480         struct weston_surface *surface = sub->surface;
2481         struct weston_subsurface *tmp;
2482
2483         /* Recursive check for effectively synchronized. */
2484         if (weston_subsurface_is_synchronized(sub)) {
2485                 weston_subsurface_commit_to_cache(sub);
2486         } else {
2487                 if (sub->has_cached_data) {
2488                         /* flush accumulated state from cache */
2489                         weston_subsurface_commit_to_cache(sub);
2490                         weston_subsurface_commit_from_cache(sub);
2491                 } else {
2492                         weston_surface_commit(surface);
2493                 }
2494
2495                 wl_list_for_each(tmp, &surface->subsurface_list, parent_link) {
2496                         if (tmp->surface != surface)
2497                                 weston_subsurface_parent_commit(tmp, 0);
2498                 }
2499         }
2500 }
2501
2502 static void
2503 weston_subsurface_synchronized_commit(struct weston_subsurface *sub)
2504 {
2505         struct weston_surface *surface = sub->surface;
2506         struct weston_subsurface *tmp;
2507
2508         /* From now on, commit_from_cache the whole sub-tree, regardless of
2509          * the synchronized mode of each child. This sub-surface or some
2510          * of its ancestors were synchronized, so we are synchronized
2511          * all the way down.
2512          */
2513
2514         if (sub->has_cached_data)
2515                 weston_subsurface_commit_from_cache(sub);
2516
2517         wl_list_for_each(tmp, &surface->subsurface_list, parent_link) {
2518                 if (tmp->surface != surface)
2519                         weston_subsurface_parent_commit(tmp, 1);
2520         }
2521 }
2522
2523 static void
2524 weston_subsurface_parent_commit(struct weston_subsurface *sub,
2525                                 int parent_is_synchronized)
2526 {
2527         struct weston_view *view;
2528         if (sub->position.set) {
2529                 wl_list_for_each(view, &sub->surface->views, surface_link)
2530                         weston_view_set_position(view,
2531                                                  sub->position.x,
2532                                                  sub->position.y);
2533
2534                 sub->position.set = 0;
2535         }
2536
2537         if (parent_is_synchronized || sub->synchronized)
2538                 weston_subsurface_synchronized_commit(sub);
2539 }
2540
2541 static void
2542 subsurface_configure(struct weston_surface *surface, int32_t dx, int32_t dy)
2543 {
2544         struct weston_compositor *compositor = surface->compositor;
2545         struct weston_view *view;
2546
2547         wl_list_for_each(view, &surface->views, surface_link)
2548                 weston_view_set_position(view,
2549                                          view->geometry.x + dx,
2550                                          view->geometry.y + dy);
2551
2552         /* No need to check parent mappedness, because if parent is not
2553          * mapped, parent is not in a visible layer, so this sub-surface
2554          * will not be drawn either.
2555          */
2556         if (!weston_surface_is_mapped(surface)) {
2557                 struct weston_output *output;
2558
2559                 /* Cannot call weston_surface_update_transform(),
2560                  * because that would call it also for the parent surface,
2561                  * which might not be mapped yet. That would lead to
2562                  * inconsistent state, where the window could never be
2563                  * mapped.
2564                  *
2565                  * Instead just assing any output, to make
2566                  * weston_surface_is_mapped() return true, so that when the
2567                  * parent surface does get mapped, this one will get
2568                  * included, too. See view_list_add().
2569                  */
2570                 assert(!wl_list_empty(&compositor->output_list));
2571                 output = container_of(compositor->output_list.next,
2572                                       struct weston_output, link);
2573
2574                 surface->output = output;
2575                 weston_surface_update_output_mask(surface, 1 << output->id);
2576         }
2577 }
2578
2579 static struct weston_subsurface *
2580 weston_surface_to_subsurface(struct weston_surface *surface)
2581 {
2582         if (surface->configure == subsurface_configure)
2583                 return surface->configure_private;
2584
2585         return NULL;
2586 }
2587
2588 WL_EXPORT struct weston_surface *
2589 weston_surface_get_main_surface(struct weston_surface *surface)
2590 {
2591         struct weston_subsurface *sub;
2592
2593         while (surface && (sub = weston_surface_to_subsurface(surface)))
2594                 surface = sub->parent;
2595
2596         return surface;
2597 }
2598
2599 static void
2600 subsurface_set_position(struct wl_client *client,
2601                         struct wl_resource *resource, int32_t x, int32_t y)
2602 {
2603         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
2604
2605         if (!sub)
2606                 return;
2607
2608         sub->position.x = x;
2609         sub->position.y = y;
2610         sub->position.set = 1;
2611 }
2612
2613 static struct weston_subsurface *
2614 subsurface_from_surface(struct weston_surface *surface)
2615 {
2616         struct weston_subsurface *sub;
2617
2618         sub = weston_surface_to_subsurface(surface);
2619         if (sub)
2620                 return sub;
2621
2622         wl_list_for_each(sub, &surface->subsurface_list, parent_link)
2623                 if (sub->surface == surface)
2624                         return sub;
2625
2626         return NULL;
2627 }
2628
2629 static struct weston_subsurface *
2630 subsurface_sibling_check(struct weston_subsurface *sub,
2631                          struct weston_surface *surface,
2632                          const char *request)
2633 {
2634         struct weston_subsurface *sibling;
2635
2636         sibling = subsurface_from_surface(surface);
2637
2638         if (!sibling) {
2639                 wl_resource_post_error(sub->resource,
2640                         WL_SUBSURFACE_ERROR_BAD_SURFACE,
2641                         "%s: wl_surface@%d is not a parent or sibling",
2642                         request, wl_resource_get_id(surface->resource));
2643                 return NULL;
2644         }
2645
2646         if (sibling->parent != sub->parent) {
2647                 wl_resource_post_error(sub->resource,
2648                         WL_SUBSURFACE_ERROR_BAD_SURFACE,
2649                         "%s: wl_surface@%d has a different parent",
2650                         request, wl_resource_get_id(surface->resource));
2651                 return NULL;
2652         }
2653
2654         return sibling;
2655 }
2656
2657 static void
2658 subsurface_place_above(struct wl_client *client,
2659                        struct wl_resource *resource,
2660                        struct wl_resource *sibling_resource)
2661 {
2662         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
2663         struct weston_surface *surface =
2664                 wl_resource_get_user_data(sibling_resource);
2665         struct weston_subsurface *sibling;
2666
2667         if (!sub)
2668                 return;
2669
2670         sibling = subsurface_sibling_check(sub, surface, "place_above");
2671         if (!sibling)
2672                 return;
2673
2674         wl_list_remove(&sub->parent_link_pending);
2675         wl_list_insert(sibling->parent_link_pending.prev,
2676                        &sub->parent_link_pending);
2677 }
2678
2679 static void
2680 subsurface_place_below(struct wl_client *client,
2681                        struct wl_resource *resource,
2682                        struct wl_resource *sibling_resource)
2683 {
2684         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
2685         struct weston_surface *surface =
2686                 wl_resource_get_user_data(sibling_resource);
2687         struct weston_subsurface *sibling;
2688
2689         if (!sub)
2690                 return;
2691
2692         sibling = subsurface_sibling_check(sub, surface, "place_below");
2693         if (!sibling)
2694                 return;
2695
2696         wl_list_remove(&sub->parent_link_pending);
2697         wl_list_insert(&sibling->parent_link_pending,
2698                        &sub->parent_link_pending);
2699 }
2700
2701 static void
2702 subsurface_set_sync(struct wl_client *client, struct wl_resource *resource)
2703 {
2704         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
2705
2706         if (sub)
2707                 sub->synchronized = 1;
2708 }
2709
2710 static void
2711 subsurface_set_desync(struct wl_client *client, struct wl_resource *resource)
2712 {
2713         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
2714
2715         if (sub && sub->synchronized) {
2716                 sub->synchronized = 0;
2717
2718                 /* If sub became effectively desynchronized, flush. */
2719                 if (!weston_subsurface_is_synchronized(sub))
2720                         weston_subsurface_synchronized_commit(sub);
2721         }
2722 }
2723
2724 static void
2725 weston_subsurface_unlink_parent(struct weston_subsurface *sub)
2726 {
2727         wl_list_remove(&sub->parent_link);
2728         wl_list_remove(&sub->parent_link_pending);
2729         wl_list_remove(&sub->parent_destroy_listener.link);
2730         sub->parent = NULL;
2731 }
2732
2733 static void
2734 weston_subsurface_destroy(struct weston_subsurface *sub);
2735
2736 static void
2737 subsurface_handle_surface_destroy(struct wl_listener *listener, void *data)
2738 {
2739         struct weston_subsurface *sub =
2740                 container_of(listener, struct weston_subsurface,
2741                              surface_destroy_listener);
2742         assert(data == &sub->surface->resource);
2743
2744         /* The protocol object (wl_resource) is left inert. */
2745         if (sub->resource)
2746                 wl_resource_set_user_data(sub->resource, NULL);
2747
2748         weston_subsurface_destroy(sub);
2749 }
2750
2751 static void
2752 subsurface_handle_parent_destroy(struct wl_listener *listener, void *data)
2753 {
2754         struct weston_subsurface *sub =
2755                 container_of(listener, struct weston_subsurface,
2756                              parent_destroy_listener);
2757         assert(data == &sub->parent->resource);
2758         assert(sub->surface != sub->parent);
2759
2760         if (weston_surface_is_mapped(sub->surface))
2761                 weston_surface_unmap(sub->surface);
2762
2763         weston_subsurface_unlink_parent(sub);
2764 }
2765
2766 static void
2767 subsurface_resource_destroy(struct wl_resource *resource)
2768 {
2769         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
2770
2771         if (sub)
2772                 weston_subsurface_destroy(sub);
2773 }
2774
2775 static void
2776 subsurface_destroy(struct wl_client *client, struct wl_resource *resource)
2777 {
2778         wl_resource_destroy(resource);
2779 }
2780
2781 static void
2782 weston_subsurface_link_parent(struct weston_subsurface *sub,
2783                               struct weston_surface *parent)
2784 {
2785         sub->parent = parent;
2786         sub->parent_destroy_listener.notify = subsurface_handle_parent_destroy;
2787         wl_signal_add(&parent->destroy_signal,
2788                       &sub->parent_destroy_listener);
2789
2790         wl_list_insert(&parent->subsurface_list, &sub->parent_link);
2791         wl_list_insert(&parent->subsurface_list_pending,
2792                        &sub->parent_link_pending);
2793 }
2794
2795 static void
2796 weston_subsurface_link_surface(struct weston_subsurface *sub,
2797                                struct weston_surface *surface)
2798 {
2799         sub->surface = surface;
2800         sub->surface_destroy_listener.notify =
2801                 subsurface_handle_surface_destroy;
2802         wl_signal_add(&surface->destroy_signal,
2803                       &sub->surface_destroy_listener);
2804 }
2805
2806 static void
2807 weston_subsurface_destroy(struct weston_subsurface *sub)
2808 {
2809         struct weston_view *view, *next;
2810
2811         assert(sub->surface);
2812
2813         if (sub->resource) {
2814                 assert(weston_surface_to_subsurface(sub->surface) == sub);
2815                 assert(sub->parent_destroy_listener.notify ==
2816                        subsurface_handle_parent_destroy);
2817
2818                 wl_list_for_each_safe(view, next, &sub->surface->views, surface_link) {
2819                         weston_view_unmap(view);
2820                         weston_view_destroy(view);
2821                 }
2822
2823                 if (sub->parent)
2824                         weston_subsurface_unlink_parent(sub);
2825
2826                 weston_surface_state_fini(&sub->cached);
2827                 weston_buffer_reference(&sub->cached_buffer_ref, NULL);
2828
2829                 sub->surface->configure = NULL;
2830                 sub->surface->configure_private = NULL;
2831         } else {
2832                 /* the dummy weston_subsurface for the parent itself */
2833                 assert(sub->parent_destroy_listener.notify == NULL);
2834                 wl_list_remove(&sub->parent_link);
2835                 wl_list_remove(&sub->parent_link_pending);
2836         }
2837
2838         wl_list_remove(&sub->surface_destroy_listener.link);
2839         free(sub);
2840 }
2841
2842 static const struct wl_subsurface_interface subsurface_implementation = {
2843         subsurface_destroy,
2844         subsurface_set_position,
2845         subsurface_place_above,
2846         subsurface_place_below,
2847         subsurface_set_sync,
2848         subsurface_set_desync
2849 };
2850
2851 static struct weston_subsurface *
2852 weston_subsurface_create(uint32_t id, struct weston_surface *surface,
2853                          struct weston_surface *parent)
2854 {
2855         struct weston_subsurface *sub;
2856         struct wl_client *client = wl_resource_get_client(surface->resource);
2857
2858         sub = calloc(1, sizeof *sub);
2859         if (!sub)
2860                 return NULL;
2861
2862         wl_list_init(&sub->unused_views);
2863
2864         sub->resource =
2865                 wl_resource_create(client, &wl_subsurface_interface, 1, id);
2866         if (!sub->resource) {
2867                 free(sub);
2868                 return NULL;
2869         }
2870
2871         wl_resource_set_implementation(sub->resource,
2872                                        &subsurface_implementation,
2873                                        sub, subsurface_resource_destroy);
2874         weston_subsurface_link_surface(sub, surface);
2875         weston_subsurface_link_parent(sub, parent);
2876         weston_surface_state_init(&sub->cached);
2877         sub->cached_buffer_ref.buffer = NULL;
2878         sub->synchronized = 1;
2879
2880         return sub;
2881 }
2882
2883 /* Create a dummy subsurface for having the parent itself in its
2884  * sub-surface lists. Makes stacking order manipulation easy.
2885  */
2886 static struct weston_subsurface *
2887 weston_subsurface_create_for_parent(struct weston_surface *parent)
2888 {
2889         struct weston_subsurface *sub;
2890
2891         sub = calloc(1, sizeof *sub);
2892         if (!sub)
2893                 return NULL;
2894
2895         weston_subsurface_link_surface(sub, parent);
2896         sub->parent = parent;
2897         wl_list_insert(&parent->subsurface_list, &sub->parent_link);
2898         wl_list_insert(&parent->subsurface_list_pending,
2899                        &sub->parent_link_pending);
2900
2901         return sub;
2902 }
2903
2904 static void
2905 subcompositor_get_subsurface(struct wl_client *client,
2906                              struct wl_resource *resource,
2907                              uint32_t id,
2908                              struct wl_resource *surface_resource,
2909                              struct wl_resource *parent_resource)
2910 {
2911         struct weston_surface *surface =
2912                 wl_resource_get_user_data(surface_resource);
2913         struct weston_surface *parent =
2914                 wl_resource_get_user_data(parent_resource);
2915         struct weston_subsurface *sub;
2916         static const char where[] = "get_subsurface: wl_subsurface@";
2917
2918         if (surface == parent) {
2919                 wl_resource_post_error(resource,
2920                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
2921                         "%s%d: wl_surface@%d cannot be its own parent",
2922                         where, id, wl_resource_get_id(surface_resource));
2923                 return;
2924         }
2925
2926         if (weston_surface_to_subsurface(surface)) {
2927                 wl_resource_post_error(resource,
2928                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
2929                         "%s%d: wl_surface@%d is already a sub-surface",
2930                         where, id, wl_resource_get_id(surface_resource));
2931                 return;
2932         }
2933
2934         if (surface->configure) {
2935                 wl_resource_post_error(resource,
2936                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
2937                         "%s%d: wl_surface@%d already has a role",
2938                         where, id, wl_resource_get_id(surface_resource));
2939                 return;
2940         }
2941
2942         if (weston_surface_get_main_surface(parent) == surface) {
2943                 wl_resource_post_error(resource,
2944                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
2945                         "%s%d: wl_surface@%d is an ancestor of parent",
2946                         where, id, wl_resource_get_id(surface_resource));
2947                 return;
2948         }
2949
2950         /* make sure the parent is in its own list */
2951         if (wl_list_empty(&parent->subsurface_list)) {
2952                 if (!weston_subsurface_create_for_parent(parent)) {
2953                         wl_resource_post_no_memory(resource);
2954                         return;
2955                 }
2956         }
2957
2958         sub = weston_subsurface_create(id, surface, parent);
2959         if (!sub) {
2960                 wl_resource_post_no_memory(resource);
2961                 return;
2962         }
2963
2964         surface->configure = subsurface_configure;
2965         surface->configure_private = sub;
2966 }
2967
2968 static void
2969 subcompositor_destroy(struct wl_client *client, struct wl_resource *resource)
2970 {
2971         wl_resource_destroy(resource);
2972 }
2973
2974 static const struct wl_subcompositor_interface subcompositor_interface = {
2975         subcompositor_destroy,
2976         subcompositor_get_subsurface
2977 };
2978
2979 static void
2980 bind_subcompositor(struct wl_client *client,
2981                    void *data, uint32_t version, uint32_t id)
2982 {
2983         struct weston_compositor *compositor = data;
2984         struct wl_resource *resource;
2985
2986         resource =
2987                 wl_resource_create(client, &wl_subcompositor_interface, 1, id);
2988         if (resource == NULL) {
2989                 wl_client_post_no_memory(client);
2990                 return;
2991         }
2992         wl_resource_set_implementation(resource, &subcompositor_interface,
2993                                        compositor, NULL);
2994 }
2995
2996 static void
2997 weston_compositor_dpms(struct weston_compositor *compositor,
2998                        enum dpms_enum state)
2999 {
3000         struct weston_output *output;
3001
3002         wl_list_for_each(output, &compositor->output_list, link)
3003                 if (output->set_dpms)
3004                         output->set_dpms(output, state);
3005 }
3006
3007 WL_EXPORT void
3008 weston_compositor_wake(struct weston_compositor *compositor)
3009 {
3010         uint32_t old_state = compositor->state;
3011
3012         /* The state needs to be changed before emitting the wake
3013          * signal because that may try to schedule a repaint which
3014          * will not work if the compositor is still sleeping */
3015         compositor->state = WESTON_COMPOSITOR_ACTIVE;
3016
3017         switch (old_state) {
3018         case WESTON_COMPOSITOR_SLEEPING:
3019                 weston_compositor_dpms(compositor, WESTON_DPMS_ON);
3020                 /* fall through */
3021         case WESTON_COMPOSITOR_IDLE:
3022         case WESTON_COMPOSITOR_OFFSCREEN:
3023                 wl_signal_emit(&compositor->wake_signal, compositor);
3024                 /* fall through */
3025         default:
3026                 wl_event_source_timer_update(compositor->idle_source,
3027                                              compositor->idle_time * 1000);
3028         }
3029 }
3030
3031 WL_EXPORT void
3032 weston_compositor_offscreen(struct weston_compositor *compositor)
3033 {
3034         switch (compositor->state) {
3035         case WESTON_COMPOSITOR_OFFSCREEN:
3036                 return;
3037         case WESTON_COMPOSITOR_SLEEPING:
3038                 weston_compositor_dpms(compositor, WESTON_DPMS_ON);
3039                 /* fall through */
3040         default:
3041                 compositor->state = WESTON_COMPOSITOR_OFFSCREEN;
3042                 wl_event_source_timer_update(compositor->idle_source, 0);
3043         }
3044 }
3045
3046 WL_EXPORT void
3047 weston_compositor_sleep(struct weston_compositor *compositor)
3048 {
3049         if (compositor->state == WESTON_COMPOSITOR_SLEEPING)
3050                 return;
3051
3052         wl_event_source_timer_update(compositor->idle_source, 0);
3053         compositor->state = WESTON_COMPOSITOR_SLEEPING;
3054         weston_compositor_dpms(compositor, WESTON_DPMS_OFF);
3055 }
3056
3057 static int
3058 idle_handler(void *data)
3059 {
3060         struct weston_compositor *compositor = data;
3061
3062         if (compositor->idle_inhibit)
3063                 return 1;
3064
3065         compositor->state = WESTON_COMPOSITOR_IDLE;
3066         wl_signal_emit(&compositor->idle_signal, compositor);
3067
3068         return 1;
3069 }
3070
3071 WL_EXPORT void
3072 weston_plane_init(struct weston_plane *plane,
3073                         struct weston_compositor *ec,
3074                         int32_t x, int32_t y)
3075 {
3076         pixman_region32_init(&plane->damage);
3077         pixman_region32_init(&plane->clip);
3078         plane->x = x;
3079         plane->y = y;
3080         plane->compositor = ec;
3081
3082         /* Init the link so that the call to wl_list_remove() when releasing
3083          * the plane without ever stacking doesn't lead to a crash */
3084         wl_list_init(&plane->link);
3085 }
3086
3087 WL_EXPORT void
3088 weston_plane_release(struct weston_plane *plane)
3089 {
3090         struct weston_view *view;
3091
3092         pixman_region32_fini(&plane->damage);
3093         pixman_region32_fini(&plane->clip);
3094
3095         wl_list_for_each(view, &plane->compositor->view_list, link) {
3096                 if (view->plane == plane)
3097                         view->plane = NULL;
3098         }
3099
3100         wl_list_remove(&plane->link);
3101 }
3102
3103 WL_EXPORT void
3104 weston_compositor_stack_plane(struct weston_compositor *ec,
3105                               struct weston_plane *plane,
3106                               struct weston_plane *above)
3107 {
3108         if (above)
3109                 wl_list_insert(above->link.prev, &plane->link);
3110         else
3111                 wl_list_insert(&ec->plane_list, &plane->link);
3112 }
3113
3114 static void unbind_resource(struct wl_resource *resource)
3115 {
3116         wl_list_remove(wl_resource_get_link(resource));
3117 }
3118
3119 static void
3120 bind_output(struct wl_client *client,
3121             void *data, uint32_t version, uint32_t id)
3122 {
3123         struct weston_output *output = data;
3124         struct weston_mode *mode;
3125         struct wl_resource *resource;
3126
3127         resource = wl_resource_create(client, &wl_output_interface,
3128                                       MIN(version, 2), id);
3129         if (resource == NULL) {
3130                 wl_client_post_no_memory(client);
3131                 return;
3132         }
3133
3134         wl_list_insert(&output->resource_list, wl_resource_get_link(resource));
3135         wl_resource_set_implementation(resource, NULL, data, unbind_resource);
3136
3137         wl_output_send_geometry(resource,
3138                                 output->x,
3139                                 output->y,
3140                                 output->mm_width,
3141                                 output->mm_height,
3142                                 output->subpixel,
3143                                 output->make, output->model,
3144                                 output->transform);
3145         if (version >= 2)
3146                 wl_output_send_scale(resource,
3147                                      output->current_scale);
3148
3149         wl_list_for_each (mode, &output->mode_list, link) {
3150                 wl_output_send_mode(resource,
3151                                     mode->flags,
3152                                     mode->width,
3153                                     mode->height,
3154                                     mode->refresh);
3155         }
3156
3157         if (version >= 2)
3158                 wl_output_send_done(resource);
3159 }
3160
3161 /* Move other outputs when one is removed so the space remains contiguos. */
3162 static void
3163 weston_compositor_remove_output(struct weston_compositor *compositor,
3164                                 struct weston_output *remove_output)
3165 {
3166         struct weston_output *output;
3167         int offset = 0;
3168
3169         wl_list_for_each(output, &compositor->output_list, link) {
3170                 if (output == remove_output) {
3171                         offset = output->width;
3172                         continue;
3173                 }
3174
3175                 if (offset > 0) {
3176                         weston_output_move(output,
3177                                            output->x - offset, output->y);
3178                         output->dirty = 1;
3179                 }
3180         }
3181 }
3182
3183 WL_EXPORT void
3184 weston_output_destroy(struct weston_output *output)
3185 {
3186         output->destroying = 1;
3187
3188         weston_compositor_remove_output(output->compositor, output);
3189         wl_list_remove(&output->link);
3190
3191         wl_signal_emit(&output->compositor->output_destroyed_signal, output);
3192         wl_signal_emit(&output->destroy_signal, output);
3193
3194         free(output->name);
3195         pixman_region32_fini(&output->region);
3196         pixman_region32_fini(&output->previous_damage);
3197         output->compositor->output_id_pool &= ~(1 << output->id);
3198
3199         wl_global_destroy(output->global);
3200 }
3201
3202 static void
3203 weston_output_compute_transform(struct weston_output *output)
3204 {
3205         struct weston_matrix transform;
3206         int flip;
3207
3208         weston_matrix_init(&transform);
3209         transform.type = WESTON_MATRIX_TRANSFORM_ROTATE;
3210
3211         switch(output->transform) {
3212         case WL_OUTPUT_TRANSFORM_FLIPPED:
3213         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
3214         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
3215         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
3216                 transform.type |= WESTON_MATRIX_TRANSFORM_OTHER;
3217                 flip = -1;
3218                 break;
3219         default:
3220                 flip = 1;
3221                 break;
3222         }
3223
3224         switch(output->transform) {
3225         case WL_OUTPUT_TRANSFORM_NORMAL:
3226         case WL_OUTPUT_TRANSFORM_FLIPPED:
3227                 transform.d[0] = flip;
3228                 transform.d[1] = 0;
3229                 transform.d[4] = 0;
3230                 transform.d[5] = 1;
3231                 break;
3232         case WL_OUTPUT_TRANSFORM_90:
3233         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
3234                 transform.d[0] = 0;
3235                 transform.d[1] = -flip;
3236                 transform.d[4] = 1;
3237                 transform.d[5] = 0;
3238                 break;
3239         case WL_OUTPUT_TRANSFORM_180:
3240         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
3241                 transform.d[0] = -flip;
3242                 transform.d[1] = 0;
3243                 transform.d[4] = 0;
3244                 transform.d[5] = -1;
3245                 break;
3246         case WL_OUTPUT_TRANSFORM_270:
3247         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
3248                 transform.d[0] = 0;
3249                 transform.d[1] = flip;
3250                 transform.d[4] = -1;
3251                 transform.d[5] = 0;
3252                 break;
3253         default:
3254                 break;
3255         }
3256
3257         weston_matrix_multiply(&output->matrix, &transform);
3258 }
3259
3260 WL_EXPORT void
3261 weston_output_update_matrix(struct weston_output *output)
3262 {
3263         float magnification;
3264
3265         weston_matrix_init(&output->matrix);
3266         weston_matrix_translate(&output->matrix,
3267                                 -(output->x + output->width / 2.0),
3268                                 -(output->y + output->height / 2.0), 0);
3269
3270         weston_matrix_scale(&output->matrix,
3271                             2.0 / output->width,
3272                             -2.0 / output->height, 1);
3273
3274         if (output->zoom.active) {
3275                 magnification = 1 / (1 - output->zoom.spring_z.current);
3276                 weston_output_update_zoom(output);
3277                 weston_matrix_translate(&output->matrix, -output->zoom.trans_x,
3278                                         output->zoom.trans_y, 0);
3279                 weston_matrix_scale(&output->matrix, magnification,
3280                                     magnification, 1.0);
3281         }
3282
3283         weston_output_compute_transform(output);
3284
3285         output->dirty = 0;
3286 }
3287
3288 static void
3289 weston_output_transform_scale_init(struct weston_output *output, uint32_t transform, uint32_t scale)
3290 {
3291         output->transform = transform;
3292
3293         switch (transform) {
3294         case WL_OUTPUT_TRANSFORM_90:
3295         case WL_OUTPUT_TRANSFORM_270:
3296         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
3297         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
3298                 /* Swap width and height */
3299                 output->width = output->current_mode->height;
3300                 output->height = output->current_mode->width;
3301                 break;
3302         case WL_OUTPUT_TRANSFORM_NORMAL:
3303         case WL_OUTPUT_TRANSFORM_180:
3304         case WL_OUTPUT_TRANSFORM_FLIPPED:
3305         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
3306                 output->width = output->current_mode->width;
3307                 output->height = output->current_mode->height;
3308                 break;
3309         default:
3310                 break;
3311         }
3312
3313         output->native_scale = output->current_scale = scale;
3314         output->width /= scale;
3315         output->height /= scale;
3316 }
3317
3318 static void
3319 weston_output_init_geometry(struct weston_output *output, int x, int y)
3320 {
3321         output->x = x;
3322         output->y = y;
3323
3324         pixman_region32_init(&output->previous_damage);
3325         pixman_region32_init_rect(&output->region, x, y,
3326                                   output->width,
3327                                   output->height);
3328 }
3329
3330 WL_EXPORT void
3331 weston_output_move(struct weston_output *output, int x, int y)
3332 {
3333         pixman_region32_t old_region;
3334         struct wl_resource *resource;
3335
3336         output->move_x = x - output->x;
3337         output->move_y = y - output->y;
3338
3339         if (output->move_x == 0 && output->move_y == 0)
3340                 return;
3341
3342         pixman_region32_init(&old_region);
3343         pixman_region32_copy(&old_region, &output->region);
3344
3345         weston_output_init_geometry(output, x, y);
3346
3347         output->dirty = 1;
3348
3349         /* Move views on this output. */
3350         wl_signal_emit(&output->compositor->output_moved_signal, output);
3351
3352         /* Notify clients of the change for output position. */
3353         wl_resource_for_each(resource, &output->resource_list) {
3354                 wl_output_send_geometry(resource,
3355                                         output->x,
3356                                         output->y,
3357                                         output->mm_width,
3358                                         output->mm_height,
3359                                         output->subpixel,
3360                                         output->make,
3361                                         output->model,
3362                                         output->transform);
3363
3364                 if (wl_resource_get_version(resource) >= 2)
3365                         wl_output_send_done(resource);
3366         }
3367 }
3368
3369 WL_EXPORT void
3370 weston_output_init(struct weston_output *output, struct weston_compositor *c,
3371                    int x, int y, int mm_width, int mm_height, uint32_t transform,
3372                    int32_t scale)
3373 {
3374         output->compositor = c;
3375         output->x = x;
3376         output->y = y;
3377         output->mm_width = mm_width;
3378         output->mm_height = mm_height;
3379         output->dirty = 1;
3380         output->original_scale = scale;
3381
3382         weston_output_transform_scale_init(output, transform, scale);
3383         weston_output_init_zoom(output);
3384
3385         weston_output_init_geometry(output, x, y);
3386         weston_output_damage(output);
3387
3388         wl_signal_init(&output->frame_signal);
3389         wl_signal_init(&output->destroy_signal);
3390         wl_list_init(&output->animation_list);
3391         wl_list_init(&output->resource_list);
3392
3393         output->id = ffs(~output->compositor->output_id_pool) - 1;
3394         output->compositor->output_id_pool |= 1 << output->id;
3395
3396         output->global =
3397                 wl_global_create(c->wl_display, &wl_output_interface, 2,
3398                                  output, bind_output);
3399         wl_signal_emit(&c->output_created_signal, output);
3400 }
3401
3402 WL_EXPORT void
3403 weston_output_transform_coordinate(struct weston_output *output,
3404                                    wl_fixed_t device_x, wl_fixed_t device_y,
3405                                    wl_fixed_t *x, wl_fixed_t *y)
3406 {
3407         wl_fixed_t tx, ty;
3408         wl_fixed_t width, height;
3409         float zoom_scale, zx, zy;
3410
3411         width = wl_fixed_from_int(output->width * output->current_scale - 1);
3412         height = wl_fixed_from_int(output->height * output->current_scale - 1);
3413
3414         switch(output->transform) {
3415         case WL_OUTPUT_TRANSFORM_NORMAL:
3416         default:
3417                 tx = device_x;
3418                 ty = device_y;
3419                 break;
3420         case WL_OUTPUT_TRANSFORM_90:
3421                 tx = device_y;
3422                 ty = height - device_x;
3423                 break;
3424         case WL_OUTPUT_TRANSFORM_180:
3425                 tx = width - device_x;
3426                 ty = height - device_y;
3427                 break;
3428         case WL_OUTPUT_TRANSFORM_270:
3429                 tx = width - device_y;
3430                 ty = device_x;
3431                 break;
3432         case WL_OUTPUT_TRANSFORM_FLIPPED:
3433                 tx = width - device_x;
3434                 ty = device_y;
3435                 break;
3436         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
3437                 tx = width - device_y;
3438                 ty = height - device_x;
3439                 break;
3440         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
3441                 tx = device_x;
3442                 ty = height - device_y;
3443                 break;
3444         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
3445                 tx = device_y;
3446                 ty = device_x;
3447                 break;
3448         }
3449
3450         tx /= output->current_scale;
3451         ty /= output->current_scale;
3452
3453         if (output->zoom.active) {
3454                 zoom_scale = output->zoom.spring_z.current;
3455                 zx = (wl_fixed_to_double(tx) * (1.0f - zoom_scale) +
3456                       output->width / 2.0f *
3457                       (zoom_scale + output->zoom.trans_x));
3458                 zy = (wl_fixed_to_double(ty) * (1.0f - zoom_scale) +
3459                       output->height / 2.0f *
3460                       (zoom_scale + output->zoom.trans_y));
3461                 tx = wl_fixed_from_double(zx);
3462                 ty = wl_fixed_from_double(zy);
3463         }
3464
3465         *x = tx + wl_fixed_from_int(output->x);
3466         *y = ty + wl_fixed_from_int(output->y);
3467 }
3468
3469 static void
3470 destroy_viewport(struct wl_resource *resource)
3471 {
3472         struct weston_surface *surface =
3473                 wl_resource_get_user_data(resource);
3474
3475         surface->viewport_resource = NULL;
3476         surface->pending.buffer_viewport.buffer.src_width =
3477                 wl_fixed_from_int(-1);
3478         surface->pending.buffer_viewport.surface.width = -1;
3479         surface->pending.buffer_viewport.changed = 1;
3480 }
3481
3482 static void
3483 viewport_destroy(struct wl_client *client,
3484                  struct wl_resource *resource)
3485 {
3486         wl_resource_destroy(resource);
3487 }
3488
3489 static void
3490 viewport_set(struct wl_client *client,
3491              struct wl_resource *resource,
3492              wl_fixed_t src_x,
3493              wl_fixed_t src_y,
3494              wl_fixed_t src_width,
3495              wl_fixed_t src_height,
3496              int32_t dst_width,
3497              int32_t dst_height)
3498 {
3499         struct weston_surface *surface =
3500                 wl_resource_get_user_data(resource);
3501
3502         assert(surface->viewport_resource != NULL);
3503
3504         if (wl_fixed_to_double(src_width) < 0 ||
3505             wl_fixed_to_double(src_height) < 0) {
3506                 wl_resource_post_error(resource,
3507                         WL_VIEWPORT_ERROR_BAD_VALUE,
3508                         "source dimensions must be non-negative (%fx%f)",
3509                         wl_fixed_to_double(src_width),
3510                         wl_fixed_to_double(src_height));
3511                 return;
3512         }
3513
3514         if (dst_width <= 0 || dst_height <= 0) {
3515                 wl_resource_post_error(resource,
3516                         WL_VIEWPORT_ERROR_BAD_VALUE,
3517                         "destination dimensions must be positive (%dx%d)",
3518                         dst_width, dst_height);
3519                 return;
3520         }
3521
3522         surface->pending.buffer_viewport.buffer.src_x = src_x;
3523         surface->pending.buffer_viewport.buffer.src_y = src_y;
3524         surface->pending.buffer_viewport.buffer.src_width = src_width;
3525         surface->pending.buffer_viewport.buffer.src_height = src_height;
3526         surface->pending.buffer_viewport.surface.width = dst_width;
3527         surface->pending.buffer_viewport.surface.height = dst_height;
3528         surface->pending.buffer_viewport.changed = 1;
3529 }
3530
3531 static void
3532 viewport_set_source(struct wl_client *client,
3533                     struct wl_resource *resource,
3534                     wl_fixed_t src_x,
3535                     wl_fixed_t src_y,
3536                     wl_fixed_t src_width,
3537                     wl_fixed_t src_height)
3538 {
3539         struct weston_surface *surface =
3540                 wl_resource_get_user_data(resource);
3541
3542         assert(surface->viewport_resource != NULL);
3543
3544         if (src_width == wl_fixed_from_int(-1) &&
3545             src_height == wl_fixed_from_int(-1)) {
3546                 /* unset source size */
3547                 surface->pending.buffer_viewport.buffer.src_width =
3548                         wl_fixed_from_int(-1);
3549                 surface->pending.buffer_viewport.changed = 1;
3550                 return;
3551         }
3552
3553         if (src_width <= 0 || src_height <= 0) {
3554                 wl_resource_post_error(resource,
3555                         WL_VIEWPORT_ERROR_BAD_VALUE,
3556                         "source size must be positive (%fx%f)",
3557                         wl_fixed_to_double(src_width),
3558                         wl_fixed_to_double(src_height));
3559                 return;
3560         }
3561
3562         surface->pending.buffer_viewport.buffer.src_x = src_x;
3563         surface->pending.buffer_viewport.buffer.src_y = src_y;
3564         surface->pending.buffer_viewport.buffer.src_width = src_width;
3565         surface->pending.buffer_viewport.buffer.src_height = src_height;
3566         surface->pending.buffer_viewport.changed = 1;
3567 }
3568
3569 static void
3570 viewport_set_destination(struct wl_client *client,
3571                          struct wl_resource *resource,
3572                          int32_t dst_width,
3573                          int32_t dst_height)
3574 {
3575         struct weston_surface *surface =
3576                 wl_resource_get_user_data(resource);
3577
3578         assert(surface->viewport_resource != NULL);
3579
3580         if (dst_width == -1 && dst_height == -1) {
3581                 /* unset destination size */
3582                 surface->pending.buffer_viewport.surface.width = -1;
3583                 surface->pending.buffer_viewport.changed = 1;
3584                 return;
3585         }
3586
3587         if (dst_width <= 0 || dst_height <= 0) {
3588                 wl_resource_post_error(resource,
3589                         WL_VIEWPORT_ERROR_BAD_VALUE,
3590                         "destination size must be positive (%dx%d)",
3591                         dst_width, dst_height);
3592                 return;
3593         }
3594
3595         surface->pending.buffer_viewport.surface.width = dst_width;
3596         surface->pending.buffer_viewport.surface.height = dst_height;
3597         surface->pending.buffer_viewport.changed = 1;
3598 }
3599
3600 static const struct wl_viewport_interface viewport_interface = {
3601         viewport_destroy,
3602         viewport_set,
3603         viewport_set_source,
3604         viewport_set_destination
3605 };
3606
3607 static void
3608 scaler_destroy(struct wl_client *client,
3609                struct wl_resource *resource)
3610 {
3611         wl_resource_destroy(resource);
3612 }
3613
3614 static void
3615 scaler_get_viewport(struct wl_client *client,
3616                     struct wl_resource *scaler,
3617                     uint32_t id,
3618                     struct wl_resource *surface_resource)
3619 {
3620         int version = wl_resource_get_version(scaler);
3621         struct weston_surface *surface =
3622                 wl_resource_get_user_data(surface_resource);
3623         struct wl_resource *resource;
3624
3625         if (surface->viewport_resource) {
3626                 wl_resource_post_error(scaler,
3627                         WL_SCALER_ERROR_VIEWPORT_EXISTS,
3628                         "a viewport for that surface already exists");
3629                 return;
3630         }
3631
3632         resource = wl_resource_create(client, &wl_viewport_interface,
3633                                       version, id);
3634         if (resource == NULL) {
3635                 wl_client_post_no_memory(client);
3636                 return;
3637         }
3638
3639         wl_resource_set_implementation(resource, &viewport_interface,
3640                                        surface, destroy_viewport);
3641
3642         surface->viewport_resource = resource;
3643 }
3644
3645 static const struct wl_scaler_interface scaler_interface = {
3646         scaler_destroy,
3647         scaler_get_viewport
3648 };
3649
3650 static void
3651 bind_scaler(struct wl_client *client,
3652             void *data, uint32_t version, uint32_t id)
3653 {
3654         struct wl_resource *resource;
3655
3656         resource = wl_resource_create(client, &wl_scaler_interface,
3657                                       MIN(version, 2), id);
3658         if (resource == NULL) {
3659                 wl_client_post_no_memory(client);
3660                 return;
3661         }
3662
3663         wl_resource_set_implementation(resource, &scaler_interface,
3664                                        NULL, NULL);
3665 }
3666
3667 static void
3668 compositor_bind(struct wl_client *client,
3669                 void *data, uint32_t version, uint32_t id)
3670 {
3671         struct weston_compositor *compositor = data;
3672         struct wl_resource *resource;
3673
3674         resource = wl_resource_create(client, &wl_compositor_interface,
3675                                       MIN(version, 3), id);
3676         if (resource == NULL) {
3677                 wl_client_post_no_memory(client);
3678                 return;
3679         }
3680
3681         wl_resource_set_implementation(resource, &compositor_interface,
3682                                        compositor, NULL);
3683 }
3684
3685 static void
3686 log_uname(void)
3687 {
3688         struct utsname usys;
3689
3690         uname(&usys);
3691
3692         weston_log("OS: %s, %s, %s, %s\n", usys.sysname, usys.release,
3693                                                 usys.version, usys.machine);
3694 }
3695
3696 WL_EXPORT int
3697 weston_environment_get_fd(const char *env)
3698 {
3699         char *e, *end;
3700         int fd, flags;
3701
3702         e = getenv(env);
3703         if (!e)
3704                 return -1;
3705         fd = strtol(e, &end, 0);
3706         if (*end != '\0')
3707                 return -1;
3708
3709         flags = fcntl(fd, F_GETFD);
3710         if (flags == -1)
3711                 return -1;
3712
3713         fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
3714         unsetenv(env);
3715
3716         return fd;
3717 }
3718
3719 WL_EXPORT int
3720 weston_compositor_init(struct weston_compositor *ec,
3721                        struct wl_display *display,
3722                        int *argc, char *argv[],
3723                        struct weston_config *config)
3724 {
3725         struct wl_event_loop *loop;
3726         struct xkb_rule_names xkb_names;
3727         struct weston_config_section *s;
3728
3729         ec->config = config;
3730         ec->wl_display = display;
3731         wl_signal_init(&ec->destroy_signal);
3732         wl_signal_init(&ec->create_surface_signal);
3733         wl_signal_init(&ec->activate_signal);
3734         wl_signal_init(&ec->transform_signal);
3735         wl_signal_init(&ec->kill_signal);
3736         wl_signal_init(&ec->idle_signal);
3737         wl_signal_init(&ec->wake_signal);
3738         wl_signal_init(&ec->show_input_panel_signal);
3739         wl_signal_init(&ec->hide_input_panel_signal);
3740         wl_signal_init(&ec->update_input_panel_signal);
3741         wl_signal_init(&ec->seat_created_signal);
3742         wl_signal_init(&ec->output_created_signal);
3743         wl_signal_init(&ec->output_destroyed_signal);
3744         wl_signal_init(&ec->output_moved_signal);
3745         wl_signal_init(&ec->session_signal);
3746         ec->session_active = 1;
3747
3748         ec->output_id_pool = 0;
3749
3750         if (!wl_global_create(display, &wl_compositor_interface, 3,
3751                               ec, compositor_bind))
3752                 return -1;
3753
3754         if (!wl_global_create(display, &wl_subcompositor_interface, 1,
3755                               ec, bind_subcompositor))
3756                 return -1;
3757
3758         if (!wl_global_create(ec->wl_display, &wl_scaler_interface, 2,
3759                               ec, bind_scaler))
3760                 return -1;
3761
3762         wl_list_init(&ec->view_list);
3763         wl_list_init(&ec->plane_list);
3764         wl_list_init(&ec->layer_list);
3765         wl_list_init(&ec->seat_list);
3766         wl_list_init(&ec->output_list);
3767         wl_list_init(&ec->key_binding_list);
3768         wl_list_init(&ec->modifier_binding_list);
3769         wl_list_init(&ec->button_binding_list);
3770         wl_list_init(&ec->touch_binding_list);
3771         wl_list_init(&ec->axis_binding_list);
3772         wl_list_init(&ec->debug_binding_list);
3773
3774         weston_plane_init(&ec->primary_plane, ec, 0, 0);
3775         weston_compositor_stack_plane(ec, &ec->primary_plane, NULL);
3776
3777         s = weston_config_get_section(ec->config, "keyboard", NULL, NULL);
3778         weston_config_section_get_string(s, "keymap_rules",
3779                                          (char **) &xkb_names.rules, NULL);
3780         weston_config_section_get_string(s, "keymap_model",
3781                                          (char **) &xkb_names.model, NULL);
3782         weston_config_section_get_string(s, "keymap_layout",
3783                                          (char **) &xkb_names.layout, NULL);
3784         weston_config_section_get_string(s, "keymap_variant",
3785                                          (char **) &xkb_names.variant, NULL);
3786         weston_config_section_get_string(s, "keymap_options",
3787                                          (char **) &xkb_names.options, NULL);
3788
3789         if (weston_compositor_xkb_init(ec, &xkb_names) < 0)
3790                 return -1;
3791
3792         text_backend_init(ec);
3793
3794         wl_data_device_manager_init(ec->wl_display);
3795
3796         wl_display_init_shm(display);
3797
3798         loop = wl_display_get_event_loop(ec->wl_display);
3799         ec->idle_source = wl_event_loop_add_timer(loop, idle_handler, ec);
3800         wl_event_source_timer_update(ec->idle_source, ec->idle_time * 1000);
3801
3802         ec->input_loop = wl_event_loop_create();
3803
3804         weston_layer_init(&ec->fade_layer, &ec->layer_list);
3805         weston_layer_init(&ec->cursor_layer, &ec->fade_layer.link);
3806
3807         weston_compositor_schedule_repaint(ec);
3808
3809         return 0;
3810 }
3811
3812 WL_EXPORT void
3813 weston_compositor_shutdown(struct weston_compositor *ec)
3814 {
3815         struct weston_output *output, *next;
3816
3817         wl_event_source_remove(ec->idle_source);
3818         if (ec->input_loop_source)
3819                 wl_event_source_remove(ec->input_loop_source);
3820
3821         /* Destroy all outputs associated with this compositor */
3822         wl_list_for_each_safe(output, next, &ec->output_list, link)
3823                 output->destroy(output);
3824
3825         if (ec->renderer)
3826                 ec->renderer->destroy(ec);
3827
3828         weston_binding_list_destroy_all(&ec->key_binding_list);
3829         weston_binding_list_destroy_all(&ec->button_binding_list);
3830         weston_binding_list_destroy_all(&ec->touch_binding_list);
3831         weston_binding_list_destroy_all(&ec->axis_binding_list);
3832         weston_binding_list_destroy_all(&ec->debug_binding_list);
3833
3834         weston_plane_release(&ec->primary_plane);
3835
3836         wl_event_loop_destroy(ec->input_loop);
3837
3838         weston_config_destroy(ec->config);
3839 }
3840
3841 WL_EXPORT void
3842 weston_compositor_set_default_pointer_grab(struct weston_compositor *ec,
3843                         const struct weston_pointer_grab_interface *interface)
3844 {
3845         struct weston_seat *seat;
3846
3847         ec->default_pointer_grab = interface;
3848         wl_list_for_each(seat, &ec->seat_list, link) {
3849                 if (seat->pointer) {
3850                         weston_pointer_set_default_grab(seat->pointer,
3851                                                         interface);
3852                 }
3853         }
3854 }
3855
3856 WL_EXPORT void
3857 weston_version(int *major, int *minor, int *micro)
3858 {
3859         *major = WESTON_VERSION_MAJOR;
3860         *minor = WESTON_VERSION_MINOR;
3861         *micro = WESTON_VERSION_MICRO;
3862 }
3863
3864 static const struct {
3865         uint32_t bit; /* enum weston_capability */
3866         const char *desc;
3867 } capability_strings[] = {
3868         { WESTON_CAP_ROTATION_ANY, "arbitrary surface rotation:" },
3869         { WESTON_CAP_CAPTURE_YFLIP, "screen capture uses y-flip:" },
3870 };
3871
3872 static void
3873 weston_compositor_log_capabilities(struct weston_compositor *compositor)
3874 {
3875         unsigned i;
3876         int yes;
3877
3878         weston_log("Compositor capabilities:\n");
3879         for (i = 0; i < ARRAY_LENGTH(capability_strings); i++) {
3880                 yes = compositor->capabilities & capability_strings[i].bit;
3881                 weston_log_continue(STAMP_SPACE "%s %s\n",
3882                                     capability_strings[i].desc,
3883                                     yes ? "yes" : "no");
3884         }
3885 }
3886
3887 static int on_term_signal(int signal_number, void *data)
3888 {
3889         struct wl_display *display = data;
3890
3891         weston_log("caught signal %d\n", signal_number);
3892         wl_display_terminate(display);
3893
3894         return 1;
3895 }
3896
3897 #ifdef HAVE_LIBUNWIND
3898
3899 static void
3900 print_backtrace(void)
3901 {
3902         unw_cursor_t cursor;
3903         unw_context_t context;
3904         unw_word_t off;
3905         unw_proc_info_t pip;
3906         int ret, i = 0;
3907         char procname[256];
3908         const char *filename;
3909         Dl_info dlinfo;
3910
3911         pip.unwind_info = NULL;
3912         ret = unw_getcontext(&context);
3913         if (ret) {
3914                 weston_log("unw_getcontext: %d\n", ret);
3915                 return;
3916         }
3917
3918         ret = unw_init_local(&cursor, &context);
3919         if (ret) {
3920                 weston_log("unw_init_local: %d\n", ret);
3921                 return;
3922         }
3923
3924         ret = unw_step(&cursor);
3925         while (ret > 0) {
3926                 ret = unw_get_proc_info(&cursor, &pip);
3927                 if (ret) {
3928                         weston_log("unw_get_proc_info: %d\n", ret);
3929                         break;
3930                 }
3931
3932                 ret = unw_get_proc_name(&cursor, procname, 256, &off);
3933                 if (ret && ret != -UNW_ENOMEM) {
3934                         if (ret != -UNW_EUNSPEC)
3935                                 weston_log("unw_get_proc_name: %d\n", ret);
3936                         procname[0] = '?';
3937                         procname[1] = 0;
3938                 }
3939
3940                 if (dladdr((void *)(pip.start_ip + off), &dlinfo) && dlinfo.dli_fname &&
3941                     *dlinfo.dli_fname)
3942                         filename = dlinfo.dli_fname;
3943                 else
3944                         filename = "?";
3945
3946                 weston_log("%u: %s (%s%s+0x%x) [%p]\n", i++, filename, procname,
3947                            ret == -UNW_ENOMEM ? "..." : "", (int)off, (void *)(pip.start_ip + off));
3948
3949                 ret = unw_step(&cursor);
3950                 if (ret < 0)
3951                         weston_log("unw_step: %d\n", ret);
3952         }
3953 }
3954
3955 #else
3956
3957 static void
3958 print_backtrace(void)
3959 {
3960         void *buffer[32];
3961         int i, count;
3962         Dl_info info;
3963
3964         count = backtrace(buffer, ARRAY_LENGTH(buffer));
3965         for (i = 0; i < count; i++) {
3966                 dladdr(buffer[i], &info);
3967                 weston_log("  [%016lx]  %s  (%s)\n",
3968                         (long) buffer[i],
3969                         info.dli_sname ? info.dli_sname : "--",
3970                         info.dli_fname);
3971         }
3972 }
3973
3974 #endif
3975
3976 static void
3977 on_caught_signal(int s, siginfo_t *siginfo, void *context)
3978 {
3979         /* This signal handler will do a best-effort backtrace, and
3980          * then call the backend restore function, which will switch
3981          * back to the vt we launched from or ungrab X etc and then
3982          * raise SIGTRAP.  If we run weston under gdb from X or a
3983          * different vt, and tell gdb "handle *s* nostop", this
3984          * will allow weston to switch back to gdb on crash and then
3985          * gdb will catch the crash with SIGTRAP.*/
3986
3987         weston_log("caught signal: %d\n", s);
3988
3989         print_backtrace();
3990
3991         segv_compositor->restore(segv_compositor);
3992
3993         raise(SIGTRAP);
3994 }
3995
3996 WL_EXPORT void *
3997 weston_load_module(const char *name, const char *entrypoint)
3998 {
3999         char path[PATH_MAX];
4000         void *module, *init;
4001
4002         if (name == NULL)
4003                 return NULL;
4004
4005         if (name[0] != '/')
4006                 snprintf(path, sizeof path, "%s/%s", MODULEDIR, name);
4007         else
4008                 snprintf(path, sizeof path, "%s", name);
4009
4010         module = dlopen(path, RTLD_NOW | RTLD_NOLOAD);
4011         if (module) {
4012                 weston_log("Module '%s' already loaded\n", path);
4013                 dlclose(module);
4014                 return NULL;
4015         }
4016
4017         weston_log("Loading module '%s'\n", path);
4018         module = dlopen(path, RTLD_NOW);
4019         if (!module) {
4020                 weston_log("Failed to load module: %s\n", dlerror());
4021                 return NULL;
4022         }
4023
4024         init = dlsym(module, entrypoint);
4025         if (!init) {
4026                 weston_log("Failed to lookup init function: %s\n", dlerror());
4027                 dlclose(module);
4028                 return NULL;
4029         }
4030
4031         return init;
4032 }
4033
4034 static int
4035 load_modules(struct weston_compositor *ec, const char *modules,
4036              int *argc, char *argv[])
4037 {
4038         const char *p, *end;
4039         char buffer[256];
4040         int (*module_init)(struct weston_compositor *ec,
4041                            int *argc, char *argv[]);
4042
4043         if (modules == NULL)
4044                 return 0;
4045
4046         p = modules;
4047         while (*p) {
4048                 end = strchrnul(p, ',');
4049                 snprintf(buffer, sizeof buffer, "%.*s", (int) (end - p), p);
4050                 module_init = weston_load_module(buffer, "module_init");
4051                 if (module_init)
4052                         module_init(ec, argc, argv);
4053                 p = end;
4054                 while (*p == ',')
4055                         p++;
4056
4057         }
4058
4059         return 0;
4060 }
4061
4062 static const char xdg_error_message[] =
4063         "fatal: environment variable XDG_RUNTIME_DIR is not set.\n";
4064
4065 static const char xdg_wrong_message[] =
4066         "fatal: environment variable XDG_RUNTIME_DIR\n"
4067         "is set to \"%s\", which is not a directory.\n";
4068
4069 static const char xdg_wrong_mode_message[] =
4070         "warning: XDG_RUNTIME_DIR \"%s\" is not configured\n"
4071         "correctly.  Unix access mode must be 0700 (current mode is %o),\n"
4072         "and must be owned by the user (current owner is UID %d).\n";
4073
4074 static const char xdg_detail_message[] =
4075         "Refer to your distribution on how to get it, or\n"
4076         "http://www.freedesktop.org/wiki/Specifications/basedir-spec\n"
4077         "on how to implement it.\n";
4078
4079 static void
4080 verify_xdg_runtime_dir(void)
4081 {
4082         char *dir = getenv("XDG_RUNTIME_DIR");
4083         struct stat s;
4084
4085         if (!dir) {
4086                 weston_log(xdg_error_message);
4087                 weston_log_continue(xdg_detail_message);
4088                 exit(EXIT_FAILURE);
4089         }
4090
4091         if (stat(dir, &s) || !S_ISDIR(s.st_mode)) {
4092                 weston_log(xdg_wrong_message, dir);
4093                 weston_log_continue(xdg_detail_message);
4094                 exit(EXIT_FAILURE);
4095         }
4096
4097         if ((s.st_mode & 0777) != 0700 || s.st_uid != getuid()) {
4098                 weston_log(xdg_wrong_mode_message,
4099                            dir, s.st_mode & 0777, s.st_uid);
4100                 weston_log_continue(xdg_detail_message);
4101         }
4102 }
4103
4104 static int
4105 usage(int error_code)
4106 {
4107         fprintf(stderr,
4108                 "Usage: weston [OPTIONS]\n\n"
4109                 "This is weston version " VERSION ", the Wayland reference compositor.\n"
4110                 "Weston supports multiple backends, and depending on which backend is in use\n"
4111                 "different options will be accepted.\n\n"
4112
4113
4114                 "Core options:\n\n"
4115                 "  --version\t\tPrint weston version\n"
4116                 "  -B, --backend=MODULE\tBackend module, one of drm-backend.so,\n"
4117                 "\t\t\t\tfbdev-backend.so, x11-backend.so or\n"
4118                 "\t\t\t\twayland-backend.so\n"
4119                 "  --shell=MODULE\tShell module, defaults to desktop-shell.so\n"
4120                 "  -S, --socket=NAME\tName of socket to listen on\n"
4121                 "  -i, --idle-time=SECS\tIdle time in seconds\n"
4122                 "  --modules\t\tLoad the comma-separated list of modules\n"
4123                 "  --log==FILE\t\tLog to the given file\n"
4124                 "  --no-config\t\tDo not read weston.ini\n"
4125                 "  -h, --help\t\tThis help message\n\n");
4126
4127         fprintf(stderr,
4128                 "Options for drm-backend.so:\n\n"
4129                 "  --connector=ID\tBring up only this connector\n"
4130                 "  --seat=SEAT\t\tThe seat that weston should run on\n"
4131                 "  --tty=TTY\t\tThe tty to use\n"
4132                 "  --use-pixman\t\tUse the pixman (CPU) renderer\n"
4133                 "  --current-mode\tPrefer current KMS mode over EDID preferred mode\n\n");
4134
4135         fprintf(stderr,
4136                 "Options for fbdev-backend.so:\n\n"
4137                 "  --tty=TTY\t\tThe tty to use\n"
4138                 "  --device=DEVICE\tThe framebuffer device to use\n\n");
4139
4140         fprintf(stderr,
4141                 "Options for x11-backend.so:\n\n"
4142                 "  --width=WIDTH\t\tWidth of X window\n"
4143                 "  --height=HEIGHT\tHeight of X window\n"
4144                 "  --fullscreen\t\tRun in fullscreen mode\n"
4145                 "  --use-pixman\t\tUse the pixman (CPU) renderer\n"
4146                 "  --output-count=COUNT\tCreate multiple outputs\n"
4147                 "  --no-input\t\tDont create input devices\n\n");
4148
4149         fprintf(stderr,
4150                 "Options for wayland-backend.so:\n\n"
4151                 "  --width=WIDTH\t\tWidth of Wayland surface\n"
4152                 "  --height=HEIGHT\tHeight of Wayland surface\n"
4153                 "  --scale=SCALE\tScale factor of ouput\n"
4154                 "  --fullscreen\t\tRun in fullscreen mode\n"
4155                 "  --use-pixman\t\tUse the pixman (CPU) renderer\n"
4156                 "  --output-count=COUNT\tCreate multiple outputs\n"
4157                 "  --sprawl\t\tCreate one fullscreen output for every parent output\n"
4158                 "  --display=DISPLAY\tWayland display to connect to\n\n");
4159
4160 #if defined(BUILD_RPI_COMPOSITOR) && defined(HAVE_BCM_HOST)
4161         fprintf(stderr,
4162                 "Options for rpi-backend.so:\n\n"
4163                 "  --tty=TTY\t\tThe tty to use\n"
4164                 "  --single-buffer\tUse single-buffered Dispmanx elements.\n"
4165                 "  --transform=TR\tThe output transformation, TR is one of:\n"
4166                 "\tnormal 90 180 270 flipped flipped-90 flipped-180 flipped-270\n"
4167                 "  --opaque-regions\tEnable support for opaque regions, can be "
4168                 "very slow without support in the GPU firmware.\n"
4169                 "\n");
4170 #endif
4171
4172 #if defined(BUILD_RDP_COMPOSITOR)
4173     fprintf(stderr,
4174        "Options for rdp-backend.so:\n\n"
4175        "  --width=WIDTH\t\tWidth of desktop\n"
4176        "  --height=HEIGHT\tHeight of desktop\n"
4177        "  --env-socket=SOCKET\tUse that socket as peer connection\n"
4178        "  --address=ADDR\tThe address to bind\n"
4179        "  --port=PORT\tThe port to listen on\n"
4180        "  --no-clients-resize\tThe RDP peers will be forced to the size of the desktop\n"
4181        "  --rdp4-key=FILE\tThe file containing the key for RDP4 encryption\n"
4182        "  --rdp-tls-cert=FILE\tThe file containing the certificate for TLS encryption\n"
4183        "  --rdp-tls-key=FILE\tThe file containing the private key for TLS encryption\n"
4184        "\n");
4185 #endif
4186
4187         exit(error_code);
4188 }
4189
4190 static void
4191 catch_signals(void)
4192 {
4193         struct sigaction action;
4194
4195         action.sa_flags = SA_SIGINFO | SA_RESETHAND;
4196         action.sa_sigaction = on_caught_signal;
4197         sigemptyset(&action.sa_mask);
4198         sigaction(SIGSEGV, &action, NULL);
4199         sigaction(SIGABRT, &action, NULL);
4200 }
4201
4202 static void
4203 handle_primary_client_destroyed(struct wl_listener *listener, void *data)
4204 {
4205         struct wl_client *client = data;
4206
4207         weston_log("Primary client died.  Closing...\n");
4208
4209         wl_display_terminate(wl_client_get_display(client));
4210 }
4211
4212 int main(int argc, char *argv[])
4213 {
4214         int ret = EXIT_SUCCESS;
4215         struct wl_display *display;
4216         struct weston_compositor *ec;
4217         struct wl_event_source *signals[4];
4218         struct wl_event_loop *loop;
4219         struct weston_compositor
4220                 *(*backend_init)(struct wl_display *display,
4221                                  int *argc, char *argv[],
4222                                  struct weston_config *config);
4223         int i, fd;
4224         char *backend = NULL;
4225         char *option_backend = NULL;
4226         char *shell = NULL;
4227         char *option_shell = NULL;
4228         char *modules, *option_modules = NULL;
4229         char *log = NULL;
4230         char *server_socket = NULL, *end;
4231         int32_t idle_time = 300;
4232         int32_t help = 0;
4233         char *socket_name = "wayland-0";
4234         int32_t version = 0;
4235         int32_t noconfig = 0;
4236         struct weston_config *config = NULL;
4237         struct weston_config_section *section;
4238         struct wl_client *primary_client;
4239         struct wl_listener primary_client_destroyed;
4240
4241         const struct weston_option core_options[] = {
4242                 { WESTON_OPTION_STRING, "backend", 'B', &option_backend },
4243                 { WESTON_OPTION_STRING, "shell", 0, &option_shell },
4244                 { WESTON_OPTION_STRING, "socket", 'S', &socket_name },
4245                 { WESTON_OPTION_INTEGER, "idle-time", 'i', &idle_time },
4246                 { WESTON_OPTION_STRING, "modules", 0, &option_modules },
4247                 { WESTON_OPTION_STRING, "log", 0, &log },
4248                 { WESTON_OPTION_BOOLEAN, "help", 'h', &help },
4249                 { WESTON_OPTION_BOOLEAN, "version", 0, &version },
4250                 { WESTON_OPTION_BOOLEAN, "no-config", 0, &noconfig },
4251         };
4252
4253         parse_options(core_options, ARRAY_LENGTH(core_options), &argc, argv);
4254
4255         if (help)
4256                 usage(EXIT_SUCCESS);
4257
4258         if (version) {
4259                 printf(PACKAGE_STRING "\n");
4260                 return EXIT_SUCCESS;
4261         }
4262
4263         weston_log_file_open(log);
4264
4265         weston_log("%s\n"
4266                    STAMP_SPACE "%s\n"
4267                    STAMP_SPACE "Bug reports to: %s\n"
4268                    STAMP_SPACE "Build: %s\n",
4269                    PACKAGE_STRING, PACKAGE_URL, PACKAGE_BUGREPORT,
4270                    BUILD_ID);
4271         log_uname();
4272
4273         verify_xdg_runtime_dir();
4274
4275         display = wl_display_create();
4276
4277         loop = wl_display_get_event_loop(display);
4278         signals[0] = wl_event_loop_add_signal(loop, SIGTERM, on_term_signal,
4279                                               display);
4280         signals[1] = wl_event_loop_add_signal(loop, SIGINT, on_term_signal,
4281                                               display);
4282         signals[2] = wl_event_loop_add_signal(loop, SIGQUIT, on_term_signal,
4283                                               display);
4284
4285         wl_list_init(&child_process_list);
4286         signals[3] = wl_event_loop_add_signal(loop, SIGCHLD, sigchld_handler,
4287                                               NULL);
4288
4289         if (!signals[0] || !signals[1] || !signals[2] || !signals[3]) {
4290                 ret = EXIT_FAILURE;
4291                 goto out_signals;
4292         }
4293
4294         if (noconfig == 0)
4295                 config = weston_config_parse("weston.ini");
4296         if (config != NULL) {
4297                 weston_log("Using config file '%s'\n",
4298                            weston_config_get_full_path(config));
4299         } else {
4300                 weston_log("Starting with no config file.\n");
4301         }
4302         section = weston_config_get_section(config, "core", NULL, NULL);
4303
4304         if (option_backend)
4305                 backend = strdup(option_backend);
4306         else
4307                 weston_config_section_get_string(section, "backend", &backend,
4308                                                  NULL);
4309
4310         if (!backend) {
4311                 if (getenv("WAYLAND_DISPLAY") || getenv("WAYLAND_SOCKET"))
4312                         backend = strdup("wayland-backend.so");
4313                 else if (getenv("DISPLAY"))
4314                         backend = strdup("x11-backend.so");
4315                 else
4316                         backend = strdup(WESTON_NATIVE_BACKEND);
4317         }
4318
4319         backend_init = weston_load_module(backend, "backend_init");
4320         free(backend);
4321         if (!backend_init) {
4322                 ret = EXIT_FAILURE;
4323                 goto out_signals;
4324         }
4325
4326         ec = backend_init(display, &argc, argv, config);
4327         if (ec == NULL) {
4328                 weston_log("fatal: failed to create compositor\n");
4329                 ret = EXIT_FAILURE;
4330                 goto out_signals;
4331         }
4332
4333         catch_signals();
4334         segv_compositor = ec;
4335
4336         ec->idle_time = idle_time;
4337         ec->default_pointer_grab = NULL;
4338
4339         setenv("WAYLAND_DISPLAY", socket_name, 1);
4340
4341         if (option_shell)
4342                 shell = strdup(option_shell);
4343         else
4344                 weston_config_section_get_string(section, "shell", &shell,
4345                                                  "desktop-shell.so");
4346
4347         if (load_modules(ec, shell, &argc, argv) < 0) {
4348                 free(shell);
4349                 goto out;
4350         }
4351         free(shell);
4352
4353         weston_config_section_get_string(section, "modules", &modules, "");
4354         if (load_modules(ec, modules, &argc, argv) < 0) {
4355                 free(modules);
4356                 goto out;
4357         }
4358         free(modules);
4359
4360         if (load_modules(ec, option_modules, &argc, argv) < 0)
4361                 goto out;
4362
4363         for (i = 1; i < argc; i++)
4364                 weston_log("fatal: unhandled option: %s\n", argv[i]);
4365         if (argc > 1) {
4366                 ret = EXIT_FAILURE;
4367                 goto out;
4368         }
4369
4370         weston_compositor_log_capabilities(ec);
4371
4372         server_socket = getenv("WAYLAND_SERVER_SOCKET");
4373         if (server_socket) {
4374                 weston_log("Running with single client\n");
4375                 fd = strtol(server_socket, &end, 0);
4376                 if (*end != '\0')
4377                         fd = -1;
4378         } else {
4379                 fd = -1;
4380         }
4381
4382         if (fd != -1) {
4383                 primary_client = wl_client_create(display, fd);
4384                 if (!primary_client) {
4385                         weston_log("fatal: failed to add client: %m\n");
4386                         ret = EXIT_FAILURE;
4387                         goto out;
4388                 }
4389                 primary_client_destroyed.notify =
4390                         handle_primary_client_destroyed;
4391                 wl_client_add_destroy_listener(primary_client,
4392                                                &primary_client_destroyed);
4393         } else {
4394                 if (wl_display_add_socket(display, socket_name)) {
4395                         weston_log("fatal: failed to add socket: %m\n");
4396                         ret = EXIT_FAILURE;
4397                         goto out;
4398                 }
4399         }
4400
4401         weston_compositor_wake(ec);
4402
4403         wl_display_run(display);
4404
4405  out:
4406         /* prevent further rendering while shutting down */
4407         ec->state = WESTON_COMPOSITOR_OFFSCREEN;
4408
4409         wl_signal_emit(&ec->destroy_signal, ec);
4410
4411         weston_compositor_xkb_destroy(ec);
4412
4413         ec->destroy(ec);
4414
4415 out_signals:
4416         for (i = ARRAY_LENGTH(signals) - 1; i >= 0; i--)
4417                 if (signals[i])
4418                         wl_event_source_remove(signals[i]);
4419
4420         wl_display_destroy(display);
4421
4422         weston_log_file_close();
4423
4424         return ret;
4425 }