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