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