compositor: Fix a couple of region leaks
[profile/ivi/weston.git] / compositor / compositor.c
1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 #define _GNU_SOURCE
20
21 #include "config.h"
22
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <stdint.h>
27 #include <limits.h>
28 #include <stdarg.h>
29 #include <assert.h>
30 #include <sys/ioctl.h>
31 #include <sys/wait.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <math.h>
35 #include <linux/input.h>
36 #include <dlfcn.h>
37 #include <getopt.h>
38 #include <signal.h>
39
40 #include "wayland-server.h"
41 #include "compositor.h"
42
43 /* The plan here is to generate a random anonymous socket name and
44  * advertise that through a service on the session dbus.
45  */
46 static const char *option_socket_name = NULL;
47 static const char *option_background = "background.png";
48 static int option_idle_time = 300;
49
50 static struct wl_list child_process_list;
51
52 static int
53 sigchld_handler(int signal_number, void *data)
54 {
55         struct wlsc_process *p;
56         int status;
57         pid_t pid;
58
59         pid = wait(&status);
60         wl_list_for_each(p, &child_process_list, link) {
61                 if (p->pid == pid)
62                         break;
63         }
64
65         if (&p->link == &child_process_list) {
66                 fprintf(stderr, "unknown child process exited\n");
67                 return 1;
68         }
69
70         wl_list_remove(&p->link);
71         p->cleanup(p, status);
72
73         return 1;
74 }
75
76 WL_EXPORT void
77 wlsc_watch_process(struct wlsc_process *process)
78 {
79         wl_list_insert(&child_process_list, &process->link);
80 }
81
82 WL_EXPORT void
83 wlsc_matrix_init(struct wlsc_matrix *matrix)
84 {
85         static const struct wlsc_matrix identity = {
86                 { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  0, 0, 0, 1 }
87         };
88
89         memcpy(matrix, &identity, sizeof identity);
90 }
91
92 static void
93 wlsc_matrix_multiply(struct wlsc_matrix *m, const struct wlsc_matrix *n)
94 {
95         struct wlsc_matrix tmp;
96         const GLfloat *row, *column;
97         div_t d;
98         int i, j;
99
100         for (i = 0; i < 16; i++) {
101                 tmp.d[i] = 0;
102                 d = div(i, 4);
103                 row = m->d + d.quot * 4;
104                 column = n->d + d.rem;
105                 for (j = 0; j < 4; j++)
106                         tmp.d[i] += row[j] * column[j * 4];
107         }
108         memcpy(m, &tmp, sizeof tmp);
109 }
110
111 WL_EXPORT void
112 wlsc_matrix_translate(struct wlsc_matrix *matrix, GLfloat x, GLfloat y, GLfloat z)
113 {
114         struct wlsc_matrix translate = {
115                 { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 }
116         };
117
118         wlsc_matrix_multiply(matrix, &translate);
119 }
120
121 WL_EXPORT void
122 wlsc_matrix_scale(struct wlsc_matrix *matrix, GLfloat x, GLfloat y, GLfloat z)
123 {
124         struct wlsc_matrix scale = {
125                 { x, 0, 0, 0,  0, y, 0, 0,  0, 0, z, 0,  0, 0, 0, 1 }
126         };
127
128         wlsc_matrix_multiply(matrix, &scale);
129 }
130
131 static void
132 wlsc_matrix_transform(struct wlsc_matrix *matrix, struct wlsc_vector *v)
133 {
134         int i, j;
135         struct wlsc_vector t;
136
137         for (i = 0; i < 4; i++) {
138                 t.f[i] = 0;
139                 for (j = 0; j < 4; j++)
140                         t.f[i] += v->f[j] * matrix->d[i + j * 4];
141         }
142
143         *v = t;
144 }
145
146 WL_EXPORT void
147 wlsc_spring_init(struct wlsc_spring *spring,
148                  double k, double current, double target)
149 {
150         spring->k = k;
151         spring->friction = 100.0;
152         spring->current = current;
153         spring->previous = current;
154         spring->target = target;
155 }
156
157 WL_EXPORT void
158 wlsc_spring_update(struct wlsc_spring *spring, uint32_t msec)
159 {
160         double force, v, current, step;
161
162         step = (msec - spring->timestamp) / 300.0;
163         spring->timestamp = msec;
164
165         current = spring->current;
166         v = current - spring->previous;
167         force = spring->k * (spring->target - current) / 10.0 +
168                 (spring->previous - current) - v * spring->friction;
169
170         spring->current =
171                 current + (current - spring->previous) + force * step * step;
172         spring->previous = current;
173
174 #if 0
175         if (spring->current >= 1.0) {
176 #ifdef TWEENER_BOUNCE
177                 spring->current = 2.0 - spring->current;
178                 spring->previous = 2.0 - spring->previous;
179 #else
180                 spring->current = 1.0;
181                 spring->previous = 1.0;
182 #endif
183         }
184
185         if (spring->current <= 0.0) {
186                 spring->current = 0.0;
187                 spring->previous = 0.0;
188         }
189 #endif
190 }
191
192 WL_EXPORT int
193 wlsc_spring_done(struct wlsc_spring *spring)
194 {
195         return fabs(spring->previous - spring->target) < 0.0002 &&
196                 fabs(spring->current - spring->target) < 0.0002;
197 }
198
199 static void
200 surface_handle_buffer_destroy(struct wl_listener *listener,
201                               struct wl_resource *resource, uint32_t time)
202 {
203         struct wlsc_surface *es = container_of(listener, struct wlsc_surface,
204                                                buffer_destroy_listener);
205         struct wl_buffer *buffer = (struct wl_buffer *) resource;
206
207         if (es->buffer == buffer)
208                 es->buffer = NULL;
209 }
210
211 static void
212 output_handle_scanout_buffer_destroy(struct wl_listener *listener,
213                                      struct wl_resource *resource,
214                                      uint32_t time)
215 {
216         struct wlsc_output *output =
217                 container_of(listener, struct wlsc_output,
218                              scanout_buffer_destroy_listener);
219         struct wl_buffer *buffer = (struct wl_buffer *) resource;
220
221         if (output->scanout_buffer == buffer)
222                 output->scanout_buffer = NULL;
223 }
224
225 WL_EXPORT struct wlsc_surface *
226 wlsc_surface_create(struct wlsc_compositor *compositor,
227                     int32_t x, int32_t y, int32_t width, int32_t height)
228 {
229         struct wlsc_surface *surface;
230
231         surface = malloc(sizeof *surface);
232         if (surface == NULL)
233                 return NULL;
234
235         wl_list_init(&surface->link);
236         wl_list_init(&surface->buffer_link);
237         surface->map_type = WLSC_SURFACE_MAP_UNMAPPED;
238
239         glGenTextures(1, &surface->texture);
240         glBindTexture(GL_TEXTURE_2D, surface->texture);
241         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
242         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
243
244         surface->surface.client = NULL;
245
246         surface->compositor = compositor;
247         surface->visual = NULL;
248         surface->image = EGL_NO_IMAGE_KHR;
249         surface->saved_texture = 0;
250         surface->x = x;
251         surface->y = y;
252         surface->width = width;
253         surface->height = height;
254
255         surface->buffer = NULL;
256
257         pixman_region32_init(&surface->damage);
258
259         surface->buffer_destroy_listener.func = surface_handle_buffer_destroy;
260         wl_list_init(&surface->buffer_destroy_listener.link);
261
262         surface->transform = NULL;
263
264         return surface;
265 }
266
267 WL_EXPORT void
268 wlsc_surface_damage_rectangle(struct wlsc_surface *surface,
269                               int32_t x, int32_t y,
270                               int32_t width, int32_t height)
271 {
272         struct wlsc_compositor *compositor = surface->compositor;
273
274         pixman_region32_union_rect(&surface->damage,
275                                    &surface->damage,
276                                    surface->x + x, surface->y + y,
277                                    width, height);
278         wlsc_compositor_schedule_repaint(compositor);
279 }
280
281 WL_EXPORT void
282 wlsc_surface_damage(struct wlsc_surface *surface)
283 {
284         wlsc_surface_damage_rectangle(surface, 0, 0,
285                                       surface->width, surface->height);
286 }
287
288 WL_EXPORT void
289 wlsc_surface_damage_below(struct wlsc_surface *surface)
290 {
291         struct wlsc_surface *below;
292
293         if (surface->link.next == &surface->compositor->surface_list)
294                 return;
295
296         below = container_of(surface->link.next, struct wlsc_surface, link);
297
298         pixman_region32_union_rect(&below->damage,
299                                    &below->damage,
300                                    surface->x, surface->y,
301                                    surface->width, surface->height);
302         wlsc_compositor_schedule_repaint(surface->compositor);
303 }
304
305 WL_EXPORT uint32_t
306 wlsc_compositor_get_time(void)
307 {
308         struct timeval tv;
309
310         gettimeofday(&tv, NULL);
311
312         return tv.tv_sec * 1000 + tv.tv_usec / 1000;
313 }
314
315 static void
316 destroy_surface(struct wl_resource *resource, struct wl_client *client)
317 {
318         struct wlsc_surface *surface =
319                 container_of(resource, struct wlsc_surface, surface.resource);
320         struct wlsc_compositor *compositor = surface->compositor;
321
322         wlsc_surface_damage_below(surface);
323
324         wl_list_remove(&surface->link);
325         if (surface->saved_texture == 0)
326                 glDeleteTextures(1, &surface->texture);
327         else
328                 glDeleteTextures(1, &surface->saved_texture);
329
330         if (surface->buffer)
331                 wl_list_remove(&surface->buffer_destroy_listener.link);
332
333         if (surface->image != EGL_NO_IMAGE_KHR)
334                 compositor->destroy_image(compositor->display,
335                                           surface->image);
336
337         wl_list_remove(&surface->buffer_link);
338
339         free(surface);
340 }
341
342 static void
343 wlsc_buffer_attach(struct wl_buffer *buffer, struct wl_surface *surface)
344 {
345         struct wlsc_surface *es = (struct wlsc_surface *) surface;
346         struct wlsc_compositor *ec = es->compositor;
347         struct wl_list *surfaces_attached_to;
348
349         if (es->saved_texture != 0)
350                 es->texture = es->saved_texture;
351
352         glBindTexture(GL_TEXTURE_2D, es->texture);
353
354         if (wl_buffer_is_shm(buffer)) {
355                 /* Unbind any EGLImage texture that may be bound, so we don't
356                  * overwrite it.*/
357                 glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
358                              0, 0, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, NULL);
359                 es->pitch = wl_shm_buffer_get_stride(buffer) / 4;
360                 glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
361                              es->pitch, buffer->height, 0,
362                              GL_BGRA_EXT, GL_UNSIGNED_BYTE,
363                              wl_shm_buffer_get_data(buffer));
364                 es->visual = buffer->visual;
365
366                 surfaces_attached_to = buffer->user_data;
367
368                 wl_list_remove(&es->buffer_link);
369                 wl_list_insert(surfaces_attached_to, &es->buffer_link);
370         } else {
371                 if (es->image != EGL_NO_IMAGE_KHR)
372                         ec->destroy_image(ec->display, es->image);
373                 es->image = ec->create_image(ec->display, NULL,
374                                              EGL_WAYLAND_BUFFER_WL,
375                                              buffer, NULL);
376                 
377                 ec->image_target_texture_2d(GL_TEXTURE_2D, es->image);
378                 es->visual = buffer->visual;
379                 es->pitch = es->width;
380         }
381 }
382
383 static void
384 wlsc_sprite_attach(struct wlsc_sprite *sprite, struct wl_surface *surface)
385 {
386         struct wlsc_surface *es = (struct wlsc_surface *) surface;
387         struct wlsc_compositor *ec = es->compositor;
388
389         es->pitch = es->width;
390         es->image = sprite->image;
391         if (sprite->image != EGL_NO_IMAGE_KHR) {
392                 glBindTexture(GL_TEXTURE_2D, es->texture);
393                 ec->image_target_texture_2d(GL_TEXTURE_2D, es->image);
394         } else {
395                 if (es->saved_texture == 0)
396                         es->saved_texture = es->texture;
397                 es->texture = sprite->texture;
398         }
399
400         es->visual = sprite->visual;
401
402         if (es->buffer)
403                 es->buffer = NULL;
404 }
405
406 enum sprite_usage {
407         SPRITE_USE_CURSOR = (1 << 0),
408 };
409
410 static struct wlsc_sprite *
411 create_sprite_from_png(struct wlsc_compositor *ec,
412                        const char *filename, uint32_t usage)
413 {
414         uint32_t *pixels;
415         struct wlsc_sprite *sprite;
416         int32_t width, height;
417         uint32_t stride;
418
419         pixels = wlsc_load_image(filename, &width, &height, &stride);
420         if (pixels == NULL)
421                 return NULL;
422
423         sprite = malloc(sizeof *sprite);
424         if (sprite == NULL) {
425                 free(pixels);
426                 return NULL;
427         }
428
429         sprite->visual = &ec->compositor.premultiplied_argb_visual;
430         sprite->width = width;
431         sprite->height = height;
432         sprite->image = EGL_NO_IMAGE_KHR;
433
434         if (usage & SPRITE_USE_CURSOR && ec->create_cursor_image != NULL)
435                 sprite->image = ec->create_cursor_image(ec, width, height);
436
437         glGenTextures(1, &sprite->texture);
438         glBindTexture(GL_TEXTURE_2D, sprite->texture);
439         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
440         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
441         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
442         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
443
444         if (sprite->image != EGL_NO_IMAGE_KHR) {
445                 ec->image_target_texture_2d(GL_TEXTURE_2D, sprite->image);
446                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height,
447                                 GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixels);
448         } else {
449                 glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT, width, height, 0,
450                              GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixels);
451         }
452
453         free(pixels);
454
455         return sprite;
456 }
457
458 static const struct {
459         const char *filename;
460         int hotspot_x, hotspot_y;
461 } pointer_images[] = {
462         { DATADIR "/wayland/bottom_left_corner.png",     6, 30 },
463         { DATADIR "/wayland/bottom_right_corner.png",   28, 28 },
464         { DATADIR "/wayland/bottom_side.png",           16, 20 },
465         { DATADIR "/wayland/grabbing.png",              20, 17 },
466         { DATADIR "/wayland/left_ptr.png",              10,  5 },
467         { DATADIR "/wayland/left_side.png",             10, 20 },
468         { DATADIR "/wayland/right_side.png",            30, 19 },
469         { DATADIR "/wayland/top_left_corner.png",        8,  8 },
470         { DATADIR "/wayland/top_right_corner.png",      26,  8 },
471         { DATADIR "/wayland/top_side.png",              18,  8 },
472         { DATADIR "/wayland/xterm.png",                 15, 15 }
473 };
474
475 static void
476 create_pointer_images(struct wlsc_compositor *ec)
477 {
478         int i, count;
479
480         count = ARRAY_LENGTH(pointer_images);
481         ec->pointer_sprites = malloc(count * sizeof *ec->pointer_sprites);
482         for (i = 0; i < count; i++) {
483                 ec->pointer_sprites[i] =
484                         create_sprite_from_png(ec,
485                                                pointer_images[i].filename,
486                                                SPRITE_USE_CURSOR);
487         }
488 }
489
490 static struct wlsc_surface *
491 background_create(struct wlsc_output *output, const char *filename)
492 {
493         struct wlsc_surface *background;
494         struct wlsc_sprite *sprite;
495
496         background = wlsc_surface_create(output->compositor,
497                                          output->x, output->y,
498                                          output->current->width,
499                                          output->current->height);
500         if (background == NULL)
501                 return NULL;
502
503         sprite = create_sprite_from_png(output->compositor, filename, 0);
504         if (sprite == NULL) {
505                 free(background);
506                 return NULL;
507         }
508
509         wlsc_sprite_attach(sprite, &background->surface);
510
511         return background;
512 }
513
514 static int
515 texture_region(struct wlsc_surface *es, pixman_region32_t *region)
516 {
517         struct wlsc_compositor *ec = es->compositor;
518         GLfloat *v, inv_width, inv_height;
519         pixman_box32_t *rectangles;
520         unsigned int *p;
521         int i, n;
522
523         rectangles = pixman_region32_rectangles(region, &n);
524         v = wl_array_add(&ec->vertices, n * 16 * sizeof *v);
525         p = wl_array_add(&ec->indices, n * 6 * sizeof *p);
526         inv_width = 1.0 / es->pitch;
527         inv_height = 1.0 / es->height;
528
529         for (i = 0; i < n; i++, v += 16, p += 6) {
530                 v[ 0] = rectangles[i].x1;
531                 v[ 1] = rectangles[i].y1;
532                 v[ 2] = (GLfloat) (rectangles[i].x1 - es->x) * inv_width;
533                 v[ 3] = (GLfloat) (rectangles[i].y1 - es->y) * inv_height;
534
535                 v[ 4] = rectangles[i].x1;
536                 v[ 5] = rectangles[i].y2;
537                 v[ 6] = v[ 2];
538                 v[ 7] = (GLfloat) (rectangles[i].y2 - es->y) * inv_height;
539
540                 v[ 8] = rectangles[i].x2;
541                 v[ 9] = rectangles[i].y1;
542                 v[10] = (GLfloat) (rectangles[i].x2 - es->x) * inv_width;
543                 v[11] = v[ 3];
544
545                 v[12] = rectangles[i].x2;
546                 v[13] = rectangles[i].y2;
547                 v[14] = v[10];
548                 v[15] = v[ 7];
549
550                 p[0] = i * 4 + 0;
551                 p[1] = i * 4 + 1;
552                 p[2] = i * 4 + 2;
553                 p[3] = i * 4 + 2;
554                 p[4] = i * 4 + 1;
555                 p[5] = i * 4 + 3;
556         }
557
558         return n;
559 }
560
561 static void
562 transform_vertex(struct wlsc_surface *surface,
563                  GLfloat x, GLfloat y, GLfloat u, GLfloat v, GLfloat *r)
564 {
565         struct wlsc_vector t;
566
567         t.f[0] = x;
568         t.f[1] = y;
569         t.f[2] = 0.0;
570         t.f[3] = 1.0;
571
572         wlsc_matrix_transform(&surface->transform->matrix, &t);
573
574         r[ 0] = t.f[0];
575         r[ 1] = t.f[1];
576         r[ 2] = u;
577         r[ 3] = v;
578 }
579
580 static int
581 texture_transformed_surface(struct wlsc_surface *es)
582 {
583         struct wlsc_compositor *ec = es->compositor;
584         GLfloat *v;
585         unsigned int *p;
586
587         v = wl_array_add(&ec->vertices, 16 * sizeof *v);
588         p = wl_array_add(&ec->indices, 6 * sizeof *p);
589
590         transform_vertex(es, es->x, es->y, 0.0, 0.0, &v[0]);
591         transform_vertex(es, es->x, es->y + es->height, 0.0, 1.0, &v[4]);
592         transform_vertex(es, es->x + es->width, es->y, 1.0, 0.0, &v[8]);
593         transform_vertex(es, es->x + es->width, es->y + es->height,
594                          1.0, 1.0, &v[12]);
595
596         p[0] = 0;
597         p[1] = 1;
598         p[2] = 2;
599         p[3] = 2;
600         p[4] = 1;
601         p[5] = 3;
602
603         return 1;
604 }
605
606 static void
607 wlsc_surface_draw(struct wlsc_surface *es,
608                   struct wlsc_output *output, pixman_region32_t *clip)
609 {
610         struct wlsc_compositor *ec = es->compositor;
611         GLfloat *v;
612         pixman_region32_t repaint;
613         GLint filter;
614         int n;
615
616         pixman_region32_init_rect(&repaint,
617                                   es->x, es->y, es->width, es->height);
618         pixman_region32_intersect(&repaint, &repaint, clip);
619         if (!pixman_region32_not_empty(&repaint))
620                 return;
621
622         if (es->visual == &ec->compositor.argb_visual) {
623                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
624                 glEnable(GL_BLEND);
625         } else if (es->visual == &ec->compositor.premultiplied_argb_visual) {
626                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
627                 glEnable(GL_BLEND);
628         } else {
629                 glDisable(GL_BLEND);
630         }
631
632         if (es->transform == NULL) {
633                 filter = GL_NEAREST;
634                 n = texture_region(es, &repaint);
635         } else {
636                 filter = GL_LINEAR;
637                 n = texture_transformed_surface(es);
638         }
639
640         glBindTexture(GL_TEXTURE_2D, es->texture);
641         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
642         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
643
644         v = ec->vertices.data;
645         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[0]);
646         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof *v, &v[2]);
647         glEnableVertexAttribArray(0);
648         glEnableVertexAttribArray(1);
649         glDrawElements(GL_TRIANGLES, n * 6, GL_UNSIGNED_INT, ec->indices.data);
650
651         ec->vertices.size = 0;
652         ec->indices.size = 0;
653         pixman_region32_fini(&repaint);
654 }
655
656 static void
657 wlsc_surface_raise(struct wlsc_surface *surface)
658 {
659         struct wlsc_compositor *compositor = surface->compositor;
660
661         wl_list_remove(&surface->link);
662         wl_list_insert(&compositor->surface_list, &surface->link);
663 }
664
665 WL_EXPORT void
666 wlsc_compositor_damage_all(struct wlsc_compositor *compositor)
667 {
668         struct wlsc_output *output;
669
670         wl_list_for_each(output, &compositor->output_list, link)
671                 wlsc_output_damage(output);
672 }
673
674 static inline void
675 wlsc_buffer_post_release(struct wl_buffer *buffer)
676 {
677         if (buffer == NULL || --buffer->busy_count > 0)
678                 return;
679
680         assert(buffer->client != NULL);
681         wl_client_post_event(buffer->client,
682                              &buffer->resource.object,
683                              WL_BUFFER_RELEASE);
684 }
685
686 WL_EXPORT void
687 wlsc_output_damage(struct wlsc_output *output)
688 {
689         struct wlsc_compositor *compositor = output->compositor;
690
691         pixman_region32_union(&compositor->damage,
692                               &compositor->damage, &output->region);
693         wlsc_compositor_schedule_repaint(compositor);
694 }
695
696 static void
697 fade_frame(struct wlsc_animation *animation,
698            struct wlsc_output *output, uint32_t msecs)
699 {
700         struct wlsc_compositor *compositor =
701                 container_of(animation,
702                              struct wlsc_compositor, fade.animation);
703
704         wlsc_spring_update(&compositor->fade.spring, msecs);
705         if (wlsc_spring_done(&compositor->fade.spring)) {
706                 if (compositor->fade.spring.current > 0.999) {
707                         compositor->state = WLSC_COMPOSITOR_SLEEPING;
708                         compositor->shell->lock(compositor->shell);
709                 }
710                 compositor->fade.spring.current =
711                         compositor->fade.spring.target;
712                 wl_list_remove(&animation->link);
713                 wl_list_init(&animation->link);
714         }
715
716         wlsc_output_damage(output);
717 }
718
719 static void
720 fade_output(struct wlsc_output *output,
721             GLfloat tint, pixman_region32_t *region)
722 {
723         struct wlsc_compositor *compositor = output->compositor;
724         struct wlsc_surface surface;
725         GLfloat color[4] = { 0.0, 0.0, 0.0, tint };
726
727         surface.compositor = compositor;
728         surface.x = output->x;
729         surface.y = output->y;
730         surface.width = output->current->width;
731         surface.height = output->current->height;
732         surface.texture = GL_NONE;
733         surface.transform = NULL;
734
735         if (tint <= 1.0)
736                 surface.visual =
737                         &compositor->compositor.premultiplied_argb_visual;
738         else
739                 surface.visual = &compositor->compositor.rgb_visual;
740
741         glUseProgram(compositor->solid_shader.program);
742         glUniformMatrix4fv(compositor->solid_shader.proj_uniform,
743                            1, GL_FALSE, output->matrix.d);
744         glUniform4fv(compositor->solid_shader.color_uniform, 1, color);
745         wlsc_surface_draw(&surface, output, region);
746 }
747  
748 static void
749 wlsc_output_repaint(struct wlsc_output *output)
750 {
751         struct wlsc_compositor *ec = output->compositor;
752         struct wlsc_surface *es;
753         struct wlsc_input_device *device;
754         pixman_region32_t clip, new_damage, total_damage, region;
755
756         output->prepare_render(output);
757
758         glViewport(0, 0, output->current->width, output->current->height);
759
760         glUseProgram(ec->texture_shader.program);
761         glUniformMatrix4fv(ec->texture_shader.proj_uniform,
762                            1, GL_FALSE, output->matrix.d);
763         glUniform1i(ec->texture_shader.tex_uniform, 0);
764
765         pixman_region32_init(&new_damage);
766         pixman_region32_intersect(&new_damage, &ec->damage, &output->region);
767         pixman_region32_init(&clip);
768         pixman_region32_copy(&clip, &output->region);
769         wl_list_for_each(es, &ec->surface_list, link) {
770                 pixman_region32_intersect(&es->damage, &es->damage, &clip);
771                 pixman_region32_union(&new_damage, &new_damage, &es->damage);
772                 if (es->visual == &ec->compositor.rgb_visual) {
773                         pixman_region32_init_rect(&region, es->x, es->y, es->width, es->height);
774                         pixman_region32_subtract(&clip, &clip, &region);
775                         pixman_region32_fini(&region);
776                 }
777         }
778
779         pixman_region32_subtract(&ec->damage, &ec->damage, &output->region);
780         pixman_region32_init(&total_damage);
781         pixman_region32_union(&total_damage, &new_damage,
782                               &output->previous_damage);
783         pixman_region32_copy(&output->previous_damage, &new_damage);
784
785         pixman_region32_fini(&clip);
786         pixman_region32_fini(&new_damage);
787
788         device = (struct wlsc_input_device *) ec->input_device;
789         if (ec->focus && ec->fade.spring.current < 0.001) {
790                 if (!wl_list_empty(&device->sprite->link)) {
791                         wl_list_remove(&device->sprite->link);
792                         wl_list_init(&device->sprite->link);
793                 }
794                 if (output->set_hardware_cursor(output, device) < 0)
795                         wl_list_insert(&ec->surface_list,
796                                        &device->sprite->link);
797         } else {
798                 output->set_hardware_cursor(output, NULL);
799                 if (wl_list_empty(&device->sprite->link))
800                         wl_list_insert(&ec->surface_list,
801                                        &device->sprite->link);
802         }
803
804         es = container_of(ec->surface_list.next, struct wlsc_surface, link);
805
806         if (es->visual == &ec->compositor.rgb_visual &&
807             output->prepare_scanout_surface(output, es) == 0) {
808                 /* We're drawing nothing now,
809                  * draw the damaged regions later. */
810                 pixman_region32_union(&ec->damage, &ec->damage, &total_damage);
811
812                 output->scanout_buffer = es->buffer;
813                 output->scanout_buffer->busy_count++;
814
815                 wl_list_remove(&output->scanout_buffer_destroy_listener.link);
816                 wl_list_insert(output->scanout_buffer->resource.destroy_listener_list.prev,
817                                &output->scanout_buffer_destroy_listener.link);
818
819                 return;
820         }
821
822         if (es->fullscreen_output == output) {
823                 if (es->width < output->current->width ||
824                     es->height < output->current->height)
825                         glClear(GL_COLOR_BUFFER_BIT);
826                 wlsc_surface_draw(es, output, &total_damage);
827         } else {
828                 glUseProgram(ec->texture_shader.program);
829                 wl_list_for_each_reverse(es, &ec->surface_list, link) {
830                         if (ec->overlay == es)
831                                 continue;
832
833                         wlsc_surface_draw(es, output, &total_damage);
834                 }
835         }
836
837         if (ec->overlay)
838                 wlsc_surface_draw(ec->overlay, output, &total_damage);
839
840         if (ec->fade.spring.current > 0.001)
841                 fade_output(output, ec->fade.spring.current, &total_damage);
842 }
843
844 static void
845 repaint(void *data, int msecs)
846 {
847         struct wlsc_output *output = data;
848         struct wlsc_compositor *compositor = output->compositor;
849         struct wlsc_surface *es;
850         struct wlsc_animation *animation, *next;
851
852         wlsc_output_repaint(output);
853         output->repaint_needed = 0;
854         output->repaint_scheduled = 1;
855         output->present(output);
856
857         /* FIXME: Keep the surfaces in an per-output list. */
858         wl_list_for_each(es, &compositor->surface_list, link) {
859                 if (es->output == output) {
860                         wl_display_post_frame(compositor->wl_display,
861                                               &es->surface, msecs);
862                 }
863         }
864
865         wl_list_for_each_safe(animation, next,
866                               &compositor->animation_list, link)
867                 animation->frame(animation, output, msecs);
868 }
869
870 static void
871 idle_repaint(void *data)
872 {
873         repaint(data, wlsc_compositor_get_time());
874 }
875
876 WL_EXPORT void
877 wlsc_output_finish_frame(struct wlsc_output *output, int msecs)
878 {
879         wlsc_buffer_post_release(output->scanout_buffer);
880         output->scanout_buffer = NULL;
881         output->repaint_scheduled = 0;
882
883         if (output->repaint_needed)
884                 repaint(output, msecs);
885 }
886
887 WL_EXPORT void
888 wlsc_compositor_schedule_repaint(struct wlsc_compositor *compositor)
889 {
890         struct wlsc_output *output;
891         struct wl_event_loop *loop;
892
893         if (compositor->state == WLSC_COMPOSITOR_SLEEPING)
894                 return;
895
896         loop = wl_display_get_event_loop(compositor->wl_display);
897         wl_list_for_each(output, &compositor->output_list, link) {
898                 output->repaint_needed = 1;
899                 if (output->repaint_scheduled)
900                         continue;
901
902                 wl_event_loop_add_idle(loop, idle_repaint, output);
903                 output->repaint_scheduled = 1;
904         }
905 }
906
907 WL_EXPORT void
908 wlsc_compositor_fade(struct wlsc_compositor *compositor, float tint)
909 {
910         int done;
911
912         done = wlsc_spring_done(&compositor->fade.spring);
913         compositor->fade.spring.target = tint;
914         if (wlsc_spring_done(&compositor->fade.spring))
915                 return;
916
917         if (done)
918                 compositor->fade.spring.timestamp =
919                         wlsc_compositor_get_time();
920
921         wlsc_compositor_damage_all(compositor);
922         if (wl_list_empty(&compositor->fade.animation.link))
923                 wl_list_insert(compositor->animation_list.prev,
924                                &compositor->fade.animation.link);
925 }
926
927 static void
928 surface_destroy(struct wl_client *client,
929                 struct wl_surface *surface)
930 {
931         wl_resource_destroy(&surface->resource, client,
932                             wlsc_compositor_get_time());
933 }
934
935 WL_EXPORT void
936 wlsc_surface_assign_output(struct wlsc_surface *es)
937 {
938         struct wlsc_compositor *ec = es->compositor;
939         struct wlsc_output *output;
940
941         struct wlsc_output *tmp = es->output;
942         es->output = NULL;
943
944         wl_list_for_each(output, &ec->output_list, link) {
945                 if (pixman_region32_contains_point(&output->region,
946                                                    es->x, es->y, NULL)) {
947                         if (output != tmp)
948                                 printf("assiging surface %p to output %p\n",
949                                        es, output);
950                         es->output = output;
951                 }
952         }
953         
954         if (es->output == NULL) {
955                 printf("no output found\n");
956                 es->output = container_of(ec->output_list.next,
957                                           struct wlsc_output, link);
958         }
959 }
960
961 static void
962 surface_attach(struct wl_client *client,
963                struct wl_surface *surface, struct wl_buffer *buffer,
964                int32_t x, int32_t y)
965 {
966         struct wlsc_surface *es = (struct wlsc_surface *) surface;
967
968         /* FIXME: This damages the entire old surface, but we should
969          * really just damage the part that's no longer covered by the
970          * surface.  Anything covered by the new surface will be
971          * damaged by the client. */
972         if (es->buffer)
973                 wlsc_surface_damage_below(es);
974
975         buffer->busy_count++;
976         wlsc_buffer_post_release(es->buffer);
977
978         es->buffer = buffer;
979         wl_list_remove(&es->buffer_destroy_listener.link);
980         wl_list_insert(es->buffer->resource.destroy_listener_list.prev,
981                        &es->buffer_destroy_listener.link);
982
983         es->x += x;
984         es->y += y;
985         es->width = buffer->width;
986         es->height = buffer->height;
987         if (x != 0 || y != 0)
988                 wlsc_surface_assign_output(es);
989         if (es->visual == NULL)
990                 wl_list_insert(&es->compositor->surface_list, &es->link);
991
992         wlsc_buffer_attach(buffer, surface);
993
994         es->compositor->shell->attach(es->compositor->shell, es);
995 }
996
997 static void
998 surface_damage(struct wl_client *client,
999                struct wl_surface *surface,
1000                int32_t x, int32_t y, int32_t width, int32_t height)
1001 {
1002         struct wlsc_surface *es = (struct wlsc_surface *) surface;
1003
1004         wlsc_surface_damage_rectangle(es, x, y, width, height);
1005 }
1006
1007 const static struct wl_surface_interface surface_interface = {
1008         surface_destroy,
1009         surface_attach,
1010         surface_damage
1011 };
1012
1013 static void
1014 wlsc_input_device_attach(struct wlsc_input_device *device,
1015                          int x, int y, int width, int height)
1016 {
1017         wlsc_surface_damage_below(device->sprite);
1018
1019         device->hotspot_x = x;
1020         device->hotspot_y = y;
1021
1022         device->sprite->x = device->input_device.x - device->hotspot_x;
1023         device->sprite->y = device->input_device.y - device->hotspot_y;
1024         device->sprite->width = width;
1025         device->sprite->height = height;
1026
1027         wlsc_surface_damage(device->sprite);
1028 }
1029
1030 static void
1031 wlsc_input_device_attach_buffer(struct wlsc_input_device *device,
1032                                 struct wl_buffer *buffer, int x, int y)
1033 {
1034         wlsc_buffer_attach(buffer, &device->sprite->surface);
1035         wlsc_input_device_attach(device, x, y, buffer->width, buffer->height);
1036 }
1037
1038 static void
1039 wlsc_input_device_attach_sprite(struct wlsc_input_device *device,
1040                                 struct wlsc_sprite *sprite, int x, int y)
1041 {
1042         wlsc_sprite_attach(sprite, &device->sprite->surface);
1043         wlsc_input_device_attach(device, x, y, sprite->width, sprite->height);
1044 }
1045
1046 WL_EXPORT void
1047 wlsc_input_device_set_pointer_image(struct wlsc_input_device *device,
1048                                     enum wlsc_pointer_type type)
1049 {
1050         struct wlsc_compositor *compositor =
1051                 (struct wlsc_compositor *) device->input_device.compositor;
1052
1053         wlsc_input_device_attach_sprite(device,
1054                                         compositor->pointer_sprites[type],
1055                                         pointer_images[type].hotspot_x,
1056                                         pointer_images[type].hotspot_y);
1057 }
1058
1059 static void
1060 compositor_create_surface(struct wl_client *client,
1061                           struct wl_compositor *compositor, uint32_t id)
1062 {
1063         struct wlsc_compositor *ec = (struct wlsc_compositor *) compositor;
1064         struct wlsc_surface *surface;
1065
1066         surface = wlsc_surface_create(ec, 0, 0, 0, 0);
1067         if (surface == NULL) {
1068                 wl_client_post_no_memory(client);
1069                 return;
1070         }
1071
1072         surface->surface.resource.destroy = destroy_surface;
1073
1074         surface->surface.resource.object.id = id;
1075         surface->surface.resource.object.interface = &wl_surface_interface;
1076         surface->surface.resource.object.implementation =
1077                 (void (**)(void)) &surface_interface;
1078         surface->surface.client = client;
1079
1080         wl_client_add_resource(client, &surface->surface.resource);
1081 }
1082
1083 const static struct wl_compositor_interface compositor_interface = {
1084         compositor_create_surface,
1085 };
1086
1087 static void
1088 wlsc_surface_transform(struct wlsc_surface *surface,
1089                        int32_t x, int32_t y, int32_t *sx, int32_t *sy)
1090 {
1091         *sx = x - surface->x;
1092         *sy = y - surface->y;
1093 }
1094
1095 WL_EXPORT struct wlsc_surface *
1096 pick_surface(struct wl_input_device *device, int32_t *sx, int32_t *sy)
1097 {
1098         struct wlsc_compositor *ec =
1099                 (struct wlsc_compositor *) device->compositor;
1100         struct wlsc_surface *es;
1101
1102         wl_list_for_each(es, &ec->surface_list, link) {
1103                 if (es->surface.client == NULL)
1104                         continue;
1105                 wlsc_surface_transform(es, device->x, device->y, sx, sy);
1106                 if (0 <= *sx && *sx < es->width &&
1107                     0 <= *sy && *sy < es->height)
1108                         return es;
1109         }
1110
1111         return NULL;
1112 }
1113
1114
1115 static void
1116 motion_grab_motion(struct wl_grab *grab,
1117                    uint32_t time, int32_t x, int32_t y)
1118 {
1119         struct wlsc_input_device *device =
1120                 (struct wlsc_input_device *) grab->input_device;
1121         struct wlsc_surface *es =
1122                 (struct wlsc_surface *) device->input_device.pointer_focus;
1123         int32_t sx, sy;
1124
1125         wlsc_surface_transform(es, x, y, &sx, &sy);
1126         wl_client_post_event(es->surface.client,
1127                              &device->input_device.object,
1128                              WL_INPUT_DEVICE_MOTION,
1129                              time, x, y, sx, sy);
1130 }
1131
1132 static void
1133 motion_grab_button(struct wl_grab *grab,
1134                    uint32_t time, int32_t button, int32_t state)
1135 {
1136         wl_client_post_event(grab->input_device->pointer_focus->client,
1137                              &grab->input_device->object,
1138                              WL_INPUT_DEVICE_BUTTON,
1139                              time, button, state);
1140 }
1141
1142 static void
1143 motion_grab_end(struct wl_grab *grab, uint32_t time)
1144 {
1145 }
1146
1147 static const struct wl_grab_interface motion_grab_interface = {
1148         motion_grab_motion,
1149         motion_grab_button,
1150         motion_grab_end
1151 };
1152
1153 WL_EXPORT void
1154 wlsc_compositor_wake(struct wlsc_compositor *compositor)
1155 {
1156         if (compositor->idle_inhibit)
1157                 return;
1158
1159         wlsc_compositor_fade(compositor, 0.0);
1160         compositor->state = WLSC_COMPOSITOR_ACTIVE;
1161
1162         wl_event_source_timer_update(compositor->idle_source,
1163                                      option_idle_time * 1000);
1164 }
1165
1166 static void
1167 wlsc_compositor_idle_inhibit(struct wlsc_compositor *compositor)
1168 {
1169         wlsc_compositor_wake(compositor);
1170         compositor->idle_inhibit++;
1171 }
1172
1173 static void
1174 wlsc_compositor_idle_release(struct wlsc_compositor *compositor)
1175 {
1176         compositor->idle_inhibit--;
1177         wlsc_compositor_wake(compositor);
1178 }
1179
1180 static int
1181 idle_handler(void *data)
1182 {
1183         struct wlsc_compositor *compositor = data;
1184
1185         if (compositor->idle_inhibit)
1186                 return 1;
1187
1188         wlsc_compositor_fade(compositor, 1.0);
1189
1190         return 1;
1191 }
1192
1193 WL_EXPORT void
1194 notify_motion(struct wl_input_device *device, uint32_t time, int x, int y)
1195 {
1196         struct wlsc_surface *es;
1197         struct wlsc_compositor *ec =
1198                 (struct wlsc_compositor *) device->compositor;
1199         struct wlsc_output *output;
1200         const struct wl_grab_interface *interface;
1201         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
1202         int32_t sx, sy;
1203         int x_valid = 0, y_valid = 0;
1204         int min_x = INT_MAX, min_y = INT_MAX, max_x = INT_MIN, max_y = INT_MIN;
1205
1206         wlsc_compositor_wake(ec);
1207
1208         wl_list_for_each(output, &ec->output_list, link) {
1209                 if (output->x <= x && x <= output->x + output->current->width)
1210                         x_valid = 1;
1211
1212                 if (output->y <= y && y <= output->y + output->current->height)
1213                         y_valid = 1;
1214
1215                 /* FIXME: calculate this only on output addition/deletion */
1216                 if (output->x < min_x)
1217                         min_x = output->x;
1218                 if (output->y < min_y)
1219                         min_y = output->y;
1220
1221                 if (output->x + output->current->width > max_x)
1222                         max_x = output->x + output->current->width;
1223                 if (output->y + output->current->height > max_y)
1224                         max_y = output->y + output->current->height;
1225         }
1226         
1227         if (!x_valid) {
1228                 if (x < min_x)
1229                         x = min_x;
1230                 else if (x >= max_x)
1231                         x = max_x;
1232         }
1233         if (!y_valid) {
1234                 if (y < min_y)
1235                         y = min_y;
1236                 else  if (y >= max_y)
1237                         y = max_y;
1238         }
1239
1240         device->x = x;
1241         device->y = y;
1242
1243         if (device->grab) {
1244                 interface = device->grab->interface;
1245                 interface->motion(device->grab, time, x, y);
1246         } else {
1247                 es = pick_surface(device, &sx, &sy);
1248                 wl_input_device_set_pointer_focus(device,
1249                                                   &es->surface,
1250                                                   time, x, y, sx, sy);
1251                 if (es)
1252                         wl_client_post_event(es->surface.client,
1253                                              &device->object,
1254                                              WL_INPUT_DEVICE_MOTION,
1255                                              time, x, y, sx, sy);
1256         }
1257
1258         wlsc_surface_damage_below(wd->sprite);
1259
1260         wd->sprite->x = device->x - wd->hotspot_x;
1261         wd->sprite->y = device->y - wd->hotspot_y;
1262
1263         wlsc_surface_damage(wd->sprite);
1264 }
1265
1266 WL_EXPORT void
1267 wlsc_surface_activate(struct wlsc_surface *surface,
1268                       struct wlsc_input_device *device, uint32_t time)
1269 {
1270         struct wlsc_shell *shell = surface->compositor->shell;
1271
1272         wlsc_surface_raise(surface);
1273         if (device->selection)
1274                 shell->set_selection_focus(shell,
1275                                            device->selection,
1276                                            &surface->surface, time);
1277
1278         wl_input_device_set_keyboard_focus(&device->input_device,
1279                                            &surface->surface,
1280                                            time);
1281 }
1282
1283 struct wlsc_binding {
1284         uint32_t key;
1285         uint32_t button;
1286         uint32_t modifier;
1287         wlsc_binding_handler_t handler;
1288         void *data;
1289         struct wl_list link;
1290 };
1291
1292 WL_EXPORT void
1293 notify_button(struct wl_input_device *device,
1294               uint32_t time, int32_t button, int32_t state)
1295 {
1296         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
1297         struct wlsc_compositor *compositor =
1298                 (struct wlsc_compositor *) device->compositor;
1299         struct wlsc_binding *b;
1300         struct wlsc_surface *surface =
1301                 (struct wlsc_surface *) device->pointer_focus;
1302
1303         if (state)
1304                 wlsc_compositor_idle_inhibit(compositor);
1305         else
1306                 wlsc_compositor_idle_release(compositor);
1307
1308         if (state && surface && device->grab == NULL) {
1309                 wlsc_surface_activate(surface, wd, time);
1310                 wl_input_device_start_grab(device,
1311                                            &device->motion_grab,
1312                                            button, time);
1313         }
1314
1315         wl_list_for_each(b, &compositor->binding_list, link) {
1316                 if (b->button == button &&
1317                     b->modifier == wd->modifier_state && state) {
1318                         b->handler(&wd->input_device,
1319                                    time, 0, button, state, b->data);
1320                         break;
1321                 }
1322         }
1323
1324         if (device->grab)
1325                 device->grab->interface->button(device->grab, time,
1326                                                 button, state);
1327
1328         if (!state && device->grab && device->grab_button == button)
1329                 wl_input_device_end_grab(device, time);
1330 }
1331
1332 static void
1333 terminate_binding(struct wl_input_device *device, uint32_t time,
1334                   uint32_t key, uint32_t button, uint32_t state, void *data)
1335 {
1336         struct wlsc_compositor *compositor = data;
1337
1338         if (state)
1339                 wl_display_terminate(compositor->wl_display);
1340 }
1341
1342 WL_EXPORT struct wlsc_binding *
1343 wlsc_compositor_add_binding(struct wlsc_compositor *compositor,
1344                             uint32_t key, uint32_t button, uint32_t modifier,
1345                             wlsc_binding_handler_t handler, void *data)
1346 {
1347         struct wlsc_binding *binding;
1348
1349         binding = malloc(sizeof *binding);
1350         if (binding == NULL)
1351                 return NULL;
1352
1353         binding->key = key;
1354         binding->button = button;
1355         binding->modifier = modifier;
1356         binding->handler = handler;
1357         binding->data = data;
1358         wl_list_insert(compositor->binding_list.prev, &binding->link);
1359
1360         return binding;
1361 }
1362
1363 WL_EXPORT void
1364 wlsc_binding_destroy(struct wlsc_binding *binding)
1365 {
1366         wl_list_remove(&binding->link);
1367         free(binding);
1368 }
1369
1370 static void
1371 update_modifier_state(struct wlsc_input_device *device,
1372                       uint32_t key, uint32_t state)
1373 {
1374         uint32_t modifier;
1375
1376         switch (key) {
1377         case KEY_LEFTCTRL:
1378         case KEY_RIGHTCTRL:
1379                 modifier = MODIFIER_CTRL;
1380                 break;
1381
1382         case KEY_LEFTALT:
1383         case KEY_RIGHTALT:
1384                 modifier = MODIFIER_ALT;
1385                 break;
1386
1387         case KEY_LEFTMETA:
1388         case KEY_RIGHTMETA:
1389                 modifier = MODIFIER_SUPER;
1390                 break;
1391
1392         default:
1393                 modifier = 0;
1394                 break;
1395         }
1396
1397         if (state)
1398                 device->modifier_state |= modifier;
1399         else
1400                 device->modifier_state &= ~modifier;
1401 }
1402
1403 WL_EXPORT void
1404 notify_key(struct wl_input_device *device,
1405            uint32_t time, uint32_t key, uint32_t state)
1406 {
1407         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
1408         struct wlsc_compositor *compositor =
1409                 (struct wlsc_compositor *) device->compositor;
1410         uint32_t *k, *end;
1411         struct wlsc_binding *b;
1412
1413         if (state)
1414                 wlsc_compositor_idle_inhibit(compositor);
1415         else
1416                 wlsc_compositor_idle_release(compositor);
1417
1418         wl_list_for_each(b, &compositor->binding_list, link) {
1419                 if (b->key == key &&
1420                     b->modifier == wd->modifier_state) {
1421                         b->handler(&wd->input_device,
1422                                    time, key, 0, state, b->data);
1423                         break;
1424                 }
1425         }
1426
1427         update_modifier_state(wd, key, state);
1428         end = device->keys.data + device->keys.size;
1429         for (k = device->keys.data; k < end; k++) {
1430                 if (*k == key)
1431                         *k = *--end;
1432         }
1433         device->keys.size = (void *) end - device->keys.data;
1434         if (state) {
1435                 k = wl_array_add(&device->keys, sizeof *k);
1436                 *k = key;
1437         }
1438
1439         if (device->keyboard_focus != NULL)
1440                 wl_client_post_event(device->keyboard_focus->client,
1441                                      &device->object,
1442                                      WL_INPUT_DEVICE_KEY, time, key, state);
1443 }
1444
1445 WL_EXPORT void
1446 notify_pointer_focus(struct wl_input_device *device,
1447                      uint32_t time, struct wlsc_output *output,
1448                      int32_t x, int32_t y)
1449 {
1450         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
1451         struct wlsc_compositor *compositor =
1452                 (struct wlsc_compositor *) device->compositor;
1453         struct wlsc_surface *es;
1454         int32_t sx, sy;
1455
1456         if (output) {
1457                 device->x = x;
1458                 device->y = y;
1459                 es = pick_surface(device, &sx, &sy);
1460                 wl_input_device_set_pointer_focus(device,
1461                                                   &es->surface,
1462                                                   time, x, y, sx, sy);
1463
1464                 compositor->focus = 1;
1465
1466                 wd->sprite->x = device->x - wd->hotspot_x;
1467                 wd->sprite->y = device->y - wd->hotspot_y;
1468         } else {
1469                 wl_input_device_set_pointer_focus(device, NULL,
1470                                                   time, 0, 0, 0, 0);
1471                 compositor->focus = 0;
1472         }
1473
1474         wlsc_surface_damage(wd->sprite);
1475 }
1476
1477 WL_EXPORT void
1478 notify_keyboard_focus(struct wl_input_device *device,
1479                       uint32_t time, struct wlsc_output *output,
1480                       struct wl_array *keys)
1481 {
1482         struct wlsc_input_device *wd =
1483                 (struct wlsc_input_device *) device;
1484         struct wlsc_compositor *compositor =
1485                 (struct wlsc_compositor *) device->compositor;
1486         struct wlsc_surface *es;
1487         uint32_t *k, *end;
1488
1489         if (!wl_list_empty(&compositor->surface_list))
1490                 es = container_of(compositor->surface_list.next,
1491                                   struct wlsc_surface, link);
1492         else
1493                 es = NULL;
1494
1495         if (output) {
1496                 wl_array_copy(&wd->input_device.keys, keys);
1497                 wd->modifier_state = 0;
1498                 end = device->keys.data + device->keys.size;
1499                 for (k = device->keys.data; k < end; k++) {
1500                         wlsc_compositor_idle_inhibit(compositor);
1501                         update_modifier_state(wd, *k, 1);
1502                 }
1503
1504                 if (es->surface.client)
1505                         wl_input_device_set_keyboard_focus(&wd->input_device,
1506                                                            &es->surface, time);
1507         } else {
1508                 end = device->keys.data + device->keys.size;
1509                 for (k = device->keys.data; k < end; k++)
1510                         wlsc_compositor_idle_release(compositor);
1511
1512                 wd->modifier_state = 0;
1513                 wl_input_device_set_keyboard_focus(&wd->input_device,
1514                                                    NULL, time);
1515         }
1516 }
1517
1518
1519 static void
1520 input_device_attach(struct wl_client *client,
1521                     struct wl_input_device *device_base,
1522                     uint32_t time,
1523                     struct wl_buffer *buffer, int32_t x, int32_t y)
1524 {
1525         struct wlsc_input_device *device =
1526                 (struct wlsc_input_device *) device_base;
1527
1528         if (time < device->input_device.pointer_focus_time)
1529                 return;
1530         if (device->input_device.pointer_focus == NULL)
1531                 return;
1532         if (device->input_device.pointer_focus->client != client)
1533                 return;
1534
1535         if (buffer == NULL) {
1536                 wlsc_input_device_set_pointer_image(device,
1537                                                     WLSC_POINTER_LEFT_PTR);
1538                 return;
1539         }
1540
1541         wlsc_input_device_attach_buffer(device, buffer, x, y);
1542 }
1543
1544 const static struct wl_input_device_interface input_device_interface = {
1545         input_device_attach,
1546 };
1547
1548 WL_EXPORT void
1549 wlsc_input_device_init(struct wlsc_input_device *device,
1550                        struct wlsc_compositor *ec)
1551 {
1552         wl_input_device_init(&device->input_device, &ec->compositor);
1553
1554         device->input_device.object.interface = &wl_input_device_interface;
1555         device->input_device.object.implementation =
1556                 (void (**)(void)) &input_device_interface;
1557         wl_display_add_object(ec->wl_display, &device->input_device.object);
1558         wl_display_add_global(ec->wl_display, &device->input_device.object, NULL);
1559
1560         device->sprite = wlsc_surface_create(ec,
1561                                              device->input_device.x,
1562                                              device->input_device.y, 32, 32);
1563         wl_list_insert(&ec->surface_list, &device->sprite->link);
1564
1565         device->hotspot_x = 16;
1566         device->hotspot_y = 16;
1567         device->modifier_state = 0;
1568
1569         device->input_device.motion_grab.interface = &motion_grab_interface;
1570
1571         wl_list_insert(ec->input_device_list.prev, &device->link);
1572
1573         wlsc_input_device_set_pointer_image(device, WLSC_POINTER_LEFT_PTR);
1574 }
1575
1576 static void
1577 wlsc_output_post_geometry(struct wl_client *client,
1578                           struct wl_object *global, uint32_t version)
1579 {
1580         struct wlsc_output *output =
1581                 container_of(global, struct wlsc_output, object);
1582         struct wlsc_mode *mode;
1583
1584         wl_client_post_event(client, global,
1585                              WL_OUTPUT_GEOMETRY,
1586                              output->x,
1587                              output->y,
1588                              output->mm_width,
1589                              output->mm_height,
1590                              output->subpixel,
1591                              output->make, output->model);
1592
1593         wl_list_for_each (mode, &output->mode_list, link) {
1594                 wl_client_post_event(client, global,
1595                                      WL_OUTPUT_MODE,
1596                                      mode->flags,
1597                                      mode->width, mode->height, mode->refresh);
1598         }
1599 }
1600
1601 static const char vertex_shader[] =
1602         "uniform mat4 proj;\n"
1603         "attribute vec2 position;\n"
1604         "attribute vec2 texcoord;\n"
1605         "varying vec2 v_texcoord;\n"
1606         "void main()\n"
1607         "{\n"
1608         "   gl_Position = proj * vec4(position, 0.0, 1.0);\n"
1609         "   v_texcoord = texcoord;\n"
1610         "}\n";
1611
1612 static const char texture_fragment_shader[] =
1613         "precision mediump float;\n"
1614         "varying vec2 v_texcoord;\n"
1615         "uniform sampler2D tex;\n"
1616         "void main()\n"
1617         "{\n"
1618         "   gl_FragColor = texture2D(tex, v_texcoord)\n;"
1619         "}\n";
1620
1621 static const char solid_fragment_shader[] =
1622         "precision mediump float;\n"
1623         "uniform vec4 color;\n"
1624         "void main()\n"
1625         "{\n"
1626         "   gl_FragColor = color\n;"
1627         "}\n";
1628
1629 static int
1630 compile_shader(GLenum type, const char *source)
1631 {
1632         GLuint s;
1633         char msg[512];
1634         GLint status;
1635
1636         s = glCreateShader(type);
1637         glShaderSource(s, 1, &source, NULL);
1638         glCompileShader(s);
1639         glGetShaderiv(s, GL_COMPILE_STATUS, &status);
1640         if (!status) {
1641                 glGetShaderInfoLog(s, sizeof msg, NULL, msg);
1642                 fprintf(stderr, "shader info: %s\n", msg);
1643                 return GL_NONE;
1644         }
1645
1646         return s;
1647 }
1648
1649 static int
1650 wlsc_shader_init(struct wlsc_shader *shader,
1651                  const char *vertex_source, const char *fragment_source)
1652 {
1653         char msg[512];
1654         GLint status;
1655
1656         shader->vertex_shader =
1657                 compile_shader(GL_VERTEX_SHADER, vertex_source);
1658         shader->fragment_shader =
1659                 compile_shader(GL_FRAGMENT_SHADER, fragment_source);
1660
1661         shader->program = glCreateProgram();
1662         glAttachShader(shader->program, shader->vertex_shader);
1663         glAttachShader(shader->program, shader->fragment_shader);
1664         glBindAttribLocation(shader->program, 0, "position");
1665         glBindAttribLocation(shader->program, 1, "texcoord");
1666
1667         glLinkProgram(shader->program);
1668         glGetProgramiv(shader->program, GL_LINK_STATUS, &status);
1669         if (!status) {
1670                 glGetProgramInfoLog(shader->program, sizeof msg, NULL, msg);
1671                 fprintf(stderr, "link info: %s\n", msg);
1672                 return -1;
1673         }
1674
1675         shader->proj_uniform = glGetUniformLocation(shader->program, "proj");
1676         shader->tex_uniform = glGetUniformLocation(shader->program, "tex");
1677
1678         return 0;
1679 }
1680
1681 static int
1682 init_solid_shader(struct wlsc_shader *shader,
1683                   GLuint vertex_shader, const char *fragment_source)
1684 {
1685         GLint status;
1686         char msg[512];
1687
1688         shader->vertex_shader = vertex_shader;
1689         shader->fragment_shader =
1690                 compile_shader(GL_FRAGMENT_SHADER, fragment_source);
1691
1692         shader->program = glCreateProgram();
1693         glAttachShader(shader->program, shader->vertex_shader);
1694         glAttachShader(shader->program, shader->fragment_shader);
1695         glBindAttribLocation(shader->program, 0, "position");
1696         glBindAttribLocation(shader->program, 1, "texcoord");
1697
1698         glLinkProgram(shader->program);
1699         glGetProgramiv(shader->program, GL_LINK_STATUS, &status);
1700         if (!status) {
1701                 glGetProgramInfoLog(shader->program, sizeof msg, NULL, msg);
1702                 fprintf(stderr, "link info: %s\n", msg);
1703                 return -1;
1704         }
1705  
1706         shader->proj_uniform = glGetUniformLocation(shader->program, "proj");
1707         shader->color_uniform = glGetUniformLocation(shader->program, "color");
1708
1709         return 0;
1710 }
1711
1712 WL_EXPORT void
1713 wlsc_output_destroy(struct wlsc_output *output)
1714 {
1715         pixman_region32_fini(&output->region);
1716         pixman_region32_fini(&output->previous_damage);
1717         destroy_surface(&output->background->surface.resource, NULL);
1718 }
1719
1720 WL_EXPORT void
1721 wlsc_output_move(struct wlsc_output *output, int x, int y)
1722 {
1723         struct wlsc_compositor *c = output->compositor;
1724         int flip;
1725
1726         output->x = x;
1727         output->y = y;
1728
1729         if (output->background) {
1730                 output->background->x = x;
1731                 output->background->y = y;
1732         }
1733
1734         pixman_region32_init(&output->previous_damage);
1735         pixman_region32_init_rect(&output->region, x, y, 
1736                                   output->current->width,
1737                                   output->current->height);
1738
1739         wlsc_matrix_init(&output->matrix);
1740         wlsc_matrix_translate(&output->matrix,
1741                               -output->x - output->current->width / 2.0,
1742                               -output->y - output->current->height / 2.0, 0);
1743
1744         flip = (output->flags & WL_OUTPUT_FLIPPED) ? -1 : 1;
1745         wlsc_matrix_scale(&output->matrix,
1746                           2.0 / output->current->width,
1747                           flip * 2.0 / output->current->height, 1);
1748
1749         pixman_region32_union(&c->damage, &c->damage, &output->region);
1750 }
1751
1752 WL_EXPORT void
1753 wlsc_output_init(struct wlsc_output *output, struct wlsc_compositor *c,
1754                  int x, int y, int width, int height, uint32_t flags)
1755 {
1756         output->compositor = c;
1757         output->x = x;
1758         output->y = y;
1759         output->mm_width = width;
1760         output->mm_height = height;
1761
1762         output->background =
1763                 background_create(output, option_background);
1764  
1765         if (output->background != NULL)
1766                 wl_list_insert(c->surface_list.prev,
1767                                &output->background->link);
1768
1769         output->flags = flags;
1770         wlsc_output_move(output, x, y);
1771
1772         output->scanout_buffer_destroy_listener.func =
1773                 output_handle_scanout_buffer_destroy;
1774         wl_list_init(&output->scanout_buffer_destroy_listener.link);
1775
1776         output->object.interface = &wl_output_interface;
1777         wl_display_add_object(c->wl_display, &output->object);
1778         wl_display_add_global(c->wl_display, &output->object,
1779                               wlsc_output_post_geometry);
1780 }
1781
1782 static void
1783 shm_buffer_created(struct wl_buffer *buffer)
1784 {
1785         struct wl_list *surfaces_attached_to;
1786
1787         surfaces_attached_to = malloc(sizeof *surfaces_attached_to);
1788         if (!surfaces_attached_to) {
1789                 buffer->user_data = NULL;
1790                 return;
1791         }
1792
1793         wl_list_init(surfaces_attached_to);
1794
1795         buffer->user_data = surfaces_attached_to;
1796 }
1797
1798 static void
1799 shm_buffer_damaged(struct wl_buffer *buffer,
1800                    int32_t x, int32_t y, int32_t width, int32_t height)
1801 {
1802         struct wl_list *surfaces_attached_to = buffer->user_data;
1803         struct wlsc_surface *es;
1804         GLsizei tex_width = wl_shm_buffer_get_stride(buffer) / 4;
1805
1806         wl_list_for_each(es, surfaces_attached_to, buffer_link) {
1807                 glBindTexture(GL_TEXTURE_2D, es->texture);
1808                 glTexImage2D(GL_TEXTURE_2D, 0, GL_BGRA_EXT,
1809                              tex_width, buffer->height, 0,
1810                              GL_BGRA_EXT, GL_UNSIGNED_BYTE,
1811                              wl_shm_buffer_get_data(buffer));
1812                 /* Hmm, should use glTexSubImage2D() here but GLES2 doesn't
1813                  * support any unpack attributes except GL_UNPACK_ALIGNMENT. */
1814         }
1815 }
1816
1817 static void
1818 shm_buffer_destroyed(struct wl_buffer *buffer)
1819 {
1820         struct wl_list *surfaces_attached_to = buffer->user_data;
1821         struct wlsc_surface *es, *next;
1822
1823         wl_list_for_each_safe(es, next, surfaces_attached_to, buffer_link) {
1824                 wl_list_remove(&es->buffer_link);
1825                 wl_list_init(&es->buffer_link);
1826         }
1827
1828         free(surfaces_attached_to);
1829 }
1830
1831 const static struct wl_shm_callbacks shm_callbacks = {
1832         shm_buffer_created,
1833         shm_buffer_damaged,
1834         shm_buffer_destroyed
1835 };
1836
1837 WL_EXPORT int
1838 wlsc_compositor_init(struct wlsc_compositor *ec, struct wl_display *display)
1839 {
1840         struct wl_event_loop *loop;
1841         const char *extensions;
1842
1843         ec->wl_display = display;
1844
1845         wl_compositor_init(&ec->compositor, &compositor_interface, display);
1846
1847         ec->shm = wl_shm_init(display, &shm_callbacks);
1848
1849         ec->image_target_texture_2d =
1850                 (void *) eglGetProcAddress("glEGLImageTargetTexture2DOES");
1851         ec->image_target_renderbuffer_storage = (void *)
1852                 eglGetProcAddress("glEGLImageTargetRenderbufferStorageOES");
1853         ec->create_image = (void *) eglGetProcAddress("eglCreateImageKHR");
1854         ec->destroy_image = (void *) eglGetProcAddress("eglDestroyImageKHR");
1855         ec->bind_display =
1856                 (void *) eglGetProcAddress("eglBindWaylandDisplayWL");
1857         ec->unbind_display =
1858                 (void *) eglGetProcAddress("eglUnbindWaylandDisplayWL");
1859
1860         extensions = (const char *) glGetString(GL_EXTENSIONS);
1861         if (!strstr(extensions, "GL_EXT_texture_format_BGRA8888")) {
1862                 fprintf(stderr,
1863                         "GL_EXT_texture_format_BGRA8888 not available\n");
1864                 return -1;
1865         }
1866
1867         extensions =
1868                 (const char *) eglQueryString(ec->display, EGL_EXTENSIONS);
1869         if (strstr(extensions, "EGL_WL_bind_wayland_display"))
1870                 ec->has_bind_display = 1;
1871         if (ec->has_bind_display)
1872                 ec->bind_display(ec->display, ec->wl_display);
1873
1874         wl_list_init(&ec->surface_list);
1875         wl_list_init(&ec->input_device_list);
1876         wl_list_init(&ec->output_list);
1877         wl_list_init(&ec->binding_list);
1878         wl_list_init(&ec->animation_list);
1879         wlsc_spring_init(&ec->fade.spring, 0.8, 0.0, 0.0);
1880         ec->fade.animation.frame = fade_frame;
1881         wl_list_init(&ec->fade.animation.link);
1882
1883         wlsc_compositor_add_binding(ec, KEY_BACKSPACE, 0,
1884                                     MODIFIER_CTRL | MODIFIER_ALT,
1885                                     terminate_binding, ec);
1886
1887         create_pointer_images(ec);
1888
1889         screenshooter_create(ec);
1890
1891         glActiveTexture(GL_TEXTURE0);
1892
1893         if (wlsc_shader_init(&ec->texture_shader,
1894                              vertex_shader, texture_fragment_shader) < 0)
1895                 return -1;
1896         if (init_solid_shader(&ec->solid_shader,
1897                               ec->texture_shader.vertex_shader,
1898                               solid_fragment_shader) < 0)
1899                 return -1;
1900
1901         loop = wl_display_get_event_loop(ec->wl_display);
1902         ec->idle_source = wl_event_loop_add_timer(loop, idle_handler, ec);
1903         wl_event_source_timer_update(ec->idle_source, option_idle_time * 1000);
1904
1905         pixman_region32_init(&ec->damage);
1906         wlsc_compositor_schedule_repaint(ec);
1907
1908         return 0;
1909 }
1910
1911 static int on_term_signal(int signal_number, void *data)
1912 {
1913         struct wlsc_compositor *ec = data;
1914
1915         wl_display_terminate(ec->wl_display);
1916
1917         return 1;
1918 }
1919
1920 static void *
1921 load_module(const char *name, const char *entrypoint, void **handle)
1922 {
1923         char path[PATH_MAX];
1924         void *module, *init;
1925
1926         if (name[0] != '/')
1927                 snprintf(path, sizeof path, MODULEDIR "/%s", name);
1928         else
1929                 snprintf(path, sizeof path, "%s", name);
1930
1931         module = dlopen(path, RTLD_LAZY);
1932         if (!module) {
1933                 fprintf(stderr,
1934                         "failed to load module: %s\n", dlerror());
1935                 return NULL;
1936         }
1937
1938         init = dlsym(module, entrypoint);
1939         if (!init) {
1940                 fprintf(stderr,
1941                         "failed to lookup init function: %s\n", dlerror());
1942                 return NULL;
1943         }
1944
1945         return init;
1946 }
1947
1948 int main(int argc, char *argv[])
1949 {
1950         struct wl_display *display;
1951         struct wlsc_compositor *ec;
1952         struct wl_event_loop *loop;
1953         int o, xserver = 0;
1954         void *shell_module, *backend_module;
1955         int (*shell_init)(struct wlsc_compositor *ec);
1956         struct wlsc_compositor
1957                 *(*backend_init)(struct wl_display *display, char *options);
1958         char *backend = NULL;
1959         char *backend_options = "";
1960         char *shell = NULL;
1961         char *p;
1962
1963         static const char opts[] = "B:b:o:S:i:s:x";
1964         static const struct option longopts[ ] = {
1965                 { "backend", 1, NULL, 'B' },
1966                 { "backend-options", 1, NULL, 'o' },
1967                 { "background", 1, NULL, 'b' },
1968                 { "socket", 1, NULL, 'S' },
1969                 { "idle-time", 1, NULL, 'i' },
1970                 { "shell", 1, NULL, 's' },
1971                 { "xserver", 0, NULL, 'x' },
1972                 { NULL, }
1973         };
1974
1975         while (o = getopt_long(argc, argv, opts, longopts, &o), o > 0) {
1976                 switch (o) {
1977                 case 'b':
1978                         option_background = optarg;
1979                         break;
1980                 case 'B':
1981                         backend = optarg;
1982                         break;
1983                 case 'o':
1984                         backend_options = optarg;
1985                         break;
1986                 case 'S':
1987                         option_socket_name = optarg;
1988                         break;
1989                 case 'i':
1990                         option_idle_time = strtol(optarg, &p, 0);
1991                         if (*p != '\0') {
1992                                 fprintf(stderr,
1993                                         "invalid idle time option: %s\n",
1994                                         optarg);
1995                                 exit(EXIT_FAILURE);
1996                         }
1997                         break;
1998                 case 's':
1999                         shell = optarg;
2000                         break;
2001                 case 'x':
2002                         xserver = 1;
2003                         break;
2004                 }
2005         }
2006
2007         display = wl_display_create();
2008
2009         ec = NULL;
2010
2011         if (!backend) {
2012                 if (getenv("WAYLAND_DISPLAY"))
2013                         backend = "wayland-backend.so";
2014                 else if (getenv("DISPLAY"))
2015                         backend = "x11-backend.so";
2016                 else if (getenv("OPENWFD"))
2017                         backend = "openwfd-backend.so";
2018                 else
2019                         backend = "drm-backend.so";
2020         }
2021
2022         if (!shell)
2023                 shell = "desktop-shell.so";
2024
2025         backend_init = load_module(backend, "backend_init", &backend_module);
2026         if (!backend_init)
2027                 exit(EXIT_FAILURE);
2028
2029         shell_init = load_module(shell, "shell_init", &shell_module);
2030         if (!shell_init)
2031                 exit(EXIT_FAILURE);
2032
2033         ec = backend_init(display, backend_options);
2034         if (ec == NULL) {
2035                 fprintf(stderr, "failed to create compositor\n");
2036                 exit(EXIT_FAILURE);
2037         }
2038
2039         if (shell_init(ec) < 0)
2040                 exit(EXIT_FAILURE);
2041
2042         if (xserver)
2043                 wlsc_xserver_init(display);
2044
2045         if (wl_display_add_socket(display, option_socket_name)) {
2046                 fprintf(stderr, "failed to add socket: %m\n");
2047                 exit(EXIT_FAILURE);
2048         }
2049
2050         loop = wl_display_get_event_loop(ec->wl_display);
2051         wl_event_loop_add_signal(loop, SIGTERM, on_term_signal, ec);
2052         wl_event_loop_add_signal(loop, SIGINT, on_term_signal, ec);
2053
2054         wl_list_init(&child_process_list);
2055         wl_event_loop_add_signal(loop, SIGCHLD, sigchld_handler, NULL);
2056
2057         wl_display_run(display);
2058
2059         if (ec->has_bind_display)
2060                 ec->unbind_display(ec->display, display);
2061         wl_display_destroy(display);
2062
2063         ec->destroy(ec);
2064
2065         return 0;
2066 }