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