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