Use pixman regions to reduce repainting
[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 <stdarg.h>
28 #include <sys/ioctl.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <gdk-pixbuf/gdk-pixbuf.h>
32 #include <math.h>
33 #include <linux/input.h>
34
35 #include "wayland-server.h"
36 #include "compositor.h"
37
38 struct wlsc_switcher {
39         struct wlsc_compositor *compositor;
40         struct wlsc_surface *current;
41         struct wl_listener listener;
42 };
43
44 /* The plan here is to generate a random anonymous socket name and
45  * advertise that through a service on the session dbus.
46  */
47 static const char *option_socket_name = NULL;
48 static const char *option_background = "background.jpg";
49 static const char *option_geometry = "1024x640";
50 static int option_connector = 0;
51
52 static const GOptionEntry option_entries[] = {
53         { "background", 'b', 0, G_OPTION_ARG_STRING,
54           &option_background, "Background image" },
55         { "connector", 'c', 0, G_OPTION_ARG_INT,
56           &option_connector, "KMS connector" },
57         { "geometry", 'g', 0, G_OPTION_ARG_STRING,
58           &option_geometry, "Geometry" },
59         { "socket", 's', 0, G_OPTION_ARG_STRING,
60           &option_socket_name, "Socket Name" },
61         { NULL }
62 };
63
64 static void
65 wlsc_matrix_init(struct wlsc_matrix *matrix)
66 {
67         static const struct wlsc_matrix identity = {
68                 { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  0, 0, 0, 1 }
69         };
70
71         memcpy(matrix, &identity, sizeof identity);
72 }
73
74 static void
75 wlsc_matrix_multiply(struct wlsc_matrix *m, const struct wlsc_matrix *n)
76 {
77         struct wlsc_matrix tmp;
78         const GLfloat *row, *column;
79         div_t d;
80         int i, j;
81
82         for (i = 0; i < 16; i++) {
83                 tmp.d[i] = 0;
84                 d = div(i, 4);
85                 row = m->d + d.quot * 4;
86                 column = n->d + d.rem;
87                 for (j = 0; j < 4; j++)
88                         tmp.d[i] += row[j] * column[j * 4];
89         }
90         memcpy(m, &tmp, sizeof tmp);
91 }
92
93 static void
94 wlsc_matrix_translate(struct wlsc_matrix *matrix, GLfloat x, GLfloat y, GLfloat z)
95 {
96         struct wlsc_matrix translate = {
97                 { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 }
98         };
99
100         wlsc_matrix_multiply(matrix, &translate);
101 }
102
103 static void
104 wlsc_matrix_scale(struct wlsc_matrix *matrix, GLfloat x, GLfloat y, GLfloat z)
105 {
106         struct wlsc_matrix scale = {
107                 { x, 0, 0, 0,  0, y, 0, 0,  0, 0, z, 0,  0, 0, 0, 1 }
108         };
109
110         wlsc_matrix_multiply(matrix, &scale);
111 }
112
113 static void
114 wlsc_matrix_transform(struct wlsc_matrix *matrix, struct wlsc_vector *v)
115 {
116         int i, j;
117         struct wlsc_vector t;
118
119         for (i = 0; i < 4; i++) {
120                 t.f[i] = 0;
121                 for (j = 0; j < 4; j++)
122                         t.f[i] += v->f[j] * matrix->d[i + j * 4];
123         }
124
125         *v = t;
126 }
127
128 static struct wlsc_surface *
129 wlsc_surface_create(struct wlsc_compositor *compositor,
130                     int32_t x, int32_t y, int32_t width, int32_t height)
131 {
132         struct wlsc_surface *surface;
133
134         surface = malloc(sizeof *surface);
135         if (surface == NULL)
136                 return NULL;
137
138         wl_list_init(&surface->surface.destroy_listener_list);
139         wl_list_init(&surface->link);
140         surface->map_type = WLSC_SURFACE_MAP_UNMAPPED;
141
142         glGenTextures(1, &surface->texture);
143         glBindTexture(GL_TEXTURE_2D, surface->texture);
144         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
145         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
146         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
147         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
148
149         surface->compositor = compositor;
150         surface->visual = NULL;
151         surface->x = x;
152         surface->y = y;
153         surface->width = width;
154         surface->height = height;
155         wlsc_matrix_init(&surface->matrix);
156         wlsc_matrix_scale(&surface->matrix, width, height, 1);
157         wlsc_matrix_translate(&surface->matrix, x, y, 0);
158
159         wlsc_matrix_init(&surface->matrix_inv);
160         wlsc_matrix_translate(&surface->matrix_inv, -x, -y, 0);
161         wlsc_matrix_scale(&surface->matrix_inv, 1.0 / width, 1.0 / height, 1);
162
163         return surface;
164 }
165
166 void
167 wlsc_surface_damage_rectangle(struct wlsc_surface *surface,
168                               int32_t x, int32_t y,
169                               int32_t width, int32_t height)
170 {
171         struct wlsc_compositor *compositor = surface->compositor;
172
173         pixman_region32_union_rect(&compositor->damage_region,
174                                    &compositor->damage_region,
175                                    surface->x + x, surface->y + y,
176                                    width, height);
177         wlsc_compositor_schedule_repaint(compositor);
178 }
179
180 void
181 wlsc_surface_damage(struct wlsc_surface *surface)
182 {
183         wlsc_surface_damage_rectangle(surface, 0, 0,
184                                       surface->width, surface->height);
185 }
186
187 uint32_t
188 get_time(void)
189 {
190         struct timeval tv;
191
192         gettimeofday(&tv, NULL);
193
194         return tv.tv_sec * 1000 + tv.tv_usec / 1000;
195 }
196
197 static void
198 destroy_surface(struct wl_resource *resource, struct wl_client *client)
199 {
200         struct wlsc_surface *surface =
201                 container_of(resource, struct wlsc_surface, surface.resource);
202         struct wl_listener *l, *next;
203         uint32_t time;
204
205         wlsc_surface_damage(surface);
206
207         wl_list_remove(&surface->link);
208         glDeleteTextures(1, &surface->texture);
209
210         time = get_time();
211         wl_list_for_each_safe(l, next,
212                               &surface->surface.destroy_listener_list, link)
213                 l->func(l, &surface->surface, time);
214
215         free(surface);
216 }
217
218 uint32_t *
219 wlsc_load_image(const char *filename, int width, int height)
220 {
221         GdkPixbuf *pixbuf;
222         GError *error = NULL;
223         int stride, i, n_channels;
224         unsigned char *pixels, *end, *argb_pixels, *s, *d;
225
226         pixbuf = gdk_pixbuf_new_from_file_at_scale(filename,
227                                                    width, height,
228                                                    FALSE, &error);
229         if (error != NULL) {
230                 fprintf(stderr, "failed to load image: %s\n", error->message);
231                 g_error_free(error);
232                 return NULL;
233         }
234
235         stride = gdk_pixbuf_get_rowstride(pixbuf);
236         pixels = gdk_pixbuf_get_pixels(pixbuf);
237         n_channels = gdk_pixbuf_get_n_channels(pixbuf);
238
239         argb_pixels = malloc (height * width * 4);
240         if (argb_pixels == NULL) {
241                 g_object_unref(pixbuf);
242                 return NULL;
243         }
244
245         if (n_channels == 4) {
246                 for (i = 0; i < height; i++) {
247                         s = pixels + i * stride;
248                         end = s + width * 4;
249                         d = argb_pixels + i * width * 4;
250                         while (s < end) {
251                                 unsigned int t;
252
253 #define MULT(_d,c,a,t) \
254         do { t = c * a + 0x7f; _d = ((t >> 8) + t) >> 8; } while (0)
255                                 
256                                 MULT(d[0], s[2], s[3], t);
257                                 MULT(d[1], s[1], s[3], t);
258                                 MULT(d[2], s[0], s[3], t);
259                                 d[3] = s[3];
260                                 s += 4;
261                                 d += 4;
262                         }
263                 }
264         } else if (n_channels == 3) {
265                 for (i = 0; i < height; i++) {
266                         s = pixels + i * stride;
267                         end = s + width * 3;
268                         d = argb_pixels + i * width * 4;
269                         while (s < end) {
270                                 d[0] = s[2];
271                                 d[1] = s[1];
272                                 d[2] = s[0];
273                                 d[3] = 0xff;
274                                 s += 3;
275                                 d += 4;
276                         }
277                 }
278         }
279
280         g_object_unref(pixbuf);
281
282         return (uint32_t *) argb_pixels;
283 }
284
285 static struct wl_buffer *
286 create_buffer_from_png(struct wlsc_compositor *ec,
287                        const char *filename, int width, int height)
288 {
289         uint32_t *pixels;
290         struct wl_buffer *buffer;
291
292         pixels = wlsc_load_image(filename, width, height);
293         if(pixels == NULL)
294             return NULL;
295
296         buffer = ec->create_buffer(ec, width, height,
297                                    &ec->compositor.premultiplied_argb_visual,
298                                    pixels);
299
300         free(pixels);
301
302         return buffer;
303 }
304
305 static const struct {
306         const char *filename;
307         int hotspot_x, hotspot_y;
308 } pointer_images[] = {
309         { DATADIR "/wayland/bottom_left_corner.png",     6, 30 },
310         { DATADIR "/wayland/bottom_right_corner.png",   28, 28 },
311         { DATADIR "/wayland/bottom_side.png",           16, 20 },
312         { DATADIR "/wayland/grabbing.png",              20, 17 },
313         { DATADIR "/wayland/left_ptr.png",              10,  5 },
314         { DATADIR "/wayland/left_side.png",             10, 20 },
315         { DATADIR "/wayland/right_side.png",            30, 19 },
316         { DATADIR "/wayland/top_left_corner.png",        8,  8 },
317         { DATADIR "/wayland/top_right_corner.png",      26,  8 },
318         { DATADIR "/wayland/top_side.png",              18,  8 },
319         { DATADIR "/wayland/xterm.png",                 15, 15 }
320 };
321
322 static void
323 create_pointer_images(struct wlsc_compositor *ec)
324 {
325         int i, count;
326         const int width = 32, height = 32;
327
328         count = ARRAY_LENGTH(pointer_images);
329         ec->pointer_buffers = malloc(count * sizeof *ec->pointer_buffers);
330         for (i = 0; i < count; i++) {
331                 ec->pointer_buffers[i] =
332                         create_buffer_from_png(ec,
333                                                pointer_images[i].filename,
334                                                width, height);
335         }
336 }
337
338 static struct wlsc_surface *
339 background_create(struct wlsc_output *output, const char *filename)
340 {
341         struct wlsc_surface *background;
342         struct wl_buffer *buffer;
343
344         background = wlsc_surface_create(output->compositor,
345                                          output->x, output->y,
346                                          output->width, output->height);
347         if (background == NULL)
348                 return NULL;
349
350         buffer = create_buffer_from_png(output->compositor,
351                                         filename,
352                                         output->width, output->height);
353         if (buffer == NULL) {
354                 free(background);
355                 return NULL;
356         }
357         buffer->attach(buffer, &background->surface);
358
359         return background;
360 }
361
362 static void
363 wlsc_surface_draw(struct wlsc_surface *es, struct wlsc_output *output)
364 {
365         struct wlsc_compositor *ec = es->compositor;
366         struct wlsc_matrix tmp;
367
368         tmp = es->matrix;
369         wlsc_matrix_multiply(&tmp, &output->matrix);
370         glUniformMatrix4fv(ec->proj_uniform, 1, GL_FALSE, tmp.d);
371         glUniform1i(ec->tex_uniform, 0);
372
373         if (es->visual == &ec->compositor.argb_visual) {
374                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
375                 glEnable(GL_BLEND);
376         } else if (es->visual == &ec->compositor.premultiplied_argb_visual) {
377                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
378                 glEnable(GL_BLEND);
379         } else {
380                 glDisable(GL_BLEND);
381         }
382
383         glBindTexture(GL_TEXTURE_2D, es->texture);
384         glBindBuffer(GL_ARRAY_BUFFER, ec->vbo);
385         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
386                               5 * sizeof(GLfloat), NULL);
387         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE,
388                               5 * sizeof(GLfloat), (GLfloat *) 0 + 3);
389         glEnableVertexAttribArray(0);
390         glEnableVertexAttribArray(1);
391         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
392 }
393
394 static void
395 wlsc_surface_raise(struct wlsc_surface *surface)
396 {
397         struct wlsc_compositor *compositor = surface->compositor;
398
399         wl_list_remove(&surface->link);
400         wl_list_insert(&compositor->surface_list, &surface->link);
401 }
402
403 void
404 wlsc_surface_update_matrix(struct wlsc_surface *es)
405 {
406         wlsc_matrix_init(&es->matrix);
407         wlsc_matrix_scale(&es->matrix, es->width, es->height, 1);
408         wlsc_matrix_translate(&es->matrix, es->x, es->y, 0);
409
410         wlsc_matrix_init(&es->matrix_inv);
411         wlsc_matrix_translate(&es->matrix_inv, -es->x, -es->y, 0);
412         wlsc_matrix_scale(&es->matrix_inv,
413                           1.0 / es->width, 1.0 / es->height, 1);
414 }
415
416 void
417 wlsc_compositor_finish_frame(struct wlsc_compositor *compositor, int msecs)
418 {
419         wl_display_post_frame(compositor->wl_display, msecs);
420         wl_event_source_timer_update(compositor->timer_source, 5);
421         compositor->repaint_on_timeout = 1;
422 }
423
424 static void
425 wlsc_output_repaint(struct wlsc_output *output)
426 {
427         struct wlsc_compositor *ec = output->compositor;
428         struct wlsc_surface *es;
429         struct wlsc_input_device *eid;
430         pixman_region32_t new_damage, total_damage;
431         pixman_box32_t *extents;
432
433         glViewport(0, 0, output->width, output->height);
434
435         pixman_region32_init(&new_damage);
436         pixman_region32_init(&total_damage);
437         pixman_region32_intersect_rect(&new_damage,
438                                        &ec->damage_region,
439                                        output->x, output->y,
440                                        output->width, output->height);
441         pixman_region32_subtract(&ec->damage_region,
442                                  &ec->damage_region, &new_damage);
443         pixman_region32_union(&total_damage, &new_damage,
444                               &output->previous_damage_region);
445         pixman_region32_copy(&output->previous_damage_region, &new_damage);
446
447         extents = pixman_region32_extents(&total_damage);
448         glEnable(GL_SCISSOR_TEST);
449         glScissor(extents->x1, extents->y1,
450                   extents->x2 - extents->x1, extents->y2 - extents->y1);
451
452         es = container_of(ec->surface_list.next, struct wlsc_surface, link);
453         if (es->map_type == WLSC_SURFACE_MAP_FULLSCREEN &&
454             es->fullscreen_output == output) {
455                 if (es->width < output->width || es->height < output->height)
456                         glClear(GL_COLOR_BUFFER_BIT);
457                 wlsc_surface_draw(es, output);
458         } else {
459                 if (output->background)
460                         wlsc_surface_draw(output->background, output);
461                 else
462                         glClear(GL_COLOR_BUFFER_BIT);
463
464                 wl_list_for_each_reverse(es, &ec->surface_list, link) {
465                         if (ec->switcher &&
466                             ec->switcher->current == es)
467                                 continue;
468
469                         wlsc_surface_draw(es, output);
470                 }
471         }
472
473         if (ec->switcher)
474                 wlsc_surface_draw(ec->switcher->current, output);
475
476         if (ec->focus)
477                 wl_list_for_each(eid, &ec->input_device_list, link)
478                         wlsc_surface_draw(eid->sprite, output);
479 }
480
481 static void
482 repaint(void *data)
483 {
484         struct wlsc_compositor *ec = data;
485         struct wlsc_output *output;
486
487         if (!ec->repaint_needed) {
488                 ec->repaint_on_timeout = 0;
489                 return;
490         }
491
492         wl_list_for_each(output, &ec->output_list, link)
493                 wlsc_output_repaint(output);
494
495         ec->present(ec);
496
497         ec->repaint_needed = 0;
498 }
499
500 void
501 wlsc_compositor_schedule_repaint(struct wlsc_compositor *compositor)
502 {
503         compositor->repaint_needed = 1;
504         if (compositor->repaint_on_timeout)
505                 return;
506
507         wl_event_source_timer_update(compositor->timer_source, 1);
508         compositor->repaint_on_timeout = 1;
509 }
510
511 static void
512 surface_destroy(struct wl_client *client,
513                 struct wl_surface *surface)
514 {
515         wl_resource_destroy(&surface->resource, client);
516 }
517
518 static void
519 surface_attach(struct wl_client *client,
520                struct wl_surface *surface, struct wl_buffer *buffer,
521                int32_t x, int32_t y)
522 {
523         struct wlsc_surface *es = (struct wlsc_surface *) surface;
524
525         /* FIXME: This damages the entire old surface, but we should
526          * really just damage the part that's no longer covered by the
527          * surface.  Anything covered by the new surface will be
528          * damaged by the client. */
529         wlsc_surface_damage(es);
530
531         buffer->attach(buffer, surface);
532         es->buffer = buffer;
533         es->x += x;
534         es->y += y;
535         es->width = buffer->width;
536         es->height = buffer->height;
537         wlsc_surface_update_matrix(es);
538 }
539
540 static void
541 surface_map_toplevel(struct wl_client *client,
542                      struct wl_surface *surface)
543 {
544         struct wlsc_surface *es = (struct wlsc_surface *) surface;
545
546         switch (es->map_type) {
547         case WLSC_SURFACE_MAP_UNMAPPED:
548                 es->x = 10 + random() % 400;
549                 es->y = 10 + random() % 400;
550                 wlsc_surface_update_matrix(es);
551                 wl_list_insert(&es->compositor->surface_list, &es->link);
552                 break;
553         case WLSC_SURFACE_MAP_TOPLEVEL:
554                 return;
555         case WLSC_SURFACE_MAP_FULLSCREEN:
556                 es->fullscreen_output = NULL;
557                 es->x = es->saved_x;
558                 es->y = es->saved_y;
559                 wlsc_surface_update_matrix(es);
560                 break;
561         default:
562                 break;
563         }
564
565         wlsc_surface_damage(es);
566         es->map_type = WLSC_SURFACE_MAP_TOPLEVEL;
567 }
568
569 static void
570 surface_map_transient(struct wl_client *client,
571                       struct wl_surface *surface, struct wl_surface *parent,
572                       int x, int y, uint32_t flags)
573 {
574         struct wlsc_surface *es = (struct wlsc_surface *) surface;
575         struct wlsc_surface *pes = (struct wlsc_surface *) parent;
576
577         switch (es->map_type) {
578         case WLSC_SURFACE_MAP_UNMAPPED:
579                 wl_list_insert(&es->compositor->surface_list, &es->link);
580                 break;
581         case WLSC_SURFACE_MAP_FULLSCREEN:
582                 es->fullscreen_output = NULL;
583                 break;
584         default:
585                 break;
586         }
587
588         es->x = pes->x + x;
589         es->y = pes->y + y;
590
591         wlsc_surface_update_matrix(es);
592         wlsc_surface_damage(es);
593         es->map_type = WLSC_SURFACE_MAP_TRANSIENT;
594 }
595
596 static void
597 surface_map_fullscreen(struct wl_client *client, struct wl_surface *surface)
598 {
599         struct wlsc_surface *es = (struct wlsc_surface *) surface;
600         struct wlsc_output *output;
601
602         switch (es->map_type) {
603         case WLSC_SURFACE_MAP_UNMAPPED:
604                 es->x = 10 + random() % 400;
605                 es->y = 10 + random() % 400;
606                 wl_list_insert(&es->compositor->surface_list, &es->link);
607                 break;
608         case WLSC_SURFACE_MAP_FULLSCREEN:
609                 return;
610         default:
611                 break;
612         }
613
614         /* FIXME: Fullscreen on first output */
615         /* FIXME: Handle output going away */
616         output = container_of(es->compositor->output_list.next,
617                               struct wlsc_output, link);
618
619         es->saved_x = es->x;
620         es->saved_y = es->y;
621         es->x = (output->width - es->width) / 2;
622         es->y = (output->height - es->height) / 2;
623         es->fullscreen_output = output;
624         wlsc_surface_update_matrix(es);
625         wlsc_surface_damage(es);
626         es->map_type = WLSC_SURFACE_MAP_FULLSCREEN;
627 }
628
629 static void
630 surface_damage(struct wl_client *client,
631                struct wl_surface *surface,
632                int32_t x, int32_t y, int32_t width, int32_t height)
633 {
634         struct wlsc_surface *es = (struct wlsc_surface *) surface;
635
636         es->buffer->damage(es->buffer, surface, x, y, width, height);
637
638         wlsc_surface_damage_rectangle(es, x, y, width, height);
639 }
640
641 const static struct wl_surface_interface surface_interface = {
642         surface_destroy,
643         surface_attach,
644         surface_map_toplevel,
645         surface_map_transient,
646         surface_map_fullscreen,
647         surface_damage
648 };
649
650 static void
651 wlsc_input_device_attach(struct wlsc_input_device *device,
652                          struct wl_buffer *buffer, int x, int y)
653 {
654         wlsc_surface_damage(device->sprite);
655
656         buffer->attach(buffer, &device->sprite->surface);
657         device->hotspot_x = x;
658         device->hotspot_y = y;
659
660         device->sprite->x = device->input_device.x - device->hotspot_x;
661         device->sprite->y = device->input_device.y - device->hotspot_y;
662         device->sprite->width = buffer->width;
663         device->sprite->height = buffer->height;
664         wlsc_surface_update_matrix(device->sprite);
665
666         wlsc_surface_damage(device->sprite);
667 }
668
669
670 void
671 wlsc_input_device_set_pointer_image(struct wlsc_input_device *device,
672                                     enum wlsc_pointer_type type)
673 {
674         struct wlsc_compositor *compositor =
675                 (struct wlsc_compositor *) device->input_device.compositor;
676
677         wlsc_input_device_attach(device,
678                                  compositor->pointer_buffers[type],
679                                  pointer_images[type].hotspot_x,
680                                  pointer_images[type].hotspot_y);
681 }
682
683 static void
684 compositor_create_surface(struct wl_client *client,
685                           struct wl_compositor *compositor, uint32_t id)
686 {
687         struct wlsc_compositor *ec = (struct wlsc_compositor *) compositor;
688         struct wlsc_surface *surface;
689
690         surface = wlsc_surface_create(ec, 0, 0, 0, 0);
691         if (surface == NULL) {
692                 wl_client_post_no_memory(client);
693                 return;
694         }
695
696         surface->surface.resource.destroy = destroy_surface;
697
698         surface->surface.resource.object.id = id;
699         surface->surface.resource.object.interface = &wl_surface_interface;
700         surface->surface.resource.object.implementation =
701                 (void (**)(void)) &surface_interface;
702         surface->surface.client = client;
703
704         wl_client_add_resource(client, &surface->surface.resource);
705 }
706
707 const static struct wl_compositor_interface compositor_interface = {
708         compositor_create_surface,
709 };
710
711 static void
712 wlsc_surface_transform(struct wlsc_surface *surface,
713                        int32_t x, int32_t y, int32_t *sx, int32_t *sy)
714 {
715         struct wlsc_vector v = { { x, y, 0, 1 } };
716
717         wlsc_matrix_transform(&surface->matrix_inv, &v);
718         *sx = v.f[0] * surface->width;
719         *sy = v.f[1] * surface->height;
720 }
721
722 struct wlsc_surface *
723 pick_surface(struct wl_input_device *device, int32_t *sx, int32_t *sy)
724 {
725         struct wlsc_compositor *ec =
726                 (struct wlsc_compositor *) device->compositor;
727         struct wlsc_surface *es;
728
729         wl_list_for_each(es, &ec->surface_list, link) {
730                 wlsc_surface_transform(es, device->x, device->y, sx, sy);
731                 if (0 <= *sx && *sx < es->width &&
732                     0 <= *sy && *sy < es->height)
733                         return es;
734         }
735
736         return NULL;
737 }
738
739
740 static void
741 motion_grab_motion(struct wl_grab *grab,
742                    uint32_t time, int32_t x, int32_t y)
743 {
744         struct wlsc_input_device *device =
745                 (struct wlsc_input_device *) grab->input_device;
746         struct wlsc_surface *es =
747                 (struct wlsc_surface *) device->input_device.pointer_focus;
748         int32_t sx, sy;
749
750         wlsc_surface_transform(es, x, y, &sx, &sy);
751         wl_client_post_event(es->surface.client,
752                              &device->input_device.object,
753                              WL_INPUT_DEVICE_MOTION,
754                              time, x, y, sx, sy);
755 }
756
757 static void
758 motion_grab_button(struct wl_grab *grab,
759                    uint32_t time, int32_t button, int32_t state)
760 {
761         wl_client_post_event(grab->input_device->pointer_focus->client,
762                              &grab->input_device->object,
763                              WL_INPUT_DEVICE_BUTTON,
764                              time, button, state);
765 }
766
767 static void
768 motion_grab_end(struct wl_grab *grab, uint32_t time)
769 {
770 }
771
772 static const struct wl_grab_interface motion_grab_interface = {
773         motion_grab_motion,
774         motion_grab_button,
775         motion_grab_end
776 };
777
778 void
779 notify_motion(struct wl_input_device *device, uint32_t time, int x, int y)
780 {
781         struct wlsc_surface *es;
782         struct wlsc_compositor *ec =
783                 (struct wlsc_compositor *) device->compositor;
784         struct wlsc_output *output;
785         const struct wl_grab_interface *interface;
786         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
787         int32_t sx, sy;
788
789         /* FIXME: We need some multi head love here. */
790         output = container_of(ec->output_list.next, struct wlsc_output, link);
791         if (x < output->x)
792                 x = 0;
793         if (y < output->y)
794                 y = 0;
795         if (x >= output->x + output->width)
796                 x = output->x + output->width - 1;
797         if (y >= output->y + output->height)
798                 y = output->y + output->height - 1;
799
800         device->x = x;
801         device->y = y;
802
803         if (device->grab) {
804                 interface = device->grab->interface;
805                 interface->motion(device->grab, time, x, y);
806         } else {
807                 es = pick_surface(device, &sx, &sy);
808                 wl_input_device_set_pointer_focus(device,
809                                                   &es->surface,
810                                                   time, x, y, sx, sy);
811                 if (es)
812                         wl_client_post_event(es->surface.client,
813                                              &device->object,
814                                              WL_INPUT_DEVICE_MOTION,
815                                              time, x, y, sx, sy);
816         }
817
818         wlsc_surface_damage(wd->sprite);
819
820         wd->sprite->x = device->x - wd->hotspot_x;
821         wd->sprite->y = device->y - wd->hotspot_y;
822         wlsc_surface_update_matrix(wd->sprite);
823
824         wlsc_surface_damage(wd->sprite);
825 }
826
827 static void
828 wlsc_surface_activate(struct wlsc_surface *surface,
829                       struct wlsc_input_device *device, uint32_t time)
830 {
831         wlsc_surface_raise(surface);
832         if (device->selection)
833                 wlsc_selection_set_focus(device->selection,
834                                          &surface->surface, time);
835
836         wl_input_device_set_keyboard_focus(&device->input_device,
837                                            &surface->surface,
838                                            time);
839 }
840
841 void
842 notify_button(struct wl_input_device *device,
843               uint32_t time, int32_t button, int32_t state)
844 {
845         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
846         struct wlsc_surface *surface;
847         struct wlsc_compositor *compositor =
848                 (struct wlsc_compositor *) device->compositor;
849
850         surface = (struct wlsc_surface *) device->pointer_focus;
851         uint32_t edges = 0;
852         int32_t x, y;
853
854         if (state && surface && device->grab == NULL) {
855                 wlsc_surface_activate(surface, wd, time);
856                 wl_input_device_start_grab(device,
857                                            &device->motion_grab,
858                                            button, time);
859         }
860
861         if (state && surface && button == BTN_LEFT &&
862             (wd->modifier_state & MODIFIER_SUPER))
863                 shell_move(NULL,
864                            (struct wl_shell *) &compositor->shell,
865                            &surface->surface, device, time);
866         else if (state && surface && button == BTN_MIDDLE &&
867                  (wd->modifier_state & MODIFIER_SUPER)) {
868
869                 x = device->grab_x - surface->x;
870                 y = device->grab_y - surface->y;
871
872                 if (x < surface->width / 3)
873                         edges |= WL_SHELL_RESIZE_LEFT;
874                 else if (x < 2 * surface->width / 3)
875                         edges |= 0;
876                 else
877                         edges |= WL_SHELL_RESIZE_RIGHT;
878
879                 if (y < surface->height / 3)
880                         edges |= WL_SHELL_RESIZE_TOP;
881                 else if (y < 2 * surface->height / 3)
882                         edges |= 0;
883                 else
884                         edges |= WL_SHELL_RESIZE_BOTTOM;
885
886                 shell_resize(NULL,
887                              (struct wl_shell *) &compositor->shell,
888                              &surface->surface, device, time, edges);
889         }
890
891         if (device->grab)
892                 device->grab->interface->button(device->grab, time,
893                                                 button, state);
894
895         if (!state && device->grab && device->grab_button == button)
896                 wl_input_device_end_grab(device, time);
897 }
898
899 static void
900 wlsc_switcher_next(struct wlsc_switcher *switcher)
901 {
902         struct wl_list *l;
903
904         wlsc_surface_damage(switcher->current);
905         l = switcher->current->link.next;
906         if (l == &switcher->compositor->surface_list)
907                 l = switcher->compositor->surface_list.next;
908         switcher->current = container_of(l, struct wlsc_surface, link);
909         wl_list_remove(&switcher->listener.link);
910         wl_list_insert(switcher->current->surface.destroy_listener_list.prev,
911                        &switcher->listener.link);
912         wlsc_surface_damage(switcher->current);
913 }
914
915 static void
916 switcher_handle_surface_destroy(struct wl_listener *listener,
917                                 struct wl_surface *surface, uint32_t time)
918 {
919         struct wlsc_switcher *switcher =
920                 container_of(listener, struct wlsc_switcher, listener);
921
922         wlsc_switcher_next(switcher);
923 }
924
925 static struct wlsc_switcher *
926 wlsc_switcher_create(struct wlsc_compositor *compositor)
927 {
928         struct wlsc_switcher *switcher;
929
930         switcher = malloc(sizeof *switcher);
931         switcher->compositor = compositor;
932         switcher->current = container_of(compositor->surface_list.next,
933                                          struct wlsc_surface, link);
934         switcher->listener.func = switcher_handle_surface_destroy;
935         wl_list_init(&switcher->listener.link);
936
937         return switcher;
938 }
939
940 static void
941 wlsc_switcher_destroy(struct wlsc_switcher *switcher)
942 {
943         wl_list_remove(&switcher->listener.link);
944         free(switcher);
945 }
946
947 void
948 notify_key(struct wl_input_device *device,
949            uint32_t time, uint32_t key, uint32_t state)
950 {
951         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
952         struct wlsc_compositor *compositor =
953                 (struct wlsc_compositor *) device->compositor;
954         uint32_t *k, *end;
955         uint32_t modifier;
956
957         switch (key | wd->modifier_state) {
958         case KEY_BACKSPACE | MODIFIER_CTRL | MODIFIER_ALT:
959                 wl_display_terminate(compositor->wl_display);
960                 return;
961
962         case KEY_TAB | MODIFIER_SUPER:
963                 if (!state)
964                         return;
965                 if (wl_list_empty(&compositor->surface_list))
966                         return;
967                 if (compositor->switcher == NULL)
968                         compositor->switcher = wlsc_switcher_create(compositor);
969
970                 wlsc_switcher_next(compositor->switcher);
971                 return;
972
973         case KEY_LEFTMETA | MODIFIER_SUPER:
974         case KEY_RIGHTMETA | MODIFIER_SUPER:
975                 if (compositor->switcher && !state) {
976                         wlsc_surface_activate(compositor->switcher->current,
977                                               wd, time);
978                         wlsc_switcher_destroy(compositor->switcher);
979                         compositor->switcher = NULL;
980                 }
981                 break;
982         }
983
984         switch (key) {
985         case KEY_LEFTCTRL:
986         case KEY_RIGHTCTRL:
987                 modifier = MODIFIER_CTRL;
988                 break;
989
990         case KEY_LEFTALT:
991         case KEY_RIGHTALT:
992                 modifier = MODIFIER_ALT;
993                 break;
994
995         case KEY_LEFTMETA:
996         case KEY_RIGHTMETA:
997                 modifier = MODIFIER_SUPER;
998                 break;
999
1000         default:
1001                 modifier = 0;
1002                 break;
1003         }
1004
1005         if (state)
1006                 wd->modifier_state |= modifier;
1007         else
1008                 wd->modifier_state &= ~modifier;
1009
1010         end = device->keys.data + device->keys.size;
1011         for (k = device->keys.data; k < end; k++) {
1012                 if (*k == key)
1013                         *k = *--end;
1014         }
1015         device->keys.size = (void *) end - device->keys.data;
1016         if (state) {
1017                 k = wl_array_add(&device->keys, sizeof *k);
1018                 *k = key;
1019         }
1020
1021         if (device->keyboard_focus != NULL)
1022                 wl_client_post_event(device->keyboard_focus->client,
1023                                      &device->object,
1024                                      WL_INPUT_DEVICE_KEY, time, key, state);
1025 }
1026
1027 void
1028 notify_pointer_focus(struct wl_input_device *device,
1029                      uint32_t time, struct wlsc_output *output,
1030                      int32_t x, int32_t y)
1031 {
1032         struct wlsc_input_device *wd = (struct wlsc_input_device *) device;
1033         struct wlsc_compositor *compositor =
1034                 (struct wlsc_compositor *) device->compositor;
1035         struct wlsc_surface *es;
1036         int32_t sx, sy;
1037
1038         if (output) {
1039                 device->x = x;
1040                 device->y = y;
1041                 es = pick_surface(device, &sx, &sy);
1042                 wl_input_device_set_pointer_focus(device,
1043                                                   &es->surface,
1044                                                   time, x, y, sx, sy);
1045
1046                 compositor->focus = 1;
1047
1048                 wd->sprite->x = device->x - wd->hotspot_x;
1049                 wd->sprite->y = device->y - wd->hotspot_y;
1050                 wlsc_surface_update_matrix(wd->sprite);
1051         } else {
1052                 wl_input_device_set_pointer_focus(device, NULL,
1053                                                   time, 0, 0, 0, 0);
1054                 compositor->focus = 0;
1055         }
1056
1057         wlsc_surface_damage(wd->sprite);
1058 }
1059
1060 void
1061 notify_keyboard_focus(struct wl_input_device *device,
1062                       uint32_t time, struct wlsc_output *output,
1063                       struct wl_array *keys)
1064 {
1065         struct wlsc_input_device *wd =
1066                 (struct wlsc_input_device *) device;
1067         struct wlsc_compositor *compositor =
1068                 (struct wlsc_compositor *) device->compositor;
1069         struct wlsc_surface *es;
1070
1071         if (!wl_list_empty(&compositor->surface_list))
1072                 es = container_of(compositor->surface_list.next,
1073                                   struct wlsc_surface, link);
1074         else
1075                 es = NULL;
1076
1077         if (output) {
1078                 wl_array_copy(&wd->input_device.keys, keys);
1079                 wl_input_device_set_keyboard_focus(&wd->input_device,
1080                                                    &es->surface, time);
1081         } else {
1082                 wl_input_device_set_keyboard_focus(&wd->input_device,
1083                                                    NULL, time);
1084         }
1085 }
1086
1087
1088 static void
1089 input_device_attach(struct wl_client *client,
1090                     struct wl_input_device *device_base,
1091                     uint32_t time,
1092                     struct wl_buffer *buffer, int32_t x, int32_t y)
1093 {
1094         struct wlsc_input_device *device =
1095                 (struct wlsc_input_device *) device_base;
1096
1097         if (time < device->input_device.pointer_focus_time)
1098                 return;
1099         if (device->input_device.pointer_focus == NULL)
1100                 return;
1101         if (device->input_device.pointer_focus->client != client)
1102                 return;
1103
1104         if (buffer == NULL) {
1105                 wlsc_input_device_set_pointer_image(device,
1106                                                     WLSC_POINTER_LEFT_PTR);
1107                 return;
1108         }
1109
1110         wlsc_input_device_attach(device, buffer, x, y);
1111 }
1112
1113 const static struct wl_input_device_interface input_device_interface = {
1114         input_device_attach,
1115 };
1116
1117 void
1118 wlsc_input_device_init(struct wlsc_input_device *device,
1119                        struct wlsc_compositor *ec)
1120 {
1121         wl_input_device_init(&device->input_device, &ec->compositor);
1122
1123         device->input_device.object.interface = &wl_input_device_interface;
1124         device->input_device.object.implementation =
1125                 (void (**)(void)) &input_device_interface;
1126         wl_display_add_object(ec->wl_display, &device->input_device.object);
1127         wl_display_add_global(ec->wl_display, &device->input_device.object, NULL);
1128
1129         device->sprite = wlsc_surface_create(ec,
1130                                              device->input_device.x,
1131                                              device->input_device.y, 32, 32);
1132         device->hotspot_x = 16;
1133         device->hotspot_y = 16;
1134
1135         device->input_device.motion_grab.interface = &motion_grab_interface;
1136
1137         wl_list_insert(ec->input_device_list.prev, &device->link);
1138
1139         wlsc_input_device_set_pointer_image(device, WLSC_POINTER_LEFT_PTR);
1140 }
1141
1142 static void
1143 wlsc_output_post_geometry(struct wl_client *client, struct wl_object *global)
1144 {
1145         struct wlsc_output *output =
1146                 container_of(global, struct wlsc_output, object);
1147
1148         wl_client_post_event(client, global,
1149                              WL_OUTPUT_GEOMETRY,
1150                              output->x, output->y,
1151                              output->width, output->height);
1152 }
1153
1154 static const char vertex_shader[] =
1155         "uniform mat4 proj;\n"
1156         "attribute vec4 position;\n"
1157         "attribute vec2 texcoord;\n"
1158         "varying vec2 v_texcoord;\n"
1159         "void main()\n"
1160         "{\n"
1161         "   gl_Position = proj * position;\n"
1162         "   v_texcoord = texcoord;\n"
1163         "}\n";
1164
1165 static const char fragment_shader[] =
1166         "precision mediump float;\n"
1167         "varying vec2 v_texcoord;\n"
1168         "uniform sampler2D tex;\n"
1169         "void main()\n"
1170         "{\n"
1171         "   gl_FragColor = texture2D(tex, v_texcoord)\n;"
1172         "}\n";
1173
1174 static int
1175 init_shaders(struct wlsc_compositor *ec)
1176 {
1177         GLuint v, f, program;
1178         const char *p;
1179         char msg[512];
1180         GLfloat vertices[4 * 5];
1181         GLint status;
1182
1183         p = vertex_shader;
1184         v = glCreateShader(GL_VERTEX_SHADER);
1185         glShaderSource(v, 1, &p, NULL);
1186         glCompileShader(v);
1187         glGetShaderiv(v, GL_COMPILE_STATUS, &status);
1188         if (!status) {
1189                 glGetShaderInfoLog(v, sizeof msg, NULL, msg);
1190                 fprintf(stderr, "vertex shader info: %s\n", msg);
1191                 return -1;
1192         }
1193
1194         p = fragment_shader;
1195         f = glCreateShader(GL_FRAGMENT_SHADER);
1196         glShaderSource(f, 1, &p, NULL);
1197         glCompileShader(f);
1198         glGetShaderiv(f, GL_COMPILE_STATUS, &status);
1199         if (!status) {
1200                 glGetShaderInfoLog(f, sizeof msg, NULL, msg);
1201                 fprintf(stderr, "fragment shader info: %s\n", msg);
1202                 return -1;
1203         }
1204
1205         program = glCreateProgram();
1206         glAttachShader(program, v);
1207         glAttachShader(program, f);
1208         glBindAttribLocation(program, 0, "position");
1209         glBindAttribLocation(program, 1, "texcoord");
1210
1211         glLinkProgram(program);
1212         glGetProgramiv(program, GL_LINK_STATUS, &status);
1213         if (!status) {
1214                 glGetProgramInfoLog(program, sizeof msg, NULL, msg);
1215                 fprintf(stderr, "link info: %s\n", msg);
1216                 return -1;
1217         }
1218
1219         glUseProgram(program);
1220         ec->proj_uniform = glGetUniformLocation(program, "proj");
1221         ec->tex_uniform = glGetUniformLocation(program, "tex");
1222
1223         vertices[ 0] = 0.0;
1224         vertices[ 1] = 0.0;
1225         vertices[ 2] = 0.0;
1226         vertices[ 3] = 0.0;
1227         vertices[ 4] = 0.0;
1228
1229         vertices[ 5] = 0.0;
1230         vertices[ 6] = 1.0;
1231         vertices[ 7] = 0.0;
1232         vertices[ 8] = 0.0;
1233         vertices[ 9] = 1.0;
1234
1235         vertices[10] = 1.0;
1236         vertices[11] = 0.0;
1237         vertices[12] = 0.0;
1238         vertices[13] = 1.0;
1239         vertices[14] = 0.0;
1240
1241         vertices[15] = 1.0;
1242         vertices[16] = 1.0;
1243         vertices[17] = 0.0;
1244         vertices[18] = 1.0;
1245         vertices[19] = 1.0;
1246
1247         glGenBuffers(1, &ec->vbo);
1248         glBindBuffer(GL_ARRAY_BUFFER, ec->vbo);
1249         glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
1250
1251         return 0;
1252 }
1253
1254 void
1255 wlsc_output_init(struct wlsc_output *output, struct wlsc_compositor *c,
1256                  int x, int y, int width, int height)
1257 {
1258         output->compositor = c;
1259         output->x = x;
1260         output->y = y;
1261         output->width = width;
1262         output->height = height;
1263
1264         pixman_region32_init(&output->previous_damage_region);
1265
1266         output->background =
1267                 background_create(output, option_background);
1268
1269         wlsc_matrix_init(&output->matrix);
1270         wlsc_matrix_translate(&output->matrix,
1271                               -output->x - output->width / 2.0,
1272                               -output->y - output->height / 2.0, 0);
1273         wlsc_matrix_scale(&output->matrix,
1274                           2.0 / output->width, 2.0 / output->height, 1);
1275
1276         output->object.interface = &wl_output_interface;
1277         wl_display_add_object(c->wl_display, &output->object);
1278         wl_display_add_global(c->wl_display, &output->object,
1279                               wlsc_output_post_geometry);
1280
1281         pixman_region32_union_rect(&c->damage_region,
1282                                    &c->damage_region,
1283                                    x, y, width, height);
1284 }
1285
1286 int
1287 wlsc_compositor_init(struct wlsc_compositor *ec, struct wl_display *display)
1288 {
1289         struct wl_event_loop *loop;
1290         const char *extensions;
1291
1292         ec->wl_display = display;
1293
1294         wl_compositor_init(&ec->compositor, &compositor_interface, display);
1295
1296         wlsc_shm_init(ec);
1297
1298         wlsc_shell_init(ec);
1299
1300         wl_list_init(&ec->surface_list);
1301         wl_list_init(&ec->input_device_list);
1302         wl_list_init(&ec->output_list);
1303
1304         create_pointer_images(ec);
1305
1306         screenshooter_create(ec);
1307
1308         extensions = (const char *) glGetString(GL_EXTENSIONS);
1309         if (!strstr(extensions, "GL_EXT_texture_format_BGRA8888")) {
1310                 fprintf(stderr,
1311                         "GL_EXT_texture_format_BGRA8888 not available\n");
1312                 return -1;
1313         }
1314
1315         glGenFramebuffers(1, &ec->fbo);
1316         glBindFramebuffer(GL_FRAMEBUFFER, ec->fbo);
1317         glActiveTexture(GL_TEXTURE0);
1318         if (init_shaders(ec) < 0)
1319                 return -1;
1320
1321         loop = wl_display_get_event_loop(ec->wl_display);
1322         ec->timer_source = wl_event_loop_add_timer(loop, repaint, ec);
1323         pixman_region32_init(&ec->damage_region);
1324         wlsc_compositor_schedule_repaint(ec);
1325
1326         return 0;
1327 }
1328
1329 static void on_term_signal(int signal_number, void *data)
1330 {
1331         struct wlsc_compositor *ec = data;
1332
1333         wl_display_terminate(ec->wl_display);
1334 }
1335
1336 int main(int argc, char *argv[])
1337 {
1338         struct wl_display *display;
1339         struct wlsc_compositor *ec;
1340         struct wl_event_loop *loop;
1341         GError *error = NULL;
1342         GOptionContext *context;
1343         int width, height;
1344
1345         g_type_init(); /* GdkPixbuf needs this, it seems. */
1346
1347         context = g_option_context_new(NULL);
1348         g_option_context_add_main_entries(context, option_entries, "Wayland");
1349         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1350                 fprintf(stderr, "option parsing failed: %s\n", error->message);
1351                 exit(EXIT_FAILURE);
1352         }
1353         if (sscanf(option_geometry, "%dx%d", &width, &height) != 2) {
1354                 fprintf(stderr, "invalid geometry option: %s \n",
1355                         option_geometry);
1356                 exit(EXIT_FAILURE);
1357         }
1358
1359         display = wl_display_create();
1360
1361         ec = NULL;
1362
1363 #if BUILD_WAYLAND_COMPOSITOR
1364         if (getenv("WAYLAND_DISPLAY"))
1365                 ec = wayland_compositor_create(display, width, height);
1366 #endif
1367
1368 #if BUILD_X11_COMPOSITOR
1369         if (ec == NULL && getenv("DISPLAY"))
1370                 ec = x11_compositor_create(display, width, height);
1371 #endif
1372
1373 #if BUILD_DRM_COMPOSITOR
1374         if (ec == NULL)
1375                 ec = drm_compositor_create(display, option_connector);
1376 #endif
1377
1378         if (ec == NULL) {
1379                 fprintf(stderr, "failed to create compositor\n");
1380                 exit(EXIT_FAILURE);
1381         }
1382
1383         if (wl_display_add_socket(display, option_socket_name)) {
1384                 fprintf(stderr, "failed to add socket: %m\n");
1385                 exit(EXIT_FAILURE);
1386         }
1387
1388         loop = wl_display_get_event_loop(ec->wl_display);
1389         wl_event_loop_add_signal(loop, SIGTERM, on_term_signal, ec);
1390         wl_event_loop_add_signal(loop, SIGINT, on_term_signal, ec);
1391
1392         wl_display_run(display);
1393
1394         wl_display_destroy(display);
1395
1396         ec->destroy(ec);
1397
1398         return 0;
1399 }