805d54ffba6560e8023b0e46c6dce855f5df9d40
[profile/ivi/wayland.git] / 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 #include <stdio.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <stdint.h>
23 #include <stdarg.h>
24 #include <termios.h>
25 #include <sys/ioctl.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <cairo.h>
29 #include <gdk-pixbuf/gdk-pixbuf.h>
30 #include <math.h>
31 #include <linux/input.h>
32 #include <linux/vt.h>
33 #include <xf86drm.h>
34 #include <xf86drmMode.h>
35 #include <time.h>
36
37 #define LIBUDEV_I_KNOW_THE_API_IS_SUBJECT_TO_CHANGE
38 #include <libudev.h>
39
40 #define GL_GLEXT_PROTOTYPES
41 #define EGL_EGLEXT_PROTOTYPES
42 #include <GLES2/gl2.h>
43 #include <GLES2/gl2ext.h>
44 #include <EGL/egl.h>
45 #include <EGL/eglext.h>
46
47 #include "wayland.h"
48 #include "wayland-protocol.h"
49 #include "cairo-util.h"
50 #include "compositor.h"
51
52 #define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0])
53
54 struct wlsc_matrix {
55         GLfloat d[16];
56 };
57
58 struct wl_visual {
59         struct wl_object base;
60 };
61
62 struct wlsc_surface;
63
64 struct wlsc_listener {
65         struct wl_list link;
66         void (*func)(struct wlsc_listener *listener,
67                      struct wlsc_surface *surface);
68 };
69
70 struct wlsc_output {
71         struct wl_object base;
72         struct wl_list link;
73         struct wlsc_compositor *compositor;
74         struct wlsc_surface *background;
75         struct wlsc_matrix matrix;
76         int32_t x, y, width, height;
77
78         drmModeModeInfo mode;
79         uint32_t crtc_id;
80         uint32_t connector_id;
81
82         GLuint rbo[2];
83         uint32_t fb_id[2];
84         EGLImageKHR image[2];
85         uint32_t current;       
86 };
87
88 struct wlsc_input_device {
89         struct wl_object base;
90         int32_t x, y;
91         struct wlsc_compositor *ec;
92         struct wlsc_surface *sprite;
93         struct wl_list link;
94
95         int grab;
96         struct wlsc_surface *grab_surface;
97         struct wlsc_surface *pointer_focus;
98         struct wlsc_surface *keyboard_focus;
99         struct wl_array keys;
100
101         struct wlsc_listener listener;
102 };
103
104 struct wlsc_compositor {
105         struct wl_compositor base;
106         struct wl_visual argb_visual, premultiplied_argb_visual, rgb_visual;
107
108         EGLDisplay display;
109         EGLContext context;
110         int drm_fd;
111         GLuint fbo, vbo;
112         GLuint proj_uniform, tex_uniform;
113         struct wl_display *wl_display;
114
115         struct wl_list output_list;
116         struct wl_list input_device_list;
117         struct wl_list surface_list;
118
119         struct wl_list surface_destroy_listener_list;
120
121         struct wl_event_source *term_signal_source;
122
123         /* tty handling state */
124         int tty_fd;
125         uint32_t vt_active : 1;
126
127         struct termios terminal_attributes;
128         struct wl_event_source *tty_input_source;
129         struct wl_event_source *enter_vt_source;
130         struct wl_event_source *leave_vt_source;
131
132         struct udev *udev;
133
134         /* Repaint state. */
135         struct wl_event_source *timer_source;
136         int repaint_needed;
137         int repaint_on_timeout;
138         struct timespec previous_swap;
139         uint32_t current_frame;
140         struct wl_event_source *drm_source;
141
142         uint32_t modifier_state;
143 };
144
145 #define MODIFIER_CTRL   (1 << 8)
146 #define MODIFIER_ALT    (1 << 9)
147
148 struct wlsc_vector {
149         GLfloat f[4];
150 };
151
152 struct wlsc_surface {
153         struct wl_surface base;
154         struct wlsc_compositor *compositor;
155         struct wl_visual *visual;
156         GLuint texture;
157         EGLImageKHR image;
158         int width, height;
159         struct wl_list link;
160         struct wlsc_matrix matrix;
161         struct wlsc_matrix matrix_inv;
162 };
163
164 static const char *option_background = "background.jpg";
165 static int option_connector = 0;
166
167 static const GOptionEntry option_entries[] = {
168         { "background", 'b', 0, G_OPTION_ARG_STRING,
169           &option_background, "Background image" },
170         { "connector", 'c', 0, G_OPTION_ARG_INT,
171           &option_connector, "KMS connector" },
172         { NULL }
173 };
174
175 struct screenshooter {
176         struct wl_object base;
177         struct wlsc_compositor *ec;
178 };
179
180 struct screenshooter_interface {
181         void (*shoot)(struct wl_client *client, struct screenshooter *shooter);
182 };
183
184 static void
185 screenshooter_shoot(struct wl_client *client, struct screenshooter *shooter)
186 {
187         struct wlsc_compositor *ec = shooter->ec;
188         struct wlsc_output *output;
189         char buffer[256];
190         GdkPixbuf *pixbuf, *normal;
191         GError *error = NULL;
192         unsigned char *data;
193         int i, j;
194
195         i = 0;
196         wl_list_for_each(output, &ec->output_list, link) {
197                 snprintf(buffer, sizeof buffer, "wayland-screenshot-%d.png", i++);
198                 data = malloc(output->width * output->height * 4);
199                 if (data == NULL) {
200                         fprintf(stderr, "couldn't allocate image buffer\n");
201                         continue;
202                 }
203
204                 glPixelStorei(GL_PACK_ALIGNMENT, 1);
205                 glReadPixels(0, 0, output->width, output->height,
206                              GL_RGBA, GL_UNSIGNED_BYTE, data);
207
208                 /* FIXME: We should just use a RGB visual for the frontbuffer. */
209                 for (j = 3; j < output->width * output->height * 4; j += 4)
210                         data[j] = 0xff;
211
212                 pixbuf = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE,
213                                                   8, output->width, output->height, output->width * 4,
214                                                   NULL, NULL);
215                 normal = gdk_pixbuf_flip(pixbuf, FALSE);
216                 gdk_pixbuf_save(normal, buffer, "png", &error, NULL);
217                 gdk_pixbuf_unref(normal);
218                 gdk_pixbuf_unref(pixbuf);
219                 free(data);
220         }
221 }
222
223 static const struct wl_message screenshooter_methods[] = {
224         { "shoot", "", NULL }
225 };
226
227 static const struct wl_interface screenshooter_interface = {
228         "screenshooter", 1,
229         ARRAY_LENGTH(screenshooter_methods),
230         screenshooter_methods,
231 };
232
233 struct screenshooter_interface screenshooter_implementation = {
234         screenshooter_shoot
235 };
236
237 static struct screenshooter *
238 screenshooter_create(struct wlsc_compositor *ec)
239 {
240         struct screenshooter *shooter;
241
242         shooter = malloc(sizeof *shooter);
243         if (shooter == NULL)
244                 return NULL;
245
246         shooter->base.interface = &screenshooter_interface;
247         shooter->base.implementation = (void(**)(void)) &screenshooter_implementation;
248         shooter->ec = ec;
249
250         return shooter;
251 };
252                                    
253 static void
254 wlsc_matrix_init(struct wlsc_matrix *matrix)
255 {
256         static const struct wlsc_matrix identity = {
257                 { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  0, 0, 0, 1 }
258         };
259
260         memcpy(matrix, &identity, sizeof identity);
261 }
262
263 static void
264 wlsc_matrix_multiply(struct wlsc_matrix *m, const struct wlsc_matrix *n)
265 {
266         struct wlsc_matrix tmp;
267         const GLfloat *row, *column;
268         div_t d;
269         int i, j;
270
271         for (i = 0; i < 16; i++) {
272                 tmp.d[i] = 0;
273                 d = div(i, 4);
274                 row = m->d + d.quot * 4;
275                 column = n->d + d.rem;
276                 for (j = 0; j < 4; j++)
277                         tmp.d[i] += row[j] * column[j * 4];
278         }
279         memcpy(m, &tmp, sizeof tmp);
280 }
281
282 static void
283 wlsc_matrix_translate(struct wlsc_matrix *matrix, GLfloat x, GLfloat y, GLfloat z)
284 {
285         struct wlsc_matrix translate = {        
286                 { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 }
287         };
288
289         wlsc_matrix_multiply(matrix, &translate);
290 }
291
292 static void
293 wlsc_matrix_scale(struct wlsc_matrix *matrix, GLfloat x, GLfloat y, GLfloat z)
294 {
295         struct wlsc_matrix scale = {
296                 { x, 0, 0, 0,  0, y, 0, 0,  0, 0, z, 0,  0, 0, 0, 1 }
297         };
298
299         wlsc_matrix_multiply(matrix, &scale);
300 }
301
302 static void
303 wlsc_matrix_rotate(struct wlsc_matrix *matrix,
304                    GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
305 {
306         GLfloat c = cos(angle);
307         GLfloat s = sin(angle);
308         struct wlsc_matrix rotate = {
309                 { x * x * (1 - c) + c,     y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
310                   x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0, 
311                   x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c,     0,
312                   0, 0, 0, 1 }
313         };
314
315         wlsc_matrix_multiply(matrix, &rotate);
316 }
317
318 static void
319 wlsc_matrix_transform(struct wlsc_matrix *matrix, struct wlsc_vector *v)
320 {
321         int i, j;
322         struct wlsc_vector t;
323
324         for (i = 0; i < 4; i++) {
325                 t.f[i] = 0;
326                 for (j = 0; j < 4; j++)
327                         t.f[i] += v->f[j] * matrix->d[i + j * 4];
328         }
329         
330         *v = t;
331 }
332
333 static void
334 wlsc_surface_init(struct wlsc_surface *surface,
335                   struct wlsc_compositor *compositor, struct wl_visual *visual,
336                   int32_t x, int32_t y, int32_t width, int32_t height)
337 {
338         glGenTextures(1, &surface->texture);
339         surface->compositor = compositor;
340         surface->visual = visual;
341         wlsc_matrix_init(&surface->matrix);
342         wlsc_matrix_scale(&surface->matrix, width, height, 1);
343         wlsc_matrix_translate(&surface->matrix, x, y, 0);
344
345         wlsc_matrix_init(&surface->matrix_inv);
346         wlsc_matrix_translate(&surface->matrix_inv, -x, -y, 0);
347         wlsc_matrix_scale(&surface->matrix_inv, 1.0 / width, 1.0 / height, 1);
348 }
349
350 static struct wlsc_surface *
351 wlsc_surface_create_from_cairo_surface(struct wlsc_compositor *ec,
352                                       cairo_surface_t *surface,
353                                       int x, int y, int width, int height)
354 {
355         struct wlsc_surface *es;
356         int stride;
357         void *data;
358
359         stride = cairo_image_surface_get_stride(surface);
360         data = cairo_image_surface_get_data(surface);
361
362         es = malloc(sizeof *es);
363         if (es == NULL)
364                 return NULL;
365
366         wlsc_surface_init(es, ec, &ec->premultiplied_argb_visual,
367                           x, y, width, height);
368         glBindTexture(GL_TEXTURE_2D, es->texture);
369         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
370         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
371         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
372         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
373         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
374                      GL_RGBA, GL_UNSIGNED_BYTE, data);
375
376         return es;
377 }
378
379 static void
380 wlsc_surface_destroy(struct wlsc_surface *surface,
381                      struct wlsc_compositor *compositor)
382 {
383         struct wlsc_listener *l;
384
385         wl_list_remove(&surface->link);
386         glDeleteTextures(1, &surface->texture);
387         wl_client_remove_surface(surface->base.client, &surface->base);
388
389         wl_list_for_each(l, &compositor->surface_destroy_listener_list, link)
390                 l->func(l, surface);
391
392         free(surface);
393 }
394
395 static void
396 pointer_path(cairo_t *cr, int x, int y)
397 {
398         const int end = 3, tx = 4, ty = 12, dx = 5, dy = 10;
399         const int width = 16, height = 16;
400
401         cairo_move_to(cr, x, y);
402         cairo_line_to(cr, x + tx, y + ty);
403         cairo_line_to(cr, x + dx, y + dy);
404         cairo_line_to(cr, x + width - end, y + height);
405         cairo_line_to(cr, x + width, y + height - end);
406         cairo_line_to(cr, x + dy, y + dx);
407         cairo_line_to(cr, x + ty, y + tx);
408         cairo_close_path(cr);
409 }
410
411 static struct wlsc_surface *
412 pointer_create(struct wlsc_compositor *ec, int x, int y, int width, int height)
413 {
414         struct wlsc_surface *es;
415         const int hotspot_x = 16, hotspot_y = 16;
416         cairo_surface_t *surface;
417         cairo_t *cr;
418
419         surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
420                                              width, height);
421
422         cr = cairo_create(surface);
423         pointer_path(cr, hotspot_x + 5, hotspot_y + 4);
424         cairo_set_line_width(cr, 2);
425         cairo_set_source_rgb(cr, 0, 0, 0);
426         cairo_stroke_preserve(cr);
427         cairo_fill(cr);
428         blur_surface(surface, width);
429
430         pointer_path(cr, hotspot_x, hotspot_y);
431         cairo_stroke_preserve(cr);
432         cairo_set_source_rgb(cr, 1, 1, 1);
433         cairo_fill(cr);
434         cairo_destroy(cr);
435
436         es = wlsc_surface_create_from_cairo_surface(ec,
437                                                    surface,
438                                                    x - hotspot_x,
439                                                    y - hotspot_y,
440                                                    width, height);
441         
442         cairo_surface_destroy(surface);
443
444         return es;
445 }
446
447 static struct wlsc_surface *
448 background_create(struct wlsc_output *output, const char *filename)
449 {
450         struct wlsc_surface *background;
451         GdkPixbuf *pixbuf;
452         GError *error = NULL;
453         void *data;
454         GLenum format;
455
456         background = malloc(sizeof *background);
457         if (background == NULL)
458                 return NULL;
459         
460         g_type_init();
461
462         pixbuf = gdk_pixbuf_new_from_file_at_scale(filename,
463                                                    output->width,
464                                                    output->height,
465                                                    FALSE, &error);
466         if (error != NULL) {
467                 free(background);
468                 return NULL;
469         }
470
471         data = gdk_pixbuf_get_pixels(pixbuf);
472
473         wlsc_surface_init(background, output->compositor,
474                           &output->compositor->rgb_visual,
475                           output->x, output->y, output->width, output->height);
476
477         glBindTexture(GL_TEXTURE_2D, background->texture);
478         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
479         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
480         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
481         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
482
483         if (gdk_pixbuf_get_has_alpha(pixbuf))
484                 format = GL_RGBA;
485         else
486                 format = GL_RGB;
487
488         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
489                      output->width, output->height, 0,
490                      format, GL_UNSIGNED_BYTE, data);
491
492         return background;
493 }
494
495 static void
496 wlsc_surface_draw(struct wlsc_surface *es, struct wlsc_output *output)
497 {
498         struct wlsc_compositor *ec = es->compositor;
499         struct wlsc_matrix tmp;
500
501         tmp = es->matrix;
502         wlsc_matrix_multiply(&tmp, &output->matrix);
503         glUniformMatrix4fv(ec->proj_uniform, 1, GL_FALSE, tmp.d);
504         glUniform1i(ec->tex_uniform, 0);
505
506         if (es->visual == &ec->argb_visual) {
507                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
508                 glEnable(GL_BLEND);
509         } else if (es->visual == &ec->premultiplied_argb_visual) {
510                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
511                 glEnable(GL_BLEND);
512         } else {
513                 glDisable(GL_BLEND);
514         }
515
516         glBindTexture(GL_TEXTURE_2D, es->texture);
517         glEnable(GL_TEXTURE_2D);
518         glBindBuffer(GL_ARRAY_BUFFER, ec->vbo);
519         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
520                               5 * sizeof(GLfloat), NULL);
521         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE,
522                               5 * sizeof(GLfloat), (GLfloat *) 0 + 3);
523         glEnableVertexAttribArray(0);
524         glEnableVertexAttribArray(1);
525         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
526 }
527
528 static void
529 wlsc_surface_raise(struct wlsc_surface *surface)
530 {
531         struct wlsc_compositor *compositor = surface->compositor;
532
533         wl_list_remove(&surface->link);
534         wl_list_insert(compositor->surface_list.prev, &surface->link);
535 }
536
537 static void
538 wlsc_surface_lower(struct wlsc_surface *surface)
539 {
540         struct wlsc_compositor *compositor = surface->compositor;
541
542         wl_list_remove(&surface->link);
543         wl_list_insert(&compositor->surface_list, &surface->link);
544 }
545
546 static void
547 page_flip_handler(int fd, unsigned int frame,
548                   unsigned int sec, unsigned int usec, void *data)
549 {
550         struct wlsc_output *output = data;
551         struct wlsc_compositor *compositor = output->compositor;
552         uint32_t msecs;
553
554         msecs = sec * 1000 + usec / 1000;
555         wl_display_post_frame(compositor->wl_display,
556                               &compositor->base,
557                               compositor->current_frame, msecs);
558
559         wl_event_source_timer_update(compositor->timer_source, 5);
560         compositor->repaint_on_timeout = 1;
561
562         compositor->current_frame++;
563 }
564
565 static void
566 repaint_output(struct wlsc_output *output)
567 {
568         struct wlsc_compositor *ec = output->compositor;
569         struct wlsc_surface *es;
570         struct wlsc_input_device *eid;
571
572         glViewport(0, 0, output->width, output->height);
573
574         if (output->background)
575                 wlsc_surface_draw(output->background, output);
576         else
577                 glClear(GL_COLOR_BUFFER_BIT);
578
579         wl_list_for_each(es, &ec->surface_list, link)
580                 wlsc_surface_draw(es, output);
581
582         wl_list_for_each(eid, &ec->input_device_list, link)
583                 wlsc_surface_draw(eid->sprite, output);
584
585         output->current ^= 1;
586
587         glFramebufferRenderbuffer(GL_FRAMEBUFFER,
588                                   GL_COLOR_ATTACHMENT0,
589                                   GL_RENDERBUFFER,
590                                   output->rbo[output->current]);
591         drmModePageFlip(ec->drm_fd, output->crtc_id,
592                         output->fb_id[output->current ^ 1],
593                         DRM_MODE_PAGE_FLIP_EVENT, output);
594 }
595
596 static void
597 repaint(void *data)
598 {
599         struct wlsc_compositor *ec = data;
600         struct wlsc_output *output;
601
602         if (!ec->repaint_needed) {
603                 ec->repaint_on_timeout = 0;
604                 return;
605         }
606
607         wl_list_for_each(output, &ec->output_list, link)
608                 repaint_output(output);
609
610         ec->repaint_needed = 0;
611 }
612
613 static void
614 wlsc_compositor_schedule_repaint(struct wlsc_compositor *compositor)
615 {
616         struct wlsc_output *output;
617
618         compositor->repaint_needed = 1;
619         if (compositor->repaint_on_timeout)
620                 return;
621
622         wl_list_for_each(output, &compositor->output_list, link)
623                 drmModePageFlip(compositor->drm_fd, output->crtc_id,
624                                 output->fb_id[output->current ^ 1],
625                                 DRM_MODE_PAGE_FLIP_EVENT, output);
626 }
627
628 static void
629 surface_destroy(struct wl_client *client,
630                 struct wl_surface *surface)
631 {
632         struct wlsc_surface *es = (struct wlsc_surface *) surface;
633         struct wlsc_compositor *ec = es->compositor;
634
635         wlsc_surface_destroy(es, ec);
636
637         wlsc_compositor_schedule_repaint(ec);
638 }
639
640 static void
641 surface_attach(struct wl_client *client,
642                struct wl_surface *surface, uint32_t name, 
643                uint32_t width, uint32_t height, uint32_t stride,
644                struct wl_object *visual)
645 {
646         struct wlsc_surface *es = (struct wlsc_surface *) surface;
647         struct wlsc_compositor *ec = es->compositor;
648         EGLint attribs[] = {
649                 EGL_WIDTH,              0,
650                 EGL_HEIGHT,             0,
651                 EGL_IMAGE_STRIDE_MESA,  0,
652                 EGL_IMAGE_FORMAT_MESA,  EGL_IMAGE_FORMAT_ARGB8888_MESA,
653                 EGL_NONE
654         };
655
656         es->width = width;
657         es->height = height;
658
659         if (visual == &ec->argb_visual.base)
660                 es->visual = &ec->argb_visual;
661         else if (visual == &ec->premultiplied_argb_visual.base)
662                 es->visual = &ec->premultiplied_argb_visual;
663         else if (visual == &ec->rgb_visual.base)
664                 es->visual = &ec->rgb_visual;
665         else
666                 /* FIXME: Smack client with an exception event */;
667
668         glBindTexture(GL_TEXTURE_2D, es->texture);
669         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
670         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
671         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
672         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
673
674         if (es->image)
675                 eglDestroyImageKHR(ec->display, es->image);
676
677         attribs[1] = width;
678         attribs[3] = height;
679         attribs[5] = stride / 4;
680
681         es->image = eglCreateImageKHR(ec->display, ec->context,
682                                       EGL_DRM_IMAGE_MESA,
683                                       (EGLClientBuffer) name, attribs);
684         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, es->image);
685         
686 }
687
688 static void
689 surface_map(struct wl_client *client,
690             struct wl_surface *surface,
691             int32_t x, int32_t y, int32_t width, int32_t height)
692 {
693         struct wlsc_surface *es = (struct wlsc_surface *) surface;
694
695         wlsc_matrix_init(&es->matrix);
696         wlsc_matrix_scale(&es->matrix, width, height, 1);
697         wlsc_matrix_translate(&es->matrix, x, y, 0);
698
699         wlsc_matrix_init(&es->matrix_inv);
700         wlsc_matrix_translate(&es->matrix_inv, -x, -y, 0);
701         wlsc_matrix_scale(&es->matrix_inv, 1.0 / width, 1.0 / height, 1);
702
703 }
704
705 static void
706 surface_damage(struct wl_client *client,
707                struct wl_surface *surface,
708                int32_t x, int32_t y, int32_t width, int32_t height)
709 {
710         /* FIXME: This need to take a damage region, of course. */
711 }
712
713 const static struct wl_surface_interface surface_interface = {
714         surface_destroy,
715         surface_attach,
716         surface_map,
717         surface_damage
718 };
719
720 static void
721 compositor_create_surface(struct wl_client *client,
722                           struct wl_compositor *compositor, uint32_t id)
723 {
724         struct wlsc_compositor *ec = (struct wlsc_compositor *) compositor;
725         struct wlsc_surface *surface;
726
727         surface = malloc(sizeof *surface);
728         if (surface == NULL)
729                 /* FIXME: Send OOM event. */
730                 return;
731
732         wlsc_surface_init(surface, ec, NULL, 0, 0, 0, 0);
733
734         wl_list_insert(ec->surface_list.prev, &surface->link);
735         wl_client_add_surface(client, &surface->base,
736                               &surface_interface, id);
737 }
738
739 static void
740 compositor_commit(struct wl_client *client,
741                   struct wl_compositor *compositor, uint32_t key)
742 {
743         struct wlsc_compositor *ec = (struct wlsc_compositor *) compositor;
744
745         wlsc_compositor_schedule_repaint(ec);
746         wl_client_send_acknowledge(client, compositor, key, ec->current_frame);
747 }
748
749 const static struct wl_compositor_interface compositor_interface = {
750         compositor_create_surface,
751         compositor_commit
752 };
753
754 static void
755 wlsc_surface_transform(struct wlsc_surface *surface,
756                        int32_t x, int32_t y, int32_t *sx, int32_t *sy)
757 {
758         struct wlsc_vector v = { { x, y, 0, 1 } };
759         
760         wlsc_matrix_transform(&surface->matrix_inv, &v);
761         *sx = v.f[0] * surface->width;
762         *sy = v.f[1] * surface->height;
763 }
764
765 static void
766 wlsc_input_device_set_keyboard_focus(struct wlsc_input_device *device,
767                                      struct wlsc_surface *surface)
768 {
769         if (device->keyboard_focus == surface)
770                 return;
771
772         if (device->keyboard_focus &&
773             (!surface || device->keyboard_focus->base.client != surface->base.client))
774                 wl_surface_post_event(&device->keyboard_focus->base,
775                                       &device->base,
776                                       WL_INPUT_KEYBOARD_FOCUS, NULL, &device->keys);
777
778         if (surface)
779                 wl_surface_post_event(&surface->base,
780                                       &device->base,
781                                       WL_INPUT_KEYBOARD_FOCUS,
782                                       &surface->base, &device->keys);
783
784         device->keyboard_focus = surface;
785 }
786
787 static void
788 wlsc_input_device_set_pointer_focus(struct wlsc_input_device *device,
789                                     struct wlsc_surface *surface)
790 {
791         if (device->pointer_focus == surface)
792                 return;
793
794         if (device->pointer_focus &&
795             (!surface || device->pointer_focus->base.client != surface->base.client))
796                 wl_surface_post_event(&device->pointer_focus->base,
797                                       &device->base,
798                                       WL_INPUT_POINTER_FOCUS, NULL);
799         if (surface)
800                 wl_surface_post_event(&surface->base,
801                                       &device->base,
802                                       WL_INPUT_POINTER_FOCUS, &surface->base);
803
804         device->pointer_focus = surface;
805 }
806
807 static struct wlsc_surface *
808 pick_surface(struct wlsc_input_device *device, int32_t *sx, int32_t *sy)
809 {
810         struct wlsc_compositor *ec = device->ec;
811         struct wlsc_surface *es;
812
813         if (device->grab > 0) {
814                 wlsc_surface_transform(device->grab_surface,
815                                        device->x, device->y, sx, sy);
816                 return device->grab_surface;
817         }
818
819         wl_list_for_each(es, &ec->surface_list, link) {
820                 wlsc_surface_transform(es, device->x, device->y, sx, sy);
821                 if (0 <= *sx && *sx < es->width &&
822                     0 <= *sy && *sy < es->height)
823                         return es;
824         }
825
826         return NULL;
827 }
828
829 void
830 notify_motion(struct wlsc_input_device *device, int x, int y)
831 {
832         struct wlsc_surface *es;
833         struct wlsc_compositor *ec = device->ec;
834         struct wlsc_output *output;
835         const int hotspot_x = 16, hotspot_y = 16;
836         int32_t sx, sy;
837
838         if (!ec->vt_active)
839                 return;
840
841         /* FIXME: We need some multi head love here. */
842         output = container_of(ec->output_list.next, struct wlsc_output, link);
843         if (x < output->x)
844                 x = 0;
845         if (y < output->y)
846                 y = 0;
847         if (x >= output->x + output->width)
848                 x = output->x + output->width - 1;
849         if (y >= output->y + output->height)
850                 y = output->y + output->height - 1;
851
852         device->x = x;
853         device->y = y;
854         es = pick_surface(device, &sx, &sy);
855
856         wlsc_input_device_set_pointer_focus(device, es);
857                 
858         if (es)
859                 wl_surface_post_event(&es->base, &device->base,
860                                       WL_INPUT_MOTION, x, y, sx, sy);
861
862         wlsc_matrix_init(&device->sprite->matrix);
863         wlsc_matrix_scale(&device->sprite->matrix, 64, 64, 1);
864         wlsc_matrix_translate(&device->sprite->matrix,
865                               x - hotspot_x, y - hotspot_y, 0);
866
867         wlsc_compositor_schedule_repaint(device->ec);
868 }
869
870 void
871 notify_button(struct wlsc_input_device *device,
872               int32_t button, int32_t state)
873 {
874         struct wlsc_surface *surface;
875         struct wlsc_compositor *compositor = device->ec;
876         int32_t sx, sy;
877
878         if (!compositor->vt_active)
879                 return;
880
881         surface = pick_surface(device, &sx, &sy);
882         if (surface) {
883                 if (state) {
884                         wlsc_surface_raise(surface);
885                         device->grab++;
886                         device->grab_surface = surface;
887                         wlsc_input_device_set_keyboard_focus(device,
888                                                              surface);
889                 } else {
890                         device->grab--;
891                 }
892
893                 /* FIXME: Swallow click on raise? */
894                 wl_surface_post_event(&surface->base, &device->base,
895                                       WL_INPUT_BUTTON, button, state,
896                                       device->x, device->y, sx, sy);
897
898                 wlsc_compositor_schedule_repaint(compositor);
899         }
900 }
901
902 static void on_term_signal(int signal_number, void *data);
903
904 void
905 notify_key(struct wlsc_input_device *device,
906            uint32_t key, uint32_t state)
907 {
908         struct wlsc_compositor *compositor = device->ec;
909         uint32_t *k, *end;
910         uint32_t modifier;
911
912         if (!compositor->vt_active)
913                 return;
914
915         switch (key | compositor->modifier_state) {
916         case KEY_BACKSPACE | MODIFIER_CTRL | MODIFIER_ALT:
917                 on_term_signal(SIGTERM, compositor);
918                 return;
919         }
920
921         switch (key) {
922         case KEY_LEFTCTRL:
923         case KEY_RIGHTCTRL:
924                 modifier = MODIFIER_CTRL;
925                 break;
926
927         case KEY_LEFTALT:
928         case KEY_RIGHTALT:
929                 modifier = MODIFIER_ALT;
930                 break;
931
932         default:
933                 modifier = 0;
934                 break;
935         }
936
937         if (state)
938                 compositor->modifier_state |= modifier;
939         else
940                 compositor->modifier_state &= ~modifier;
941
942         end = device->keys.data + device->keys.size;
943         for (k = device->keys.data; k < end; k++) {
944                 if (*k == key)
945                         *k = *--end;
946         }
947         device->keys.size = (void *) end - device->keys.data;
948         if (state) {
949                 k = wl_array_add(&device->keys, sizeof *k);
950                 *k = key;
951         }
952
953         if (device->keyboard_focus != NULL)
954                 wl_surface_post_event(&device->keyboard_focus->base,
955                                       &device->base, 
956                                       WL_INPUT_KEY, key, state);
957 }
958
959 struct evdev_input_device *
960 evdev_input_device_create(struct wlsc_input_device *device,
961                           struct wl_display *display, const char *path);
962
963 static void
964 handle_surface_destroy(struct wlsc_listener *listener,
965                        struct wlsc_surface *surface)
966 {
967         struct wlsc_input_device *device =
968                 container_of(listener, struct wlsc_input_device, listener);
969         struct wlsc_surface *focus;
970         int32_t sx, sy;
971
972         if (device->grab_surface == surface) {
973                 device->grab_surface = NULL;
974                 device->grab = 0;
975         }
976         if (device->keyboard_focus == surface)
977                 wlsc_input_device_set_keyboard_focus(device, NULL);
978         if (device->pointer_focus == surface) {
979                 focus = pick_surface(device, &sx, &sy);
980                 wlsc_input_device_set_pointer_focus(device, focus);
981                 fprintf(stderr, "lost pointer focus surface, reverting to %p\n", focus);
982         }
983 }
984
985 static struct wlsc_input_device *
986 create_input_device(struct wlsc_compositor *ec)
987 {
988         struct wlsc_input_device *device;
989
990         device = malloc(sizeof *device);
991         if (device == NULL)
992                 return NULL;
993
994         memset(device, 0, sizeof *device);
995         device->base.interface = &wl_input_device_interface;
996         device->base.implementation = NULL;
997         wl_display_add_object(ec->wl_display, &device->base);
998         wl_display_add_global(ec->wl_display, &device->base, NULL);
999         device->x = 100;
1000         device->y = 100;
1001         device->ec = ec;
1002
1003         device->listener.func = handle_surface_destroy;
1004         wl_list_insert(ec->surface_destroy_listener_list.prev,
1005                        &device->listener.link);
1006         wl_list_insert(ec->input_device_list.prev, &device->link);
1007
1008         return device;
1009 }
1010
1011 void
1012 wlsc_device_get_position(struct wlsc_input_device *device, int32_t *x, int32_t *y)
1013 {
1014         *x = device->x;
1015         *y = device->y;
1016 }
1017
1018 static void
1019 post_output_geometry(struct wl_client *client, struct wl_object *global)
1020 {
1021         struct wlsc_output *output =
1022                 container_of(global, struct wlsc_output, base);
1023
1024         wl_client_post_event(client, global,
1025                              WL_OUTPUT_GEOMETRY,
1026                              output->width, output->height);
1027 }
1028
1029 static void
1030 on_drm_input(int fd, uint32_t mask, void *data)
1031 {
1032         drmEventContext evctx;
1033
1034         memset(&evctx, 0, sizeof evctx);
1035         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1036         evctx.page_flip_handler = page_flip_handler;
1037         drmHandleEvent(fd, &evctx);
1038 }
1039
1040 static const char vertex_shader[] =
1041         "uniform mat4 proj;\n"
1042         "attribute vec4 position;\n"
1043         "attribute vec2 texcoord;\n"
1044         "varying vec2 v_texcoord;\n"
1045         "void main()\n"
1046         "{\n"
1047         "   gl_Position = proj * position;\n"
1048         "   v_texcoord = texcoord;\n"
1049         "}\n";
1050
1051 static const char fragment_shader[] =
1052         /* "precision mediump float;\n" */
1053         "varying vec2 v_texcoord;\n"
1054         "uniform sampler2D tex;\n"
1055         "void main()\n"
1056         "{\n"
1057         "   gl_FragColor = texture2D(tex, v_texcoord)\n;"
1058         "}\n";
1059
1060 static void
1061 init_shaders(struct wlsc_compositor *ec)
1062 {
1063    GLuint v, f, program;
1064    const char *p;
1065    char msg[512];
1066    GLfloat vertices[4 * 5];
1067
1068    p = vertex_shader;
1069    v = glCreateShader(GL_VERTEX_SHADER);
1070    glShaderSource(v, 1, &p, NULL);
1071    glCompileShader(v);
1072    glGetShaderInfoLog(v, sizeof msg, NULL, msg);
1073    printf("vertex shader info: %s\n", msg);
1074
1075    p = fragment_shader;
1076    f = glCreateShader(GL_FRAGMENT_SHADER);
1077    glShaderSource(f, 1, &p, NULL);
1078    glCompileShader(f);
1079    glGetShaderInfoLog(f, sizeof msg, NULL, msg);
1080    printf("fragment shader info: %s\n", msg);
1081
1082    program = glCreateProgram();
1083    glAttachShader(program, v);
1084    glAttachShader(program, f);
1085    glBindAttribLocation(program, 0, "position");
1086    glBindAttribLocation(program, 1, "texcoord");
1087
1088    glLinkProgram(program);
1089    glGetProgramInfoLog(program, sizeof msg, NULL, msg);
1090    printf("info: %s\n", msg);
1091
1092    glUseProgram(program);
1093    ec->proj_uniform = glGetUniformLocation(program, "proj");
1094    ec->tex_uniform = glGetUniformLocation(program, "tex");
1095
1096    vertices[ 0] = 0.0;
1097    vertices[ 1] = 0.0;
1098    vertices[ 2] = 0.0;
1099    vertices[ 3] = 0.0;
1100    vertices[ 4] = 0.0;
1101
1102    vertices[ 5] = 0.0;
1103    vertices[ 6] = 1.0;
1104    vertices[ 7] = 0.0;
1105    vertices[ 8] = 0.0;
1106    vertices[ 9] = 1.0;
1107
1108    vertices[10] = 1.0;
1109    vertices[11] = 0.0;
1110    vertices[12] = 0.0;
1111    vertices[13] = 1.0;
1112    vertices[14] = 0.0;
1113
1114    vertices[15] = 1.0;
1115    vertices[16] = 1.0;
1116    vertices[17] = 0.0;
1117    vertices[18] = 1.0;
1118    vertices[19] = 1.0;
1119
1120    glGenBuffers(1, &ec->vbo);
1121    glBindBuffer(GL_ARRAY_BUFFER, ec->vbo);
1122    glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
1123 }
1124
1125 static int
1126 init_egl(struct wlsc_compositor *ec, struct udev_device *device)
1127 {
1128         struct wl_event_loop *loop;
1129         EGLint major, minor, count;
1130         EGLConfig config;
1131         PFNEGLGETTYPEDDISPLAYMESA get_typed_display_mesa;
1132
1133         static const EGLint config_attribs[] = {
1134                 EGL_SURFACE_TYPE,               0,
1135                 EGL_NO_SURFACE_CAPABLE_MESA,    EGL_OPENGL_BIT,
1136                 EGL_RENDERABLE_TYPE,            EGL_OPENGL_BIT,
1137                 EGL_NONE
1138         };
1139
1140         get_typed_display_mesa =
1141                 (PFNEGLGETTYPEDDISPLAYMESA) eglGetProcAddress("eglGetTypedDisplayMESA");
1142         if (get_typed_display_mesa == NULL) {
1143                 fprintf(stderr, "eglGetDisplayMESA() not found\n");
1144                 return -1;
1145         }
1146
1147         ec->base.device = strdup(udev_device_get_devnode(device));
1148         ec->drm_fd = open(ec->base.device, O_RDWR);
1149         if (ec->drm_fd < 0) {
1150                 /* Probably permissions error */
1151                 fprintf(stderr, "couldn't open %s, skipping\n",
1152                         udev_device_get_devnode(device));
1153                 return -1;
1154         }
1155
1156         ec->display = get_typed_display_mesa(EGL_DRM_DISPLAY_TYPE_MESA,
1157                                              (void *) ec->drm_fd);
1158         if (ec->display == NULL) {
1159                 fprintf(stderr, "failed to create display\n");
1160                 return -1;
1161         }
1162
1163         if (!eglInitialize(ec->display, &major, &minor)) {
1164                 fprintf(stderr, "failed to initialize display\n");
1165                 return -1;
1166         }
1167
1168         if (!eglChooseConfig(ec->display, config_attribs, &config, 1, &count) ||
1169             count == 0) {
1170                 fprintf(stderr, "eglChooseConfig() failed\n");
1171                 return -1;
1172         }
1173
1174         eglBindAPI(EGL_OPENGL_API);
1175         ec->context = eglCreateContext(ec->display, config, EGL_NO_CONTEXT, NULL);
1176         if (ec->context == NULL) {
1177                 fprintf(stderr, "failed to create context\n");
1178                 return -1;
1179         }
1180
1181         if (!eglMakeCurrent(ec->display, EGL_NO_SURFACE, EGL_NO_SURFACE, ec->context)) {
1182                 fprintf(stderr, "failed to make context current\n");
1183                 return -1;
1184         }
1185
1186         glGenFramebuffers(1, &ec->fbo);
1187         glBindFramebuffer(GL_FRAMEBUFFER, ec->fbo);
1188         glActiveTexture(GL_TEXTURE0);
1189         init_shaders(ec);
1190
1191         loop = wl_display_get_event_loop(ec->wl_display);
1192         ec->drm_source =
1193                 wl_event_loop_add_fd(loop, ec->drm_fd,
1194                                      WL_EVENT_READABLE, on_drm_input, ec);
1195
1196         return 0;
1197 }
1198
1199 static drmModeModeInfo builtin_1024x768 = {
1200         63500,                  /* clock */
1201         1024, 1072, 1176, 1328, 0,
1202         768, 771, 775, 798, 0,
1203         59920,
1204         DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC,
1205         0,
1206         "1024x768"
1207 };
1208
1209 static int
1210 create_output_for_connector(struct wlsc_compositor *ec,
1211                             drmModeRes *resources,
1212                             drmModeConnector *connector)
1213 {
1214         struct wlsc_output *output;
1215         drmModeEncoder *encoder;
1216         drmModeModeInfo *mode;
1217         int i, ret;
1218         EGLint handle, stride, attribs[] = {
1219                 EGL_WIDTH,              0,
1220                 EGL_HEIGHT,             0,
1221                 EGL_IMAGE_FORMAT_MESA,  EGL_IMAGE_FORMAT_ARGB8888_MESA,
1222                 EGL_IMAGE_USE_MESA,     EGL_IMAGE_USE_SCANOUT_MESA,
1223                 EGL_NONE
1224         };
1225
1226         output = malloc(sizeof *output);
1227         if (output == NULL)
1228                 return -1;
1229
1230         if (connector->count_modes > 0) 
1231                 mode = &connector->modes[0];
1232         else
1233                 mode = &builtin_1024x768;
1234
1235         encoder = drmModeGetEncoder(ec->drm_fd, connector->encoders[0]);
1236         if (encoder == NULL) {
1237                 fprintf(stderr, "No encoder for connector.\n");
1238                 return -1;
1239         }
1240
1241         for (i = 0; i < resources->count_crtcs; i++) {
1242                 if (encoder->possible_crtcs & (1 << i))
1243                         break;
1244         }
1245         if (i == resources->count_crtcs) {
1246                 fprintf(stderr, "No usable crtc for encoder.\n");
1247                 return -1;
1248         }
1249
1250         output->compositor = ec;
1251         output->crtc_id = resources->crtcs[i];
1252         output->connector_id = connector->connector_id;
1253         output->mode = *mode;
1254         output->x = 0;
1255         output->y = 0;
1256         output->width = mode->hdisplay;
1257         output->height = mode->vdisplay;
1258         wlsc_matrix_init(&output->matrix);
1259
1260         wlsc_matrix_translate(&output->matrix,
1261                               -output->x - output->width / 2.0,
1262                               -output->y - output->height / 2.0, 0);
1263         wlsc_matrix_scale(&output->matrix,
1264                           2.0 / output->width, 2.0 / output->height, 1);
1265
1266         drmModeFreeEncoder(encoder);
1267
1268         glGenRenderbuffers(2, output->rbo);
1269         for (i = 0; i < 2; i++) {
1270                 glBindRenderbuffer(GL_RENDERBUFFER, output->rbo[i]);
1271
1272                 attribs[1] = output->width;
1273                 attribs[3] = output->height;
1274                 output->image[i] = eglCreateDRMImageMESA(ec->display, attribs);
1275                 glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, output->image[i]);
1276                 eglExportDRMImageMESA(ec->display, output->image[i], NULL, &handle, &stride);
1277
1278                 ret = drmModeAddFB(ec->drm_fd, output->width, output->height,
1279                                    32, 32, stride, handle, &output->fb_id[i]);
1280                 if (ret) {
1281                         fprintf(stderr, "failed to add fb %d: %m\n", i);
1282                         return -1;
1283                 }
1284         }
1285
1286         output->current = 0;
1287         glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1288                                   GL_COLOR_ATTACHMENT0,
1289                                   GL_RENDERBUFFER,
1290                                   output->rbo[output->current]);
1291         ret = drmModeSetCrtc(ec->drm_fd, output->crtc_id,
1292                              output->fb_id[output->current ^ 1], 0, 0,
1293                              &output->connector_id, 1, &output->mode);
1294         if (ret) {
1295                 fprintf(stderr, "failed to set mode: %m\n");
1296                 return -1;
1297         }
1298
1299         output->base.interface = &wl_output_interface;
1300         wl_display_add_object(ec->wl_display, &output->base);
1301         wl_display_add_global(ec->wl_display, &output->base, post_output_geometry);
1302         wl_list_insert(ec->output_list.prev, &output->link);
1303
1304         output->background = background_create(output, option_background);
1305
1306         return 0;
1307 }
1308
1309 static int
1310 create_outputs(struct wlsc_compositor *ec)
1311 {
1312         drmModeConnector *connector;
1313         drmModeRes *resources;
1314         int i;
1315
1316         resources = drmModeGetResources(ec->drm_fd);
1317         if (!resources) {
1318                 fprintf(stderr, "drmModeGetResources failed\n");
1319                 return -1;
1320         }
1321
1322         for (i = 0; i < resources->count_connectors; i++) {
1323                 connector = drmModeGetConnector(ec->drm_fd, resources->connectors[i]);
1324                 if (connector == NULL)
1325                         continue;
1326
1327                 if (connector->connection == DRM_MODE_CONNECTED &&
1328                     (option_connector == 0 ||
1329                      connector->connector_id == option_connector))
1330                         if (create_output_for_connector(ec, resources, connector) < 0)
1331                                 return -1;
1332
1333                 drmModeFreeConnector(connector);
1334         }
1335
1336         if (wl_list_empty(&ec->output_list)) {
1337                 fprintf(stderr, "No currently active connector found.\n");
1338                 return -1;
1339         }
1340
1341         drmModeFreeResources(resources);
1342
1343         return 0;
1344 }
1345
1346 static const struct wl_interface visual_interface = {
1347         "visual", 1,
1348 };
1349
1350 static void
1351 add_visuals(struct wlsc_compositor *ec)
1352 {
1353         ec->argb_visual.base.interface = &visual_interface;
1354         ec->argb_visual.base.implementation = NULL;
1355         wl_display_add_object(ec->wl_display, &ec->argb_visual.base);
1356         wl_display_add_global(ec->wl_display, &ec->argb_visual.base, NULL);
1357
1358         ec->premultiplied_argb_visual.base.interface = &visual_interface;
1359         ec->premultiplied_argb_visual.base.implementation = NULL;
1360         wl_display_add_object(ec->wl_display,
1361                               &ec->premultiplied_argb_visual.base);
1362         wl_display_add_global(ec->wl_display,
1363                               &ec->premultiplied_argb_visual.base, NULL);
1364
1365         ec->rgb_visual.base.interface = &visual_interface;
1366         ec->rgb_visual.base.implementation = NULL;
1367         wl_display_add_object(ec->wl_display, &ec->rgb_visual.base);
1368         wl_display_add_global(ec->wl_display, &ec->rgb_visual.base, NULL);
1369 }
1370
1371 static void on_enter_vt(int signal_number, void *data)
1372 {
1373         struct wlsc_compositor *ec = data;
1374         struct wlsc_output *output;
1375         int ret;
1376
1377         ret = drmSetMaster(ec->drm_fd);
1378         if (ret) {
1379                 fprintf(stderr, "failed to set drm master\n");
1380                 on_term_signal(SIGTERM, ec);
1381                 return;
1382         }
1383
1384         ioctl(ec->tty_fd, VT_RELDISP, VT_ACKACQ);
1385         ec->vt_active = TRUE;
1386
1387         wl_list_for_each(output, &ec->output_list, link) {
1388                 ret = drmModeSetCrtc(ec->drm_fd, output->crtc_id,
1389                                      output->fb_id[output->current ^ 1], 0, 0,
1390                                      &output->connector_id, 1, &output->mode);
1391                 if (ret)
1392                         fprintf(stderr, "failed to set mode for connector %d: %m\n",
1393                                 output->connector_id);
1394         }
1395 }
1396
1397 static void on_leave_vt(int signal_number, void *data)
1398 {
1399         struct wlsc_compositor *ec = data;
1400         int ret;
1401
1402         ret = drmDropMaster(ec->drm_fd);
1403         if (ret) {
1404                 fprintf(stderr, "failed to drop drm master\n");
1405                 on_term_signal(SIGTERM, ec);
1406                 return;
1407         }
1408
1409         ioctl (ec->tty_fd, VT_RELDISP, 1);
1410         ec->vt_active = FALSE;
1411 }
1412
1413 static void
1414 on_tty_input(int fd, uint32_t mask, void *data)
1415 {
1416         struct wlsc_compositor *ec = data;
1417
1418         /* Ignore input to tty.  We get keyboard events from evdev
1419          */
1420         tcflush(ec->tty_fd, TCIFLUSH);
1421 }
1422
1423 static void on_term_signal(int signal_number, void *data)
1424 {
1425         struct wlsc_compositor *ec = data;
1426
1427         if (tcsetattr(ec->tty_fd, TCSANOW, &ec->terminal_attributes) < 0)
1428                 fprintf(stderr, "could not restore terminal to canonical mode\n");
1429
1430         exit(0);
1431 }
1432
1433 static int setup_tty(struct wlsc_compositor *ec, struct wl_event_loop *loop)
1434 {
1435         struct termios raw_attributes;
1436         struct vt_mode mode = { 0 };
1437
1438         ec->tty_fd = open("/dev/tty0", O_RDWR | O_NOCTTY);
1439         if (ec->tty_fd <= 0) {
1440                 fprintf(stderr, "failed to open active tty: %m\n");
1441                 return -1;
1442         }
1443
1444         if (tcgetattr(ec->tty_fd, &ec->terminal_attributes) < 0) {
1445                 fprintf(stderr, "could not get terminal attributes: %m\n");
1446                 return -1;
1447         }
1448
1449         /* Ignore control characters and disable echo */
1450         raw_attributes = ec->terminal_attributes;
1451         cfmakeraw(&raw_attributes);
1452
1453         /* Fix up line endings to be normal (cfmakeraw hoses them) */
1454         raw_attributes.c_oflag |= OPOST | OCRNL;
1455
1456         if (tcsetattr(ec->tty_fd, TCSANOW, &raw_attributes) < 0)
1457                 fprintf(stderr, "could not put terminal into raw mode: %m\n");
1458
1459         ec->term_signal_source =
1460                 wl_event_loop_add_signal(loop, SIGTERM, on_term_signal, ec);
1461
1462         ec->tty_input_source =
1463                 wl_event_loop_add_fd(loop, ec->tty_fd,
1464                                      WL_EVENT_READABLE, on_tty_input, ec);
1465
1466         ec->vt_active = TRUE;
1467         mode.mode = VT_PROCESS;
1468         mode.relsig = SIGUSR1;
1469         mode.acqsig = SIGUSR2;
1470         if (!ioctl(ec->tty_fd, VT_SETMODE, &mode) < 0) {
1471                 fprintf(stderr, "failed to take control of vt handling\n");
1472         }
1473
1474         ec->leave_vt_source =
1475                 wl_event_loop_add_signal(loop, SIGUSR1, on_leave_vt, ec);
1476         ec->enter_vt_source =
1477                 wl_event_loop_add_signal(loop, SIGUSR2, on_enter_vt, ec);
1478
1479         return 0;
1480 }
1481
1482 static int
1483 init_libudev(struct wlsc_compositor *ec)
1484 {
1485         struct udev_enumerate *e;
1486         struct udev_list_entry *entry;
1487         struct udev_device *device;
1488         const char *path;
1489         struct wlsc_input_device *input_device;
1490
1491         ec->udev = udev_new();
1492         if (ec->udev == NULL) {
1493                 fprintf(stderr, "failed to initialize udev context\n");
1494                 return -1;
1495         }
1496
1497         input_device = create_input_device(ec);
1498
1499         e = udev_enumerate_new(ec->udev);
1500         udev_enumerate_add_match_subsystem(e, "input");
1501         udev_enumerate_add_match_property(e, "WAYLAND_SEAT", "1");
1502         udev_enumerate_scan_devices(e);
1503         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
1504                 path = udev_list_entry_get_name(entry);
1505                 device = udev_device_new_from_syspath(ec->udev, path);
1506                 evdev_input_device_create(input_device, ec->wl_display,
1507                                           udev_device_get_devnode(device));
1508         }
1509         udev_enumerate_unref(e);
1510
1511         e = udev_enumerate_new(ec->udev);
1512         udev_enumerate_add_match_subsystem(e, "drm");
1513         udev_enumerate_add_match_property(e, "WAYLAND_SEAT", "1");
1514         udev_enumerate_scan_devices(e);
1515         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
1516                 path = udev_list_entry_get_name(entry);
1517                 device = udev_device_new_from_syspath(ec->udev, path);
1518                 if (init_egl(ec, device) < 0) {
1519                         fprintf(stderr, "failed to initialize egl\n");
1520                         return -1;
1521                 }
1522                 if (create_outputs(ec) < 0) {
1523                         fprintf(stderr, "failed to create output for %s\n", path);
1524                         return -1;
1525                 }
1526         }
1527         udev_enumerate_unref(e);
1528
1529         /* Create the pointer surface now that we have a current EGL context. */
1530         input_device->sprite =
1531                 pointer_create(ec, input_device->x, input_device->y, 64, 64);
1532
1533         return 0;
1534 }
1535
1536 static struct wlsc_compositor *
1537 wlsc_compositor_create(struct wl_display *display)
1538 {
1539         struct wlsc_compositor *ec;
1540         struct screenshooter *shooter;
1541         struct wl_event_loop *loop;
1542
1543         ec = malloc(sizeof *ec);
1544         if (ec == NULL)
1545                 return NULL;
1546
1547         memset(ec, 0, sizeof *ec);
1548         ec->wl_display = display;
1549
1550         wl_display_set_compositor(display, &ec->base, &compositor_interface); 
1551
1552         add_visuals(ec);
1553
1554         wl_list_init(&ec->surface_list);
1555         wl_list_init(&ec->input_device_list);
1556         wl_list_init(&ec->output_list);
1557         wl_list_init(&ec->surface_destroy_listener_list);
1558         if (init_libudev(ec) < 0) {
1559                 fprintf(stderr, "failed to initialize devices\n");
1560                 return NULL;
1561         }
1562
1563         shooter = screenshooter_create(ec);
1564         wl_display_add_object(display, &shooter->base);
1565         wl_display_add_global(display, &shooter->base, NULL);
1566
1567         loop = wl_display_get_event_loop(ec->wl_display);
1568
1569         setup_tty(ec, loop);
1570
1571         ec->timer_source = wl_event_loop_add_timer(loop, repaint, ec);
1572         wlsc_compositor_schedule_repaint(ec);
1573
1574         return ec;
1575 }
1576
1577 /* The plan here is to generate a random anonymous socket name and
1578  * advertise that through a service on the session dbus.
1579  */
1580 static const char socket_name[] = "\0wayland";
1581
1582 int main(int argc, char *argv[])
1583 {
1584         struct wl_display *display;
1585         struct wlsc_compositor *ec;
1586         GError *error = NULL;
1587         GOptionContext *context;
1588
1589         context = g_option_context_new(NULL);
1590         g_option_context_add_main_entries(context, option_entries, "Wayland");
1591         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1592                 fprintf(stderr, "option parsing failed: %s\n", error->message);
1593                 exit(EXIT_FAILURE);
1594         }
1595
1596         display = wl_display_create();
1597
1598         ec = wlsc_compositor_create(display);
1599         if (ec == NULL) {
1600                 fprintf(stderr, "failed to create compositor\n");
1601                 exit(EXIT_FAILURE);
1602         }
1603                 
1604         if (wl_display_add_socket(display, socket_name, sizeof socket_name)) {
1605                 fprintf(stderr, "failed to add socket: %m\n");
1606                 exit(EXIT_FAILURE);
1607         }
1608
1609         wl_display_run(display);
1610
1611         return 0;
1612 }