2ecd2a2b5da9df3f8b67287680b0eec41dd14927
[profile/ivi/wayland.git] / compositor-x11.c
1 /*
2  * Copyright © 2008-2010 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 <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <sys/time.h>
27 #include <linux/input.h>
28
29 #include <xcb/xcb.h>
30 #include <xcb/dri2.h>
31 #include <xcb/xfixes.h>
32
33 #define GL_GLEXT_PROTOTYPES
34 #define EGL_EGLEXT_PROTOTYPES
35 #include <GLES2/gl2.h>
36 #include <GLES2/gl2ext.h>
37 #include <EGL/egl.h>
38 #include <EGL/eglext.h>
39
40 #include "wayland.h"
41 #include "wayland-protocol.h"
42 #include "compositor.h"
43
44 #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
45
46 struct x11_compositor {
47         struct wlsc_compositor   base;
48
49         xcb_connection_t        *conn;
50         xcb_screen_t            *screen;
51         xcb_cursor_t             null_cursor;
52         int                      dri2_major;
53         int                      dri2_minor;
54         int                      drm_fd;
55         struct wl_event_source  *xcb_source;
56         struct {
57                 xcb_atom_t               wm_protocols;
58                 xcb_atom_t               wm_normal_hints;
59                 xcb_atom_t               wm_size_hints;
60                 xcb_atom_t               wm_delete_window;
61                 xcb_atom_t               net_wm_name;
62                 xcb_atom_t               utf8_string;
63         } atom;
64 };
65
66 struct x11_output {
67         struct wlsc_output      base;
68
69         xcb_xfixes_region_t     region;
70         xcb_window_t            window;
71         GLuint                  rbo;
72         EGLImageKHR             image;
73         xcb_rectangle_t         damage[16];
74         int                     damage_count;
75 };
76
77 struct x11_input {
78         struct wlsc_input_device base;
79 };
80
81
82 static void
83 x11_input_create(struct x11_compositor *c)
84 {
85         struct x11_input *input;
86
87         input = malloc(sizeof *input);
88         if (input == NULL)
89                 return;
90
91         memset(input, 0, sizeof *input);
92         wlsc_input_device_init(&input->base, &c->base);
93
94         c->base.input_device = &input->base;
95 }
96
97
98 static int
99 dri2_connect(struct x11_compositor *c)
100 {
101         xcb_xfixes_query_version_reply_t *xfixes_query;
102         xcb_xfixes_query_version_cookie_t xfixes_query_cookie;
103         xcb_dri2_query_version_reply_t *dri2_query;
104         xcb_dri2_query_version_cookie_t dri2_query_cookie;
105         xcb_dri2_connect_reply_t *connect;
106         xcb_dri2_connect_cookie_t connect_cookie;
107         xcb_generic_error_t *error;
108
109         xcb_prefetch_extension_data (c->conn, &xcb_xfixes_id);
110         xcb_prefetch_extension_data (c->conn, &xcb_dri2_id);
111
112         xfixes_query_cookie =
113                 xcb_xfixes_query_version(c->conn,
114                                          XCB_XFIXES_MAJOR_VERSION,
115                                          XCB_XFIXES_MINOR_VERSION);
116    
117         dri2_query_cookie =
118                 xcb_dri2_query_version (c->conn,
119                                         XCB_DRI2_MAJOR_VERSION,
120                                         XCB_DRI2_MINOR_VERSION);
121
122         connect_cookie = xcb_dri2_connect_unchecked (c->conn,
123                                                      c->screen->root,
124                                                      XCB_DRI2_DRIVER_TYPE_DRI);
125    
126         xfixes_query =
127                 xcb_xfixes_query_version_reply (c->conn,
128                                                 xfixes_query_cookie, &error);
129         if (xfixes_query == NULL ||
130             error != NULL || xfixes_query->major_version < 2) {
131                 free(error);
132                 return -1;
133         }
134         free(xfixes_query);
135
136         dri2_query =
137                 xcb_dri2_query_version_reply (c->conn,
138                                               dri2_query_cookie, &error);
139         if (dri2_query == NULL || error != NULL) {
140                 fprintf(stderr, "DRI2: failed to query version");
141                 free(error);
142                 return EGL_FALSE;
143         }
144         c->dri2_major = dri2_query->major_version;
145         c->dri2_minor = dri2_query->minor_version;
146         free(dri2_query);
147
148         connect = xcb_dri2_connect_reply (c->conn,
149                                           connect_cookie, NULL);
150         if (connect == NULL ||
151             connect->driver_name_length + connect->device_name_length == 0) {
152                 fprintf(stderr, "DRI2: failed to authenticate");
153                 return -1;
154         }
155
156         c->base.base.device =
157                 strndup(xcb_dri2_connect_device_name (connect),
158                         xcb_dri2_connect_device_name_length (connect));
159                    
160         if (c->base.base.device == NULL) {
161                 free(connect);
162                 return -1;
163         }
164         free(connect);
165
166         return 0;
167 }
168
169 static int
170 dri2_authenticate(struct x11_compositor *c)
171 {
172         xcb_dri2_authenticate_reply_t *authenticate;
173         xcb_dri2_authenticate_cookie_t authenticate_cookie;
174         drm_magic_t magic;
175
176         if (drmGetMagic(c->drm_fd, &magic)) {
177                 fprintf(stderr, "DRI2: failed to get drm magic");
178                 return -1;
179         }
180
181         authenticate_cookie =
182                 xcb_dri2_authenticate_unchecked(c->conn,
183                                                 c->screen->root, magic);
184         authenticate =
185                 xcb_dri2_authenticate_reply(c->conn,
186                                             authenticate_cookie, NULL);
187         if (authenticate == NULL || !authenticate->authenticated) {
188                 fprintf(stderr, "DRI2: failed to authenticate");
189                 free(authenticate);
190                 return -1;
191         }
192
193         free(authenticate);
194
195         return 0;
196 }
197
198 static int
199 x11_compositor_init_egl(struct x11_compositor *c)
200 {
201         PFNEGLGETTYPEDDISPLAYMESA get_typed_display_mesa;
202         EGLint major, minor, count;
203         EGLConfig config;
204
205         static const EGLint config_attribs[] = {
206                 EGL_SURFACE_TYPE,               0,
207                 EGL_NO_SURFACE_CAPABLE_MESA,    EGL_OPENGL_BIT,
208                 EGL_RENDERABLE_TYPE,            EGL_OPENGL_BIT,
209                 EGL_NONE
210         };
211
212         if (dri2_connect(c) < 0)
213                 return -1;
214         
215         c->drm_fd = open(c->base.base.device, O_RDWR);
216         if (c->drm_fd == -1) {
217                 fprintf(stderr,
218                         "DRI2: could not open %s (%s)", c->base.base.device,
219                         strerror(errno));
220                 return -1;
221         }
222
223         if (dri2_authenticate(c) < 0)
224                 return -1;
225
226         get_typed_display_mesa =
227                 (PFNEGLGETTYPEDDISPLAYMESA)
228                 eglGetProcAddress("eglGetTypedDisplayMESA");
229         if (get_typed_display_mesa == NULL) {
230                 fprintf(stderr, "eglGetTypedDisplayMESA() not found\n");
231                 return -1;
232         }
233
234         c->base.display = get_typed_display_mesa(EGL_DRM_DISPLAY_TYPE_MESA,
235                                                  (void *) c->drm_fd);
236         if (c->base.display == NULL) {
237                 fprintf(stderr, "failed to create display\n");
238                 return -1;
239         }
240
241         if (!eglInitialize(c->base.display, &major, &minor)) {
242                 fprintf(stderr, "failed to initialize display\n");
243                 return -1;
244         }
245
246         if (!eglChooseConfig(c->base.display,
247                              config_attribs, &config, 1, &count) ||
248             count == 0) {
249                 fprintf(stderr, "eglChooseConfig() failed\n");
250                 return -1;
251         }
252
253         eglBindAPI(EGL_OPENGL_API);
254         c->base.context = eglCreateContext(c->base.display,
255                                            config, EGL_NO_CONTEXT, NULL);
256         if (c->base.context == NULL) {
257                 fprintf(stderr, "failed to create context\n");
258                 return -1;
259         }
260
261         if (!eglMakeCurrent(c->base.display, EGL_NO_SURFACE,
262                             EGL_NO_SURFACE, c->base.context)) {
263                 fprintf(stderr, "failed to make context current\n");
264                 return -1;
265         }
266
267         return 0;
268 }
269
270 static void
271 x11_compositor_present(struct wlsc_compositor *base)
272 {
273         struct x11_compositor *c = (struct x11_compositor *) base;
274         struct x11_output *output;
275         xcb_dri2_copy_region_cookie_t cookie;
276         struct timeval tv;
277         uint32_t msec;
278
279         glFlush();
280
281         wl_list_for_each(output, &c->base.output_list, base.link) {
282                 cookie = xcb_dri2_copy_region_unchecked(c->conn,
283                                                         output->window,
284                                                         output->region,
285                                                         XCB_DRI2_ATTACHMENT_BUFFER_FRONT_LEFT,
286                                                         XCB_DRI2_ATTACHMENT_BUFFER_BACK_LEFT);
287                 free(xcb_dri2_copy_region_reply(c->conn, cookie, NULL));
288         }       
289
290         gettimeofday(&tv, NULL);
291         msec = tv.tv_sec * 1000 + tv.tv_usec / 1000;
292         wlsc_compositor_finish_frame(&c->base, msec);
293 }
294
295 static void
296 x11_output_set_wm_protocols(struct x11_output *output)
297 {
298         xcb_atom_t list[1];
299         struct x11_compositor *c =
300                 (struct x11_compositor *) output->base.compositor;
301
302         list[0] = c->atom.wm_delete_window;
303         xcb_change_property (c->conn, 
304                              XCB_PROP_MODE_REPLACE,
305                              output->window,
306                              c->atom.wm_protocols,
307                              XCB_ATOM_ATOM,
308                              32,
309                              ARRAY_SIZE(list),
310                              list);
311 }
312
313 struct wm_normal_hints {
314         uint32_t flags;
315         uint32_t pad[4];
316         int32_t min_width, min_height;
317         int32_t max_width, max_height;
318         int32_t width_inc, height_inc;
319         int32_t min_aspect_x, min_aspect_y;
320         int32_t max_aspect_x, max_aspect_y;
321         int32_t base_width, base_height;
322         int32_t win_gravity;
323 };
324
325 #define WM_NORMAL_HINTS_MIN_SIZE        16
326 #define WM_NORMAL_HINTS_MAX_SIZE        32
327
328 static int
329 x11_compositor_create_output(struct x11_compositor *c, int width, int height)
330 {
331         static const char name[] = "Wayland Compositor";
332         struct x11_output *output;
333         xcb_dri2_dri2_buffer_t *buffers;
334         xcb_dri2_get_buffers_reply_t *reply;
335         xcb_dri2_get_buffers_cookie_t cookie;
336         xcb_screen_iterator_t iter;
337         xcb_rectangle_t rectangle;
338         struct wm_normal_hints normal_hints;
339         unsigned int attachments[] =
340                 { XCB_DRI2_ATTACHMENT_BUFFER_BACK_LEFT};
341         uint32_t mask = XCB_CW_EVENT_MASK | XCB_CW_CURSOR;
342         uint32_t values[2] = { 
343                 XCB_EVENT_MASK_KEY_PRESS |
344                 XCB_EVENT_MASK_KEY_RELEASE |
345                 XCB_EVENT_MASK_BUTTON_PRESS |
346                 XCB_EVENT_MASK_BUTTON_RELEASE |
347                 XCB_EVENT_MASK_POINTER_MOTION |
348                 XCB_EVENT_MASK_EXPOSURE |
349                 XCB_EVENT_MASK_STRUCTURE_NOTIFY |
350                 XCB_EVENT_MASK_ENTER_WINDOW |
351                 XCB_EVENT_MASK_LEAVE_WINDOW,
352                 0
353         };
354
355         EGLint attribs[] = {
356                 EGL_WIDTH,              0,
357                 EGL_HEIGHT,             0,
358                 EGL_IMAGE_STRIDE_MESA,  0,
359                 EGL_IMAGE_FORMAT_MESA,  EGL_IMAGE_FORMAT_ARGB8888_MESA,
360                 EGL_NONE
361         };
362
363         output = malloc(sizeof *output);
364         if (output == NULL)
365                 return -1;
366
367         memset(output, 0, sizeof *output);
368         wlsc_output_init(&output->base, &c->base, 0, 0, width, height);
369
370         values[1] = c->null_cursor;
371         output->window = xcb_generate_id(c->conn);
372         iter = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
373         xcb_create_window(c->conn,
374                           XCB_COPY_FROM_PARENT,
375                           output->window,
376                           iter.data->root,
377                           0, 0,
378                           width, height,
379                           0,
380                           XCB_WINDOW_CLASS_INPUT_OUTPUT,
381                           iter.data->root_visual,
382                           mask, values);
383
384         /* Don't resize me. */
385         memset(&normal_hints, 0, sizeof normal_hints);
386         normal_hints.flags =
387                 WM_NORMAL_HINTS_MAX_SIZE | WM_NORMAL_HINTS_MIN_SIZE;
388         normal_hints.min_width = width;
389         normal_hints.min_height = height;
390         normal_hints.max_width = width;
391         normal_hints.max_height = height;
392         xcb_change_property (c->conn, XCB_PROP_MODE_REPLACE, output->window,
393                              c->atom.wm_normal_hints,
394                              c->atom.wm_size_hints, 32,
395                              sizeof normal_hints / 4,
396                              (uint8_t *) &normal_hints);
397
398         xcb_map_window(c->conn, output->window);
399
400         /* Set window name.  Don't bother with non-EWMH WMs. */
401         xcb_change_property(c->conn, XCB_PROP_MODE_REPLACE, output->window,
402                             c->atom.net_wm_name, c->atom.utf8_string, 8,
403                             strlen(name), name);
404
405         rectangle.x = 0;
406         rectangle.y = 0;
407         rectangle.width = width;
408         rectangle.height = height;
409         output->region = xcb_generate_id(c->conn);
410         xcb_xfixes_create_region(c->conn, output->region, 1, &rectangle);
411
412         xcb_dri2_create_drawable (c->conn, output->window);
413
414         x11_output_set_wm_protocols(output);
415
416         cookie = xcb_dri2_get_buffers_unchecked (c->conn,
417                                                  output->window,
418                                                  1, 1, attachments);
419         reply = xcb_dri2_get_buffers_reply (c->conn, cookie, NULL);
420         if (reply == NULL)
421                 return -1;
422         buffers = xcb_dri2_get_buffers_buffers (reply);
423         if (buffers == NULL)
424                 return -1;
425
426         if (reply->count != 1) {
427                 fprintf(stderr,
428                         "got wrong number of buffers (%d)\n", reply->count);
429                 return -1;
430         }
431
432         attribs[1] = reply->width;
433         attribs[3] = reply->height;
434         attribs[5] = buffers[0].pitch / 4;
435         free(reply);
436
437         output->image =
438                 eglCreateImageKHR(c->base.display, c->base.context,
439                                   EGL_DRM_IMAGE_MESA,
440                                   (EGLClientBuffer) buffers[0].name,
441                                   attribs);
442
443         glGenRenderbuffers(1, &output->rbo);
444         glBindRenderbuffer(GL_RENDERBUFFER, output->rbo);
445
446         glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER,
447                                                output->image);
448
449         glFramebufferRenderbuffer(GL_FRAMEBUFFER,
450                                   GL_COLOR_ATTACHMENT0,
451                                   GL_RENDERBUFFER,
452                                   output->rbo);
453
454         wl_list_insert(c->base.output_list.prev, &output->base.link);
455
456         return 0;
457 }
458
459 static void
460 idle_repaint(void *data)
461 {
462         struct x11_output *output = data;
463         struct x11_compositor *c =
464                 (struct x11_compositor *) output->base.compositor;
465         xcb_xfixes_region_t region;
466         xcb_dri2_copy_region_cookie_t cookie;
467         
468         if (output->damage_count <= ARRAY_SIZE(output->damage)) {
469                 region = xcb_generate_id(c->conn);
470                 xcb_xfixes_create_region(c->conn, region,
471                                          output->damage_count, output->damage);
472         } else {
473                 region = output->region;
474         }
475
476         cookie = xcb_dri2_copy_region_unchecked(c->conn,
477                                                 output->window,
478                                                 region,
479                                                 XCB_DRI2_ATTACHMENT_BUFFER_FRONT_LEFT,
480                                                 XCB_DRI2_ATTACHMENT_BUFFER_BACK_LEFT);
481
482         if (region != output->region)
483                 xcb_xfixes_destroy_region(c->conn, region);
484
485         free(xcb_dri2_copy_region_reply(c->conn, cookie, NULL));
486         output->damage_count = 0;
487 }
488
489 static struct x11_output *
490 x11_compositor_find_output(struct x11_compositor *c, xcb_window_t window)
491 {
492         struct x11_output *output;
493
494         wl_list_for_each(output, &c->base.output_list, base.link) {
495                 if (output->window == window)
496                         return output;
497         }
498
499         return NULL;
500 }
501
502 static void
503 x11_compositor_handle_event(int fd, uint32_t mask, void *data)
504 {
505         struct x11_compositor *c = data;
506         struct x11_output *output;
507         xcb_generic_event_t *event;
508         struct wl_event_loop *loop;
509         xcb_client_message_event_t *client_message;
510         xcb_motion_notify_event_t *motion_notify;
511         xcb_key_press_event_t *key_press;
512         xcb_button_press_event_t *button_press;
513         xcb_expose_event_t *expose;
514         xcb_rectangle_t *r;
515         xcb_atom_t atom;
516
517         loop = wl_display_get_event_loop(c->base.wl_display);
518         while (event = xcb_poll_for_event (c->conn), event != NULL) {
519                 switch (event->response_type & ~0x80) {
520
521                 case XCB_KEY_PRESS:
522                         key_press = (xcb_key_press_event_t *) event;
523                         notify_key(c->base.input_device,
524                                    key_press->detail - 8, 1);
525                         break;
526                 case XCB_KEY_RELEASE:
527                         key_press = (xcb_key_press_event_t *) event;
528                         notify_key(c->base.input_device,
529                                    key_press->detail - 8, 0);
530                         break;
531                 case XCB_BUTTON_PRESS:
532                         button_press = (xcb_button_press_event_t *) event;
533                         notify_button(c->base.input_device,
534                                       button_press->detail + BTN_LEFT - 1, 1);
535                         break;
536                 case XCB_BUTTON_RELEASE:
537                         button_press = (xcb_button_press_event_t *) event;
538                         notify_button(c->base.input_device,
539                                       button_press->detail + BTN_LEFT - 1, 0);
540                         break;
541
542                 case XCB_MOTION_NOTIFY:
543                         motion_notify = (xcb_motion_notify_event_t *) event;
544                         notify_motion(c->base.input_device,
545                                       motion_notify->event_x,
546                                       motion_notify->event_y);
547                         break;
548
549                 case XCB_EXPOSE:
550                         expose = (xcb_expose_event_t *) event;
551                         output = x11_compositor_find_output(c, expose->window);
552                         if (output->damage_count == 0)
553                                 wl_event_loop_add_idle(loop,
554                                                        idle_repaint, output);
555
556                         r = &output->damage[output->damage_count++];
557                         if (output->damage_count > 16)
558                                 break;
559                         r->x = expose->x;
560                         r->y = expose->y;
561                         r->width = expose->width;
562                         r->height = expose->height;
563                         break;
564
565                 case XCB_ENTER_NOTIFY:
566                         c->base.focus = 1;
567                         wlsc_compositor_schedule_repaint(&c->base);
568                         break;
569
570                 case XCB_LEAVE_NOTIFY:
571                         c->base.focus = 0;
572                         wlsc_compositor_schedule_repaint(&c->base);
573                         break;
574
575                 case XCB_CLIENT_MESSAGE:
576                         client_message = (xcb_client_message_event_t *) event;
577                         atom = client_message->data.data32[0];
578                         if (atom == c->atom.wm_delete_window)
579                                 exit(1);
580                         break;
581                 default: 
582
583                         break;
584                 }
585
586                 free (event);
587         }
588 }
589
590 #define F(field) offsetof(struct x11_compositor, field)
591
592 static void
593 x11_compositor_get_resources(struct x11_compositor *c)
594 {
595         static const struct { const char *name; int offset; } atoms[] = {
596                 { "WM_PROTOCOLS",       F(atom.wm_protocols) },
597                 { "WM_NORMAL_HINTS",    F(atom.wm_normal_hints) },
598                 { "WM_SIZE_HINTS",      F(atom.wm_size_hints) },
599                 { "WM_DELETE_WINDOW",   F(atom.wm_delete_window) },
600                 { "_NET_WM_NAME",       F(atom.net_wm_name) },
601                 { "UTF8_STRING",        F(atom.utf8_string) },
602         };
603
604         xcb_intern_atom_cookie_t cookies[ARRAY_SIZE(atoms)];
605         xcb_intern_atom_reply_t *reply;
606         xcb_pixmap_t pixmap;
607         xcb_gc_t gc;
608         int i;
609         uint8_t data[] = { 0, 0, 0, 0 };
610
611         for (i = 0; i < ARRAY_SIZE(atoms); i++)
612                 cookies[i] = xcb_intern_atom (c->conn, 0,
613                                               strlen(atoms[i].name),
614                                               atoms[i].name);
615
616         for (i = 0; i < ARRAY_SIZE(atoms); i++) {
617                 reply = xcb_intern_atom_reply (c->conn, cookies[i], NULL);
618                 *(xcb_atom_t *) ((char *) c + atoms[i].offset) = reply->atom;
619                 free(reply);
620         }
621
622         pixmap = xcb_generate_id(c->conn);
623         gc = xcb_generate_id(c->conn);
624         xcb_create_pixmap(c->conn, 1, pixmap, c->screen->root, 1, 1);
625         xcb_create_gc(c->conn, gc, pixmap, 0, NULL);
626         xcb_put_image(c->conn, XCB_IMAGE_FORMAT_XY_PIXMAP,
627                       pixmap, gc, 1, 1, 0, 0, 0, 32, sizeof data, data);
628         c->null_cursor = xcb_generate_id(c->conn);
629         xcb_create_cursor (c->conn, c->null_cursor,
630                            pixmap, pixmap, 0, 0, 0,  0, 0, 0,  1, 1);
631         xcb_free_gc(c->conn, gc);
632         xcb_free_pixmap(c->conn, pixmap);
633 }
634
635 struct wlsc_compositor *
636 x11_compositor_create(struct wl_display *display)
637 {
638         struct x11_compositor *c;
639         struct wl_event_loop *loop;
640         xcb_screen_iterator_t s;
641
642         c = malloc(sizeof *c);
643         if (c == NULL)
644                 return NULL;
645
646         memset(c, 0, sizeof *c);
647         c->conn = xcb_connect(0, 0);
648
649         if (xcb_connection_has_error(c->conn))
650                 return NULL;
651
652         s = xcb_setup_roots_iterator(xcb_get_setup(c->conn));
653         c->screen = s.data;
654
655         x11_compositor_get_resources(c);
656
657         x11_compositor_init_egl(c);
658
659         /* Can't init base class until we have a current egl context */
660         if (wlsc_compositor_init(&c->base, display) < 0)
661                 return NULL;
662
663         x11_compositor_create_output(c, 1024, 640);
664
665         x11_input_create(c);
666
667         loop = wl_display_get_event_loop(c->base.wl_display);
668
669         c->xcb_source =
670                 wl_event_loop_add_fd(loop, xcb_get_file_descriptor(c->conn),
671                                      WL_EVENT_READABLE,
672                                      x11_compositor_handle_event, c);
673
674         c->base.present = x11_compositor_present;
675
676         return &c->base;
677 }