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