Switch to global output repaint timer
[platform/upstream/weston.git] / libweston / compositor.c
1 /*
2  * Copyright © 2010-2011 Intel Corporation
3  * Copyright © 2008-2011 Kristian Høgsberg
4  * Copyright © 2012-2015 Collabora, Ltd.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial
16  * portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
22  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
23  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  */
27
28 #include "config.h"
29
30 #include <fcntl.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <stdint.h>
35 #include <limits.h>
36 #include <stdarg.h>
37 #include <assert.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/wait.h>
41 #include <sys/socket.h>
42 #include <sys/utsname.h>
43 #include <sys/stat.h>
44 #include <unistd.h>
45 #include <math.h>
46 #include <linux/input.h>
47 #include <dlfcn.h>
48 #include <signal.h>
49 #include <setjmp.h>
50 #include <sys/time.h>
51 #include <time.h>
52 #include <errno.h>
53
54 #include "timeline.h"
55
56 #include "compositor.h"
57 #include "viewporter-server-protocol.h"
58 #include "presentation-time-server-protocol.h"
59 #include "shared/helpers.h"
60 #include "shared/os-compatibility.h"
61 #include "shared/string-helpers.h"
62 #include "shared/timespec-util.h"
63 #include "git-version.h"
64 #include "version.h"
65 #include "plugin-registry.h"
66
67 #define DEFAULT_REPAINT_WINDOW 7 /* milliseconds */
68
69 static void
70 weston_output_transform_scale_init(struct weston_output *output,
71                                    uint32_t transform, uint32_t scale);
72
73 static void
74 weston_compositor_build_view_list(struct weston_compositor *compositor);
75
76 static void weston_mode_switch_finish(struct weston_output *output,
77                                       int mode_changed,
78                                       int scale_changed)
79 {
80         struct weston_seat *seat;
81         struct wl_resource *resource;
82         pixman_region32_t old_output_region;
83         int version;
84
85         pixman_region32_init(&old_output_region);
86         pixman_region32_copy(&old_output_region, &output->region);
87
88         /* Update output region and transformation matrix */
89         weston_output_transform_scale_init(output, output->transform, output->current_scale);
90
91         pixman_region32_init(&output->previous_damage);
92         pixman_region32_init_rect(&output->region, output->x, output->y,
93                                   output->width, output->height);
94
95         weston_output_update_matrix(output);
96
97         /* If a pointer falls outside the outputs new geometry, move it to its
98          * lower-right corner */
99         wl_list_for_each(seat, &output->compositor->seat_list, link) {
100                 struct weston_pointer *pointer = weston_seat_get_pointer(seat);
101                 int32_t x, y;
102
103                 if (!pointer)
104                         continue;
105
106                 x = wl_fixed_to_int(pointer->x);
107                 y = wl_fixed_to_int(pointer->y);
108
109                 if (!pixman_region32_contains_point(&old_output_region,
110                                                     x, y, NULL) ||
111                     pixman_region32_contains_point(&output->region,
112                                                    x, y, NULL))
113                         continue;
114
115                 if (x >= output->x + output->width)
116                         x = output->x + output->width - 1;
117                 if (y >= output->y + output->height)
118                         y = output->y + output->height - 1;
119
120                 pointer->x = wl_fixed_from_int(x);
121                 pointer->y = wl_fixed_from_int(y);
122         }
123
124         pixman_region32_fini(&old_output_region);
125
126         if (!mode_changed && !scale_changed)
127                 return;
128
129         /* notify clients of the changes */
130         wl_resource_for_each(resource, &output->resource_list) {
131                 if (mode_changed) {
132                         wl_output_send_mode(resource,
133                                             output->current_mode->flags,
134                                             output->current_mode->width,
135                                             output->current_mode->height,
136                                             output->current_mode->refresh);
137                 }
138
139                 version = wl_resource_get_version(resource);
140                 if (version >= WL_OUTPUT_SCALE_SINCE_VERSION && scale_changed)
141                         wl_output_send_scale(resource, output->current_scale);
142
143                 if (version >= WL_OUTPUT_DONE_SINCE_VERSION)
144                         wl_output_send_done(resource);
145         }
146 }
147
148
149 static void
150 weston_compositor_reflow_outputs(struct weston_compositor *compositor,
151                                 struct weston_output *resized_output, int delta_width);
152
153 WL_EXPORT int
154 weston_output_mode_set_native(struct weston_output *output,
155                               struct weston_mode *mode,
156                               int32_t scale)
157 {
158         int ret;
159         int mode_changed = 0, scale_changed = 0;
160         int32_t old_width;
161
162         if (!output->switch_mode)
163                 return -1;
164
165         if (!output->original_mode) {
166                 mode_changed = 1;
167                 ret = output->switch_mode(output, mode);
168                 if (ret < 0)
169                         return ret;
170                 if (output->current_scale != scale) {
171                         scale_changed = 1;
172                         output->current_scale = scale;
173                 }
174         }
175
176         old_width = output->width;
177         output->native_mode = mode;
178         output->native_scale = scale;
179
180         weston_mode_switch_finish(output, mode_changed, scale_changed);
181
182         if (mode_changed || scale_changed) {
183                 weston_compositor_reflow_outputs(output->compositor, output, output->width - old_width);
184
185                 wl_signal_emit(&output->compositor->output_resized_signal, output);
186         }
187         return 0;
188 }
189
190 WL_EXPORT int
191 weston_output_mode_switch_to_native(struct weston_output *output)
192 {
193         int ret;
194         int mode_changed = 0, scale_changed = 0;
195
196         if (!output->switch_mode)
197                 return -1;
198
199         if (!output->original_mode) {
200                 weston_log("already in the native mode\n");
201                 return -1;
202         }
203         /* the non fullscreen clients haven't seen a mode set since we
204          * switched into a temporary, so we need to notify them if the
205          * mode at that time is different from the native mode now.
206          */
207         mode_changed = (output->original_mode != output->native_mode);
208         scale_changed = (output->original_scale != output->native_scale);
209
210         ret = output->switch_mode(output, output->native_mode);
211         if (ret < 0)
212                 return ret;
213
214         output->current_scale = output->native_scale;
215
216         output->original_mode = NULL;
217         output->original_scale = 0;
218
219         weston_mode_switch_finish(output, mode_changed, scale_changed);
220
221         return 0;
222 }
223
224 WL_EXPORT int
225 weston_output_mode_switch_to_temporary(struct weston_output *output,
226                                        struct weston_mode *mode,
227                                        int32_t scale)
228 {
229         int ret;
230
231         if (!output->switch_mode)
232                 return -1;
233
234         /* original_mode is the last mode non full screen clients have seen,
235          * so we shouldn't change it if we already have one set.
236          */
237         if (!output->original_mode) {
238                 output->original_mode = output->native_mode;
239                 output->original_scale = output->native_scale;
240         }
241         ret = output->switch_mode(output, mode);
242         if (ret < 0)
243                 return ret;
244
245         output->current_scale = scale;
246
247         weston_mode_switch_finish(output, 0, 0);
248
249         return 0;
250 }
251
252 static void
253 region_init_infinite(pixman_region32_t *region)
254 {
255         pixman_region32_init_rect(region, INT32_MIN, INT32_MIN,
256                                   UINT32_MAX, UINT32_MAX);
257 }
258
259 static struct weston_subsurface *
260 weston_surface_to_subsurface(struct weston_surface *surface);
261
262 WL_EXPORT struct weston_view *
263 weston_view_create(struct weston_surface *surface)
264 {
265         struct weston_view *view;
266
267         view = zalloc(sizeof *view);
268         if (view == NULL)
269                 return NULL;
270
271         view->surface = surface;
272         view->plane = &surface->compositor->primary_plane;
273
274         /* Assign to surface */
275         wl_list_insert(&surface->views, &view->surface_link);
276
277         wl_signal_init(&view->destroy_signal);
278         wl_list_init(&view->link);
279         wl_list_init(&view->layer_link.link);
280
281         pixman_region32_init(&view->clip);
282
283         view->alpha = 1.0;
284         pixman_region32_init(&view->transform.opaque);
285
286         wl_list_init(&view->geometry.transformation_list);
287         wl_list_insert(&view->geometry.transformation_list,
288                        &view->transform.position.link);
289         weston_matrix_init(&view->transform.position.matrix);
290         wl_list_init(&view->geometry.child_list);
291         pixman_region32_init(&view->geometry.scissor);
292         pixman_region32_init(&view->transform.boundingbox);
293         view->transform.dirty = 1;
294
295         return view;
296 }
297
298 struct weston_frame_callback {
299         struct wl_resource *resource;
300         struct wl_list link;
301 };
302
303 struct weston_presentation_feedback {
304         struct wl_resource *resource;
305
306         /* XXX: could use just wl_resource_get_link() instead */
307         struct wl_list link;
308
309         /* The per-surface feedback flags */
310         uint32_t psf_flags;
311 };
312
313 static void
314 weston_presentation_feedback_discard(
315                 struct weston_presentation_feedback *feedback)
316 {
317         wp_presentation_feedback_send_discarded(feedback->resource);
318         wl_resource_destroy(feedback->resource);
319 }
320
321 static void
322 weston_presentation_feedback_discard_list(struct wl_list *list)
323 {
324         struct weston_presentation_feedback *feedback, *tmp;
325
326         wl_list_for_each_safe(feedback, tmp, list, link)
327                 weston_presentation_feedback_discard(feedback);
328 }
329
330 static void
331 weston_presentation_feedback_present(
332                 struct weston_presentation_feedback *feedback,
333                 struct weston_output *output,
334                 uint32_t refresh_nsec,
335                 const struct timespec *ts,
336                 uint64_t seq,
337                 uint32_t flags)
338 {
339         struct wl_client *client = wl_resource_get_client(feedback->resource);
340         struct wl_resource *o;
341         uint64_t secs;
342
343         wl_resource_for_each(o, &output->resource_list) {
344                 if (wl_resource_get_client(o) != client)
345                         continue;
346
347                 wp_presentation_feedback_send_sync_output(feedback->resource, o);
348         }
349
350         secs = ts->tv_sec;
351         wp_presentation_feedback_send_presented(feedback->resource,
352                                                 secs >> 32, secs & 0xffffffff,
353                                                 ts->tv_nsec,
354                                                 refresh_nsec,
355                                                 seq >> 32, seq & 0xffffffff,
356                                                 flags | feedback->psf_flags);
357         wl_resource_destroy(feedback->resource);
358 }
359
360 static void
361 weston_presentation_feedback_present_list(struct wl_list *list,
362                                           struct weston_output *output,
363                                           uint32_t refresh_nsec,
364                                           const struct timespec *ts,
365                                           uint64_t seq,
366                                           uint32_t flags)
367 {
368         struct weston_presentation_feedback *feedback, *tmp;
369
370         assert(!(flags & WP_PRESENTATION_FEEDBACK_INVALID) ||
371                wl_list_empty(list));
372
373         wl_list_for_each_safe(feedback, tmp, list, link)
374                 weston_presentation_feedback_present(feedback, output,
375                                                      refresh_nsec, ts, seq,
376                                                      flags);
377 }
378
379 static void
380 surface_state_handle_buffer_destroy(struct wl_listener *listener, void *data)
381 {
382         struct weston_surface_state *state =
383                 container_of(listener, struct weston_surface_state,
384                              buffer_destroy_listener);
385
386         state->buffer = NULL;
387 }
388
389 static void
390 weston_surface_state_init(struct weston_surface_state *state)
391 {
392         state->newly_attached = 0;
393         state->buffer = NULL;
394         state->buffer_destroy_listener.notify =
395                 surface_state_handle_buffer_destroy;
396         state->sx = 0;
397         state->sy = 0;
398
399         pixman_region32_init(&state->damage_surface);
400         pixman_region32_init(&state->damage_buffer);
401         pixman_region32_init(&state->opaque);
402         region_init_infinite(&state->input);
403
404         wl_list_init(&state->frame_callback_list);
405         wl_list_init(&state->feedback_list);
406
407         state->buffer_viewport.buffer.transform = WL_OUTPUT_TRANSFORM_NORMAL;
408         state->buffer_viewport.buffer.scale = 1;
409         state->buffer_viewport.buffer.src_width = wl_fixed_from_int(-1);
410         state->buffer_viewport.surface.width = -1;
411         state->buffer_viewport.changed = 0;
412 }
413
414 static void
415 weston_surface_state_fini(struct weston_surface_state *state)
416 {
417         struct weston_frame_callback *cb, *next;
418
419         wl_list_for_each_safe(cb, next,
420                               &state->frame_callback_list, link)
421                 wl_resource_destroy(cb->resource);
422
423         weston_presentation_feedback_discard_list(&state->feedback_list);
424
425         pixman_region32_fini(&state->input);
426         pixman_region32_fini(&state->opaque);
427         pixman_region32_fini(&state->damage_surface);
428         pixman_region32_fini(&state->damage_buffer);
429
430         if (state->buffer)
431                 wl_list_remove(&state->buffer_destroy_listener.link);
432         state->buffer = NULL;
433 }
434
435 static void
436 weston_surface_state_set_buffer(struct weston_surface_state *state,
437                                 struct weston_buffer *buffer)
438 {
439         if (state->buffer == buffer)
440                 return;
441
442         if (state->buffer)
443                 wl_list_remove(&state->buffer_destroy_listener.link);
444         state->buffer = buffer;
445         if (state->buffer)
446                 wl_signal_add(&state->buffer->destroy_signal,
447                               &state->buffer_destroy_listener);
448 }
449
450 WL_EXPORT struct weston_surface *
451 weston_surface_create(struct weston_compositor *compositor)
452 {
453         struct weston_surface *surface;
454
455         surface = zalloc(sizeof *surface);
456         if (surface == NULL)
457                 return NULL;
458
459         wl_signal_init(&surface->destroy_signal);
460         wl_signal_init(&surface->commit_signal);
461
462         surface->compositor = compositor;
463         surface->ref_count = 1;
464
465         surface->buffer_viewport.buffer.transform = WL_OUTPUT_TRANSFORM_NORMAL;
466         surface->buffer_viewport.buffer.scale = 1;
467         surface->buffer_viewport.buffer.src_width = wl_fixed_from_int(-1);
468         surface->buffer_viewport.surface.width = -1;
469
470         weston_surface_state_init(&surface->pending);
471
472         pixman_region32_init(&surface->damage);
473         pixman_region32_init(&surface->opaque);
474         region_init_infinite(&surface->input);
475
476         wl_list_init(&surface->views);
477
478         wl_list_init(&surface->frame_callback_list);
479         wl_list_init(&surface->feedback_list);
480
481         wl_list_init(&surface->subsurface_list);
482         wl_list_init(&surface->subsurface_list_pending);
483
484         weston_matrix_init(&surface->buffer_to_surface_matrix);
485         weston_matrix_init(&surface->surface_to_buffer_matrix);
486
487         wl_list_init(&surface->pointer_constraints);
488
489         return surface;
490 }
491
492 WL_EXPORT void
493 weston_surface_set_color(struct weston_surface *surface,
494                  float red, float green, float blue, float alpha)
495 {
496         surface->compositor->renderer->surface_set_color(surface, red, green, blue, alpha);
497 }
498
499 WL_EXPORT void
500 weston_view_to_global_float(struct weston_view *view,
501                             float sx, float sy, float *x, float *y)
502 {
503         if (view->transform.enabled) {
504                 struct weston_vector v = { { sx, sy, 0.0f, 1.0f } };
505
506                 weston_matrix_transform(&view->transform.matrix, &v);
507
508                 if (fabsf(v.f[3]) < 1e-6) {
509                         weston_log("warning: numerical instability in "
510                                 "%s(), divisor = %g\n", __func__,
511                                 v.f[3]);
512                         *x = 0;
513                         *y = 0;
514                         return;
515                 }
516
517                 *x = v.f[0] / v.f[3];
518                 *y = v.f[1] / v.f[3];
519         } else {
520                 *x = sx + view->geometry.x;
521                 *y = sy + view->geometry.y;
522         }
523 }
524
525 WL_EXPORT void
526 weston_transformed_coord(int width, int height,
527                          enum wl_output_transform transform,
528                          int32_t scale,
529                          float sx, float sy, float *bx, float *by)
530 {
531         switch (transform) {
532         case WL_OUTPUT_TRANSFORM_NORMAL:
533         default:
534                 *bx = sx;
535                 *by = sy;
536                 break;
537         case WL_OUTPUT_TRANSFORM_FLIPPED:
538                 *bx = width - sx;
539                 *by = sy;
540                 break;
541         case WL_OUTPUT_TRANSFORM_90:
542                 *bx = height - sy;
543                 *by = sx;
544                 break;
545         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
546                 *bx = height - sy;
547                 *by = width - sx;
548                 break;
549         case WL_OUTPUT_TRANSFORM_180:
550                 *bx = width - sx;
551                 *by = height - sy;
552                 break;
553         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
554                 *bx = sx;
555                 *by = height - sy;
556                 break;
557         case WL_OUTPUT_TRANSFORM_270:
558                 *bx = sy;
559                 *by = width - sx;
560                 break;
561         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
562                 *bx = sy;
563                 *by = sx;
564                 break;
565         }
566
567         *bx *= scale;
568         *by *= scale;
569 }
570
571 WL_EXPORT pixman_box32_t
572 weston_transformed_rect(int width, int height,
573                         enum wl_output_transform transform,
574                         int32_t scale,
575                         pixman_box32_t rect)
576 {
577         float x1, x2, y1, y2;
578
579         pixman_box32_t ret;
580
581         weston_transformed_coord(width, height, transform, scale,
582                                  rect.x1, rect.y1, &x1, &y1);
583         weston_transformed_coord(width, height, transform, scale,
584                                  rect.x2, rect.y2, &x2, &y2);
585
586         if (x1 <= x2) {
587                 ret.x1 = x1;
588                 ret.x2 = x2;
589         } else {
590                 ret.x1 = x2;
591                 ret.x2 = x1;
592         }
593
594         if (y1 <= y2) {
595                 ret.y1 = y1;
596                 ret.y2 = y2;
597         } else {
598                 ret.y1 = y2;
599                 ret.y2 = y1;
600         }
601
602         return ret;
603 }
604
605 /** Transform a region by a matrix, restricted to axis-aligned transformations
606  *
607  * Warning: This function does not work for projective, affine, or matrices
608  * that encode arbitrary rotations. Only 90-degree step rotations are
609  * supported.
610  */
611 WL_EXPORT void
612 weston_matrix_transform_region(pixman_region32_t *dest,
613                                struct weston_matrix *matrix,
614                                pixman_region32_t *src)
615 {
616         pixman_box32_t *src_rects, *dest_rects;
617         int nrects, i;
618
619         src_rects = pixman_region32_rectangles(src, &nrects);
620         dest_rects = malloc(nrects * sizeof(*dest_rects));
621         if (!dest_rects)
622                 return;
623
624         for (i = 0; i < nrects; i++) {
625                 struct weston_vector vec1 = {{
626                         src_rects[i].x1, src_rects[i].y1, 0, 1
627                 }};
628                 weston_matrix_transform(matrix, &vec1);
629                 vec1.f[0] /= vec1.f[3];
630                 vec1.f[1] /= vec1.f[3];
631
632                 struct weston_vector vec2 = {{
633                         src_rects[i].x2, src_rects[i].y2, 0, 1
634                 }};
635                 weston_matrix_transform(matrix, &vec2);
636                 vec2.f[0] /= vec2.f[3];
637                 vec2.f[1] /= vec2.f[3];
638
639                 if (vec1.f[0] < vec2.f[0]) {
640                         dest_rects[i].x1 = floor(vec1.f[0]);
641                         dest_rects[i].x2 = ceil(vec2.f[0]);
642                 } else {
643                         dest_rects[i].x1 = floor(vec2.f[0]);
644                         dest_rects[i].x2 = ceil(vec1.f[0]);
645                 }
646
647                 if (vec1.f[1] < vec2.f[1]) {
648                         dest_rects[i].y1 = floor(vec1.f[1]);
649                         dest_rects[i].y2 = ceil(vec2.f[1]);
650                 } else {
651                         dest_rects[i].y1 = floor(vec2.f[1]);
652                         dest_rects[i].y2 = ceil(vec1.f[1]);
653                 }
654         }
655
656         pixman_region32_clear(dest);
657         pixman_region32_init_rects(dest, dest_rects, nrects);
658         free(dest_rects);
659 }
660
661 WL_EXPORT void
662 weston_transformed_region(int width, int height,
663                           enum wl_output_transform transform,
664                           int32_t scale,
665                           pixman_region32_t *src, pixman_region32_t *dest)
666 {
667         pixman_box32_t *src_rects, *dest_rects;
668         int nrects, i;
669
670         if (transform == WL_OUTPUT_TRANSFORM_NORMAL && scale == 1) {
671                 if (src != dest)
672                         pixman_region32_copy(dest, src);
673                 return;
674         }
675
676         src_rects = pixman_region32_rectangles(src, &nrects);
677         dest_rects = malloc(nrects * sizeof(*dest_rects));
678         if (!dest_rects)
679                 return;
680
681         if (transform == WL_OUTPUT_TRANSFORM_NORMAL) {
682                 memcpy(dest_rects, src_rects, nrects * sizeof(*dest_rects));
683         } else {
684                 for (i = 0; i < nrects; i++) {
685                         switch (transform) {
686                         default:
687                         case WL_OUTPUT_TRANSFORM_NORMAL:
688                                 dest_rects[i].x1 = src_rects[i].x1;
689                                 dest_rects[i].y1 = src_rects[i].y1;
690                                 dest_rects[i].x2 = src_rects[i].x2;
691                                 dest_rects[i].y2 = src_rects[i].y2;
692                                 break;
693                         case WL_OUTPUT_TRANSFORM_90:
694                                 dest_rects[i].x1 = height - src_rects[i].y2;
695                                 dest_rects[i].y1 = src_rects[i].x1;
696                                 dest_rects[i].x2 = height - src_rects[i].y1;
697                                 dest_rects[i].y2 = src_rects[i].x2;
698                                 break;
699                         case WL_OUTPUT_TRANSFORM_180:
700                                 dest_rects[i].x1 = width - src_rects[i].x2;
701                                 dest_rects[i].y1 = height - src_rects[i].y2;
702                                 dest_rects[i].x2 = width - src_rects[i].x1;
703                                 dest_rects[i].y2 = height - src_rects[i].y1;
704                                 break;
705                         case WL_OUTPUT_TRANSFORM_270:
706                                 dest_rects[i].x1 = src_rects[i].y1;
707                                 dest_rects[i].y1 = width - src_rects[i].x2;
708                                 dest_rects[i].x2 = src_rects[i].y2;
709                                 dest_rects[i].y2 = width - src_rects[i].x1;
710                                 break;
711                         case WL_OUTPUT_TRANSFORM_FLIPPED:
712                                 dest_rects[i].x1 = width - src_rects[i].x2;
713                                 dest_rects[i].y1 = src_rects[i].y1;
714                                 dest_rects[i].x2 = width - src_rects[i].x1;
715                                 dest_rects[i].y2 = src_rects[i].y2;
716                                 break;
717                         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
718                                 dest_rects[i].x1 = height - src_rects[i].y2;
719                                 dest_rects[i].y1 = width - src_rects[i].x2;
720                                 dest_rects[i].x2 = height - src_rects[i].y1;
721                                 dest_rects[i].y2 = width - src_rects[i].x1;
722                                 break;
723                         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
724                                 dest_rects[i].x1 = src_rects[i].x1;
725                                 dest_rects[i].y1 = height - src_rects[i].y2;
726                                 dest_rects[i].x2 = src_rects[i].x2;
727                                 dest_rects[i].y2 = height - src_rects[i].y1;
728                                 break;
729                         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
730                                 dest_rects[i].x1 = src_rects[i].y1;
731                                 dest_rects[i].y1 = src_rects[i].x1;
732                                 dest_rects[i].x2 = src_rects[i].y2;
733                                 dest_rects[i].y2 = src_rects[i].x2;
734                                 break;
735                         }
736                 }
737         }
738
739         if (scale != 1) {
740                 for (i = 0; i < nrects; i++) {
741                         dest_rects[i].x1 *= scale;
742                         dest_rects[i].x2 *= scale;
743                         dest_rects[i].y1 *= scale;
744                         dest_rects[i].y2 *= scale;
745                 }
746         }
747
748         pixman_region32_clear(dest);
749         pixman_region32_init_rects(dest, dest_rects, nrects);
750         free(dest_rects);
751 }
752
753 static void
754 viewport_surface_to_buffer(struct weston_surface *surface,
755                            float sx, float sy, float *bx, float *by)
756 {
757         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
758         double src_width, src_height;
759         double src_x, src_y;
760
761         if (vp->buffer.src_width == wl_fixed_from_int(-1)) {
762                 if (vp->surface.width == -1) {
763                         *bx = sx;
764                         *by = sy;
765                         return;
766                 }
767
768                 src_x = 0.0;
769                 src_y = 0.0;
770                 src_width = surface->width_from_buffer;
771                 src_height = surface->height_from_buffer;
772         } else {
773                 src_x = wl_fixed_to_double(vp->buffer.src_x);
774                 src_y = wl_fixed_to_double(vp->buffer.src_y);
775                 src_width = wl_fixed_to_double(vp->buffer.src_width);
776                 src_height = wl_fixed_to_double(vp->buffer.src_height);
777         }
778
779         *bx = sx * src_width / surface->width + src_x;
780         *by = sy * src_height / surface->height + src_y;
781 }
782
783 WL_EXPORT void
784 weston_surface_to_buffer_float(struct weston_surface *surface,
785                                float sx, float sy, float *bx, float *by)
786 {
787         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
788
789         /* first transform coordinates if the viewport is set */
790         viewport_surface_to_buffer(surface, sx, sy, bx, by);
791
792         weston_transformed_coord(surface->width_from_buffer,
793                                  surface->height_from_buffer,
794                                  vp->buffer.transform, vp->buffer.scale,
795                                  *bx, *by, bx, by);
796 }
797
798 /** Transform a rectangle from surface coordinates to buffer coordinates
799  *
800  * \param surface The surface to fetch wp_viewport and buffer transformation
801  * from.
802  * \param rect The rectangle to transform.
803  * \return The transformed rectangle.
804  *
805  * Viewport and buffer transformations can only do translation, scaling,
806  * and rotations in 90-degree steps. Therefore the only loss in the
807  * conversion is coordinate rounding.
808  *
809  * However, some coordinate rounding takes place as an intermediate
810  * step before the buffer scale factor is applied, so the rectangle
811  * boundary may not be exactly as expected.
812  *
813  * This is OK for damage tracking since a little extra coverage is
814  * not a problem.
815  */
816 WL_EXPORT pixman_box32_t
817 weston_surface_to_buffer_rect(struct weston_surface *surface,
818                               pixman_box32_t rect)
819 {
820         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
821         float xf, yf;
822
823         /* first transform box coordinates if the viewport is set */
824         viewport_surface_to_buffer(surface, rect.x1, rect.y1, &xf, &yf);
825         rect.x1 = floorf(xf);
826         rect.y1 = floorf(yf);
827
828         viewport_surface_to_buffer(surface, rect.x2, rect.y2, &xf, &yf);
829         rect.x2 = ceilf(xf);
830         rect.y2 = ceilf(yf);
831
832         return weston_transformed_rect(surface->width_from_buffer,
833                                        surface->height_from_buffer,
834                                        vp->buffer.transform, vp->buffer.scale,
835                                        rect);
836 }
837
838 /** Transform a region from surface coordinates to buffer coordinates
839  *
840  * \param surface The surface to fetch wp_viewport and buffer transformation
841  * from.
842  * \param surface_region[in] The region in surface coordinates.
843  * \param buffer_region[out] The region converted to buffer coordinates.
844  *
845  * Buffer_region must be init'd, but will be completely overwritten.
846  *
847  * Viewport and buffer transformations can only do translation, scaling,
848  * and rotations in 90-degree steps. Therefore the only loss in the
849  * conversion is from the coordinate rounding that takes place in
850  * \ref weston_surface_to_buffer_rect.
851  */
852 WL_EXPORT void
853 weston_surface_to_buffer_region(struct weston_surface *surface,
854                                 pixman_region32_t *surface_region,
855                                 pixman_region32_t *buffer_region)
856 {
857         pixman_box32_t *src_rects, *dest_rects;
858         int nrects, i;
859
860         src_rects = pixman_region32_rectangles(surface_region, &nrects);
861         dest_rects = malloc(nrects * sizeof(*dest_rects));
862         if (!dest_rects)
863                 return;
864
865         for (i = 0; i < nrects; i++) {
866                 dest_rects[i] = weston_surface_to_buffer_rect(surface,
867                                                               src_rects[i]);
868         }
869
870         pixman_region32_fini(buffer_region);
871         pixman_region32_init_rects(buffer_region, dest_rects, nrects);
872         free(dest_rects);
873 }
874
875 WL_EXPORT void
876 weston_view_move_to_plane(struct weston_view *view,
877                              struct weston_plane *plane)
878 {
879         if (view->plane == plane)
880                 return;
881
882         weston_view_damage_below(view);
883         view->plane = plane;
884         weston_surface_damage(view->surface);
885 }
886
887 /** Inflict damage on the plane where the view is visible.
888  *
889  * \param view The view that causes the damage.
890  *
891  * If the view is currently on a plane (including the primary plane),
892  * take the view's boundingbox, subtract all the opaque views that cover it,
893  * and add the remaining region as damage to the plane. This corresponds
894  * to the damage inflicted to the plane if this view disappeared.
895  *
896  * A repaint is scheduled for this view.
897  *
898  * The region of all opaque views covering this view is stored in
899  * weston_view::clip and updated by view_accumulate_damage() during
900  * weston_output_repaint(). Specifically, that region matches the
901  * scenegraph as it was last painted.
902  */
903 WL_EXPORT void
904 weston_view_damage_below(struct weston_view *view)
905 {
906         pixman_region32_t damage;
907
908         pixman_region32_init(&damage);
909         pixman_region32_subtract(&damage, &view->transform.boundingbox,
910                                  &view->clip);
911         if (view->plane)
912                 pixman_region32_union(&view->plane->damage,
913                                       &view->plane->damage, &damage);
914         pixman_region32_fini(&damage);
915         weston_view_schedule_repaint(view);
916 }
917
918 /**
919  * \param es    The surface
920  * \param mask  The new set of outputs for the surface
921  *
922  * Sets the surface's set of outputs to the ones specified by
923  * the new output mask provided.  Identifies the outputs that
924  * have changed, the posts enter and leave events for these
925  * outputs as appropriate.
926  */
927 static void
928 weston_surface_update_output_mask(struct weston_surface *es, uint32_t mask)
929 {
930         uint32_t different = es->output_mask ^ mask;
931         uint32_t entered = mask & different;
932         uint32_t left = es->output_mask & different;
933         struct weston_output *output;
934         struct wl_resource *resource = NULL;
935         struct wl_client *client;
936
937         es->output_mask = mask;
938         if (es->resource == NULL)
939                 return;
940         if (different == 0)
941                 return;
942
943         client = wl_resource_get_client(es->resource);
944
945         wl_list_for_each(output, &es->compositor->output_list, link) {
946                 if (1u << output->id & different)
947                         resource =
948                                 wl_resource_find_for_client(&output->resource_list,
949                                                          client);
950                 if (resource == NULL)
951                         continue;
952                 if (1u << output->id & entered)
953                         wl_surface_send_enter(es->resource, resource);
954                 if (1u << output->id & left)
955                         wl_surface_send_leave(es->resource, resource);
956         }
957 }
958
959 /** Recalculate which output(s) the surface has views displayed on
960  *
961  * \param es  The surface to remap to outputs
962  *
963  * Finds the output that is showing the largest amount of one
964  * of the surface's various views.  This output becomes the
965  * surface's primary output for vsync and frame callback purposes.
966  *
967  * Also notes all outputs of all of the surface's views
968  * in the output_mask for the surface.
969  */
970 static void
971 weston_surface_assign_output(struct weston_surface *es)
972 {
973         struct weston_output *new_output;
974         struct weston_view *view;
975         pixman_region32_t region;
976         uint32_t max, area, mask;
977         pixman_box32_t *e;
978
979         new_output = NULL;
980         max = 0;
981         mask = 0;
982         pixman_region32_init(&region);
983         wl_list_for_each(view, &es->views, surface_link) {
984                 if (!view->output)
985                         continue;
986
987                 pixman_region32_intersect(&region, &view->transform.boundingbox,
988                                           &view->output->region);
989
990                 e = pixman_region32_extents(&region);
991                 area = (e->x2 - e->x1) * (e->y2 - e->y1);
992
993                 mask |= view->output_mask;
994
995                 if (area >= max) {
996                         new_output = view->output;
997                         max = area;
998                 }
999         }
1000         pixman_region32_fini(&region);
1001
1002         es->output = new_output;
1003         weston_surface_update_output_mask(es, mask);
1004 }
1005
1006 /** Recalculate which output(s) the view is displayed on
1007  *
1008  * \param ev  The view to remap to outputs
1009  *
1010  * Identifies the set of outputs that the view is visible on,
1011  * noting them into the output_mask.  The output that the view
1012  * is most visible on is set as the view's primary output.
1013  *
1014  * Also does the same for the view's surface.  See
1015  * weston_surface_assign_output().
1016  */
1017 static void
1018 weston_view_assign_output(struct weston_view *ev)
1019 {
1020         struct weston_compositor *ec = ev->surface->compositor;
1021         struct weston_output *output, *new_output;
1022         pixman_region32_t region;
1023         uint32_t max, area, mask;
1024         pixman_box32_t *e;
1025
1026         new_output = NULL;
1027         max = 0;
1028         mask = 0;
1029         pixman_region32_init(&region);
1030         wl_list_for_each(output, &ec->output_list, link) {
1031                 if (output->destroying)
1032                         continue;
1033
1034                 pixman_region32_intersect(&region, &ev->transform.boundingbox,
1035                                           &output->region);
1036
1037                 e = pixman_region32_extents(&region);
1038                 area = (e->x2 - e->x1) * (e->y2 - e->y1);
1039
1040                 if (area > 0)
1041                         mask |= 1u << output->id;
1042
1043                 if (area >= max) {
1044                         new_output = output;
1045                         max = area;
1046                 }
1047         }
1048         pixman_region32_fini(&region);
1049
1050         ev->output = new_output;
1051         ev->output_mask = mask;
1052
1053         weston_surface_assign_output(ev->surface);
1054 }
1055
1056 static void
1057 weston_view_to_view_map(struct weston_view *from, struct weston_view *to,
1058                         int from_x, int from_y, int *to_x, int *to_y)
1059 {
1060         float x, y;
1061
1062         weston_view_to_global_float(from, from_x, from_y, &x, &y);
1063         weston_view_from_global_float(to, x, y, &x, &y);
1064
1065         *to_x = round(x);
1066         *to_y = round(y);
1067 }
1068
1069 static void
1070 weston_view_transfer_scissor(struct weston_view *from, struct weston_view *to)
1071 {
1072         pixman_box32_t *a;
1073         pixman_box32_t b;
1074
1075         a = pixman_region32_extents(&from->geometry.scissor);
1076
1077         weston_view_to_view_map(from, to, a->x1, a->y1, &b.x1, &b.y1);
1078         weston_view_to_view_map(from, to, a->x2, a->y2, &b.x2, &b.y2);
1079
1080         pixman_region32_fini(&to->geometry.scissor);
1081         pixman_region32_init_with_extents(&to->geometry.scissor, &b);
1082 }
1083
1084 static void
1085 view_compute_bbox(struct weston_view *view, const pixman_box32_t *inbox,
1086                   pixman_region32_t *bbox)
1087 {
1088         float min_x = HUGE_VALF,  min_y = HUGE_VALF;
1089         float max_x = -HUGE_VALF, max_y = -HUGE_VALF;
1090         int32_t s[4][2] = {
1091                 { inbox->x1, inbox->y1 },
1092                 { inbox->x1, inbox->y2 },
1093                 { inbox->x2, inbox->y1 },
1094                 { inbox->x2, inbox->y2 },
1095         };
1096         float int_x, int_y;
1097         int i;
1098
1099         if (inbox->x1 == inbox->x2 || inbox->y1 == inbox->y2) {
1100                 /* avoid rounding empty bbox to 1x1 */
1101                 pixman_region32_init(bbox);
1102                 return;
1103         }
1104
1105         for (i = 0; i < 4; ++i) {
1106                 float x, y;
1107                 weston_view_to_global_float(view, s[i][0], s[i][1], &x, &y);
1108                 if (x < min_x)
1109                         min_x = x;
1110                 if (x > max_x)
1111                         max_x = x;
1112                 if (y < min_y)
1113                         min_y = y;
1114                 if (y > max_y)
1115                         max_y = y;
1116         }
1117
1118         int_x = floorf(min_x);
1119         int_y = floorf(min_y);
1120         pixman_region32_init_rect(bbox, int_x, int_y,
1121                                   ceilf(max_x) - int_x, ceilf(max_y) - int_y);
1122 }
1123
1124 static void
1125 weston_view_update_transform_disable(struct weston_view *view)
1126 {
1127         view->transform.enabled = 0;
1128
1129         /* round off fractions when not transformed */
1130         view->geometry.x = roundf(view->geometry.x);
1131         view->geometry.y = roundf(view->geometry.y);
1132
1133         /* Otherwise identity matrix, but with x and y translation. */
1134         view->transform.position.matrix.type = WESTON_MATRIX_TRANSFORM_TRANSLATE;
1135         view->transform.position.matrix.d[12] = view->geometry.x;
1136         view->transform.position.matrix.d[13] = view->geometry.y;
1137
1138         view->transform.matrix = view->transform.position.matrix;
1139
1140         view->transform.inverse = view->transform.position.matrix;
1141         view->transform.inverse.d[12] = -view->geometry.x;
1142         view->transform.inverse.d[13] = -view->geometry.y;
1143
1144         pixman_region32_init_rect(&view->transform.boundingbox,
1145                                   0, 0,
1146                                   view->surface->width,
1147                                   view->surface->height);
1148         if (view->geometry.scissor_enabled)
1149                 pixman_region32_intersect(&view->transform.boundingbox,
1150                                           &view->transform.boundingbox,
1151                                           &view->geometry.scissor);
1152
1153         pixman_region32_translate(&view->transform.boundingbox,
1154                                   view->geometry.x, view->geometry.y);
1155
1156         if (view->alpha == 1.0) {
1157                 pixman_region32_copy(&view->transform.opaque,
1158                                      &view->surface->opaque);
1159                 pixman_region32_translate(&view->transform.opaque,
1160                                           view->geometry.x,
1161                                           view->geometry.y);
1162         }
1163 }
1164
1165 static int
1166 weston_view_update_transform_enable(struct weston_view *view)
1167 {
1168         struct weston_view *parent = view->geometry.parent;
1169         struct weston_matrix *matrix = &view->transform.matrix;
1170         struct weston_matrix *inverse = &view->transform.inverse;
1171         struct weston_transform *tform;
1172         pixman_region32_t surfregion;
1173         const pixman_box32_t *surfbox;
1174
1175         view->transform.enabled = 1;
1176
1177         /* Otherwise identity matrix, but with x and y translation. */
1178         view->transform.position.matrix.type = WESTON_MATRIX_TRANSFORM_TRANSLATE;
1179         view->transform.position.matrix.d[12] = view->geometry.x;
1180         view->transform.position.matrix.d[13] = view->geometry.y;
1181
1182         weston_matrix_init(matrix);
1183         wl_list_for_each(tform, &view->geometry.transformation_list, link)
1184                 weston_matrix_multiply(matrix, &tform->matrix);
1185
1186         if (parent)
1187                 weston_matrix_multiply(matrix, &parent->transform.matrix);
1188
1189         if (weston_matrix_invert(inverse, matrix) < 0) {
1190                 /* Oops, bad total transformation, not invertible */
1191                 weston_log("error: weston_view %p"
1192                         " transformation not invertible.\n", view);
1193                 return -1;
1194         }
1195
1196         if (view->alpha == 1.0 &&
1197             matrix->type == WESTON_MATRIX_TRANSFORM_TRANSLATE) {
1198                 pixman_region32_copy(&view->transform.opaque,
1199                                      &view->surface->opaque);
1200                 pixman_region32_translate(&view->transform.opaque,
1201                                           matrix->d[12],
1202                                           matrix->d[13]);
1203         }
1204
1205         pixman_region32_init_rect(&surfregion, 0, 0,
1206                                   view->surface->width, view->surface->height);
1207         if (view->geometry.scissor_enabled)
1208                 pixman_region32_intersect(&surfregion, &surfregion,
1209                                           &view->geometry.scissor);
1210         surfbox = pixman_region32_extents(&surfregion);
1211
1212         view_compute_bbox(view, surfbox, &view->transform.boundingbox);
1213         pixman_region32_fini(&surfregion);
1214
1215         return 0;
1216 }
1217
1218 static struct weston_layer *
1219 get_view_layer(struct weston_view *view)
1220 {
1221         if (view->parent_view)
1222                 return get_view_layer(view->parent_view);
1223         return view->layer_link.layer;
1224 }
1225
1226 WL_EXPORT void
1227 weston_view_update_transform(struct weston_view *view)
1228 {
1229         struct weston_view *parent = view->geometry.parent;
1230         struct weston_layer *layer;
1231         pixman_region32_t mask;
1232
1233         if (!view->transform.dirty)
1234                 return;
1235
1236         if (parent)
1237                 weston_view_update_transform(parent);
1238
1239         view->transform.dirty = 0;
1240
1241         weston_view_damage_below(view);
1242
1243         pixman_region32_fini(&view->transform.boundingbox);
1244         pixman_region32_fini(&view->transform.opaque);
1245         pixman_region32_init(&view->transform.opaque);
1246
1247         /* transform.position is always in transformation_list */
1248         if (view->geometry.transformation_list.next ==
1249             &view->transform.position.link &&
1250             view->geometry.transformation_list.prev ==
1251             &view->transform.position.link &&
1252             !parent) {
1253                 weston_view_update_transform_disable(view);
1254         } else {
1255                 if (weston_view_update_transform_enable(view) < 0)
1256                         weston_view_update_transform_disable(view);
1257         }
1258
1259         layer = get_view_layer(view);
1260         if (layer) {
1261                 pixman_region32_init_with_extents(&mask, &layer->mask);
1262                 pixman_region32_intersect(&view->transform.boundingbox,
1263                                           &view->transform.boundingbox, &mask);
1264                 pixman_region32_intersect(&view->transform.opaque,
1265                                           &view->transform.opaque, &mask);
1266                 pixman_region32_fini(&mask);
1267         }
1268
1269         if (parent) {
1270                 if (parent->geometry.scissor_enabled) {
1271                         view->geometry.scissor_enabled = true;
1272                         weston_view_transfer_scissor(parent, view);
1273                 } else {
1274                         view->geometry.scissor_enabled = false;
1275                 }
1276         }
1277
1278         weston_view_damage_below(view);
1279
1280         weston_view_assign_output(view);
1281
1282         wl_signal_emit(&view->surface->compositor->transform_signal,
1283                        view->surface);
1284 }
1285
1286 WL_EXPORT void
1287 weston_view_geometry_dirty(struct weston_view *view)
1288 {
1289         struct weston_view *child;
1290
1291         /*
1292          * The invariant: if view->geometry.dirty, then all views
1293          * in view->geometry.child_list have geometry.dirty too.
1294          * Corollary: if not parent->geometry.dirty, then all ancestors
1295          * are not dirty.
1296          */
1297
1298         if (view->transform.dirty)
1299                 return;
1300
1301         view->transform.dirty = 1;
1302
1303         wl_list_for_each(child, &view->geometry.child_list,
1304                          geometry.parent_link)
1305                 weston_view_geometry_dirty(child);
1306 }
1307
1308 WL_EXPORT void
1309 weston_view_to_global_fixed(struct weston_view *view,
1310                             wl_fixed_t vx, wl_fixed_t vy,
1311                             wl_fixed_t *x, wl_fixed_t *y)
1312 {
1313         float xf, yf;
1314
1315         weston_view_to_global_float(view,
1316                                     wl_fixed_to_double(vx),
1317                                     wl_fixed_to_double(vy),
1318                                     &xf, &yf);
1319         *x = wl_fixed_from_double(xf);
1320         *y = wl_fixed_from_double(yf);
1321 }
1322
1323 WL_EXPORT void
1324 weston_view_from_global_float(struct weston_view *view,
1325                               float x, float y, float *vx, float *vy)
1326 {
1327         if (view->transform.enabled) {
1328                 struct weston_vector v = { { x, y, 0.0f, 1.0f } };
1329
1330                 weston_matrix_transform(&view->transform.inverse, &v);
1331
1332                 if (fabsf(v.f[3]) < 1e-6) {
1333                         weston_log("warning: numerical instability in "
1334                                 "weston_view_from_global(), divisor = %g\n",
1335                                 v.f[3]);
1336                         *vx = 0;
1337                         *vy = 0;
1338                         return;
1339                 }
1340
1341                 *vx = v.f[0] / v.f[3];
1342                 *vy = v.f[1] / v.f[3];
1343         } else {
1344                 *vx = x - view->geometry.x;
1345                 *vy = y - view->geometry.y;
1346         }
1347 }
1348
1349 WL_EXPORT void
1350 weston_view_from_global_fixed(struct weston_view *view,
1351                               wl_fixed_t x, wl_fixed_t y,
1352                               wl_fixed_t *vx, wl_fixed_t *vy)
1353 {
1354         float vxf, vyf;
1355
1356         weston_view_from_global_float(view,
1357                                       wl_fixed_to_double(x),
1358                                       wl_fixed_to_double(y),
1359                                       &vxf, &vyf);
1360         *vx = wl_fixed_from_double(vxf);
1361         *vy = wl_fixed_from_double(vyf);
1362 }
1363
1364 WL_EXPORT void
1365 weston_view_from_global(struct weston_view *view,
1366                         int32_t x, int32_t y, int32_t *vx, int32_t *vy)
1367 {
1368         float vxf, vyf;
1369
1370         weston_view_from_global_float(view, x, y, &vxf, &vyf);
1371         *vx = floorf(vxf);
1372         *vy = floorf(vyf);
1373 }
1374
1375 /**
1376  * \param surface  The surface to be repainted
1377  *
1378  * Marks the output(s) that the surface is shown on as needing to be
1379  * repainted.  See weston_output_schedule_repaint().
1380  */
1381 WL_EXPORT void
1382 weston_surface_schedule_repaint(struct weston_surface *surface)
1383 {
1384         struct weston_output *output;
1385
1386         wl_list_for_each(output, &surface->compositor->output_list, link)
1387                 if (surface->output_mask & (1u << output->id))
1388                         weston_output_schedule_repaint(output);
1389 }
1390
1391 /**
1392  * \param view  The view to be repainted
1393  *
1394  * Marks the output(s) that the view is shown on as needing to be
1395  * repainted.  See weston_output_schedule_repaint().
1396  */
1397 WL_EXPORT void
1398 weston_view_schedule_repaint(struct weston_view *view)
1399 {
1400         struct weston_output *output;
1401
1402         wl_list_for_each(output, &view->surface->compositor->output_list, link)
1403                 if (view->output_mask & (1u << output->id))
1404                         weston_output_schedule_repaint(output);
1405 }
1406
1407 /**
1408  * XXX: This function does it the wrong way.
1409  * surface->damage is the damage from the client, and causes
1410  * surface_flush_damage() to copy pixels. No window management action can
1411  * cause damage to the client-provided content, warranting re-upload!
1412  *
1413  * Instead of surface->damage, this function should record the damage
1414  * with all the views for this surface to avoid extraneous texture
1415  * uploads.
1416  */
1417 WL_EXPORT void
1418 weston_surface_damage(struct weston_surface *surface)
1419 {
1420         pixman_region32_union_rect(&surface->damage, &surface->damage,
1421                                    0, 0, surface->width,
1422                                    surface->height);
1423
1424         weston_surface_schedule_repaint(surface);
1425 }
1426
1427 WL_EXPORT void
1428 weston_view_set_position(struct weston_view *view, float x, float y)
1429 {
1430         if (view->geometry.x == x && view->geometry.y == y)
1431                 return;
1432
1433         view->geometry.x = x;
1434         view->geometry.y = y;
1435         weston_view_geometry_dirty(view);
1436 }
1437
1438 static void
1439 transform_parent_handle_parent_destroy(struct wl_listener *listener,
1440                                        void *data)
1441 {
1442         struct weston_view *view =
1443                 container_of(listener, struct weston_view,
1444                              geometry.parent_destroy_listener);
1445
1446         weston_view_set_transform_parent(view, NULL);
1447 }
1448
1449 WL_EXPORT void
1450 weston_view_set_transform_parent(struct weston_view *view,
1451                                  struct weston_view *parent)
1452 {
1453         if (view->geometry.parent) {
1454                 wl_list_remove(&view->geometry.parent_destroy_listener.link);
1455                 wl_list_remove(&view->geometry.parent_link);
1456
1457                 if (!parent)
1458                         view->geometry.scissor_enabled = false;
1459         }
1460
1461         view->geometry.parent = parent;
1462
1463         view->geometry.parent_destroy_listener.notify =
1464                 transform_parent_handle_parent_destroy;
1465         if (parent) {
1466                 wl_signal_add(&parent->destroy_signal,
1467                               &view->geometry.parent_destroy_listener);
1468                 wl_list_insert(&parent->geometry.child_list,
1469                                &view->geometry.parent_link);
1470         }
1471
1472         weston_view_geometry_dirty(view);
1473 }
1474
1475 /** Set a clip mask rectangle on a view
1476  *
1477  * \param view The view to set the clip mask on.
1478  * \param x Top-left corner X coordinate of the clip rectangle.
1479  * \param y Top-left corner Y coordinate of the clip rectangle.
1480  * \param width Width of the clip rectangle, non-negative.
1481  * \param height Height of the clip rectangle, non-negative.
1482  *
1483  * A shell may set a clip mask rectangle on a view. Everything outside
1484  * the rectangle is cut away for input and output purposes: it is
1485  * not drawn and cannot be hit by hit-test based input like pointer
1486  * motion or touch-downs. Everything inside the rectangle will behave
1487  * normally. Clients are unaware of clipping.
1488  *
1489  * The rectangle is set in surface-local coordinates. Setting a clip
1490  * mask rectangle does not affect the view position, the view is positioned
1491  * as it would be without a clip. The clip also does not change
1492  * weston_surface::width,height.
1493  *
1494  * The clip mask rectangle is part of transformation inheritance
1495  * (weston_view_set_transform_parent()). A clip set in the root of the
1496  * transformation inheritance tree will affect all views in the tree.
1497  * A clip can be set only on the root view. Attempting to set a clip
1498  * on view that has a transformation parent will fail. Assigning a parent
1499  * to a view that has a clip set will cause the clip to be forgotten.
1500  *
1501  * Because the clip mask is an axis-aligned rectangle, it poses restrictions
1502  * on the additional transformations in the child views. These transformations
1503  * may not rotate the coordinate axes, i.e., only translation and scaling
1504  * are allowed. Violating this restriction causes the clipping to malfunction.
1505  * Furthermore, using scaling may cause rounding errors in child clipping.
1506  *
1507  * The clip mask rectangle is not automatically adjusted based on
1508  * wl_surface.attach dx and dy arguments.
1509  *
1510  * A clip mask rectangle can be set only if the compositor capability
1511  * WESTON_CAP_VIEW_CLIP_MASK is present.
1512  *
1513  * This function sets the clip mask rectangle and schedules a repaint for
1514  * the view.
1515  */
1516 WL_EXPORT void
1517 weston_view_set_mask(struct weston_view *view,
1518                      int x, int y, int width, int height)
1519 {
1520         struct weston_compositor *compositor = view->surface->compositor;
1521
1522         if (!(compositor->capabilities & WESTON_CAP_VIEW_CLIP_MASK)) {
1523                 weston_log("%s not allowed without capability!\n", __func__);
1524                 return;
1525         }
1526
1527         if (view->geometry.parent) {
1528                 weston_log("view %p has a parent, clip forbidden!\n", view);
1529                 return;
1530         }
1531
1532         if (width < 0 || height < 0) {
1533                 weston_log("%s: illegal args %d, %d, %d, %d\n", __func__,
1534                            x, y, width, height);
1535                 return;
1536         }
1537
1538         pixman_region32_fini(&view->geometry.scissor);
1539         pixman_region32_init_rect(&view->geometry.scissor, x, y, width, height);
1540         view->geometry.scissor_enabled = true;
1541         weston_view_geometry_dirty(view);
1542         weston_view_schedule_repaint(view);
1543 }
1544
1545 /** Remove the clip mask from a view
1546  *
1547  * \param view The view to remove the clip mask from.
1548  *
1549  * Removed the clip mask rectangle and schedules a repaint.
1550  *
1551  * \sa weston_view_set_mask
1552  */
1553 WL_EXPORT void
1554 weston_view_set_mask_infinite(struct weston_view *view)
1555 {
1556         view->geometry.scissor_enabled = false;
1557         weston_view_geometry_dirty(view);
1558         weston_view_schedule_repaint(view);
1559 }
1560
1561 /* Check if view should be displayed
1562  *
1563  * The indicator is set manually when assigning
1564  * a view to a surface.
1565  *
1566  * This needs reworking. See the thread starting at:
1567  *
1568  * https://lists.freedesktop.org/archives/wayland-devel/2016-June/029656.html
1569  */
1570 WL_EXPORT bool
1571 weston_view_is_mapped(struct weston_view *view)
1572 {
1573         return view->is_mapped;
1574 }
1575
1576 /* Check if a surface has a view assigned to it
1577  *
1578  * The indicator is set manually when mapping
1579  * a surface and creating a view for it.
1580  *
1581  * This needs to go. See the thread starting at:
1582  *
1583  * https://lists.freedesktop.org/archives/wayland-devel/2016-June/029656.html
1584  *
1585  */
1586 WL_EXPORT bool
1587 weston_surface_is_mapped(struct weston_surface *surface)
1588 {
1589         return surface->is_mapped;
1590 }
1591
1592 static void
1593 surface_set_size(struct weston_surface *surface, int32_t width, int32_t height)
1594 {
1595         struct weston_view *view;
1596
1597         if (surface->width == width && surface->height == height)
1598                 return;
1599
1600         surface->width = width;
1601         surface->height = height;
1602
1603         wl_list_for_each(view, &surface->views, surface_link)
1604                 weston_view_geometry_dirty(view);
1605 }
1606
1607 WL_EXPORT void
1608 weston_surface_set_size(struct weston_surface *surface,
1609                         int32_t width, int32_t height)
1610 {
1611         assert(!surface->resource);
1612         surface_set_size(surface, width, height);
1613 }
1614
1615 static int
1616 fixed_round_up_to_int(wl_fixed_t f)
1617 {
1618         return wl_fixed_to_int(wl_fixed_from_int(1) - 1 + f);
1619 }
1620
1621 static void
1622 convert_size_by_transform_scale(int32_t *width_out, int32_t *height_out,
1623                                 int32_t width, int32_t height,
1624                                 uint32_t transform,
1625                                 int32_t scale)
1626 {
1627         assert(scale > 0);
1628
1629         switch (transform) {
1630         case WL_OUTPUT_TRANSFORM_NORMAL:
1631         case WL_OUTPUT_TRANSFORM_180:
1632         case WL_OUTPUT_TRANSFORM_FLIPPED:
1633         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
1634                 *width_out = width / scale;
1635                 *height_out = height / scale;
1636                 break;
1637         case WL_OUTPUT_TRANSFORM_90:
1638         case WL_OUTPUT_TRANSFORM_270:
1639         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1640         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1641                 *width_out = height / scale;
1642                 *height_out = width / scale;
1643                 break;
1644         default:
1645                 assert(0 && "invalid transform");
1646         }
1647 }
1648
1649 static void
1650 weston_surface_calculate_size_from_buffer(struct weston_surface *surface)
1651 {
1652         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
1653
1654         if (!surface->buffer_ref.buffer) {
1655                 surface->width_from_buffer = 0;
1656                 surface->height_from_buffer = 0;
1657                 return;
1658         }
1659
1660         convert_size_by_transform_scale(&surface->width_from_buffer,
1661                                         &surface->height_from_buffer,
1662                                         surface->buffer_ref.buffer->width,
1663                                         surface->buffer_ref.buffer->height,
1664                                         vp->buffer.transform,
1665                                         vp->buffer.scale);
1666 }
1667
1668 static void
1669 weston_surface_update_size(struct weston_surface *surface)
1670 {
1671         struct weston_buffer_viewport *vp = &surface->buffer_viewport;
1672         int32_t width, height;
1673
1674         width = surface->width_from_buffer;
1675         height = surface->height_from_buffer;
1676
1677         if (width != 0 && vp->surface.width != -1) {
1678                 surface_set_size(surface,
1679                                  vp->surface.width, vp->surface.height);
1680                 return;
1681         }
1682
1683         if (width != 0 && vp->buffer.src_width != wl_fixed_from_int(-1)) {
1684                 int32_t w = fixed_round_up_to_int(vp->buffer.src_width);
1685                 int32_t h = fixed_round_up_to_int(vp->buffer.src_height);
1686
1687                 surface_set_size(surface, w ?: 1, h ?: 1);
1688                 return;
1689         }
1690
1691         surface_set_size(surface, width, height);
1692 }
1693
1694 WL_EXPORT uint32_t
1695 weston_compositor_get_time(void)
1696 {
1697        struct timeval tv;
1698
1699        gettimeofday(&tv, NULL);
1700
1701        return tv.tv_sec * 1000 + tv.tv_usec / 1000;
1702 }
1703
1704 WL_EXPORT struct weston_view *
1705 weston_compositor_pick_view(struct weston_compositor *compositor,
1706                             wl_fixed_t x, wl_fixed_t y,
1707                             wl_fixed_t *vx, wl_fixed_t *vy)
1708 {
1709         struct weston_view *view;
1710         wl_fixed_t view_x, view_y;
1711         int view_ix, view_iy;
1712         int ix = wl_fixed_to_int(x);
1713         int iy = wl_fixed_to_int(y);
1714
1715         wl_list_for_each(view, &compositor->view_list, link) {
1716                 if (!pixman_region32_contains_point(
1717                                 &view->transform.boundingbox, ix, iy, NULL))
1718                         continue;
1719
1720                 weston_view_from_global_fixed(view, x, y, &view_x, &view_y);
1721                 view_ix = wl_fixed_to_int(view_x);
1722                 view_iy = wl_fixed_to_int(view_y);
1723
1724                 if (!pixman_region32_contains_point(&view->surface->input,
1725                                                     view_ix, view_iy, NULL))
1726                         continue;
1727
1728                 if (view->geometry.scissor_enabled &&
1729                     !pixman_region32_contains_point(&view->geometry.scissor,
1730                                                     view_ix, view_iy, NULL))
1731                         continue;
1732
1733                 *vx = view_x;
1734                 *vy = view_y;
1735                 return view;
1736         }
1737
1738         *vx = wl_fixed_from_int(-1000000);
1739         *vy = wl_fixed_from_int(-1000000);
1740         return NULL;
1741 }
1742
1743 static void
1744 weston_compositor_repick(struct weston_compositor *compositor)
1745 {
1746         struct weston_seat *seat;
1747
1748         if (!compositor->session_active)
1749                 return;
1750
1751         wl_list_for_each(seat, &compositor->seat_list, link)
1752                 weston_seat_repick(seat);
1753 }
1754
1755 WL_EXPORT void
1756 weston_view_unmap(struct weston_view *view)
1757 {
1758         struct weston_seat *seat;
1759
1760         if (!weston_view_is_mapped(view))
1761                 return;
1762
1763         weston_view_damage_below(view);
1764         view->output = NULL;
1765         view->plane = NULL;
1766         view->is_mapped = false;
1767         weston_layer_entry_remove(&view->layer_link);
1768         wl_list_remove(&view->link);
1769         wl_list_init(&view->link);
1770         view->output_mask = 0;
1771         weston_surface_assign_output(view->surface);
1772
1773         if (weston_surface_is_mapped(view->surface))
1774                 return;
1775
1776         wl_list_for_each(seat, &view->surface->compositor->seat_list, link) {
1777                 struct weston_touch *touch = weston_seat_get_touch(seat);
1778                 struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1779                 struct weston_keyboard *keyboard =
1780                         weston_seat_get_keyboard(seat);
1781
1782                 if (keyboard && keyboard->focus == view->surface)
1783                         weston_keyboard_set_focus(keyboard, NULL);
1784                 if (pointer && pointer->focus == view)
1785                         weston_pointer_clear_focus(pointer);
1786                 if (touch && touch->focus == view)
1787                         weston_touch_set_focus(touch, NULL);
1788         }
1789 }
1790
1791 WL_EXPORT void
1792 weston_surface_unmap(struct weston_surface *surface)
1793 {
1794         struct weston_view *view;
1795
1796         surface->is_mapped = false;
1797         wl_list_for_each(view, &surface->views, surface_link)
1798                 weston_view_unmap(view);
1799         surface->output = NULL;
1800 }
1801
1802 static void
1803 weston_surface_reset_pending_buffer(struct weston_surface *surface)
1804 {
1805         weston_surface_state_set_buffer(&surface->pending, NULL);
1806         surface->pending.sx = 0;
1807         surface->pending.sy = 0;
1808         surface->pending.newly_attached = 0;
1809         surface->pending.buffer_viewport.changed = 0;
1810 }
1811
1812 WL_EXPORT void
1813 weston_view_destroy(struct weston_view *view)
1814 {
1815         wl_signal_emit(&view->destroy_signal, view);
1816
1817         assert(wl_list_empty(&view->geometry.child_list));
1818
1819         if (weston_view_is_mapped(view)) {
1820                 weston_view_unmap(view);
1821                 weston_compositor_build_view_list(view->surface->compositor);
1822         }
1823
1824         wl_list_remove(&view->link);
1825         weston_layer_entry_remove(&view->layer_link);
1826
1827         pixman_region32_fini(&view->clip);
1828         pixman_region32_fini(&view->geometry.scissor);
1829         pixman_region32_fini(&view->transform.boundingbox);
1830         pixman_region32_fini(&view->transform.opaque);
1831
1832         weston_view_set_transform_parent(view, NULL);
1833
1834         wl_list_remove(&view->surface_link);
1835
1836         free(view);
1837 }
1838
1839 WL_EXPORT void
1840 weston_surface_destroy(struct weston_surface *surface)
1841 {
1842         struct weston_frame_callback *cb, *next;
1843         struct weston_view *ev, *nv;
1844         struct weston_pointer_constraint *constraint, *next_constraint;
1845
1846         if (--surface->ref_count > 0)
1847                 return;
1848
1849         assert(surface->resource == NULL);
1850
1851         wl_signal_emit(&surface->destroy_signal, surface);
1852
1853         assert(wl_list_empty(&surface->subsurface_list_pending));
1854         assert(wl_list_empty(&surface->subsurface_list));
1855
1856         wl_list_for_each_safe(ev, nv, &surface->views, surface_link)
1857                 weston_view_destroy(ev);
1858
1859         weston_surface_state_fini(&surface->pending);
1860
1861         weston_buffer_reference(&surface->buffer_ref, NULL);
1862
1863         pixman_region32_fini(&surface->damage);
1864         pixman_region32_fini(&surface->opaque);
1865         pixman_region32_fini(&surface->input);
1866
1867         wl_list_for_each_safe(cb, next, &surface->frame_callback_list, link)
1868                 wl_resource_destroy(cb->resource);
1869
1870         weston_presentation_feedback_discard_list(&surface->feedback_list);
1871
1872         wl_list_for_each_safe(constraint, next_constraint,
1873                               &surface->pointer_constraints,
1874                               link)
1875                 weston_pointer_constraint_destroy(constraint);
1876
1877         free(surface);
1878 }
1879
1880 static void
1881 destroy_surface(struct wl_resource *resource)
1882 {
1883         struct weston_surface *surface = wl_resource_get_user_data(resource);
1884
1885         assert(surface);
1886
1887         /* Set the resource to NULL, since we don't want to leave a
1888          * dangling pointer if the surface was refcounted and survives
1889          * the weston_surface_destroy() call. */
1890         surface->resource = NULL;
1891
1892         if (surface->viewport_resource)
1893                 wl_resource_set_user_data(surface->viewport_resource, NULL);
1894
1895         weston_surface_destroy(surface);
1896 }
1897
1898 static void
1899 weston_buffer_destroy_handler(struct wl_listener *listener, void *data)
1900 {
1901         struct weston_buffer *buffer =
1902                 container_of(listener, struct weston_buffer, destroy_listener);
1903
1904         wl_signal_emit(&buffer->destroy_signal, buffer);
1905         free(buffer);
1906 }
1907
1908 WL_EXPORT struct weston_buffer *
1909 weston_buffer_from_resource(struct wl_resource *resource)
1910 {
1911         struct weston_buffer *buffer;
1912         struct wl_listener *listener;
1913
1914         listener = wl_resource_get_destroy_listener(resource,
1915                                                     weston_buffer_destroy_handler);
1916
1917         if (listener)
1918                 return container_of(listener, struct weston_buffer,
1919                                     destroy_listener);
1920
1921         buffer = zalloc(sizeof *buffer);
1922         if (buffer == NULL)
1923                 return NULL;
1924
1925         buffer->resource = resource;
1926         wl_signal_init(&buffer->destroy_signal);
1927         buffer->destroy_listener.notify = weston_buffer_destroy_handler;
1928         buffer->y_inverted = 1;
1929         wl_resource_add_destroy_listener(resource, &buffer->destroy_listener);
1930
1931         return buffer;
1932 }
1933
1934 static void
1935 weston_buffer_reference_handle_destroy(struct wl_listener *listener,
1936                                        void *data)
1937 {
1938         struct weston_buffer_reference *ref =
1939                 container_of(listener, struct weston_buffer_reference,
1940                              destroy_listener);
1941
1942         assert((struct weston_buffer *)data == ref->buffer);
1943         ref->buffer = NULL;
1944 }
1945
1946 WL_EXPORT void
1947 weston_buffer_reference(struct weston_buffer_reference *ref,
1948                         struct weston_buffer *buffer)
1949 {
1950         if (ref->buffer && buffer != ref->buffer) {
1951                 ref->buffer->busy_count--;
1952                 if (ref->buffer->busy_count == 0) {
1953                         assert(wl_resource_get_client(ref->buffer->resource));
1954                         wl_resource_queue_event(ref->buffer->resource,
1955                                                 WL_BUFFER_RELEASE);
1956                 }
1957                 wl_list_remove(&ref->destroy_listener.link);
1958         }
1959
1960         if (buffer && buffer != ref->buffer) {
1961                 buffer->busy_count++;
1962                 wl_signal_add(&buffer->destroy_signal,
1963                               &ref->destroy_listener);
1964         }
1965
1966         ref->buffer = buffer;
1967         ref->destroy_listener.notify = weston_buffer_reference_handle_destroy;
1968 }
1969
1970 static void
1971 weston_surface_attach(struct weston_surface *surface,
1972                       struct weston_buffer *buffer)
1973 {
1974         weston_buffer_reference(&surface->buffer_ref, buffer);
1975
1976         if (!buffer) {
1977                 if (weston_surface_is_mapped(surface))
1978                         weston_surface_unmap(surface);
1979         }
1980
1981         surface->compositor->renderer->attach(surface, buffer);
1982
1983         weston_surface_calculate_size_from_buffer(surface);
1984         weston_presentation_feedback_discard_list(&surface->feedback_list);
1985 }
1986
1987 WL_EXPORT void
1988 weston_compositor_damage_all(struct weston_compositor *compositor)
1989 {
1990         struct weston_output *output;
1991
1992         wl_list_for_each(output, &compositor->output_list, link)
1993                 weston_output_damage(output);
1994 }
1995
1996 WL_EXPORT void
1997 weston_output_damage(struct weston_output *output)
1998 {
1999         struct weston_compositor *compositor = output->compositor;
2000
2001         pixman_region32_union(&compositor->primary_plane.damage,
2002                               &compositor->primary_plane.damage,
2003                               &output->region);
2004         weston_output_schedule_repaint(output);
2005 }
2006
2007 static void
2008 surface_flush_damage(struct weston_surface *surface)
2009 {
2010         if (surface->buffer_ref.buffer &&
2011             wl_shm_buffer_get(surface->buffer_ref.buffer->resource))
2012                 surface->compositor->renderer->flush_damage(surface);
2013
2014         if (weston_timeline_enabled_ &&
2015             pixman_region32_not_empty(&surface->damage))
2016                 TL_POINT("core_flush_damage", TLP_SURFACE(surface),
2017                          TLP_OUTPUT(surface->output), TLP_END);
2018
2019         pixman_region32_clear(&surface->damage);
2020 }
2021
2022 static void
2023 view_accumulate_damage(struct weston_view *view,
2024                        pixman_region32_t *opaque)
2025 {
2026         pixman_region32_t damage;
2027
2028         pixman_region32_init(&damage);
2029         if (view->transform.enabled) {
2030                 pixman_box32_t *extents;
2031
2032                 extents = pixman_region32_extents(&view->surface->damage);
2033                 view_compute_bbox(view, extents, &damage);
2034         } else {
2035                 pixman_region32_copy(&damage, &view->surface->damage);
2036                 pixman_region32_translate(&damage,
2037                                           view->geometry.x, view->geometry.y);
2038         }
2039
2040         pixman_region32_intersect(&damage, &damage,
2041                                   &view->transform.boundingbox);
2042         pixman_region32_subtract(&damage, &damage, opaque);
2043         pixman_region32_union(&view->plane->damage,
2044                               &view->plane->damage, &damage);
2045         pixman_region32_fini(&damage);
2046         pixman_region32_copy(&view->clip, opaque);
2047         pixman_region32_union(opaque, opaque, &view->transform.opaque);
2048 }
2049
2050 static void
2051 compositor_accumulate_damage(struct weston_compositor *ec)
2052 {
2053         struct weston_plane *plane;
2054         struct weston_view *ev;
2055         pixman_region32_t opaque, clip;
2056
2057         pixman_region32_init(&clip);
2058
2059         wl_list_for_each(plane, &ec->plane_list, link) {
2060                 pixman_region32_copy(&plane->clip, &clip);
2061
2062                 pixman_region32_init(&opaque);
2063
2064                 wl_list_for_each(ev, &ec->view_list, link) {
2065                         if (ev->plane != plane)
2066                                 continue;
2067
2068                         view_accumulate_damage(ev, &opaque);
2069                 }
2070
2071                 pixman_region32_union(&clip, &clip, &opaque);
2072                 pixman_region32_fini(&opaque);
2073         }
2074
2075         pixman_region32_fini(&clip);
2076
2077         wl_list_for_each(ev, &ec->view_list, link)
2078                 ev->surface->touched = false;
2079
2080         wl_list_for_each(ev, &ec->view_list, link) {
2081                 if (ev->surface->touched)
2082                         continue;
2083                 ev->surface->touched = true;
2084
2085                 surface_flush_damage(ev->surface);
2086
2087                 /* Both the renderer and the backend have seen the buffer
2088                  * by now. If renderer needs the buffer, it has its own
2089                  * reference set. If the backend wants to keep the buffer
2090                  * around for migrating the surface into a non-primary plane
2091                  * later, keep_buffer is true. Otherwise, drop the core
2092                  * reference now, and allow early buffer release. This enables
2093                  * clients to use single-buffering.
2094                  */
2095                 if (!ev->surface->keep_buffer)
2096                         weston_buffer_reference(&ev->surface->buffer_ref, NULL);
2097         }
2098 }
2099
2100 static void
2101 surface_stash_subsurface_views(struct weston_surface *surface)
2102 {
2103         struct weston_subsurface *sub;
2104
2105         wl_list_for_each(sub, &surface->subsurface_list, parent_link) {
2106                 if (sub->surface == surface)
2107                         continue;
2108
2109                 wl_list_insert_list(&sub->unused_views, &sub->surface->views);
2110                 wl_list_init(&sub->surface->views);
2111
2112                 surface_stash_subsurface_views(sub->surface);
2113         }
2114 }
2115
2116 static void
2117 surface_free_unused_subsurface_views(struct weston_surface *surface)
2118 {
2119         struct weston_subsurface *sub;
2120         struct weston_view *view, *nv;
2121
2122         wl_list_for_each(sub, &surface->subsurface_list, parent_link) {
2123                 if (sub->surface == surface)
2124                         continue;
2125
2126                 wl_list_for_each_safe(view, nv, &sub->unused_views, surface_link) {
2127                         weston_view_unmap (view);
2128                         weston_view_destroy(view);
2129                 }
2130
2131                 surface_free_unused_subsurface_views(sub->surface);
2132         }
2133 }
2134
2135 static void
2136 view_list_add_subsurface_view(struct weston_compositor *compositor,
2137                               struct weston_subsurface *sub,
2138                               struct weston_view *parent)
2139 {
2140         struct weston_subsurface *child;
2141         struct weston_view *view = NULL, *iv;
2142
2143         if (!weston_surface_is_mapped(sub->surface))
2144                 return;
2145
2146         wl_list_for_each(iv, &sub->unused_views, surface_link) {
2147                 if (iv->geometry.parent == parent) {
2148                         view = iv;
2149                         break;
2150                 }
2151         }
2152
2153         if (view) {
2154                 /* Put it back in the surface's list of views */
2155                 wl_list_remove(&view->surface_link);
2156                 wl_list_insert(&sub->surface->views, &view->surface_link);
2157         } else {
2158                 view = weston_view_create(sub->surface);
2159                 weston_view_set_position(view,
2160                                          sub->position.x,
2161                                          sub->position.y);
2162                 weston_view_set_transform_parent(view, parent);
2163         }
2164
2165         view->parent_view = parent;
2166         weston_view_update_transform(view);
2167         view->is_mapped = true;
2168
2169         if (wl_list_empty(&sub->surface->subsurface_list)) {
2170                 wl_list_insert(compositor->view_list.prev, &view->link);
2171                 return;
2172         }
2173
2174         wl_list_for_each(child, &sub->surface->subsurface_list, parent_link) {
2175                 if (child->surface == sub->surface)
2176                         wl_list_insert(compositor->view_list.prev, &view->link);
2177                 else
2178                         view_list_add_subsurface_view(compositor, child, view);
2179         }
2180 }
2181
2182 /* This recursively adds the sub-surfaces for a view, relying on the
2183  * sub-surface order. Thus, if a client restacks the sub-surfaces, that
2184  * change first happens to the sub-surface list, and then automatically
2185  * propagates here. See weston_surface_damage_subsurfaces() for how the
2186  * sub-surfaces receive damage when the client changes the state.
2187  */
2188 static void
2189 view_list_add(struct weston_compositor *compositor,
2190               struct weston_view *view)
2191 {
2192         struct weston_subsurface *sub;
2193
2194         weston_view_update_transform(view);
2195
2196         if (wl_list_empty(&view->surface->subsurface_list)) {
2197                 wl_list_insert(compositor->view_list.prev, &view->link);
2198                 return;
2199         }
2200
2201         wl_list_for_each(sub, &view->surface->subsurface_list, parent_link) {
2202                 if (sub->surface == view->surface)
2203                         wl_list_insert(compositor->view_list.prev, &view->link);
2204                 else
2205                         view_list_add_subsurface_view(compositor, sub, view);
2206         }
2207 }
2208
2209 static void
2210 weston_compositor_build_view_list(struct weston_compositor *compositor)
2211 {
2212         struct weston_view *view;
2213         struct weston_layer *layer;
2214
2215         wl_list_for_each(layer, &compositor->layer_list, link)
2216                 wl_list_for_each(view, &layer->view_list.link, layer_link.link)
2217                         surface_stash_subsurface_views(view->surface);
2218
2219         wl_list_init(&compositor->view_list);
2220         wl_list_for_each(layer, &compositor->layer_list, link) {
2221                 wl_list_for_each(view, &layer->view_list.link, layer_link.link) {
2222                         view_list_add(compositor, view);
2223                 }
2224         }
2225
2226         wl_list_for_each(layer, &compositor->layer_list, link)
2227                 wl_list_for_each(view, &layer->view_list.link, layer_link.link)
2228                         surface_free_unused_subsurface_views(view->surface);
2229 }
2230
2231 static void
2232 weston_output_take_feedback_list(struct weston_output *output,
2233                                  struct weston_surface *surface)
2234 {
2235         struct weston_view *view;
2236         struct weston_presentation_feedback *feedback;
2237         uint32_t flags = 0xffffffff;
2238
2239         if (wl_list_empty(&surface->feedback_list))
2240                 return;
2241
2242         /* All views must have the flag for the flag to survive. */
2243         wl_list_for_each(view, &surface->views, surface_link) {
2244                 /* ignore views that are not on this output at all */
2245                 if (view->output_mask & (1u << output->id))
2246                         flags &= view->psf_flags;
2247         }
2248
2249         wl_list_for_each(feedback, &surface->feedback_list, link)
2250                 feedback->psf_flags = flags;
2251
2252         wl_list_insert_list(&output->feedback_list, &surface->feedback_list);
2253         wl_list_init(&surface->feedback_list);
2254 }
2255
2256 static int
2257 weston_output_repaint(struct weston_output *output)
2258 {
2259         struct weston_compositor *ec = output->compositor;
2260         struct weston_view *ev;
2261         struct weston_animation *animation, *next;
2262         struct weston_frame_callback *cb, *cnext;
2263         struct wl_list frame_callback_list;
2264         pixman_region32_t output_damage;
2265         int r;
2266
2267         if (output->destroying)
2268                 return 0;
2269
2270         TL_POINT("core_repaint_begin", TLP_OUTPUT(output), TLP_END);
2271
2272         /* Rebuild the surface list and update surface transforms up front. */
2273         weston_compositor_build_view_list(ec);
2274
2275         if (output->assign_planes && !output->disable_planes) {
2276                 output->assign_planes(output);
2277         } else {
2278                 wl_list_for_each(ev, &ec->view_list, link) {
2279                         weston_view_move_to_plane(ev, &ec->primary_plane);
2280                         ev->psf_flags = 0;
2281                 }
2282         }
2283
2284         wl_list_init(&frame_callback_list);
2285         wl_list_for_each(ev, &ec->view_list, link) {
2286                 /* Note: This operation is safe to do multiple times on the
2287                  * same surface.
2288                  */
2289                 if (ev->surface->output == output) {
2290                         wl_list_insert_list(&frame_callback_list,
2291                                             &ev->surface->frame_callback_list);
2292                         wl_list_init(&ev->surface->frame_callback_list);
2293
2294                         weston_output_take_feedback_list(output, ev->surface);
2295                 }
2296         }
2297
2298         compositor_accumulate_damage(ec);
2299
2300         pixman_region32_init(&output_damage);
2301         pixman_region32_intersect(&output_damage,
2302                                   &ec->primary_plane.damage, &output->region);
2303         pixman_region32_subtract(&output_damage,
2304                                  &output_damage, &ec->primary_plane.clip);
2305
2306         if (output->dirty)
2307                 weston_output_update_matrix(output);
2308
2309         r = output->repaint(output, &output_damage);
2310
2311         pixman_region32_fini(&output_damage);
2312
2313         output->repaint_needed = false;
2314         if (r == 0)
2315                 output->repaint_status = REPAINT_AWAITING_COMPLETION;
2316
2317         weston_compositor_repick(ec);
2318
2319         wl_list_for_each_safe(cb, cnext, &frame_callback_list, link) {
2320                 wl_callback_send_done(cb->resource, output->frame_time);
2321                 wl_resource_destroy(cb->resource);
2322         }
2323
2324         wl_list_for_each_safe(animation, next, &output->animation_list, link) {
2325                 animation->frame_counter++;
2326                 animation->frame(animation, output, output->frame_time);
2327         }
2328
2329         TL_POINT("core_repaint_posted", TLP_OUTPUT(output), TLP_END);
2330
2331         return r;
2332 }
2333
2334 static void
2335 weston_output_schedule_repaint_reset(struct weston_output *output)
2336 {
2337         output->repaint_status = REPAINT_NOT_SCHEDULED;
2338         TL_POINT("core_repaint_exit_loop", TLP_OUTPUT(output), TLP_END);
2339 }
2340
2341 static void
2342 weston_output_maybe_repaint(struct weston_output *output,
2343                             struct timespec *now)
2344 {
2345         struct weston_compositor *compositor = output->compositor;
2346         int ret;
2347         int64_t msec_to_repaint;
2348
2349         /* We're not ready yet; come back to make a decision later. */
2350         if (output->repaint_status != REPAINT_SCHEDULED)
2351                 return;
2352
2353         msec_to_repaint = timespec_sub_to_msec(&output->next_repaint, now);
2354         if (msec_to_repaint > 1)
2355                 return;
2356
2357         /* If we're sleeping, drop the repaint machinery entirely; we will
2358          * explicitly repaint all outputs when we come back. */
2359         if (compositor->state == WESTON_COMPOSITOR_SLEEPING ||
2360             compositor->state == WESTON_COMPOSITOR_OFFSCREEN)
2361                 goto err;
2362
2363         /* We don't actually need to repaint this output; drop it from
2364          * repaint until something causes damage. */
2365         if (!output->repaint_needed)
2366                 goto err;
2367
2368         /* If repaint fails, we aren't going to get weston_output_finish_frame
2369          * to trigger a new repaint, so drop it from repaint and hope
2370          * something schedules a successful repaint later. As repainting may
2371          * take some time, re-read our clock as a courtesy to the next
2372          * output. */
2373         ret = weston_output_repaint(output);
2374         weston_compositor_read_presentation_clock(compositor, now);
2375         if (ret != 0)
2376                 goto err;
2377
2378         return;
2379
2380 err:
2381         weston_output_schedule_repaint_reset(output);
2382 }
2383
2384 static void
2385 output_repaint_timer_arm(struct weston_compositor *compositor)
2386 {
2387         struct weston_output *output;
2388         bool any_should_repaint = false;
2389         struct timespec now;
2390         int64_t msec_to_next;
2391
2392         weston_compositor_read_presentation_clock(compositor, &now);
2393
2394         wl_list_for_each(output, &compositor->output_list, link) {
2395                 int64_t msec_to_this;
2396
2397                 if (output->repaint_status != REPAINT_SCHEDULED)
2398                         continue;
2399
2400                 msec_to_this = timespec_sub_to_msec(&output->next_repaint,
2401                                                     &now);
2402                 if (!any_should_repaint || msec_to_this < msec_to_next)
2403                         msec_to_next = msec_to_this;
2404
2405                 any_should_repaint = true;
2406         }
2407
2408         if (!any_should_repaint)
2409                 return;
2410
2411         /* Even if we should repaint immediately, add the minimum 1 ms delay.
2412          * This is a workaround to allow coalescing multiple output repaints
2413          * particularly from weston_output_finish_frame()
2414          * into the same call, which would not happen if we called
2415          * output_repaint_timer_handler() directly.
2416          */
2417         if (msec_to_next < 1)
2418                 msec_to_next = 1;
2419
2420         wl_event_source_timer_update(compositor->repaint_timer, msec_to_next);
2421 }
2422
2423 static int
2424 output_repaint_timer_handler(void *data)
2425 {
2426         struct weston_compositor *compositor = data;
2427         struct weston_output *output;
2428         struct timespec now;
2429
2430         weston_compositor_read_presentation_clock(compositor, &now);
2431         wl_list_for_each(output, &compositor->output_list, link)
2432                 weston_output_maybe_repaint(output, &now);
2433
2434         output_repaint_timer_arm(compositor);
2435
2436         return 0;
2437 }
2438
2439 WL_EXPORT void
2440 weston_output_finish_frame(struct weston_output *output,
2441                            const struct timespec *stamp,
2442                            uint32_t presented_flags)
2443 {
2444         struct weston_compositor *compositor = output->compositor;
2445         int32_t refresh_nsec;
2446         struct timespec now;
2447         int64_t msec_rel;
2448
2449         TL_POINT("core_repaint_finished", TLP_OUTPUT(output),
2450                  TLP_VBLANK(stamp), TLP_END);
2451
2452         assert(output->repaint_status == REPAINT_AWAITING_COMPLETION);
2453         assert(stamp || (presented_flags & WP_PRESENTATION_FEEDBACK_INVALID));
2454
2455         weston_compositor_read_presentation_clock(compositor, &now);
2456
2457         /* If we haven't been supplied any timestamp at all, we don't have a
2458          * timebase to work against, so any delay just wastes time. Push a
2459          * repaint as soon as possible so we can get on with it. */
2460         if (!stamp) {
2461                 output->next_repaint = now;
2462                 goto out;
2463         }
2464
2465         refresh_nsec = millihz_to_nsec(output->current_mode->refresh);
2466         weston_presentation_feedback_present_list(&output->feedback_list,
2467                                                   output, refresh_nsec, stamp,
2468                                                   output->msc,
2469                                                   presented_flags);
2470
2471         output->frame_time = timespec_to_msec(stamp);
2472
2473         timespec_add_nsec(&output->next_repaint, stamp, refresh_nsec);
2474         timespec_add_msec(&output->next_repaint, &output->next_repaint,
2475                           -compositor->repaint_msec);
2476         msec_rel = timespec_sub_to_msec(&output->next_repaint, &now);
2477
2478         if (msec_rel < -1000 || msec_rel > 1000) {
2479                 static bool warned;
2480
2481                 if (!warned)
2482                         weston_log("Warning: computed repaint delay is "
2483                                    "insane: %lld msec\n", (long long) msec_rel);
2484                 warned = true;
2485
2486                 output->next_repaint = now;
2487         }
2488
2489         /* Called from restart_repaint_loop and restart happens already after
2490          * the deadline given by repaint_msec? In that case we delay until
2491          * the deadline of the next frame, to give clients a more predictable
2492          * timing of the repaint cycle to lock on. */
2493         if (presented_flags == WP_PRESENTATION_FEEDBACK_INVALID && msec_rel < 0)
2494                 timespec_add_nsec(&output->next_repaint, &output->next_repaint,
2495                                   refresh_nsec);
2496
2497 out:
2498         output->repaint_status = REPAINT_SCHEDULED;
2499         output_repaint_timer_arm(compositor);
2500 }
2501
2502 static void
2503 idle_repaint(void *data)
2504 {
2505         struct weston_output *output = data;
2506
2507         assert(output->repaint_status == REPAINT_BEGIN_FROM_IDLE);
2508         output->repaint_status = REPAINT_AWAITING_COMPLETION;
2509         output->start_repaint_loop(output);
2510 }
2511
2512 WL_EXPORT void
2513 weston_layer_entry_insert(struct weston_layer_entry *list,
2514                           struct weston_layer_entry *entry)
2515 {
2516         wl_list_insert(&list->link, &entry->link);
2517         entry->layer = list->layer;
2518 }
2519
2520 WL_EXPORT void
2521 weston_layer_entry_remove(struct weston_layer_entry *entry)
2522 {
2523         wl_list_remove(&entry->link);
2524         wl_list_init(&entry->link);
2525         entry->layer = NULL;
2526 }
2527
2528
2529 /** Initialize the weston_layer struct.
2530  *
2531  * \param compositor The compositor instance
2532  * \param layer The layer to initialize
2533  */
2534 WL_EXPORT void
2535 weston_layer_init(struct weston_layer *layer,
2536                   struct weston_compositor *compositor)
2537 {
2538         layer->compositor = compositor;
2539         wl_list_init(&layer->link);
2540         wl_list_init(&layer->view_list.link);
2541         layer->view_list.layer = layer;
2542         weston_layer_set_mask_infinite(layer);
2543 }
2544
2545 /** Sets the position of the layer in the layer list. The layer will be placed
2546  * below any layer with the same position value, if any.
2547  * This function is safe to call if the layer is already on the list, but the
2548  * layer may be moved below other layers at the same position, if any.
2549  *
2550  * \param layer The layer to modify
2551  * \param position The position the layer will be placed at
2552  */
2553 WL_EXPORT void
2554 weston_layer_set_position(struct weston_layer *layer,
2555                           enum weston_layer_position position)
2556 {
2557         struct weston_layer *below;
2558
2559         wl_list_remove(&layer->link);
2560
2561         /* layer_list is ordered from top to bottom, the last layer being the
2562          * background with the smallest position value */
2563
2564         layer->position = position;
2565         wl_list_for_each_reverse(below, &layer->compositor->layer_list, link) {
2566                 if (below->position >= layer->position) {
2567                         wl_list_insert(&below->link, &layer->link);
2568                         return;
2569                 }
2570         }
2571         wl_list_insert(&layer->compositor->layer_list, &layer->link);
2572 }
2573
2574 /** Hide a layer by taking it off the layer list.
2575  * This function is safe to call if the layer is not on the list.
2576  *
2577  * \param layer The layer to hide
2578  */
2579 WL_EXPORT void
2580 weston_layer_unset_position(struct weston_layer *layer)
2581 {
2582         wl_list_remove(&layer->link);
2583         wl_list_init(&layer->link);
2584 }
2585
2586 WL_EXPORT void
2587 weston_layer_set_mask(struct weston_layer *layer,
2588                       int x, int y, int width, int height)
2589 {
2590         struct weston_view *view;
2591
2592         layer->mask.x1 = x;
2593         layer->mask.x2 = x + width;
2594         layer->mask.y1 = y;
2595         layer->mask.y2 = y + height;
2596
2597         wl_list_for_each(view, &layer->view_list.link, layer_link.link) {
2598                 weston_view_geometry_dirty(view);
2599         }
2600 }
2601
2602 WL_EXPORT void
2603 weston_layer_set_mask_infinite(struct weston_layer *layer)
2604 {
2605         weston_layer_set_mask(layer, INT32_MIN, INT32_MIN,
2606                                      UINT32_MAX, UINT32_MAX);
2607 }
2608
2609 WL_EXPORT void
2610 weston_output_schedule_repaint(struct weston_output *output)
2611 {
2612         struct weston_compositor *compositor = output->compositor;
2613         struct wl_event_loop *loop;
2614
2615         if (compositor->state == WESTON_COMPOSITOR_SLEEPING ||
2616             compositor->state == WESTON_COMPOSITOR_OFFSCREEN)
2617                 return;
2618
2619         if (!output->repaint_needed)
2620                 TL_POINT("core_repaint_req", TLP_OUTPUT(output), TLP_END);
2621
2622         loop = wl_display_get_event_loop(compositor->wl_display);
2623         output->repaint_needed = true;
2624
2625         /* If we already have a repaint scheduled for our idle handler,
2626          * no need to set it again. If the repaint has been called but
2627          * not finished, then weston_output_finish_frame() will notice
2628          * that a repaint is needed and schedule one. */
2629         if (output->repaint_status != REPAINT_NOT_SCHEDULED)
2630                 return;
2631
2632         output->repaint_status = REPAINT_BEGIN_FROM_IDLE;
2633         wl_event_loop_add_idle(loop, idle_repaint, output);
2634         TL_POINT("core_repaint_enter_loop", TLP_OUTPUT(output), TLP_END);
2635 }
2636
2637 WL_EXPORT void
2638 weston_compositor_schedule_repaint(struct weston_compositor *compositor)
2639 {
2640         struct weston_output *output;
2641
2642         wl_list_for_each(output, &compositor->output_list, link)
2643                 weston_output_schedule_repaint(output);
2644 }
2645
2646 static void
2647 surface_destroy(struct wl_client *client, struct wl_resource *resource)
2648 {
2649         wl_resource_destroy(resource);
2650 }
2651
2652 static void
2653 surface_attach(struct wl_client *client,
2654                struct wl_resource *resource,
2655                struct wl_resource *buffer_resource, int32_t sx, int32_t sy)
2656 {
2657         struct weston_surface *surface = wl_resource_get_user_data(resource);
2658         struct weston_buffer *buffer = NULL;
2659
2660         if (buffer_resource) {
2661                 buffer = weston_buffer_from_resource(buffer_resource);
2662                 if (buffer == NULL) {
2663                         wl_client_post_no_memory(client);
2664                         return;
2665                 }
2666         }
2667
2668         /* Attach, attach, without commit in between does not send
2669          * wl_buffer.release. */
2670         weston_surface_state_set_buffer(&surface->pending, buffer);
2671
2672         surface->pending.sx = sx;
2673         surface->pending.sy = sy;
2674         surface->pending.newly_attached = 1;
2675 }
2676
2677 static void
2678 surface_damage(struct wl_client *client,
2679                struct wl_resource *resource,
2680                int32_t x, int32_t y, int32_t width, int32_t height)
2681 {
2682         struct weston_surface *surface = wl_resource_get_user_data(resource);
2683
2684         if (width <= 0 || height <= 0)
2685                 return;
2686
2687         pixman_region32_union_rect(&surface->pending.damage_surface,
2688                                    &surface->pending.damage_surface,
2689                                    x, y, width, height);
2690 }
2691
2692 static void
2693 surface_damage_buffer(struct wl_client *client,
2694                       struct wl_resource *resource,
2695                       int32_t x, int32_t y, int32_t width, int32_t height)
2696 {
2697         struct weston_surface *surface = wl_resource_get_user_data(resource);
2698
2699         if (width <= 0 || height <= 0)
2700                 return;
2701
2702         pixman_region32_union_rect(&surface->pending.damage_buffer,
2703                                    &surface->pending.damage_buffer,
2704                                    x, y, width, height);
2705 }
2706
2707 static void
2708 destroy_frame_callback(struct wl_resource *resource)
2709 {
2710         struct weston_frame_callback *cb = wl_resource_get_user_data(resource);
2711
2712         wl_list_remove(&cb->link);
2713         free(cb);
2714 }
2715
2716 static void
2717 surface_frame(struct wl_client *client,
2718               struct wl_resource *resource, uint32_t callback)
2719 {
2720         struct weston_frame_callback *cb;
2721         struct weston_surface *surface = wl_resource_get_user_data(resource);
2722
2723         cb = malloc(sizeof *cb);
2724         if (cb == NULL) {
2725                 wl_resource_post_no_memory(resource);
2726                 return;
2727         }
2728
2729         cb->resource = wl_resource_create(client, &wl_callback_interface, 1,
2730                                           callback);
2731         if (cb->resource == NULL) {
2732                 free(cb);
2733                 wl_resource_post_no_memory(resource);
2734                 return;
2735         }
2736
2737         wl_resource_set_implementation(cb->resource, NULL, cb,
2738                                        destroy_frame_callback);
2739
2740         wl_list_insert(surface->pending.frame_callback_list.prev, &cb->link);
2741 }
2742
2743 static void
2744 surface_set_opaque_region(struct wl_client *client,
2745                           struct wl_resource *resource,
2746                           struct wl_resource *region_resource)
2747 {
2748         struct weston_surface *surface = wl_resource_get_user_data(resource);
2749         struct weston_region *region;
2750
2751         if (region_resource) {
2752                 region = wl_resource_get_user_data(region_resource);
2753                 pixman_region32_copy(&surface->pending.opaque,
2754                                      &region->region);
2755         } else {
2756                 pixman_region32_clear(&surface->pending.opaque);
2757         }
2758 }
2759
2760 static void
2761 surface_set_input_region(struct wl_client *client,
2762                          struct wl_resource *resource,
2763                          struct wl_resource *region_resource)
2764 {
2765         struct weston_surface *surface = wl_resource_get_user_data(resource);
2766         struct weston_region *region;
2767
2768         if (region_resource) {
2769                 region = wl_resource_get_user_data(region_resource);
2770                 pixman_region32_copy(&surface->pending.input,
2771                                      &region->region);
2772         } else {
2773                 pixman_region32_fini(&surface->pending.input);
2774                 region_init_infinite(&surface->pending.input);
2775         }
2776 }
2777
2778 /* Cause damage to this sub-surface and all its children.
2779  *
2780  * This is useful when there are state changes that need an implicit
2781  * damage, e.g. a z-order change.
2782  */
2783 static void
2784 weston_surface_damage_subsurfaces(struct weston_subsurface *sub)
2785 {
2786         struct weston_subsurface *child;
2787
2788         weston_surface_damage(sub->surface);
2789         sub->reordered = false;
2790
2791         wl_list_for_each(child, &sub->surface->subsurface_list, parent_link)
2792                 if (child != sub)
2793                         weston_surface_damage_subsurfaces(child);
2794 }
2795
2796 static void
2797 weston_surface_commit_subsurface_order(struct weston_surface *surface)
2798 {
2799         struct weston_subsurface *sub;
2800
2801         wl_list_for_each_reverse(sub, &surface->subsurface_list_pending,
2802                                  parent_link_pending) {
2803                 wl_list_remove(&sub->parent_link);
2804                 wl_list_insert(&surface->subsurface_list, &sub->parent_link);
2805
2806                 if (sub->reordered)
2807                         weston_surface_damage_subsurfaces(sub);
2808         }
2809 }
2810
2811 static void
2812 weston_surface_build_buffer_matrix(const struct weston_surface *surface,
2813                                    struct weston_matrix *matrix)
2814 {
2815         const struct weston_buffer_viewport *vp = &surface->buffer_viewport;
2816         double src_width, src_height, dest_width, dest_height;
2817
2818         weston_matrix_init(matrix);
2819
2820         if (vp->buffer.src_width == wl_fixed_from_int(-1)) {
2821                 src_width = surface->width_from_buffer;
2822                 src_height = surface->height_from_buffer;
2823         } else {
2824                 src_width = wl_fixed_to_double(vp->buffer.src_width);
2825                 src_height = wl_fixed_to_double(vp->buffer.src_height);
2826         }
2827
2828         if (vp->surface.width == -1) {
2829                 dest_width = src_width;
2830                 dest_height = src_height;
2831         } else {
2832                 dest_width = vp->surface.width;
2833                 dest_height = vp->surface.height;
2834         }
2835
2836         if (src_width != dest_width || src_height != dest_height)
2837                 weston_matrix_scale(matrix,
2838                                     src_width / dest_width,
2839                                     src_height / dest_height, 1);
2840
2841         if (vp->buffer.src_width != wl_fixed_from_int(-1))
2842                 weston_matrix_translate(matrix,
2843                                         wl_fixed_to_double(vp->buffer.src_x),
2844                                         wl_fixed_to_double(vp->buffer.src_y),
2845                                         0);
2846
2847         switch (vp->buffer.transform) {
2848         case WL_OUTPUT_TRANSFORM_FLIPPED:
2849         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
2850         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
2851         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
2852                 weston_matrix_scale(matrix, -1, 1, 1);
2853                 weston_matrix_translate(matrix,
2854                                         surface->width_from_buffer, 0, 0);
2855                 break;
2856         }
2857
2858         switch (vp->buffer.transform) {
2859         default:
2860         case WL_OUTPUT_TRANSFORM_NORMAL:
2861         case WL_OUTPUT_TRANSFORM_FLIPPED:
2862                 break;
2863         case WL_OUTPUT_TRANSFORM_90:
2864         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
2865                 weston_matrix_rotate_xy(matrix, 0, 1);
2866                 weston_matrix_translate(matrix,
2867                                         surface->height_from_buffer, 0, 0);
2868                 break;
2869         case WL_OUTPUT_TRANSFORM_180:
2870         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
2871                 weston_matrix_rotate_xy(matrix, -1, 0);
2872                 weston_matrix_translate(matrix,
2873                                         surface->width_from_buffer,
2874                                         surface->height_from_buffer, 0);
2875                 break;
2876         case WL_OUTPUT_TRANSFORM_270:
2877         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
2878                 weston_matrix_rotate_xy(matrix, 0, -1);
2879                 weston_matrix_translate(matrix,
2880                                         0, surface->width_from_buffer, 0);
2881                 break;
2882         }
2883
2884         weston_matrix_scale(matrix, vp->buffer.scale, vp->buffer.scale, 1);
2885 }
2886
2887 /**
2888  * Compute a + b > c while being safe to overflows.
2889  */
2890 static bool
2891 fixed_sum_gt(wl_fixed_t a, wl_fixed_t b, wl_fixed_t c)
2892 {
2893         return (int64_t)a + (int64_t)b > (int64_t)c;
2894 }
2895
2896 static bool
2897 weston_surface_is_pending_viewport_source_valid(
2898         const struct weston_surface *surface)
2899 {
2900         const struct weston_surface_state *pend = &surface->pending;
2901         const struct weston_buffer_viewport *vp = &pend->buffer_viewport;
2902         int width_from_buffer = 0;
2903         int height_from_buffer = 0;
2904         wl_fixed_t w;
2905         wl_fixed_t h;
2906
2907         /* If viewport source rect is not set, it is always ok. */
2908         if (vp->buffer.src_width == wl_fixed_from_int(-1))
2909                 return true;
2910
2911         if (pend->newly_attached) {
2912                 if (pend->buffer) {
2913                         convert_size_by_transform_scale(&width_from_buffer,
2914                                                         &height_from_buffer,
2915                                                         pend->buffer->width,
2916                                                         pend->buffer->height,
2917                                                         vp->buffer.transform,
2918                                                         vp->buffer.scale);
2919                 } else {
2920                         /* No buffer: viewport is irrelevant. */
2921                         return true;
2922                 }
2923         } else {
2924                 width_from_buffer = surface->width_from_buffer;
2925                 height_from_buffer = surface->height_from_buffer;
2926         }
2927
2928         assert((width_from_buffer == 0) == (height_from_buffer == 0));
2929         assert(width_from_buffer >= 0 && height_from_buffer >= 0);
2930
2931         /* No buffer: viewport is irrelevant. */
2932         if (width_from_buffer == 0 || height_from_buffer == 0)
2933                 return true;
2934
2935         /* overflow checks for wl_fixed_from_int() */
2936         if (width_from_buffer > wl_fixed_to_int(INT32_MAX))
2937                 return false;
2938         if (height_from_buffer > wl_fixed_to_int(INT32_MAX))
2939                 return false;
2940
2941         w = wl_fixed_from_int(width_from_buffer);
2942         h = wl_fixed_from_int(height_from_buffer);
2943
2944         if (fixed_sum_gt(vp->buffer.src_x, vp->buffer.src_width, w))
2945                 return false;
2946         if (fixed_sum_gt(vp->buffer.src_y, vp->buffer.src_height, h))
2947                 return false;
2948
2949         return true;
2950 }
2951
2952 static bool
2953 fixed_is_integer(wl_fixed_t v)
2954 {
2955         return (v & 0xff) == 0;
2956 }
2957
2958 static bool
2959 weston_surface_is_pending_viewport_dst_size_int(
2960         const struct weston_surface *surface)
2961 {
2962         const struct weston_buffer_viewport *vp =
2963                 &surface->pending.buffer_viewport;
2964
2965         if (vp->surface.width != -1) {
2966                 assert(vp->surface.width > 0 && vp->surface.height > 0);
2967                 return true;
2968         }
2969
2970         return fixed_is_integer(vp->buffer.src_width) &&
2971                fixed_is_integer(vp->buffer.src_height);
2972 }
2973
2974 /* Translate pending damage in buffer co-ordinates to surface
2975  * co-ordinates and union it with a pixman_region32_t.
2976  * This should only be called after the buffer is attached.
2977  */
2978 static void
2979 apply_damage_buffer(pixman_region32_t *dest,
2980                     struct weston_surface *surface,
2981                     struct weston_surface_state *state)
2982 {
2983         struct weston_buffer *buffer = surface->buffer_ref.buffer;
2984
2985         /* wl_surface.damage_buffer needs to be clipped to the buffer,
2986          * translated into surface co-ordinates and unioned with
2987          * any other surface damage.
2988          * None of this makes sense if there is no buffer though.
2989          */
2990         if (buffer && pixman_region32_not_empty(&state->damage_buffer)) {
2991                 pixman_region32_t buffer_damage;
2992
2993                 pixman_region32_intersect_rect(&state->damage_buffer,
2994                                                &state->damage_buffer,
2995                                                0, 0, buffer->width,
2996                                                buffer->height);
2997                 pixman_region32_init(&buffer_damage);
2998                 weston_matrix_transform_region(&buffer_damage,
2999                                                &surface->buffer_to_surface_matrix,
3000                                                &state->damage_buffer);
3001                 pixman_region32_union(dest, dest, &buffer_damage);
3002                 pixman_region32_fini(&buffer_damage);
3003         }
3004         /* We should clear this on commit even if there was no buffer */
3005         pixman_region32_clear(&state->damage_buffer);
3006 }
3007
3008 static void
3009 weston_surface_commit_state(struct weston_surface *surface,
3010                             struct weston_surface_state *state)
3011 {
3012         struct weston_view *view;
3013         pixman_region32_t opaque;
3014
3015         /* wl_surface.set_buffer_transform */
3016         /* wl_surface.set_buffer_scale */
3017         /* wp_viewport.set_source */
3018         /* wp_viewport.set_destination */
3019         surface->buffer_viewport = state->buffer_viewport;
3020
3021         /* wl_surface.attach */
3022         if (state->newly_attached)
3023                 weston_surface_attach(surface, state->buffer);
3024         weston_surface_state_set_buffer(state, NULL);
3025
3026         weston_surface_build_buffer_matrix(surface,
3027                                            &surface->surface_to_buffer_matrix);
3028         weston_matrix_invert(&surface->buffer_to_surface_matrix,
3029                              &surface->surface_to_buffer_matrix);
3030
3031         if (state->newly_attached || state->buffer_viewport.changed) {
3032                 weston_surface_update_size(surface);
3033                 if (surface->committed)
3034                         surface->committed(surface, state->sx, state->sy);
3035         }
3036
3037         state->sx = 0;
3038         state->sy = 0;
3039         state->newly_attached = 0;
3040         state->buffer_viewport.changed = 0;
3041
3042         /* wl_surface.damage and wl_surface.damage_buffer */
3043         if (weston_timeline_enabled_ &&
3044             (pixman_region32_not_empty(&state->damage_surface) ||
3045              pixman_region32_not_empty(&state->damage_buffer)))
3046                 TL_POINT("core_commit_damage", TLP_SURFACE(surface), TLP_END);
3047
3048         pixman_region32_union(&surface->damage, &surface->damage,
3049                               &state->damage_surface);
3050
3051         apply_damage_buffer(&surface->damage, surface, state);
3052
3053         pixman_region32_intersect_rect(&surface->damage, &surface->damage,
3054                                        0, 0, surface->width, surface->height);
3055         pixman_region32_clear(&state->damage_surface);
3056
3057         /* wl_surface.set_opaque_region */
3058         pixman_region32_init(&opaque);
3059         pixman_region32_intersect_rect(&opaque, &state->opaque,
3060                                        0, 0, surface->width, surface->height);
3061
3062         if (!pixman_region32_equal(&opaque, &surface->opaque)) {
3063                 pixman_region32_copy(&surface->opaque, &opaque);
3064                 wl_list_for_each(view, &surface->views, surface_link)
3065                         weston_view_geometry_dirty(view);
3066         }
3067
3068         pixman_region32_fini(&opaque);
3069
3070         /* wl_surface.set_input_region */
3071         pixman_region32_intersect_rect(&surface->input, &state->input,
3072                                        0, 0, surface->width, surface->height);
3073
3074         /* wl_surface.frame */
3075         wl_list_insert_list(&surface->frame_callback_list,
3076                             &state->frame_callback_list);
3077         wl_list_init(&state->frame_callback_list);
3078
3079         /* XXX:
3080          * What should happen with a feedback request, if there
3081          * is no wl_buffer attached for this commit?
3082          */
3083
3084         /* presentation.feedback */
3085         wl_list_insert_list(&surface->feedback_list,
3086                             &state->feedback_list);
3087         wl_list_init(&state->feedback_list);
3088
3089         wl_signal_emit(&surface->commit_signal, surface);
3090 }
3091
3092 static void
3093 weston_surface_commit(struct weston_surface *surface)
3094 {
3095         weston_surface_commit_state(surface, &surface->pending);
3096
3097         weston_surface_commit_subsurface_order(surface);
3098
3099         weston_surface_schedule_repaint(surface);
3100 }
3101
3102 static void
3103 weston_subsurface_commit(struct weston_subsurface *sub);
3104
3105 static void
3106 weston_subsurface_parent_commit(struct weston_subsurface *sub,
3107                                 int parent_is_synchronized);
3108
3109 static void
3110 surface_commit(struct wl_client *client, struct wl_resource *resource)
3111 {
3112         struct weston_surface *surface = wl_resource_get_user_data(resource);
3113         struct weston_subsurface *sub = weston_surface_to_subsurface(surface);
3114
3115         if (!weston_surface_is_pending_viewport_source_valid(surface)) {
3116                 assert(surface->viewport_resource);
3117
3118                 wl_resource_post_error(surface->viewport_resource,
3119                         WP_VIEWPORT_ERROR_OUT_OF_BUFFER,
3120                         "wl_surface@%d has viewport source outside buffer",
3121                         wl_resource_get_id(resource));
3122                 return;
3123         }
3124
3125         if (!weston_surface_is_pending_viewport_dst_size_int(surface)) {
3126                 assert(surface->viewport_resource);
3127
3128                 wl_resource_post_error(surface->viewport_resource,
3129                         WP_VIEWPORT_ERROR_BAD_SIZE,
3130                         "wl_surface@%d viewport dst size not integer",
3131                         wl_resource_get_id(resource));
3132                 return;
3133         }
3134
3135         if (sub) {
3136                 weston_subsurface_commit(sub);
3137                 return;
3138         }
3139
3140         weston_surface_commit(surface);
3141
3142         wl_list_for_each(sub, &surface->subsurface_list, parent_link) {
3143                 if (sub->surface != surface)
3144                         weston_subsurface_parent_commit(sub, 0);
3145         }
3146 }
3147
3148 static void
3149 surface_set_buffer_transform(struct wl_client *client,
3150                              struct wl_resource *resource, int transform)
3151 {
3152         struct weston_surface *surface = wl_resource_get_user_data(resource);
3153
3154         /* if wl_output.transform grows more members this will need to be updated. */
3155         if (transform < 0 ||
3156             transform > WL_OUTPUT_TRANSFORM_FLIPPED_270) {
3157                 wl_resource_post_error(resource,
3158                         WL_SURFACE_ERROR_INVALID_TRANSFORM,
3159                         "buffer transform must be a valid transform "
3160                         "('%d' specified)", transform);
3161                 return;
3162         }
3163
3164         surface->pending.buffer_viewport.buffer.transform = transform;
3165         surface->pending.buffer_viewport.changed = 1;
3166 }
3167
3168 static void
3169 surface_set_buffer_scale(struct wl_client *client,
3170                          struct wl_resource *resource,
3171                          int32_t scale)
3172 {
3173         struct weston_surface *surface = wl_resource_get_user_data(resource);
3174
3175         if (scale < 1) {
3176                 wl_resource_post_error(resource,
3177                         WL_SURFACE_ERROR_INVALID_SCALE,
3178                         "buffer scale must be at least one "
3179                         "('%d' specified)", scale);
3180                 return;
3181         }
3182
3183         surface->pending.buffer_viewport.buffer.scale = scale;
3184         surface->pending.buffer_viewport.changed = 1;
3185 }
3186
3187 static const struct wl_surface_interface surface_interface = {
3188         surface_destroy,
3189         surface_attach,
3190         surface_damage,
3191         surface_frame,
3192         surface_set_opaque_region,
3193         surface_set_input_region,
3194         surface_commit,
3195         surface_set_buffer_transform,
3196         surface_set_buffer_scale,
3197         surface_damage_buffer
3198 };
3199
3200 static void
3201 compositor_create_surface(struct wl_client *client,
3202                           struct wl_resource *resource, uint32_t id)
3203 {
3204         struct weston_compositor *ec = wl_resource_get_user_data(resource);
3205         struct weston_surface *surface;
3206
3207         surface = weston_surface_create(ec);
3208         if (surface == NULL) {
3209                 wl_resource_post_no_memory(resource);
3210                 return;
3211         }
3212
3213         surface->resource =
3214                 wl_resource_create(client, &wl_surface_interface,
3215                                    wl_resource_get_version(resource), id);
3216         if (surface->resource == NULL) {
3217                 weston_surface_destroy(surface);
3218                 wl_resource_post_no_memory(resource);
3219                 return;
3220         }
3221         wl_resource_set_implementation(surface->resource, &surface_interface,
3222                                        surface, destroy_surface);
3223
3224         wl_signal_emit(&ec->create_surface_signal, surface);
3225 }
3226
3227 static void
3228 destroy_region(struct wl_resource *resource)
3229 {
3230         struct weston_region *region = wl_resource_get_user_data(resource);
3231
3232         pixman_region32_fini(&region->region);
3233         free(region);
3234 }
3235
3236 static void
3237 region_destroy(struct wl_client *client, struct wl_resource *resource)
3238 {
3239         wl_resource_destroy(resource);
3240 }
3241
3242 static void
3243 region_add(struct wl_client *client, struct wl_resource *resource,
3244            int32_t x, int32_t y, int32_t width, int32_t height)
3245 {
3246         struct weston_region *region = wl_resource_get_user_data(resource);
3247
3248         pixman_region32_union_rect(&region->region, &region->region,
3249                                    x, y, width, height);
3250 }
3251
3252 static void
3253 region_subtract(struct wl_client *client, struct wl_resource *resource,
3254                 int32_t x, int32_t y, int32_t width, int32_t height)
3255 {
3256         struct weston_region *region = wl_resource_get_user_data(resource);
3257         pixman_region32_t rect;
3258
3259         pixman_region32_init_rect(&rect, x, y, width, height);
3260         pixman_region32_subtract(&region->region, &region->region, &rect);
3261         pixman_region32_fini(&rect);
3262 }
3263
3264 static const struct wl_region_interface region_interface = {
3265         region_destroy,
3266         region_add,
3267         region_subtract
3268 };
3269
3270 static void
3271 compositor_create_region(struct wl_client *client,
3272                          struct wl_resource *resource, uint32_t id)
3273 {
3274         struct weston_region *region;
3275
3276         region = malloc(sizeof *region);
3277         if (region == NULL) {
3278                 wl_resource_post_no_memory(resource);
3279                 return;
3280         }
3281
3282         pixman_region32_init(&region->region);
3283
3284         region->resource =
3285                 wl_resource_create(client, &wl_region_interface, 1, id);
3286         if (region->resource == NULL) {
3287                 free(region);
3288                 wl_resource_post_no_memory(resource);
3289                 return;
3290         }
3291         wl_resource_set_implementation(region->resource, &region_interface,
3292                                        region, destroy_region);
3293 }
3294
3295 static const struct wl_compositor_interface compositor_interface = {
3296         compositor_create_surface,
3297         compositor_create_region
3298 };
3299
3300 static void
3301 weston_subsurface_commit_from_cache(struct weston_subsurface *sub)
3302 {
3303         struct weston_surface *surface = sub->surface;
3304
3305         weston_surface_commit_state(surface, &sub->cached);
3306         weston_buffer_reference(&sub->cached_buffer_ref, NULL);
3307
3308         weston_surface_commit_subsurface_order(surface);
3309
3310         weston_surface_schedule_repaint(surface);
3311
3312         sub->has_cached_data = 0;
3313 }
3314
3315 static void
3316 weston_subsurface_commit_to_cache(struct weston_subsurface *sub)
3317 {
3318         struct weston_surface *surface = sub->surface;
3319
3320         /*
3321          * If this commit would cause the surface to move by the
3322          * attach(dx, dy) parameters, the old damage region must be
3323          * translated to correspond to the new surface coordinate system
3324          * origin.
3325          */
3326         pixman_region32_translate(&sub->cached.damage_surface,
3327                                   -surface->pending.sx, -surface->pending.sy);
3328         pixman_region32_union(&sub->cached.damage_surface,
3329                               &sub->cached.damage_surface,
3330                               &surface->pending.damage_surface);
3331         pixman_region32_clear(&surface->pending.damage_surface);
3332
3333         if (surface->pending.newly_attached) {
3334                 sub->cached.newly_attached = 1;
3335                 weston_surface_state_set_buffer(&sub->cached,
3336                                                 surface->pending.buffer);
3337                 weston_buffer_reference(&sub->cached_buffer_ref,
3338                                         surface->pending.buffer);
3339                 weston_presentation_feedback_discard_list(
3340                                         &sub->cached.feedback_list);
3341         }
3342         sub->cached.sx += surface->pending.sx;
3343         sub->cached.sy += surface->pending.sy;
3344
3345         apply_damage_buffer(&sub->cached.damage_surface, surface, &surface->pending);
3346
3347         sub->cached.buffer_viewport.changed |=
3348                 surface->pending.buffer_viewport.changed;
3349         sub->cached.buffer_viewport.buffer =
3350                 surface->pending.buffer_viewport.buffer;
3351         sub->cached.buffer_viewport.surface =
3352                 surface->pending.buffer_viewport.surface;
3353
3354         weston_surface_reset_pending_buffer(surface);
3355
3356         pixman_region32_copy(&sub->cached.opaque, &surface->pending.opaque);
3357
3358         pixman_region32_copy(&sub->cached.input, &surface->pending.input);
3359
3360         wl_list_insert_list(&sub->cached.frame_callback_list,
3361                             &surface->pending.frame_callback_list);
3362         wl_list_init(&surface->pending.frame_callback_list);
3363
3364         wl_list_insert_list(&sub->cached.feedback_list,
3365                             &surface->pending.feedback_list);
3366         wl_list_init(&surface->pending.feedback_list);
3367
3368         sub->has_cached_data = 1;
3369 }
3370
3371 static bool
3372 weston_subsurface_is_synchronized(struct weston_subsurface *sub)
3373 {
3374         while (sub) {
3375                 if (sub->synchronized)
3376                         return true;
3377
3378                 if (!sub->parent)
3379                         return false;
3380
3381                 sub = weston_surface_to_subsurface(sub->parent);
3382         }
3383
3384         return false;
3385 }
3386
3387 static void
3388 weston_subsurface_commit(struct weston_subsurface *sub)
3389 {
3390         struct weston_surface *surface = sub->surface;
3391         struct weston_subsurface *tmp;
3392
3393         /* Recursive check for effectively synchronized. */
3394         if (weston_subsurface_is_synchronized(sub)) {
3395                 weston_subsurface_commit_to_cache(sub);
3396         } else {
3397                 if (sub->has_cached_data) {
3398                         /* flush accumulated state from cache */
3399                         weston_subsurface_commit_to_cache(sub);
3400                         weston_subsurface_commit_from_cache(sub);
3401                 } else {
3402                         weston_surface_commit(surface);
3403                 }
3404
3405                 wl_list_for_each(tmp, &surface->subsurface_list, parent_link) {
3406                         if (tmp->surface != surface)
3407                                 weston_subsurface_parent_commit(tmp, 0);
3408                 }
3409         }
3410 }
3411
3412 static void
3413 weston_subsurface_synchronized_commit(struct weston_subsurface *sub)
3414 {
3415         struct weston_surface *surface = sub->surface;
3416         struct weston_subsurface *tmp;
3417
3418         /* From now on, commit_from_cache the whole sub-tree, regardless of
3419          * the synchronized mode of each child. This sub-surface or some
3420          * of its ancestors were synchronized, so we are synchronized
3421          * all the way down.
3422          */
3423
3424         if (sub->has_cached_data)
3425                 weston_subsurface_commit_from_cache(sub);
3426
3427         wl_list_for_each(tmp, &surface->subsurface_list, parent_link) {
3428                 if (tmp->surface != surface)
3429                         weston_subsurface_parent_commit(tmp, 1);
3430         }
3431 }
3432
3433 static void
3434 weston_subsurface_parent_commit(struct weston_subsurface *sub,
3435                                 int parent_is_synchronized)
3436 {
3437         struct weston_view *view;
3438         if (sub->position.set) {
3439                 wl_list_for_each(view, &sub->surface->views, surface_link)
3440                         weston_view_set_position(view,
3441                                                  sub->position.x,
3442                                                  sub->position.y);
3443
3444                 sub->position.set = 0;
3445         }
3446
3447         if (parent_is_synchronized || sub->synchronized)
3448                 weston_subsurface_synchronized_commit(sub);
3449 }
3450
3451 static int
3452 subsurface_get_label(struct weston_surface *surface, char *buf, size_t len)
3453 {
3454         return snprintf(buf, len, "sub-surface");
3455 }
3456
3457 static void
3458 subsurface_committed(struct weston_surface *surface, int32_t dx, int32_t dy)
3459 {
3460         struct weston_view *view;
3461
3462         wl_list_for_each(view, &surface->views, surface_link)
3463                 weston_view_set_position(view,
3464                                          view->geometry.x + dx,
3465                                          view->geometry.y + dy);
3466
3467         /* No need to check parent mappedness, because if parent is not
3468          * mapped, parent is not in a visible layer, so this sub-surface
3469          * will not be drawn either.
3470          */
3471
3472         if (!weston_surface_is_mapped(surface)) {
3473                 surface->is_mapped = true;
3474
3475                 /* Cannot call weston_view_update_transform(),
3476                  * because that would call it also for the parent surface,
3477                  * which might not be mapped yet. That would lead to
3478                  * inconsistent state, where the window could never be
3479                  * mapped.
3480                  *
3481                  * Instead just force the is_mapped flag on, to make
3482                  * weston_surface_is_mapped() return true, so that when the
3483                  * parent surface does get mapped, this one will get
3484                  * included, too. See view_list_add().
3485                  */
3486         }
3487 }
3488
3489 static struct weston_subsurface *
3490 weston_surface_to_subsurface(struct weston_surface *surface)
3491 {
3492         if (surface->committed == subsurface_committed)
3493                 return surface->committed_private;
3494
3495         return NULL;
3496 }
3497
3498 WL_EXPORT struct weston_surface *
3499 weston_surface_get_main_surface(struct weston_surface *surface)
3500 {
3501         struct weston_subsurface *sub;
3502
3503         while (surface && (sub = weston_surface_to_subsurface(surface)))
3504                 surface = sub->parent;
3505
3506         return surface;
3507 }
3508
3509 WL_EXPORT int
3510 weston_surface_set_role(struct weston_surface *surface,
3511                         const char *role_name,
3512                         struct wl_resource *error_resource,
3513                         uint32_t error_code)
3514 {
3515         assert(role_name);
3516
3517         if (surface->role_name == NULL ||
3518             surface->role_name == role_name ||
3519             strcmp(surface->role_name, role_name) == 0) {
3520                 surface->role_name = role_name;
3521
3522                 return 0;
3523         }
3524
3525         wl_resource_post_error(error_resource, error_code,
3526                                "Cannot assign role %s to wl_surface@%d,"
3527                                " already has role %s\n",
3528                                role_name,
3529                                wl_resource_get_id(surface->resource),
3530                                surface->role_name);
3531         return -1;
3532 }
3533
3534 WL_EXPORT const char *
3535 weston_surface_get_role(struct weston_surface *surface)
3536 {
3537         return surface->role_name;
3538 }
3539
3540 WL_EXPORT void
3541 weston_surface_set_label_func(struct weston_surface *surface,
3542                               int (*desc)(struct weston_surface *,
3543                                           char *, size_t))
3544 {
3545         surface->get_label = desc;
3546         surface->timeline.force_refresh = 1;
3547 }
3548
3549 /** Get the size of surface contents
3550  *
3551  * \param surface The surface to query.
3552  * \param width Returns the width of raw contents.
3553  * \param height Returns the height of raw contents.
3554  *
3555  * Retrieves the raw surface content size in pixels for the given surface.
3556  * This is the whole content size in buffer pixels. If the surface
3557  * has no content or the renderer does not implement this feature,
3558  * zeroes are returned.
3559  *
3560  * This function is used to determine the buffer size needed for
3561  * a weston_surface_copy_content() call.
3562  */
3563 WL_EXPORT void
3564 weston_surface_get_content_size(struct weston_surface *surface,
3565                                 int *width, int *height)
3566 {
3567         struct weston_renderer *rer = surface->compositor->renderer;
3568
3569         if (!rer->surface_get_content_size) {
3570                 *width = 0;
3571                 *height = 0;
3572                 return;
3573         }
3574
3575         rer->surface_get_content_size(surface, width, height);
3576 }
3577
3578 /** Get the bounding box of a surface and its subsurfaces
3579  *
3580  * \param surface The surface to query.
3581  * \return The bounding box relative to the surface origin.
3582  *
3583  */
3584 WL_EXPORT struct weston_geometry
3585 weston_surface_get_bounding_box(struct weston_surface *surface)
3586 {
3587         pixman_region32_t region;
3588         pixman_box32_t *box;
3589         struct weston_subsurface *subsurface;
3590
3591         pixman_region32_init_rect(&region,
3592                                   0, 0,
3593                                   surface->width, surface->height);
3594
3595         wl_list_for_each(subsurface, &surface->subsurface_list, parent_link)
3596                 pixman_region32_union_rect(&region, &region,
3597                                            subsurface->position.x,
3598                                            subsurface->position.y,
3599                                            subsurface->surface->width,
3600                                            subsurface->surface->height);
3601
3602         box = pixman_region32_extents(&region);
3603         struct weston_geometry geometry = {
3604                 .x = box->x1,
3605                 .y = box->y1,
3606                 .width = box->x2 - box->x1,
3607                 .height = box->y2 - box->y1,
3608         };
3609
3610         pixman_region32_fini(&region);
3611
3612         return geometry;
3613 }
3614
3615 /** Copy surface contents to system memory.
3616  *
3617  * \param surface The surface to copy from.
3618  * \param target Pointer to the target memory buffer.
3619  * \param size Size of the target buffer in bytes.
3620  * \param src_x X location on contents to copy from.
3621  * \param src_y Y location on contents to copy from.
3622  * \param width Width in pixels of the area to copy.
3623  * \param height Height in pixels of the area to copy.
3624  * \return 0 for success, -1 for failure.
3625  *
3626  * Surface contents are maintained by the renderer. They can be in a
3627  * reserved weston_buffer or as a copy, e.g. a GL texture, or something
3628  * else.
3629  *
3630  * Surface contents are copied into memory pointed to by target,
3631  * which has size bytes of space available. The target memory
3632  * may be larger than needed, but being smaller returns an error.
3633  * The extra bytes in target may or may not be written; their content is
3634  * unspecified. Size must be large enough to hold the image.
3635  *
3636  * The image in the target memory will be arranged in rows from
3637  * top to bottom, and pixels on a row from left to right. The pixel
3638  * format is PIXMAN_a8b8g8r8, 4 bytes per pixel, and stride is exactly
3639  * width * 4.
3640  *
3641  * Parameters src_x and src_y define the upper-left corner in buffer
3642  * coordinates (pixels) to copy from. Parameters width and height
3643  * define the size of the area to copy in pixels.
3644  *
3645  * The rectangle defined by src_x, src_y, width, height must fit in
3646  * the surface contents. Otherwise an error is returned.
3647  *
3648  * Use surface_get_data_size to determine the content size; the
3649  * needed target buffer size and rectangle limits.
3650  *
3651  * CURRENT IMPLEMENTATION RESTRICTIONS:
3652  * - the machine must be little-endian due to Pixman formats.
3653  *
3654  * NOTE: Pixman formats are premultiplied.
3655  */
3656 WL_EXPORT int
3657 weston_surface_copy_content(struct weston_surface *surface,
3658                             void *target, size_t size,
3659                             int src_x, int src_y,
3660                             int width, int height)
3661 {
3662         struct weston_renderer *rer = surface->compositor->renderer;
3663         int cw, ch;
3664         const size_t bytespp = 4; /* PIXMAN_a8b8g8r8 */
3665
3666         if (!rer->surface_copy_content)
3667                 return -1;
3668
3669         weston_surface_get_content_size(surface, &cw, &ch);
3670
3671         if (src_x < 0 || src_y < 0)
3672                 return -1;
3673
3674         if (width <= 0 || height <= 0)
3675                 return -1;
3676
3677         if (src_x + width > cw || src_y + height > ch)
3678                 return -1;
3679
3680         if (width * bytespp * height > size)
3681                 return -1;
3682
3683         return rer->surface_copy_content(surface, target, size,
3684                                          src_x, src_y, width, height);
3685 }
3686
3687 static void
3688 subsurface_set_position(struct wl_client *client,
3689                         struct wl_resource *resource, int32_t x, int32_t y)
3690 {
3691         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
3692
3693         if (!sub)
3694                 return;
3695
3696         sub->position.x = x;
3697         sub->position.y = y;
3698         sub->position.set = 1;
3699 }
3700
3701 static struct weston_subsurface *
3702 subsurface_find_sibling(struct weston_subsurface *sub,
3703                        struct weston_surface *surface)
3704 {
3705         struct weston_surface *parent = sub->parent;
3706         struct weston_subsurface *sibling;
3707
3708         wl_list_for_each(sibling, &parent->subsurface_list, parent_link) {
3709                 if (sibling->surface == surface && sibling != sub)
3710                         return sibling;
3711         }
3712
3713         return NULL;
3714 }
3715
3716 static struct weston_subsurface *
3717 subsurface_sibling_check(struct weston_subsurface *sub,
3718                          struct weston_surface *surface,
3719                          const char *request)
3720 {
3721         struct weston_subsurface *sibling;
3722
3723         sibling = subsurface_find_sibling(sub, surface);
3724         if (!sibling) {
3725                 wl_resource_post_error(sub->resource,
3726                         WL_SUBSURFACE_ERROR_BAD_SURFACE,
3727                         "%s: wl_surface@%d is not a parent or sibling",
3728                         request, wl_resource_get_id(surface->resource));
3729                 return NULL;
3730         }
3731
3732         assert(sibling->parent == sub->parent);
3733
3734         return sibling;
3735 }
3736
3737 static void
3738 subsurface_place_above(struct wl_client *client,
3739                        struct wl_resource *resource,
3740                        struct wl_resource *sibling_resource)
3741 {
3742         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
3743         struct weston_surface *surface =
3744                 wl_resource_get_user_data(sibling_resource);
3745         struct weston_subsurface *sibling;
3746
3747         if (!sub)
3748                 return;
3749
3750         sibling = subsurface_sibling_check(sub, surface, "place_above");
3751         if (!sibling)
3752                 return;
3753
3754         wl_list_remove(&sub->parent_link_pending);
3755         wl_list_insert(sibling->parent_link_pending.prev,
3756                        &sub->parent_link_pending);
3757
3758         sub->reordered = true;
3759 }
3760
3761 static void
3762 subsurface_place_below(struct wl_client *client,
3763                        struct wl_resource *resource,
3764                        struct wl_resource *sibling_resource)
3765 {
3766         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
3767         struct weston_surface *surface =
3768                 wl_resource_get_user_data(sibling_resource);
3769         struct weston_subsurface *sibling;
3770
3771         if (!sub)
3772                 return;
3773
3774         sibling = subsurface_sibling_check(sub, surface, "place_below");
3775         if (!sibling)
3776                 return;
3777
3778         wl_list_remove(&sub->parent_link_pending);
3779         wl_list_insert(&sibling->parent_link_pending,
3780                        &sub->parent_link_pending);
3781
3782         sub->reordered = true;
3783 }
3784
3785 static void
3786 subsurface_set_sync(struct wl_client *client, struct wl_resource *resource)
3787 {
3788         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
3789
3790         if (sub)
3791                 sub->synchronized = 1;
3792 }
3793
3794 static void
3795 subsurface_set_desync(struct wl_client *client, struct wl_resource *resource)
3796 {
3797         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
3798
3799         if (sub && sub->synchronized) {
3800                 sub->synchronized = 0;
3801
3802                 /* If sub became effectively desynchronized, flush. */
3803                 if (!weston_subsurface_is_synchronized(sub))
3804                         weston_subsurface_synchronized_commit(sub);
3805         }
3806 }
3807
3808 static void
3809 weston_subsurface_unlink_parent(struct weston_subsurface *sub)
3810 {
3811         wl_list_remove(&sub->parent_link);
3812         wl_list_remove(&sub->parent_link_pending);
3813         wl_list_remove(&sub->parent_destroy_listener.link);
3814         sub->parent = NULL;
3815 }
3816
3817 static void
3818 weston_subsurface_destroy(struct weston_subsurface *sub);
3819
3820 static void
3821 subsurface_handle_surface_destroy(struct wl_listener *listener, void *data)
3822 {
3823         struct weston_subsurface *sub =
3824                 container_of(listener, struct weston_subsurface,
3825                              surface_destroy_listener);
3826         assert(data == sub->surface);
3827
3828         /* The protocol object (wl_resource) is left inert. */
3829         if (sub->resource)
3830                 wl_resource_set_user_data(sub->resource, NULL);
3831
3832         weston_subsurface_destroy(sub);
3833 }
3834
3835 static void
3836 subsurface_handle_parent_destroy(struct wl_listener *listener, void *data)
3837 {
3838         struct weston_subsurface *sub =
3839                 container_of(listener, struct weston_subsurface,
3840                              parent_destroy_listener);
3841         assert(data == sub->parent);
3842         assert(sub->surface != sub->parent);
3843
3844         if (weston_surface_is_mapped(sub->surface))
3845                 weston_surface_unmap(sub->surface);
3846
3847         weston_subsurface_unlink_parent(sub);
3848 }
3849
3850 static void
3851 subsurface_resource_destroy(struct wl_resource *resource)
3852 {
3853         struct weston_subsurface *sub = wl_resource_get_user_data(resource);
3854
3855         if (sub)
3856                 weston_subsurface_destroy(sub);
3857 }
3858
3859 static void
3860 subsurface_destroy(struct wl_client *client, struct wl_resource *resource)
3861 {
3862         wl_resource_destroy(resource);
3863 }
3864
3865 static void
3866 weston_subsurface_link_parent(struct weston_subsurface *sub,
3867                               struct weston_surface *parent)
3868 {
3869         sub->parent = parent;
3870         sub->parent_destroy_listener.notify = subsurface_handle_parent_destroy;
3871         wl_signal_add(&parent->destroy_signal,
3872                       &sub->parent_destroy_listener);
3873
3874         wl_list_insert(&parent->subsurface_list, &sub->parent_link);
3875         wl_list_insert(&parent->subsurface_list_pending,
3876                        &sub->parent_link_pending);
3877 }
3878
3879 static void
3880 weston_subsurface_link_surface(struct weston_subsurface *sub,
3881                                struct weston_surface *surface)
3882 {
3883         sub->surface = surface;
3884         sub->surface_destroy_listener.notify =
3885                 subsurface_handle_surface_destroy;
3886         wl_signal_add(&surface->destroy_signal,
3887                       &sub->surface_destroy_listener);
3888 }
3889
3890 static void
3891 weston_subsurface_destroy(struct weston_subsurface *sub)
3892 {
3893         struct weston_view *view, *next;
3894
3895         assert(sub->surface);
3896
3897         if (sub->resource) {
3898                 assert(weston_surface_to_subsurface(sub->surface) == sub);
3899                 assert(sub->parent_destroy_listener.notify ==
3900                        subsurface_handle_parent_destroy);
3901
3902                 wl_list_for_each_safe(view, next, &sub->surface->views, surface_link) {
3903                         weston_view_unmap(view);
3904                         weston_view_destroy(view);
3905                 }
3906
3907                 if (sub->parent)
3908                         weston_subsurface_unlink_parent(sub);
3909
3910                 weston_surface_state_fini(&sub->cached);
3911                 weston_buffer_reference(&sub->cached_buffer_ref, NULL);
3912
3913                 sub->surface->committed = NULL;
3914                 sub->surface->committed_private = NULL;
3915                 weston_surface_set_label_func(sub->surface, NULL);
3916         } else {
3917                 /* the dummy weston_subsurface for the parent itself */
3918                 assert(sub->parent_destroy_listener.notify == NULL);
3919                 wl_list_remove(&sub->parent_link);
3920                 wl_list_remove(&sub->parent_link_pending);
3921         }
3922
3923         wl_list_remove(&sub->surface_destroy_listener.link);
3924         free(sub);
3925 }
3926
3927 static const struct wl_subsurface_interface subsurface_implementation = {
3928         subsurface_destroy,
3929         subsurface_set_position,
3930         subsurface_place_above,
3931         subsurface_place_below,
3932         subsurface_set_sync,
3933         subsurface_set_desync
3934 };
3935
3936 static struct weston_subsurface *
3937 weston_subsurface_create(uint32_t id, struct weston_surface *surface,
3938                          struct weston_surface *parent)
3939 {
3940         struct weston_subsurface *sub;
3941         struct wl_client *client = wl_resource_get_client(surface->resource);
3942
3943         sub = zalloc(sizeof *sub);
3944         if (sub == NULL)
3945                 return NULL;
3946
3947         wl_list_init(&sub->unused_views);
3948
3949         sub->resource =
3950                 wl_resource_create(client, &wl_subsurface_interface, 1, id);
3951         if (!sub->resource) {
3952                 free(sub);
3953                 return NULL;
3954         }
3955
3956         wl_resource_set_implementation(sub->resource,
3957                                        &subsurface_implementation,
3958                                        sub, subsurface_resource_destroy);
3959         weston_subsurface_link_surface(sub, surface);
3960         weston_subsurface_link_parent(sub, parent);
3961         weston_surface_state_init(&sub->cached);
3962         sub->cached_buffer_ref.buffer = NULL;
3963         sub->synchronized = 1;
3964
3965         return sub;
3966 }
3967
3968 /* Create a dummy subsurface for having the parent itself in its
3969  * sub-surface lists. Makes stacking order manipulation easy.
3970  */
3971 static struct weston_subsurface *
3972 weston_subsurface_create_for_parent(struct weston_surface *parent)
3973 {
3974         struct weston_subsurface *sub;
3975
3976         sub = zalloc(sizeof *sub);
3977         if (sub == NULL)
3978                 return NULL;
3979
3980         weston_subsurface_link_surface(sub, parent);
3981         sub->parent = parent;
3982         wl_list_insert(&parent->subsurface_list, &sub->parent_link);
3983         wl_list_insert(&parent->subsurface_list_pending,
3984                        &sub->parent_link_pending);
3985
3986         return sub;
3987 }
3988
3989 static void
3990 subcompositor_get_subsurface(struct wl_client *client,
3991                              struct wl_resource *resource,
3992                              uint32_t id,
3993                              struct wl_resource *surface_resource,
3994                              struct wl_resource *parent_resource)
3995 {
3996         struct weston_surface *surface =
3997                 wl_resource_get_user_data(surface_resource);
3998         struct weston_surface *parent =
3999                 wl_resource_get_user_data(parent_resource);
4000         struct weston_subsurface *sub;
4001         static const char where[] = "get_subsurface: wl_subsurface@";
4002
4003         if (surface == parent) {
4004                 wl_resource_post_error(resource,
4005                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
4006                         "%s%d: wl_surface@%d cannot be its own parent",
4007                         where, id, wl_resource_get_id(surface_resource));
4008                 return;
4009         }
4010
4011         if (weston_surface_to_subsurface(surface)) {
4012                 wl_resource_post_error(resource,
4013                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
4014                         "%s%d: wl_surface@%d is already a sub-surface",
4015                         where, id, wl_resource_get_id(surface_resource));
4016                 return;
4017         }
4018
4019         if (weston_surface_set_role(surface, "wl_subsurface", resource,
4020                                     WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE) < 0)
4021                 return;
4022
4023         if (weston_surface_get_main_surface(parent) == surface) {
4024                 wl_resource_post_error(resource,
4025                         WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE,
4026                         "%s%d: wl_surface@%d is an ancestor of parent",
4027                         where, id, wl_resource_get_id(surface_resource));
4028                 return;
4029         }
4030
4031         /* make sure the parent is in its own list */
4032         if (wl_list_empty(&parent->subsurface_list)) {
4033                 if (!weston_subsurface_create_for_parent(parent)) {
4034                         wl_resource_post_no_memory(resource);
4035                         return;
4036                 }
4037         }
4038
4039         sub = weston_subsurface_create(id, surface, parent);
4040         if (!sub) {
4041                 wl_resource_post_no_memory(resource);
4042                 return;
4043         }
4044
4045         surface->committed = subsurface_committed;
4046         surface->committed_private = sub;
4047         weston_surface_set_label_func(surface, subsurface_get_label);
4048 }
4049
4050 static void
4051 subcompositor_destroy(struct wl_client *client, struct wl_resource *resource)
4052 {
4053         wl_resource_destroy(resource);
4054 }
4055
4056 static const struct wl_subcompositor_interface subcompositor_interface = {
4057         subcompositor_destroy,
4058         subcompositor_get_subsurface
4059 };
4060
4061 static void
4062 bind_subcompositor(struct wl_client *client,
4063                    void *data, uint32_t version, uint32_t id)
4064 {
4065         struct weston_compositor *compositor = data;
4066         struct wl_resource *resource;
4067
4068         resource =
4069                 wl_resource_create(client, &wl_subcompositor_interface, 1, id);
4070         if (resource == NULL) {
4071                 wl_client_post_no_memory(client);
4072                 return;
4073         }
4074         wl_resource_set_implementation(resource, &subcompositor_interface,
4075                                        compositor, NULL);
4076 }
4077
4078 /** Set a DPMS mode on all of the compositor's outputs
4079  *
4080  * \param compositor The compositor instance
4081  * \param state The DPMS state the outputs will be set to
4082  */
4083 static void
4084 weston_compositor_dpms(struct weston_compositor *compositor,
4085                        enum dpms_enum state)
4086 {
4087         struct weston_output *output;
4088
4089         wl_list_for_each(output, &compositor->output_list, link)
4090                 if (output->set_dpms)
4091                         output->set_dpms(output, state);
4092 }
4093
4094 /** Restores the compositor to active status
4095  *
4096  * \param compositor The compositor instance
4097  *
4098  * If the compositor was in a sleeping mode, all outputs are powered
4099  * back on via DPMS.  Otherwise if the compositor was inactive
4100  * (idle/locked, offscreen, or sleeping) then the compositor's wake
4101  * signal will fire.
4102  *
4103  * Restarts the idle timer.
4104  */
4105 WL_EXPORT void
4106 weston_compositor_wake(struct weston_compositor *compositor)
4107 {
4108         uint32_t old_state = compositor->state;
4109
4110         /* The state needs to be changed before emitting the wake
4111          * signal because that may try to schedule a repaint which
4112          * will not work if the compositor is still sleeping */
4113         compositor->state = WESTON_COMPOSITOR_ACTIVE;
4114
4115         switch (old_state) {
4116         case WESTON_COMPOSITOR_SLEEPING:
4117         case WESTON_COMPOSITOR_IDLE:
4118         case WESTON_COMPOSITOR_OFFSCREEN:
4119                 weston_compositor_dpms(compositor, WESTON_DPMS_ON);
4120                 wl_signal_emit(&compositor->wake_signal, compositor);
4121                 /* fall through */
4122         default:
4123                 wl_event_source_timer_update(compositor->idle_source,
4124                                              compositor->idle_time * 1000);
4125         }
4126 }
4127
4128 /** Turns off rendering and frame events for the compositor.
4129  *
4130  * \param compositor The compositor instance
4131  *
4132  * This is used for example to prevent further rendering while the
4133  * compositor is shutting down.
4134  *
4135  * Stops the idle timer.
4136  */
4137 WL_EXPORT void
4138 weston_compositor_offscreen(struct weston_compositor *compositor)
4139 {
4140         switch (compositor->state) {
4141         case WESTON_COMPOSITOR_OFFSCREEN:
4142                 return;
4143         case WESTON_COMPOSITOR_SLEEPING:
4144         default:
4145                 compositor->state = WESTON_COMPOSITOR_OFFSCREEN;
4146                 wl_event_source_timer_update(compositor->idle_source, 0);
4147         }
4148 }
4149
4150 /** Powers down all attached output devices
4151  *
4152  * \param compositor The compositor instance
4153  *
4154  * Causes rendering to the outputs to cease, and no frame events to be
4155  * sent.  Only powers down the outputs if the compositor is not already
4156  * in sleep mode.
4157  *
4158  * Stops the idle timer.
4159  */
4160 WL_EXPORT void
4161 weston_compositor_sleep(struct weston_compositor *compositor)
4162 {
4163         if (compositor->state == WESTON_COMPOSITOR_SLEEPING)
4164                 return;
4165
4166         wl_event_source_timer_update(compositor->idle_source, 0);
4167         compositor->state = WESTON_COMPOSITOR_SLEEPING;
4168         weston_compositor_dpms(compositor, WESTON_DPMS_OFF);
4169 }
4170
4171 /** Sets compositor to idle mode
4172  *
4173  * \param data The compositor instance
4174  *
4175  * This is called when the idle timer fires.  Once the compositor is in
4176  * idle mode it requires a wake action (e.g. via
4177  * weston_compositor_wake()) to restore it.  The compositor's
4178  * idle_signal will be triggered when the idle event occurs.
4179  *
4180  * Idleness can be inhibited by setting the compositor's idle_inhibit
4181  * property.
4182  */
4183 static int
4184 idle_handler(void *data)
4185 {
4186         struct weston_compositor *compositor = data;
4187
4188         if (compositor->idle_inhibit)
4189                 return 1;
4190
4191         compositor->state = WESTON_COMPOSITOR_IDLE;
4192         wl_signal_emit(&compositor->idle_signal, compositor);
4193
4194         return 1;
4195 }
4196
4197 WL_EXPORT void
4198 weston_plane_init(struct weston_plane *plane,
4199                         struct weston_compositor *ec,
4200                         int32_t x, int32_t y)
4201 {
4202         pixman_region32_init(&plane->damage);
4203         pixman_region32_init(&plane->clip);
4204         plane->x = x;
4205         plane->y = y;
4206         plane->compositor = ec;
4207
4208         /* Init the link so that the call to wl_list_remove() when releasing
4209          * the plane without ever stacking doesn't lead to a crash */
4210         wl_list_init(&plane->link);
4211 }
4212
4213 WL_EXPORT void
4214 weston_plane_release(struct weston_plane *plane)
4215 {
4216         struct weston_view *view;
4217
4218         pixman_region32_fini(&plane->damage);
4219         pixman_region32_fini(&plane->clip);
4220
4221         wl_list_for_each(view, &plane->compositor->view_list, link) {
4222                 if (view->plane == plane)
4223                         view->plane = NULL;
4224         }
4225
4226         wl_list_remove(&plane->link);
4227 }
4228
4229 WL_EXPORT void
4230 weston_compositor_stack_plane(struct weston_compositor *ec,
4231                               struct weston_plane *plane,
4232                               struct weston_plane *above)
4233 {
4234         if (above)
4235                 wl_list_insert(above->link.prev, &plane->link);
4236         else
4237                 wl_list_insert(&ec->plane_list, &plane->link);
4238 }
4239
4240 static void
4241 output_release(struct wl_client *client, struct wl_resource *resource)
4242 {
4243         wl_resource_destroy(resource);
4244 }
4245
4246 static const struct wl_output_interface output_interface = {
4247         output_release,
4248 };
4249
4250
4251 static void unbind_resource(struct wl_resource *resource)
4252 {
4253         wl_list_remove(wl_resource_get_link(resource));
4254 }
4255
4256 static void
4257 bind_output(struct wl_client *client,
4258             void *data, uint32_t version, uint32_t id)
4259 {
4260         struct weston_output *output = data;
4261         struct weston_mode *mode;
4262         struct wl_resource *resource;
4263
4264         resource = wl_resource_create(client, &wl_output_interface,
4265                                       version, id);
4266         if (resource == NULL) {
4267                 wl_client_post_no_memory(client);
4268                 return;
4269         }
4270
4271         wl_list_insert(&output->resource_list, wl_resource_get_link(resource));
4272         wl_resource_set_implementation(resource, &output_interface, data, unbind_resource);
4273
4274         wl_output_send_geometry(resource,
4275                                 output->x,
4276                                 output->y,
4277                                 output->mm_width,
4278                                 output->mm_height,
4279                                 output->subpixel,
4280                                 output->make, output->model,
4281                                 output->transform);
4282         if (version >= WL_OUTPUT_SCALE_SINCE_VERSION)
4283                 wl_output_send_scale(resource,
4284                                      output->current_scale);
4285
4286         wl_list_for_each (mode, &output->mode_list, link) {
4287                 wl_output_send_mode(resource,
4288                                     mode->flags,
4289                                     mode->width,
4290                                     mode->height,
4291                                     mode->refresh);
4292         }
4293
4294         if (version >= WL_OUTPUT_DONE_SINCE_VERSION)
4295                 wl_output_send_done(resource);
4296 }
4297
4298 /* Move other outputs when one is resized so the space remains contiguous. */
4299 static void
4300 weston_compositor_reflow_outputs(struct weston_compositor *compositor,
4301                                 struct weston_output *resized_output, int delta_width)
4302 {
4303         struct weston_output *output;
4304         bool start_resizing = false;
4305
4306         if (!delta_width)
4307                 return;
4308
4309         wl_list_for_each(output, &compositor->output_list, link) {
4310                 if (output == resized_output) {
4311                         start_resizing = true;
4312                         continue;
4313                 }
4314
4315                 if (start_resizing) {
4316                         weston_output_move(output, output->x + delta_width, output->y);
4317                         output->dirty = 1;
4318                 }
4319         }
4320 }
4321
4322 WL_EXPORT void
4323 weston_output_update_matrix(struct weston_output *output)
4324 {
4325         float magnification;
4326
4327         weston_matrix_init(&output->matrix);
4328         weston_matrix_translate(&output->matrix, -output->x, -output->y, 0);
4329
4330         if (output->zoom.active) {
4331                 magnification = 1 / (1 - output->zoom.spring_z.current);
4332                 weston_output_update_zoom(output);
4333                 weston_matrix_translate(&output->matrix, -output->zoom.trans_x,
4334                                         -output->zoom.trans_y, 0);
4335                 weston_matrix_scale(&output->matrix, magnification,
4336                                     magnification, 1.0);
4337         }
4338
4339         switch (output->transform) {
4340         case WL_OUTPUT_TRANSFORM_FLIPPED:
4341         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
4342         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
4343         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
4344                 weston_matrix_translate(&output->matrix, -output->width, 0, 0);
4345                 weston_matrix_scale(&output->matrix, -1, 1, 1);
4346                 break;
4347         }
4348
4349         switch (output->transform) {
4350         default:
4351         case WL_OUTPUT_TRANSFORM_NORMAL:
4352         case WL_OUTPUT_TRANSFORM_FLIPPED:
4353                 break;
4354         case WL_OUTPUT_TRANSFORM_90:
4355         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
4356                 weston_matrix_translate(&output->matrix, 0, -output->height, 0);
4357                 weston_matrix_rotate_xy(&output->matrix, 0, 1);
4358                 break;
4359         case WL_OUTPUT_TRANSFORM_180:
4360         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
4361                 weston_matrix_translate(&output->matrix,
4362                                         -output->width, -output->height, 0);
4363                 weston_matrix_rotate_xy(&output->matrix, -1, 0);
4364                 break;
4365         case WL_OUTPUT_TRANSFORM_270:
4366         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
4367                 weston_matrix_translate(&output->matrix, -output->width, 0, 0);
4368                 weston_matrix_rotate_xy(&output->matrix, 0, -1);
4369                 break;
4370         }
4371
4372         if (output->current_scale != 1)
4373                 weston_matrix_scale(&output->matrix,
4374                                     output->current_scale,
4375                                     output->current_scale, 1);
4376
4377         output->dirty = 0;
4378
4379         weston_matrix_invert(&output->inverse_matrix, &output->matrix);
4380 }
4381
4382 static void
4383 weston_output_transform_scale_init(struct weston_output *output, uint32_t transform, uint32_t scale)
4384 {
4385         output->transform = transform;
4386         output->native_scale = scale;
4387         output->current_scale = scale;
4388
4389         convert_size_by_transform_scale(&output->width, &output->height,
4390                                         output->current_mode->width,
4391                                         output->current_mode->height,
4392                                         transform, scale);
4393 }
4394
4395 static void
4396 weston_output_init_geometry(struct weston_output *output, int x, int y)
4397 {
4398         output->x = x;
4399         output->y = y;
4400
4401         pixman_region32_init(&output->previous_damage);
4402         pixman_region32_init_rect(&output->region, x, y,
4403                                   output->width,
4404                                   output->height);
4405 }
4406
4407 WL_EXPORT void
4408 weston_output_move(struct weston_output *output, int x, int y)
4409 {
4410         struct wl_resource *resource;
4411
4412         output->move_x = x - output->x;
4413         output->move_y = y - output->y;
4414
4415         if (output->move_x == 0 && output->move_y == 0)
4416                 return;
4417
4418         weston_output_init_geometry(output, x, y);
4419
4420         output->dirty = 1;
4421
4422         /* Move views on this output. */
4423         wl_signal_emit(&output->compositor->output_moved_signal, output);
4424
4425         /* Notify clients of the change for output position. */
4426         wl_resource_for_each(resource, &output->resource_list) {
4427                 wl_output_send_geometry(resource,
4428                                         output->x,
4429                                         output->y,
4430                                         output->mm_width,
4431                                         output->mm_height,
4432                                         output->subpixel,
4433                                         output->make,
4434                                         output->model,
4435                                         output->transform);
4436
4437                 if (wl_resource_get_version(resource) >= WL_OUTPUT_DONE_SINCE_VERSION)
4438                         wl_output_send_done(resource);
4439         }
4440 }
4441
4442 /** Adds an output to the compositor's output list and
4443  *  send the compositor's output_created signal.
4444  *
4445  * \param compositor The compositor instance.
4446  * \param output The output to be added.
4447  */
4448 WL_EXPORT void
4449 weston_compositor_add_output(struct weston_compositor *compositor,
4450                              struct weston_output *output)
4451 {
4452         struct weston_view *view, *next;
4453
4454         wl_list_insert(compositor->output_list.prev, &output->link);
4455         wl_signal_emit(&compositor->output_created_signal, output);
4456
4457         wl_list_for_each_safe(view, next, &compositor->view_list, link)
4458                 weston_view_geometry_dirty(view);
4459 }
4460
4461 WL_EXPORT void
4462 weston_output_transform_coordinate(struct weston_output *output,
4463                                    double device_x, double device_y,
4464                                    double *x, double *y)
4465 {
4466         struct weston_vector p = { {
4467                 device_x,
4468                 device_y,
4469                 0.0,
4470                 1.0 } };
4471
4472         weston_matrix_transform(&output->inverse_matrix, &p);
4473
4474         *x = p.f[0] / p.f[3];
4475         *y = p.f[1] / p.f[3];
4476 }
4477
4478 /** Undoes changes to an output done by weston_output_enable()
4479  *
4480  * \param output The weston_output object that needs the changes undone.
4481  *
4482  * Removes the repaint timer.
4483  * Destroys the Wayland global assigned to the output.
4484  * Destroys pixman regions allocated to the output.
4485  * Deallocates output's ID and updates compositor's output_id_pool.
4486  */
4487 static void
4488 weston_output_enable_undo(struct weston_output *output)
4489 {
4490         wl_global_destroy(output->global);
4491
4492         pixman_region32_fini(&output->region);
4493         pixman_region32_fini(&output->previous_damage);
4494         output->compositor->output_id_pool &= ~(1u << output->id);
4495
4496         output->enabled = false;
4497 }
4498
4499 /** Removes output from compositor's output list
4500  *
4501  * \param output The weston_output object that is being removed.
4502  *
4503  * Presentation feedback is discarded.
4504  * Compositor is notified that outputs were changed and
4505  * applies the necessary changes.
4506  * All views assigned to the weston_output object are
4507  * moved to a new output.
4508  * Signal is emitted to notify all users of the weston_output
4509  * object that the output is being destroyed.
4510  * wl_output protocol objects referencing this weston_output
4511  * are made inert.
4512  */
4513 static void
4514 weston_compositor_remove_output(struct weston_output *output)
4515 {
4516         struct wl_resource *resource;
4517         struct weston_view *view;
4518
4519         assert(output->destroying);
4520
4521         wl_list_for_each(view, &output->compositor->view_list, link) {
4522                 if (view->output_mask & (1u << output->id))
4523                         weston_view_assign_output(view);
4524         }
4525
4526         weston_presentation_feedback_discard_list(&output->feedback_list);
4527
4528         weston_compositor_reflow_outputs(output->compositor, output, output->width);
4529         wl_list_remove(&output->link);
4530
4531         wl_signal_emit(&output->compositor->output_destroyed_signal, output);
4532         wl_signal_emit(&output->destroy_signal, output);
4533
4534         wl_resource_for_each(resource, &output->resource_list) {
4535                 wl_resource_set_destructor(resource, NULL);
4536         }
4537 }
4538
4539 /** Sets the output scale for a given output.
4540  *
4541  * \param output The weston_output object that the scale is set for.
4542  * \param scale  Scale factor for the given output.
4543  *
4544  * It only supports setting scale for an output that
4545  * is not enabled and it can only be ran once.
4546  */
4547 WL_EXPORT void
4548 weston_output_set_scale(struct weston_output *output,
4549                         int32_t scale)
4550 {
4551         /* We can only set scale on a disabled output */
4552         assert(!output->enabled);
4553
4554         /* We only want to set scale once */
4555         assert(!output->scale);
4556
4557         output->scale = scale;
4558 }
4559
4560 /** Sets the output transform for a given output.
4561  *
4562  * \param output    The weston_output object that the transform is set for.
4563  * \param transform Transform value for the given output.
4564  *
4565  * It only supports setting transform for an output that is
4566  * not enabled and it can only be ran once.
4567  *
4568  * Refer to wl_output::transform section located at
4569  * https://wayland.freedesktop.org/docs/html/apa.html#protocol-spec-wl_output
4570  * for list of values that can be passed to this function.
4571  */
4572 WL_EXPORT void
4573 weston_output_set_transform(struct weston_output *output,
4574                             uint32_t transform)
4575 {
4576         /* We can only set transform on a disabled output */
4577         assert(!output->enabled);
4578
4579         /* We only want to set transform once */
4580         assert(output->transform == UINT32_MAX);
4581
4582         output->transform = transform;
4583 }
4584
4585 /** Initializes a weston_output object with enough data so
4586  ** an output can be configured.
4587  *
4588  * \param output     The weston_output object to initialize
4589  * \param compositor The compositor instance.
4590  *
4591  * Sets initial values for fields that are expected to be
4592  * configured either by compositors or backends.
4593  */
4594 WL_EXPORT void
4595 weston_output_init(struct weston_output *output,
4596                    struct weston_compositor *compositor)
4597 {
4598         output->compositor = compositor;
4599         output->destroying = 0;
4600
4601         /* Backends must set output->name */
4602         assert(output->name);
4603
4604         wl_list_init(&output->link);
4605
4606         output->enabled = false;
4607
4608         /* Add some (in)sane defaults which can be used
4609          * for checking if an output was properly configured
4610          */
4611         output->mm_width = 0;
4612         output->mm_height = 0;
4613         output->scale = 0;
4614         /* Can't use -1 on uint32_t and 0 is valid enum value */
4615         output->transform = UINT32_MAX;
4616 }
4617
4618 /** Adds weston_output object to pending output list.
4619  *
4620  * \param output     The weston_output object to add
4621  * \param compositor The compositor instance.
4622  *
4623  * Also notifies the compositor that an output is pending for
4624  * configuration.
4625  */
4626 WL_EXPORT void
4627 weston_compositor_add_pending_output(struct weston_output *output,
4628                                      struct weston_compositor *compositor)
4629 {
4630         wl_list_insert(compositor->pending_output_list.prev, &output->link);
4631         wl_signal_emit(&compositor->output_pending_signal, output);
4632 }
4633
4634 /** Constructs a weston_output object that can be used by the compositor.
4635  *
4636  * \param output The weston_output object that needs to be enabled.
4637  *
4638  * Output coordinates are calculated and each new output is by default
4639  * assigned to the right of previous one.
4640  *
4641  * Sets up the transformation, zoom, and geometry of the output using
4642  * the properties that need to be configured by the compositor.
4643  *
4644  * Establishes a repaint timer for the output with the relevant display
4645  * object's event loop. See output_repaint_timer_handler().
4646  *
4647  * The output is assigned an ID. Weston can support up to 32 distinct
4648  * outputs, with IDs numbered from 0-31; the compositor's output_id_pool
4649  * is referred to and used to find the first available ID number, and
4650  * then this ID is marked as used in output_id_pool.
4651  *
4652  * The output is also assigned a Wayland global with the wl_output
4653  * external interface.
4654  *
4655  * Backend specific function is called to set up the output output.
4656  *
4657  * Output is added to the compositor's output list
4658  *
4659  * If the backend specific function fails, the weston_output object
4660  * is returned to a state it was before calling this function and
4661  * is added to the compositor's pending_output_list in case it needs
4662  * to be reconfigured or just so it can be destroyed at shutdown.
4663  *
4664  * 0 is returned on success, -1 on failure.
4665  */
4666 WL_EXPORT int
4667 weston_output_enable(struct weston_output *output)
4668 {
4669         struct weston_compositor *c = output->compositor;
4670         struct weston_output *iterator;
4671         int x = 0, y = 0;
4672
4673         assert(output->enable);
4674
4675         iterator = container_of(c->output_list.prev,
4676                                 struct weston_output, link);
4677
4678         if (!wl_list_empty(&c->output_list))
4679                 x = iterator->x + iterator->width;
4680
4681         /* Make sure the scale is set up */
4682         assert(output->scale);
4683
4684         /* Make sure we have a transform set */
4685         assert(output->transform != UINT32_MAX);
4686
4687         /* Remove it from pending/disabled output list */
4688         wl_list_remove(&output->link);
4689
4690         /* Verify we haven't reached the limit of 32 available output IDs */
4691         assert(ffs(~c->output_id_pool) > 0);
4692
4693         output->x = x;
4694         output->y = y;
4695         output->dirty = 1;
4696         output->original_scale = output->scale;
4697
4698         weston_output_transform_scale_init(output, output->transform, output->scale);
4699         weston_output_init_zoom(output);
4700
4701         weston_output_init_geometry(output, x, y);
4702         weston_output_damage(output);
4703
4704         wl_signal_init(&output->frame_signal);
4705         wl_signal_init(&output->destroy_signal);
4706         wl_list_init(&output->animation_list);
4707         wl_list_init(&output->resource_list);
4708         wl_list_init(&output->feedback_list);
4709         wl_list_init(&output->link);
4710
4711         /* Invert the output id pool and look for the lowest numbered
4712          * switch (the least significant bit).  Take that bit's position
4713          * as our ID, and mark it used in the compositor's output_id_pool.
4714          */
4715         output->id = ffs(~output->compositor->output_id_pool) - 1;
4716         output->compositor->output_id_pool |= 1u << output->id;
4717
4718         output->global =
4719                 wl_global_create(c->wl_display, &wl_output_interface, 3,
4720                                  output, bind_output);
4721
4722         output->enabled = true;
4723
4724         /* Enable the output (set up the crtc or create a
4725          * window representing the output, set up the
4726          * renderer, etc)
4727          */
4728         if (output->enable(output) < 0) {
4729                 weston_log("Enabling output \"%s\" failed.\n", output->name);
4730
4731                 weston_output_enable_undo(output);
4732                 wl_list_insert(output->compositor->pending_output_list.prev,
4733                                &output->link);
4734                 return -1;
4735         }
4736
4737         weston_compositor_add_output(output->compositor, output);
4738
4739         return 0;
4740 }
4741
4742 /** Converts a weston_output object to a pending output state, so it
4743  ** can be configured again or destroyed.
4744  *
4745  * \param output The weston_output object that needs to be disabled.
4746  *
4747  * See weston_output_init() for more information on the
4748  * state output is returned to.
4749  *
4750  * Calls a backend specific function to disable an output, in case
4751  * such function exists.
4752  *
4753  * If the output is being used by the compositor, it is first removed
4754  * from weston's output_list (see weston_compositor_remove_output())
4755  * and is returned to a state it was before weston_output_enable()
4756  * was ran (see weston_output_enable_undo()).
4757  *
4758  * Output is added to pending_output_list so it will get destroyed
4759  * if the output does not get configured again when the compositor
4760  * shuts down. If an output is to be used immediately, it needs to
4761  * be manually removed from the list (the compositor specific functions
4762  * for handling pending outputs will take care of that).
4763  *
4764  * If backend specific disable function returns negative value,
4765  * this function will return too. It can be used as an indicator
4766  * that output cannot be disabled at the present time. In that case
4767  * backend needs to make sure the output is disabled when it is
4768  * possible.
4769  */
4770 WL_EXPORT void
4771 weston_output_disable(struct weston_output *output)
4772 {
4773         assert(output->disable);
4774
4775         /* Should we rename this? */
4776         output->destroying = 1;
4777
4778         if (output->disable(output) < 0)
4779                 return;
4780
4781         if (output->enabled) {
4782                 weston_compositor_remove_output(output);
4783                 weston_output_enable_undo(output);
4784
4785                 /* We need to preserve it somewhere so it can be destroyed on shutdown
4786                    if nobody wants to configure it again */
4787                 wl_list_insert(output->compositor->pending_output_list.prev, &output->link);
4788         }
4789
4790         output->destroying = 0;
4791 }
4792
4793 /** Emits a signal to indicate that there are outputs waiting to be configured.
4794  *
4795  * \param compositor The compositor instance
4796  */
4797 WL_EXPORT void
4798 weston_pending_output_coldplug(struct weston_compositor *compositor)
4799 {
4800         struct weston_output *output, *next;
4801
4802         wl_list_for_each_safe(output, next, &compositor->pending_output_list, link)
4803                 wl_signal_emit(&compositor->output_pending_signal, output);
4804 }
4805
4806 WL_EXPORT void
4807 weston_output_destroy(struct weston_output *output)
4808 {
4809         output->destroying = 1;
4810
4811         if (output->enabled) {
4812                 weston_compositor_remove_output(output);
4813                 weston_output_enable_undo(output);
4814         }
4815
4816         free(output->name);
4817 }
4818
4819 static void
4820 destroy_viewport(struct wl_resource *resource)
4821 {
4822         struct weston_surface *surface =
4823                 wl_resource_get_user_data(resource);
4824
4825         if (!surface)
4826                 return;
4827
4828         surface->viewport_resource = NULL;
4829         surface->pending.buffer_viewport.buffer.src_width =
4830                 wl_fixed_from_int(-1);
4831         surface->pending.buffer_viewport.surface.width = -1;
4832         surface->pending.buffer_viewport.changed = 1;
4833 }
4834
4835 static void
4836 viewport_destroy(struct wl_client *client,
4837                  struct wl_resource *resource)
4838 {
4839         wl_resource_destroy(resource);
4840 }
4841
4842 static void
4843 viewport_set_source(struct wl_client *client,
4844                     struct wl_resource *resource,
4845                     wl_fixed_t src_x,
4846                     wl_fixed_t src_y,
4847                     wl_fixed_t src_width,
4848                     wl_fixed_t src_height)
4849 {
4850         struct weston_surface *surface =
4851                 wl_resource_get_user_data(resource);
4852
4853         if (!surface) {
4854                 wl_resource_post_error(resource,
4855                         WP_VIEWPORT_ERROR_NO_SURFACE,
4856                         "wl_surface for this viewport is no longer exists");
4857                 return;
4858         }
4859
4860         assert(surface->viewport_resource == resource);
4861         assert(surface->resource);
4862
4863         if (src_width == wl_fixed_from_int(-1) &&
4864             src_height == wl_fixed_from_int(-1) &&
4865             src_x == wl_fixed_from_int(-1) &&
4866             src_y == wl_fixed_from_int(-1)) {
4867                 /* unset source rect */
4868                 surface->pending.buffer_viewport.buffer.src_width =
4869                         wl_fixed_from_int(-1);
4870                 surface->pending.buffer_viewport.changed = 1;
4871                 return;
4872         }
4873
4874         if (src_width <= 0 || src_height <= 0 || src_x < 0 || src_y < 0) {
4875                 wl_resource_post_error(resource,
4876                         WP_VIEWPORT_ERROR_BAD_VALUE,
4877                         "wl_surface@%d viewport source "
4878                         "w=%f <= 0, h=%f <= 0, x=%f < 0, or y=%f < 0",
4879                         wl_resource_get_id(surface->resource),
4880                         wl_fixed_to_double(src_width),
4881                         wl_fixed_to_double(src_height),
4882                         wl_fixed_to_double(src_x),
4883                         wl_fixed_to_double(src_y));
4884                 return;
4885         }
4886
4887         surface->pending.buffer_viewport.buffer.src_x = src_x;
4888         surface->pending.buffer_viewport.buffer.src_y = src_y;
4889         surface->pending.buffer_viewport.buffer.src_width = src_width;
4890         surface->pending.buffer_viewport.buffer.src_height = src_height;
4891         surface->pending.buffer_viewport.changed = 1;
4892 }
4893
4894 static void
4895 viewport_set_destination(struct wl_client *client,
4896                          struct wl_resource *resource,
4897                          int32_t dst_width,
4898                          int32_t dst_height)
4899 {
4900         struct weston_surface *surface =
4901                 wl_resource_get_user_data(resource);
4902
4903         if (!surface) {
4904                 wl_resource_post_error(resource,
4905                         WP_VIEWPORT_ERROR_NO_SURFACE,
4906                         "wl_surface for this viewport no longer exists");
4907                 return;
4908         }
4909
4910         assert(surface->viewport_resource == resource);
4911
4912         if (dst_width == -1 && dst_height == -1) {
4913                 /* unset destination size */
4914                 surface->pending.buffer_viewport.surface.width = -1;
4915                 surface->pending.buffer_viewport.changed = 1;
4916                 return;
4917         }
4918
4919         if (dst_width <= 0 || dst_height <= 0) {
4920                 wl_resource_post_error(resource,
4921                         WP_VIEWPORT_ERROR_BAD_VALUE,
4922                         "destination size must be positive (%dx%d)",
4923                         dst_width, dst_height);
4924                 return;
4925         }
4926
4927         surface->pending.buffer_viewport.surface.width = dst_width;
4928         surface->pending.buffer_viewport.surface.height = dst_height;
4929         surface->pending.buffer_viewport.changed = 1;
4930 }
4931
4932 static const struct wp_viewport_interface viewport_interface = {
4933         viewport_destroy,
4934         viewport_set_source,
4935         viewport_set_destination
4936 };
4937
4938 static void
4939 viewporter_destroy(struct wl_client *client,
4940                    struct wl_resource *resource)
4941 {
4942         wl_resource_destroy(resource);
4943 }
4944
4945 static void
4946 viewporter_get_viewport(struct wl_client *client,
4947                         struct wl_resource *viewporter,
4948                         uint32_t id,
4949                         struct wl_resource *surface_resource)
4950 {
4951         int version = wl_resource_get_version(viewporter);
4952         struct weston_surface *surface =
4953                 wl_resource_get_user_data(surface_resource);
4954         struct wl_resource *resource;
4955
4956         if (surface->viewport_resource) {
4957                 wl_resource_post_error(viewporter,
4958                         WP_VIEWPORTER_ERROR_VIEWPORT_EXISTS,
4959                         "a viewport for that surface already exists");
4960                 return;
4961         }
4962
4963         resource = wl_resource_create(client, &wp_viewport_interface,
4964                                       version, id);
4965         if (resource == NULL) {
4966                 wl_client_post_no_memory(client);
4967                 return;
4968         }
4969
4970         wl_resource_set_implementation(resource, &viewport_interface,
4971                                        surface, destroy_viewport);
4972
4973         surface->viewport_resource = resource;
4974 }
4975
4976 static const struct wp_viewporter_interface viewporter_interface = {
4977         viewporter_destroy,
4978         viewporter_get_viewport
4979 };
4980
4981 static void
4982 bind_viewporter(struct wl_client *client,
4983                 void *data, uint32_t version, uint32_t id)
4984 {
4985         struct wl_resource *resource;
4986
4987         resource = wl_resource_create(client, &wp_viewporter_interface,
4988                                       version, id);
4989         if (resource == NULL) {
4990                 wl_client_post_no_memory(client);
4991                 return;
4992         }
4993
4994         wl_resource_set_implementation(resource, &viewporter_interface,
4995                                        NULL, NULL);
4996 }
4997
4998 static void
4999 destroy_presentation_feedback(struct wl_resource *feedback_resource)
5000 {
5001         struct weston_presentation_feedback *feedback;
5002
5003         feedback = wl_resource_get_user_data(feedback_resource);
5004
5005         wl_list_remove(&feedback->link);
5006         free(feedback);
5007 }
5008
5009 static void
5010 presentation_destroy(struct wl_client *client, struct wl_resource *resource)
5011 {
5012         wl_resource_destroy(resource);
5013 }
5014
5015 static void
5016 presentation_feedback(struct wl_client *client,
5017                       struct wl_resource *presentation_resource,
5018                       struct wl_resource *surface_resource,
5019                       uint32_t callback)
5020 {
5021         struct weston_surface *surface;
5022         struct weston_presentation_feedback *feedback;
5023
5024         surface = wl_resource_get_user_data(surface_resource);
5025
5026         feedback = zalloc(sizeof *feedback);
5027         if (feedback == NULL)
5028                 goto err_calloc;
5029
5030         feedback->resource = wl_resource_create(client,
5031                                         &wp_presentation_feedback_interface,
5032                                         1, callback);
5033         if (!feedback->resource)
5034                 goto err_create;
5035
5036         wl_resource_set_implementation(feedback->resource, NULL, feedback,
5037                                        destroy_presentation_feedback);
5038
5039         wl_list_insert(&surface->pending.feedback_list, &feedback->link);
5040
5041         return;
5042
5043 err_create:
5044         free(feedback);
5045
5046 err_calloc:
5047         wl_client_post_no_memory(client);
5048 }
5049
5050 static const struct wp_presentation_interface presentation_implementation = {
5051         presentation_destroy,
5052         presentation_feedback
5053 };
5054
5055 static void
5056 bind_presentation(struct wl_client *client,
5057                   void *data, uint32_t version, uint32_t id)
5058 {
5059         struct weston_compositor *compositor = data;
5060         struct wl_resource *resource;
5061
5062         resource = wl_resource_create(client, &wp_presentation_interface,
5063                                       version, id);
5064         if (resource == NULL) {
5065                 wl_client_post_no_memory(client);
5066                 return;
5067         }
5068
5069         wl_resource_set_implementation(resource, &presentation_implementation,
5070                                        compositor, NULL);
5071         wp_presentation_send_clock_id(resource, compositor->presentation_clock);
5072 }
5073
5074 static void
5075 compositor_bind(struct wl_client *client,
5076                 void *data, uint32_t version, uint32_t id)
5077 {
5078         struct weston_compositor *compositor = data;
5079         struct wl_resource *resource;
5080
5081         resource = wl_resource_create(client, &wl_compositor_interface,
5082                                       version, id);
5083         if (resource == NULL) {
5084                 wl_client_post_no_memory(client);
5085                 return;
5086         }
5087
5088         wl_resource_set_implementation(resource, &compositor_interface,
5089                                        compositor, NULL);
5090 }
5091
5092 WL_EXPORT int
5093 weston_environment_get_fd(const char *env)
5094 {
5095         char *e;
5096         int fd, flags;
5097
5098         e = getenv(env);
5099         if (!e || !safe_strtoint(e, &fd))
5100                 return -1;
5101
5102         flags = fcntl(fd, F_GETFD);
5103         if (flags == -1)
5104                 return -1;
5105
5106         fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
5107         unsetenv(env);
5108
5109         return fd;
5110 }
5111
5112 static void
5113 timeline_key_binding_handler(struct weston_keyboard *keyboard, uint32_t time,
5114                              uint32_t key, void *data)
5115 {
5116         struct weston_compositor *compositor = data;
5117
5118         if (weston_timeline_enabled_)
5119                 weston_timeline_close();
5120         else
5121                 weston_timeline_open(compositor);
5122 }
5123
5124 /** Create the compositor.
5125  *
5126  * This functions creates and initializes a compositor instance.
5127  *
5128  * \param display The Wayland display to be used.
5129  * \param user_data A pointer to an object that can later be retrieved
5130  * using the \ref weston_compositor_get_user_data function.
5131  * \return The compositor instance on success or NULL on failure.
5132  */
5133 WL_EXPORT struct weston_compositor *
5134 weston_compositor_create(struct wl_display *display, void *user_data)
5135 {
5136         struct weston_compositor *ec;
5137         struct wl_event_loop *loop;
5138
5139         ec = zalloc(sizeof *ec);
5140         if (!ec)
5141                 return NULL;
5142
5143         ec->wl_display = display;
5144         ec->user_data = user_data;
5145         wl_signal_init(&ec->destroy_signal);
5146         wl_signal_init(&ec->create_surface_signal);
5147         wl_signal_init(&ec->activate_signal);
5148         wl_signal_init(&ec->transform_signal);
5149         wl_signal_init(&ec->kill_signal);
5150         wl_signal_init(&ec->idle_signal);
5151         wl_signal_init(&ec->wake_signal);
5152         wl_signal_init(&ec->show_input_panel_signal);
5153         wl_signal_init(&ec->hide_input_panel_signal);
5154         wl_signal_init(&ec->update_input_panel_signal);
5155         wl_signal_init(&ec->seat_created_signal);
5156         wl_signal_init(&ec->output_pending_signal);
5157         wl_signal_init(&ec->output_created_signal);
5158         wl_signal_init(&ec->output_destroyed_signal);
5159         wl_signal_init(&ec->output_moved_signal);
5160         wl_signal_init(&ec->output_resized_signal);
5161         wl_signal_init(&ec->session_signal);
5162         ec->session_active = 1;
5163
5164         ec->output_id_pool = 0;
5165         ec->repaint_msec = DEFAULT_REPAINT_WINDOW;
5166
5167         ec->activate_serial = 1;
5168
5169         if (!wl_global_create(ec->wl_display, &wl_compositor_interface, 4,
5170                               ec, compositor_bind))
5171                 goto fail;
5172
5173         if (!wl_global_create(ec->wl_display, &wl_subcompositor_interface, 1,
5174                               ec, bind_subcompositor))
5175                 goto fail;
5176
5177         if (!wl_global_create(ec->wl_display, &wp_viewporter_interface, 1,
5178                               ec, bind_viewporter))
5179                 goto fail;
5180
5181         if (!wl_global_create(ec->wl_display, &wp_presentation_interface, 1,
5182                               ec, bind_presentation))
5183                 goto fail;
5184
5185         if (weston_input_init(ec) != 0)
5186                 goto fail;
5187
5188         wl_list_init(&ec->view_list);
5189         wl_list_init(&ec->plane_list);
5190         wl_list_init(&ec->layer_list);
5191         wl_list_init(&ec->seat_list);
5192         wl_list_init(&ec->pending_output_list);
5193         wl_list_init(&ec->output_list);
5194         wl_list_init(&ec->key_binding_list);
5195         wl_list_init(&ec->modifier_binding_list);
5196         wl_list_init(&ec->button_binding_list);
5197         wl_list_init(&ec->touch_binding_list);
5198         wl_list_init(&ec->axis_binding_list);
5199         wl_list_init(&ec->debug_binding_list);
5200
5201         wl_list_init(&ec->plugin_api_list);
5202
5203         weston_plane_init(&ec->primary_plane, ec, 0, 0);
5204         weston_compositor_stack_plane(ec, &ec->primary_plane, NULL);
5205
5206         wl_data_device_manager_init(ec->wl_display);
5207
5208         wl_display_init_shm(ec->wl_display);
5209
5210         loop = wl_display_get_event_loop(ec->wl_display);
5211         ec->idle_source = wl_event_loop_add_timer(loop, idle_handler, ec);
5212         ec->repaint_timer =
5213                 wl_event_loop_add_timer(loop, output_repaint_timer_handler,
5214                                         ec);
5215
5216         weston_layer_init(&ec->fade_layer, ec);
5217         weston_layer_init(&ec->cursor_layer, ec);
5218
5219         weston_layer_set_position(&ec->fade_layer, WESTON_LAYER_POSITION_FADE);
5220         weston_layer_set_position(&ec->cursor_layer,
5221                                   WESTON_LAYER_POSITION_CURSOR);
5222
5223         weston_compositor_add_debug_binding(ec, KEY_T,
5224                                             timeline_key_binding_handler, ec);
5225
5226         return ec;
5227
5228 fail:
5229         free(ec);
5230         return NULL;
5231 }
5232
5233 WL_EXPORT void
5234 weston_compositor_shutdown(struct weston_compositor *ec)
5235 {
5236         struct weston_output *output, *next;
5237
5238         wl_event_source_remove(ec->idle_source);
5239
5240         /* Destroy all outputs associated with this compositor */
5241         wl_list_for_each_safe(output, next, &ec->output_list, link)
5242                 output->destroy(output);
5243
5244         /* Destroy all pending outputs associated with this compositor */
5245         wl_list_for_each_safe(output, next, &ec->pending_output_list, link)
5246                 output->destroy(output);
5247
5248         if (ec->renderer)
5249                 ec->renderer->destroy(ec);
5250
5251         weston_binding_list_destroy_all(&ec->key_binding_list);
5252         weston_binding_list_destroy_all(&ec->modifier_binding_list);
5253         weston_binding_list_destroy_all(&ec->button_binding_list);
5254         weston_binding_list_destroy_all(&ec->touch_binding_list);
5255         weston_binding_list_destroy_all(&ec->axis_binding_list);
5256         weston_binding_list_destroy_all(&ec->debug_binding_list);
5257
5258         weston_plane_release(&ec->primary_plane);
5259 }
5260
5261 WL_EXPORT void
5262 weston_compositor_exit_with_code(struct weston_compositor *compositor,
5263                                  int exit_code)
5264 {
5265         if (compositor->exit_code == EXIT_SUCCESS)
5266                 compositor->exit_code = exit_code;
5267
5268         weston_compositor_exit(compositor);
5269 }
5270
5271 WL_EXPORT void
5272 weston_compositor_set_default_pointer_grab(struct weston_compositor *ec,
5273                         const struct weston_pointer_grab_interface *interface)
5274 {
5275         struct weston_seat *seat;
5276
5277         ec->default_pointer_grab = interface;
5278         wl_list_for_each(seat, &ec->seat_list, link) {
5279                 struct weston_pointer *pointer = weston_seat_get_pointer(seat);
5280
5281                 if (pointer)
5282                         weston_pointer_set_default_grab(pointer, interface);
5283         }
5284 }
5285
5286 WL_EXPORT int
5287 weston_compositor_set_presentation_clock(struct weston_compositor *compositor,
5288                                          clockid_t clk_id)
5289 {
5290         struct timespec ts;
5291
5292         if (clock_gettime(clk_id, &ts) < 0)
5293                 return -1;
5294
5295         compositor->presentation_clock = clk_id;
5296
5297         return 0;
5298 }
5299
5300 /*
5301  * For choosing the software clock, when the display hardware or API
5302  * does not expose a compatible presentation timestamp.
5303  */
5304 WL_EXPORT int
5305 weston_compositor_set_presentation_clock_software(
5306                                         struct weston_compositor *compositor)
5307 {
5308         /* In order of preference */
5309         static const clockid_t clocks[] = {
5310                 CLOCK_MONOTONIC_RAW,    /* no jumps, no crawling */
5311                 CLOCK_MONOTONIC_COARSE, /* no jumps, may crawl, fast & coarse */
5312                 CLOCK_MONOTONIC,        /* no jumps, may crawl */
5313                 CLOCK_REALTIME_COARSE,  /* may jump and crawl, fast & coarse */
5314                 CLOCK_REALTIME          /* may jump and crawl */
5315         };
5316         unsigned i;
5317
5318         for (i = 0; i < ARRAY_LENGTH(clocks); i++)
5319                 if (weston_compositor_set_presentation_clock(compositor,
5320                                                              clocks[i]) == 0)
5321                         return 0;
5322
5323         weston_log("Error: no suitable presentation clock available.\n");
5324
5325         return -1;
5326 }
5327
5328 /** Read the current time from the Presentation clock
5329  *
5330  * \param compositor
5331  * \param ts[out] The current time.
5332  *
5333  * \note Reading the current time in user space is always imprecise to some
5334  * degree.
5335  *
5336  * This function is never meant to fail. If reading the clock does fail,
5337  * an error message is logged and a zero time is returned. Callers are not
5338  * supposed to detect or react to failures.
5339  */
5340 WL_EXPORT void
5341 weston_compositor_read_presentation_clock(
5342                         const struct weston_compositor *compositor,
5343                         struct timespec *ts)
5344 {
5345         static bool warned;
5346         int ret;
5347
5348         ret = clock_gettime(compositor->presentation_clock, ts);
5349         if (ret < 0) {
5350                 ts->tv_sec = 0;
5351                 ts->tv_nsec = 0;
5352
5353                 if (!warned)
5354                         weston_log("Error: failure to read "
5355                                    "the presentation clock %#x: '%m' (%d)\n",
5356                                    compositor->presentation_clock, errno);
5357                 warned = true;
5358         }
5359 }
5360
5361 /** Import dmabuf buffer into current renderer
5362  *
5363  * \param compositor
5364  * \param buffer the dmabuf buffer to import
5365  * \return true on usable buffers, false otherwise
5366  *
5367  * This function tests that the linux_dmabuf_buffer is usable
5368  * for the current renderer. Returns false on unusable buffers. Usually
5369  * usability is tested by importing the dmabufs for composition.
5370  *
5371  * This hook is also used for detecting if the renderer supports
5372  * dmabufs at all. If the renderer hook is NULL, dmabufs are not
5373  * supported.
5374  * */
5375 WL_EXPORT bool
5376 weston_compositor_import_dmabuf(struct weston_compositor *compositor,
5377                                 struct linux_dmabuf_buffer *buffer)
5378 {
5379         struct weston_renderer *renderer;
5380
5381         renderer = compositor->renderer;
5382
5383         if (renderer->import_dmabuf == NULL)
5384                 return false;
5385
5386         return renderer->import_dmabuf(compositor, buffer);
5387 }
5388
5389 WL_EXPORT void
5390 weston_version(int *major, int *minor, int *micro)
5391 {
5392         *major = WESTON_VERSION_MAJOR;
5393         *minor = WESTON_VERSION_MINOR;
5394         *micro = WESTON_VERSION_MICRO;
5395 }
5396
5397 WL_EXPORT void *
5398 weston_load_module(const char *name, const char *entrypoint)
5399 {
5400         const char *builddir = getenv("WESTON_BUILD_DIR");
5401         char path[PATH_MAX];
5402         void *module, *init;
5403         size_t len;
5404
5405         if (name == NULL)
5406                 return NULL;
5407
5408         if (name[0] != '/') {
5409                 if (builddir)
5410                         len = snprintf(path, sizeof path, "%s/.libs/%s",
5411                                        builddir, name);
5412                 else
5413                         len = snprintf(path, sizeof path, "%s/%s",
5414                                        LIBWESTON_MODULEDIR, name);
5415         } else {
5416                 len = snprintf(path, sizeof path, "%s", name);
5417         }
5418
5419         /* snprintf returns the length of the string it would've written,
5420          * _excluding_ the NUL byte. So even being equal to the size of
5421          * our buffer is an error here. */
5422         if (len >= sizeof path)
5423                 return NULL;
5424
5425         module = dlopen(path, RTLD_NOW | RTLD_NOLOAD);
5426         if (module) {
5427                 weston_log("Module '%s' already loaded\n", path);
5428                 dlclose(module);
5429                 return NULL;
5430         }
5431
5432         weston_log("Loading module '%s'\n", path);
5433         module = dlopen(path, RTLD_NOW);
5434         if (!module) {
5435                 weston_log("Failed to load module: %s\n", dlerror());
5436                 return NULL;
5437         }
5438
5439         init = dlsym(module, entrypoint);
5440         if (!init) {
5441                 weston_log("Failed to lookup init function: %s\n", dlerror());
5442                 dlclose(module);
5443                 return NULL;
5444         }
5445
5446         return init;
5447 }
5448
5449
5450 /** Destroys the compositor.
5451  *
5452  * This function cleans up the compositor state and destroys it.
5453  *
5454  * \param compositor The compositor to be destroyed.
5455  */
5456 WL_EXPORT void
5457 weston_compositor_destroy(struct weston_compositor *compositor)
5458 {
5459         /* prevent further rendering while shutting down */
5460         compositor->state = WESTON_COMPOSITOR_OFFSCREEN;
5461
5462         wl_signal_emit(&compositor->destroy_signal, compositor);
5463
5464         weston_compositor_xkb_destroy(compositor);
5465
5466         if (compositor->backend)
5467                 compositor->backend->destroy(compositor);
5468
5469         weston_plugin_api_destroy_list(compositor);
5470
5471         free(compositor);
5472 }
5473
5474 /** Instruct the compositor to exit.
5475  *
5476  * This functions does not directly destroy the compositor object, it merely
5477  * command it to start the tear down process. It is not guaranteed that the
5478  * tear down will happen immediately.
5479  *
5480  * \param compositor The compositor to tear down.
5481  */
5482 WL_EXPORT void
5483 weston_compositor_exit(struct weston_compositor *compositor)
5484 {
5485         compositor->exit(compositor);
5486 }
5487
5488 /** Return the user data stored in the compositor.
5489  *
5490  * This function returns the user data pointer set with user_data parameter
5491  * to the \ref weston_compositor_create function.
5492  */
5493 WL_EXPORT void *
5494 weston_compositor_get_user_data(struct weston_compositor *compositor)
5495 {
5496         return compositor->user_data;
5497 }
5498
5499 static const char * const backend_map[] = {
5500         [WESTON_BACKEND_DRM] =          "drm-backend.so",
5501         [WESTON_BACKEND_FBDEV] =        "fbdev-backend.so",
5502         [WESTON_BACKEND_HEADLESS] =     "headless-backend.so",
5503         [WESTON_BACKEND_RDP] =          "rdp-backend.so",
5504         [WESTON_BACKEND_WAYLAND] =      "wayland-backend.so",
5505         [WESTON_BACKEND_X11] =          "x11-backend.so",
5506 };
5507
5508 /** Load a backend into a weston_compositor
5509  *
5510  * A backend must be loaded to make a weston_compositor work. A backend
5511  * provides input and output capabilities, and determines the renderer to use.
5512  *
5513  * \param compositor A compositor that has not had a backend loaded yet.
5514  * \param backend Name of the backend file.
5515  * \param config_base A pointer to a backend-specific configuration
5516  * structure's 'base' member.
5517  *
5518  * \return 0 on success, or -1 on error.
5519  */
5520 WL_EXPORT int
5521 weston_compositor_load_backend(struct weston_compositor *compositor,
5522                                enum weston_compositor_backend backend,
5523                                struct weston_backend_config *config_base)
5524 {
5525         int (*backend_init)(struct weston_compositor *c,
5526                             struct weston_backend_config *config_base);
5527
5528         if (backend >= ARRAY_LENGTH(backend_map))
5529                 return -1;
5530
5531         backend_init = weston_load_module(backend_map[backend], "weston_backend_init");
5532         if (!backend_init)
5533                 return -1;
5534
5535         return backend_init(compositor, config_base);
5536 }
5537
5538 WL_EXPORT int
5539 weston_compositor_load_xwayland(struct weston_compositor *compositor)
5540 {
5541         int (*module_init)(struct weston_compositor *ec);
5542
5543         module_init = weston_load_module("xwayland.so", "weston_module_init");
5544         if (!module_init)
5545                 return -1;
5546         if (module_init(compositor) < 0)
5547                 return -1;
5548         return 0;
5549 }