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