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