tests: Add agl-client-shell test
[src/agl-compositor.git] / tests / weston-test-client-helper.c
1 /*
2  * Copyright © 2012 Intel Corporation
3  * Copyright © 2015 Samsung Electronics Co., Ltd
4  * Copyright 2016, 2017 Collabora, Ltd.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial
16  * portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
22  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
23  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  */
27
28 #include "config.h"
29
30 #include <stdlib.h>
31 #include <stdint.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <sys/mman.h>
37 #include <cairo.h>
38
39 #include "test-config.h"
40 #include "shared/os-compatibility.h"
41 #include "shared/xalloc.h"
42 #include <libweston/zalloc.h>
43 #include "weston-test-client-helper.h"
44
45 #define max(a, b) (((a) > (b)) ? (a) : (b))
46 #define min(a, b) (((a) > (b)) ? (b) : (a))
47 #define clip(x, a, b)  min(max(x, a), b)
48
49 int
50 surface_contains(struct surface *surface, int x, int y)
51 {
52         /* test whether a global x,y point is contained in the surface */
53         int sx = surface->x;
54         int sy = surface->y;
55         int sw = surface->width;
56         int sh = surface->height;
57         return x >= sx && y >= sy && x < sx + sw && y < sy + sh;
58 }
59
60 static void
61 frame_callback_handler(void *data, struct wl_callback *callback, uint32_t time)
62 {
63         int *done = data;
64
65         *done = 1;
66
67         wl_callback_destroy(callback);
68 }
69
70 static const struct wl_callback_listener frame_listener = {
71         frame_callback_handler
72 };
73
74 struct wl_callback *
75 frame_callback_set(struct wl_surface *surface, int *done)
76 {
77         struct wl_callback *callback;
78
79         *done = 0;
80         callback = wl_surface_frame(surface);
81         wl_callback_add_listener(callback, &frame_listener, done);
82
83         return callback;
84 }
85
86 int
87 frame_callback_wait_nofail(struct client *client, int *done)
88 {
89         while (!*done) {
90                 if (wl_display_dispatch(client->wl_display) < 0)
91                         return 0;
92         }
93
94         return 1;
95 }
96
97 void
98 move_client(struct client *client, int x, int y)
99 {
100         struct surface *surface = client->surface;
101         int done;
102
103         client->surface->x = x;
104         client->surface->y = y;
105         weston_test_move_surface(client->test->weston_test, surface->wl_surface,
106                              surface->x, surface->y);
107         /* The attach here is necessary because commit() will call configure
108          * only on surfaces newly attached, and the one that sets the surface
109          * position is the configure. */
110         wl_surface_attach(surface->wl_surface, surface->buffer->proxy, 0, 0);
111         wl_surface_damage(surface->wl_surface, 0, 0, surface->width,
112                           surface->height);
113
114         frame_callback_set(surface->wl_surface, &done);
115
116         wl_surface_commit(surface->wl_surface);
117
118         frame_callback_wait(client, &done);
119 }
120
121 static void
122 pointer_handle_enter(void *data, struct wl_pointer *wl_pointer,
123                      uint32_t serial, struct wl_surface *wl_surface,
124                      wl_fixed_t x, wl_fixed_t y)
125 {
126         struct pointer *pointer = data;
127
128         if (wl_surface)
129                 pointer->focus = wl_surface_get_user_data(wl_surface);
130         else
131                 pointer->focus = NULL;
132
133         pointer->x = wl_fixed_to_int(x);
134         pointer->y = wl_fixed_to_int(y);
135
136         testlog("test-client: got pointer enter %d %d, surface %p\n",
137                 pointer->x, pointer->y, pointer->focus);
138 }
139
140 static void
141 pointer_handle_leave(void *data, struct wl_pointer *wl_pointer,
142                      uint32_t serial, struct wl_surface *wl_surface)
143 {
144         struct pointer *pointer = data;
145
146         pointer->focus = NULL;
147
148         testlog("test-client: got pointer leave, surface %p\n",
149                 wl_surface ? wl_surface_get_user_data(wl_surface) : NULL);
150 }
151
152 static void
153 pointer_handle_motion(void *data, struct wl_pointer *wl_pointer,
154                       uint32_t time_msec, wl_fixed_t x, wl_fixed_t y)
155 {
156         struct pointer *pointer = data;
157
158         pointer->x = wl_fixed_to_int(x);
159         pointer->y = wl_fixed_to_int(y);
160         pointer->motion_time_msec = time_msec;
161         pointer->motion_time_timespec = pointer->input_timestamp;
162         pointer->input_timestamp = (struct timespec) { 0 };
163
164         testlog("test-client: got pointer motion %d %d\n",
165                 pointer->x, pointer->y);
166 }
167
168 static void
169 pointer_handle_button(void *data, struct wl_pointer *wl_pointer,
170                       uint32_t serial, uint32_t time_msec, uint32_t button,
171                       uint32_t state)
172 {
173         struct pointer *pointer = data;
174
175         pointer->button = button;
176         pointer->state = state;
177         pointer->button_time_msec = time_msec;
178         pointer->button_time_timespec = pointer->input_timestamp;
179         pointer->input_timestamp = (struct timespec) { 0 };
180
181         testlog("test-client: got pointer button %u %u\n", button, state);
182 }
183
184 static void
185 pointer_handle_axis(void *data, struct wl_pointer *wl_pointer,
186                     uint32_t time_msec, uint32_t axis, wl_fixed_t value)
187 {
188         struct pointer *pointer = data;
189
190         pointer->axis = axis;
191         pointer->axis_value = wl_fixed_to_double(value);
192         pointer->axis_time_msec = time_msec;
193         pointer->axis_time_timespec = pointer->input_timestamp;
194         pointer->input_timestamp = (struct timespec) { 0 };
195
196         testlog("test-client: got pointer axis %u %f\n",
197                 axis, wl_fixed_to_double(value));
198 }
199
200 static void
201 pointer_handle_frame(void *data, struct wl_pointer *wl_pointer)
202 {
203         testlog("test-client: got pointer frame\n");
204 }
205
206 static void
207 pointer_handle_axis_source(void *data, struct wl_pointer *wl_pointer,
208                              uint32_t source)
209 {
210         testlog("test-client: got pointer axis source %u\n", source);
211 }
212
213 static void
214 pointer_handle_axis_stop(void *data, struct wl_pointer *wl_pointer,
215                          uint32_t time_msec, uint32_t axis)
216 {
217         struct pointer *pointer = data;
218
219         pointer->axis = axis;
220         pointer->axis_stop_time_msec = time_msec;
221         pointer->axis_stop_time_timespec = pointer->input_timestamp;
222         pointer->input_timestamp = (struct timespec) { 0 };
223
224         testlog("test-client: got pointer axis stop %u\n", axis);
225 }
226
227 static void
228 pointer_handle_axis_discrete(void *data, struct wl_pointer *wl_pointer,
229                              uint32_t axis, int32_t value)
230 {
231         testlog("test-client: got pointer axis discrete %u %d\n", axis, value);
232 }
233
234 static const struct wl_pointer_listener pointer_listener = {
235         pointer_handle_enter,
236         pointer_handle_leave,
237         pointer_handle_motion,
238         pointer_handle_button,
239         pointer_handle_axis,
240         pointer_handle_frame,
241         pointer_handle_axis_source,
242         pointer_handle_axis_stop,
243         pointer_handle_axis_discrete,
244 };
245
246 static void
247 keyboard_handle_keymap(void *data, struct wl_keyboard *wl_keyboard,
248                        uint32_t format, int fd, uint32_t size)
249 {
250         close(fd);
251
252         testlog("test-client: got keyboard keymap\n");
253 }
254
255 static void
256 keyboard_handle_enter(void *data, struct wl_keyboard *wl_keyboard,
257                       uint32_t serial, struct wl_surface *wl_surface,
258                       struct wl_array *keys)
259 {
260         struct keyboard *keyboard = data;
261
262         if (wl_surface)
263                 keyboard->focus = wl_surface_get_user_data(wl_surface);
264         else
265                 keyboard->focus = NULL;
266
267         testlog("test-client: got keyboard enter, surface %p\n",
268                 keyboard->focus);
269 }
270
271 static void
272 keyboard_handle_leave(void *data, struct wl_keyboard *wl_keyboard,
273                       uint32_t serial, struct wl_surface *wl_surface)
274 {
275         struct keyboard *keyboard = data;
276
277         keyboard->focus = NULL;
278
279         testlog("test-client: got keyboard leave, surface %p\n",
280                 wl_surface ? wl_surface_get_user_data(wl_surface) : NULL);
281 }
282
283 static void
284 keyboard_handle_key(void *data, struct wl_keyboard *wl_keyboard,
285                     uint32_t serial, uint32_t time_msec, uint32_t key,
286                     uint32_t state)
287 {
288         struct keyboard *keyboard = data;
289
290         keyboard->key = key;
291         keyboard->state = state;
292         keyboard->key_time_msec = time_msec;
293         keyboard->key_time_timespec = keyboard->input_timestamp;
294         keyboard->input_timestamp = (struct timespec) { 0 };
295
296         testlog("test-client: got keyboard key %u %u\n", key, state);
297 }
298
299 static void
300 keyboard_handle_modifiers(void *data, struct wl_keyboard *wl_keyboard,
301                           uint32_t serial, uint32_t mods_depressed,
302                           uint32_t mods_latched, uint32_t mods_locked,
303                           uint32_t group)
304 {
305         struct keyboard *keyboard = data;
306
307         keyboard->mods_depressed = mods_depressed;
308         keyboard->mods_latched = mods_latched;
309         keyboard->mods_locked = mods_locked;
310         keyboard->group = group;
311
312         testlog("test-client: got keyboard modifiers %u %u %u %u\n",
313                 mods_depressed, mods_latched, mods_locked, group);
314 }
315
316 static void
317 keyboard_handle_repeat_info(void *data, struct wl_keyboard *wl_keyboard,
318                             int32_t rate, int32_t delay)
319 {
320         struct keyboard *keyboard = data;
321
322         keyboard->repeat_info.rate = rate;
323         keyboard->repeat_info.delay = delay;
324
325         testlog("test-client: got keyboard repeat_info %d %d\n", rate, delay);
326 }
327
328 static const struct wl_keyboard_listener keyboard_listener = {
329         keyboard_handle_keymap,
330         keyboard_handle_enter,
331         keyboard_handle_leave,
332         keyboard_handle_key,
333         keyboard_handle_modifiers,
334         keyboard_handle_repeat_info,
335 };
336
337 static void
338 touch_handle_down(void *data, struct wl_touch *wl_touch,
339                   uint32_t serial, uint32_t time_msec,
340                   struct wl_surface *surface, int32_t id,
341                   wl_fixed_t x_w, wl_fixed_t y_w)
342 {
343         struct touch *touch = data;
344
345         touch->down_x = wl_fixed_to_int(x_w);
346         touch->down_y = wl_fixed_to_int(y_w);
347         touch->id = id;
348         touch->down_time_msec = time_msec;
349         touch->down_time_timespec = touch->input_timestamp;
350         touch->input_timestamp = (struct timespec) { 0 };
351
352         testlog("test-client: got touch down %d %d, surf: %p, id: %d\n",
353                 touch->down_x, touch->down_y, surface, id);
354 }
355
356 static void
357 touch_handle_up(void *data, struct wl_touch *wl_touch,
358                 uint32_t serial, uint32_t time_msec, int32_t id)
359 {
360         struct touch *touch = data;
361         touch->up_id = id;
362         touch->up_time_msec = time_msec;
363         touch->up_time_timespec = touch->input_timestamp;
364         touch->input_timestamp = (struct timespec) { 0 };
365
366         testlog("test-client: got touch up, id: %d\n", id);
367 }
368
369 static void
370 touch_handle_motion(void *data, struct wl_touch *wl_touch,
371                     uint32_t time_msec, int32_t id,
372                     wl_fixed_t x_w, wl_fixed_t y_w)
373 {
374         struct touch *touch = data;
375         touch->x = wl_fixed_to_int(x_w);
376         touch->y = wl_fixed_to_int(y_w);
377         touch->motion_time_msec = time_msec;
378         touch->motion_time_timespec = touch->input_timestamp;
379         touch->input_timestamp = (struct timespec) { 0 };
380
381         testlog("test-client: got touch motion, %d %d, id: %d\n",
382                 touch->x, touch->y, id);
383 }
384
385 static void
386 touch_handle_frame(void *data, struct wl_touch *wl_touch)
387 {
388         struct touch *touch = data;
389
390         ++touch->frame_no;
391
392         testlog("test-client: got touch frame (%d)\n", touch->frame_no);
393 }
394
395 static void
396 touch_handle_cancel(void *data, struct wl_touch *wl_touch)
397 {
398         struct touch *touch = data;
399
400         ++touch->cancel_no;
401
402         testlog("test-client: got touch cancel (%d)\n", touch->cancel_no);
403 }
404
405 static const struct wl_touch_listener touch_listener = {
406         touch_handle_down,
407         touch_handle_up,
408         touch_handle_motion,
409         touch_handle_frame,
410         touch_handle_cancel,
411 };
412
413 static void
414 surface_enter(void *data,
415               struct wl_surface *wl_surface, struct wl_output *output)
416 {
417         struct surface *surface = data;
418
419         surface->output = wl_output_get_user_data(output);
420
421         testlog("test-client: got surface enter output %p\n", surface->output);
422 }
423
424 static void
425 surface_leave(void *data,
426               struct wl_surface *wl_surface, struct wl_output *output)
427 {
428         struct surface *surface = data;
429
430         surface->output = NULL;
431
432         testlog("test-client: got surface leave output %p\n",
433                 wl_output_get_user_data(output));
434 }
435
436 static const struct wl_surface_listener surface_listener = {
437         surface_enter,
438         surface_leave
439 };
440
441 static struct buffer *
442 create_shm_buffer(struct client *client, int width, int height,
443                   pixman_format_code_t format, uint32_t wlfmt)
444 {
445         struct wl_shm *shm = client->wl_shm;
446         struct buffer *buf;
447         size_t stride_bytes;
448         struct wl_shm_pool *pool;
449         int fd;
450         void *data;
451         size_t bytes_pp;
452
453         assert(width > 0);
454         assert(height > 0);
455
456         buf = xzalloc(sizeof *buf);
457
458         bytes_pp = PIXMAN_FORMAT_BPP(format) / 8;
459         stride_bytes = width * bytes_pp;
460         /* round up to multiple of 4 bytes for Pixman */
461         stride_bytes = (stride_bytes + 3) & ~3u;
462         assert(stride_bytes / bytes_pp >= (unsigned)width);
463
464         buf->len = stride_bytes * height;
465         assert(buf->len / stride_bytes == (unsigned)height);
466
467         fd = os_create_anonymous_file(buf->len);
468         assert(fd >= 0);
469
470         data = mmap(NULL, buf->len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
471         if (data == MAP_FAILED) {
472                 close(fd);
473                 assert(data != MAP_FAILED);
474         }
475
476         pool = wl_shm_create_pool(shm, fd, buf->len);
477         buf->proxy = wl_shm_pool_create_buffer(pool, 0, width, height,
478                                                stride_bytes, wlfmt);
479         wl_shm_pool_destroy(pool);
480         close(fd);
481
482         buf->image = pixman_image_create_bits(format, width, height,
483                                               data, stride_bytes);
484
485         assert(buf->proxy);
486         assert(buf->image);
487
488         return buf;
489 }
490
491 struct buffer *
492 create_shm_buffer_a8r8g8b8(struct client *client, int width, int height)
493 {
494         assert(client->has_argb);
495
496         return create_shm_buffer(client, width, height,
497                                  PIXMAN_a8r8g8b8, WL_SHM_FORMAT_ARGB8888);
498 }
499
500 void
501 buffer_destroy(struct buffer *buf)
502 {
503         void *pixels;
504
505         pixels = pixman_image_get_data(buf->image);
506
507         if (buf->proxy) {
508                 wl_buffer_destroy(buf->proxy);
509                 assert(munmap(pixels, buf->len) == 0);
510         }
511
512         assert(pixman_image_unref(buf->image));
513
514         free(buf);
515 }
516
517 static void
518 shm_format(void *data, struct wl_shm *wl_shm, uint32_t format)
519 {
520         struct client *client = data;
521
522         if (format == WL_SHM_FORMAT_ARGB8888)
523                 client->has_argb = 1;
524 }
525
526 struct wl_shm_listener shm_listener = {
527         shm_format
528 };
529
530 static void
531 test_handle_pointer_position(void *data, struct weston_test *weston_test,
532                              wl_fixed_t x, wl_fixed_t y)
533 {
534         struct test *test = data;
535         test->pointer_x = wl_fixed_to_int(x);
536         test->pointer_y = wl_fixed_to_int(y);
537
538         testlog("test-client: got global pointer %d %d\n",
539                 test->pointer_x, test->pointer_y);
540 }
541
542 static void
543 test_handle_capture_screenshot_done(void *data, struct weston_test *weston_test)
544 {
545         struct test *test = data;
546
547         testlog("Screenshot has been captured\n");
548         test->buffer_copy_done = 1;
549 }
550
551 static const struct weston_test_listener test_listener = {
552         test_handle_pointer_position,
553         test_handle_capture_screenshot_done,
554 };
555
556 static void
557 input_destroy(struct input *inp)
558 {
559         if (inp->pointer) {
560                 wl_pointer_release(inp->pointer->wl_pointer);
561                 free(inp->pointer);
562         }
563         if (inp->keyboard) {
564                 wl_keyboard_release(inp->keyboard->wl_keyboard);
565                 free(inp->keyboard);
566         }
567         if (inp->touch) {
568                 wl_touch_release(inp->touch->wl_touch);
569                 free(inp->touch);
570         }
571         wl_list_remove(&inp->link);
572         wl_seat_release(inp->wl_seat);
573         free(inp->seat_name);
574         free(inp);
575 }
576
577 static void
578 input_update_devices(struct input *input)
579 {
580         struct pointer *pointer;
581         struct keyboard *keyboard;
582         struct touch *touch;
583
584         struct wl_seat *seat = input->wl_seat;
585         enum wl_seat_capability caps = input->caps;
586
587         if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) {
588                 pointer = xzalloc(sizeof *pointer);
589                 pointer->wl_pointer = wl_seat_get_pointer(seat);
590                 wl_pointer_set_user_data(pointer->wl_pointer, pointer);
591                 wl_pointer_add_listener(pointer->wl_pointer, &pointer_listener,
592                                         pointer);
593                 input->pointer = pointer;
594         } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) {
595                 wl_pointer_destroy(input->pointer->wl_pointer);
596                 free(input->pointer);
597                 input->pointer = NULL;
598         }
599
600         if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) {
601                 keyboard = xzalloc(sizeof *keyboard);
602                 keyboard->wl_keyboard = wl_seat_get_keyboard(seat);
603                 wl_keyboard_set_user_data(keyboard->wl_keyboard, keyboard);
604                 wl_keyboard_add_listener(keyboard->wl_keyboard, &keyboard_listener,
605                                          keyboard);
606                 input->keyboard = keyboard;
607         } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) {
608                 wl_keyboard_destroy(input->keyboard->wl_keyboard);
609                 free(input->keyboard);
610                 input->keyboard = NULL;
611         }
612
613         if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) {
614                 touch = xzalloc(sizeof *touch);
615                 touch->wl_touch = wl_seat_get_touch(seat);
616                 wl_touch_set_user_data(touch->wl_touch, touch);
617                 wl_touch_add_listener(touch->wl_touch, &touch_listener,
618                                          touch);
619                 input->touch = touch;
620         } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) {
621                 wl_touch_destroy(input->touch->wl_touch);
622                 free(input->touch);
623                 input->touch = NULL;
624         }
625 }
626
627 static void
628 seat_handle_capabilities(void *data, struct wl_seat *seat,
629                          enum wl_seat_capability caps)
630 {
631         struct input *input = data;
632
633         input->caps = caps;
634
635         /* we will create/update the devices only with the right (test) seat.
636          * If we haven't discovered which seat is the test seat, just
637          * store capabilities and bail out */
638         if (input->seat_name && strcmp(input->seat_name, "test-seat") == 0)
639                 input_update_devices(input);
640
641         testlog("test-client: got seat %p capabilities: %x\n", input, caps);
642 }
643
644 static void
645 seat_handle_name(void *data, struct wl_seat *seat, const char *name)
646 {
647         struct input *input = data;
648
649         input->seat_name = strdup(name);
650         assert(input->seat_name && "No memory");
651
652         /* We only update the devices and set client input for the test seat */
653         if (strcmp(name, "test-seat") == 0) {
654                 assert(!input->client->input &&
655                        "Multiple test seats detected!");
656
657                 input_update_devices(input);
658                 input->client->input = input;
659         }
660
661         testlog("test-client: got seat %p name: \'%s\'\n", input, name);
662 }
663
664 static const struct wl_seat_listener seat_listener = {
665         seat_handle_capabilities,
666         seat_handle_name,
667 };
668
669 static void
670 output_handle_geometry(void *data,
671                        struct wl_output *wl_output,
672                        int x, int y,
673                        int physical_width,
674                        int physical_height,
675                        int subpixel,
676                        const char *make,
677                        const char *model,
678                        int32_t transform)
679 {
680         struct output *output = data;
681
682         output->x = x;
683         output->y = y;
684 }
685
686 static void
687 output_handle_mode(void *data,
688                    struct wl_output *wl_output,
689                    uint32_t flags,
690                    int width,
691                    int height,
692                    int refresh)
693 {
694         struct output *output = data;
695
696         if (flags & WL_OUTPUT_MODE_CURRENT) {
697                 output->width = width;
698                 output->height = height;
699         }
700 }
701
702 static void
703 output_handle_scale(void *data,
704                     struct wl_output *wl_output,
705                     int scale)
706 {
707         struct output *output = data;
708
709         output->scale = scale;
710 }
711
712 static void
713 output_handle_done(void *data,
714                    struct wl_output *wl_output)
715 {
716         struct output *output = data;
717
718         output->initialized = 1;
719 }
720
721 static const struct wl_output_listener output_listener = {
722         output_handle_geometry,
723         output_handle_mode,
724         output_handle_done,
725         output_handle_scale,
726 };
727
728 static void
729 output_destroy(struct output *output)
730 {
731         assert(wl_proxy_get_version((struct wl_proxy *)output->wl_output) >= 3);
732         wl_output_release(output->wl_output);
733         wl_list_remove(&output->link);
734         free(output);
735 }
736
737 static void
738 handle_global(void *data, struct wl_registry *registry,
739               uint32_t id, const char *interface, uint32_t version)
740 {
741         struct client *client = data;
742         struct output *output;
743         struct test *test;
744         struct global *global;
745         struct input *input;
746
747         global = xzalloc(sizeof *global);
748         global->name = id;
749         global->interface = strdup(interface);
750         assert(interface);
751         global->version = version;
752         wl_list_insert(client->global_list.prev, &global->link);
753
754         /* We deliberately bind all globals with the maximum (advertised)
755          * version, because this test suite must be kept up-to-date with
756          * Weston. We must always implement at least the version advertised
757          * by Weston. This is not ok for normal clients, but it is ok in
758          * this test suite.
759          */
760
761         if (strcmp(interface, "wl_compositor") == 0) {
762                 client->wl_compositor =
763                         wl_registry_bind(registry, id,
764                                          &wl_compositor_interface, version);
765         } else if (strcmp(interface, "wl_seat") == 0) {
766                 input = xzalloc(sizeof *input);
767                 input->client = client;
768                 input->global_name = global->name;
769                 input->wl_seat =
770                         wl_registry_bind(registry, id,
771                                          &wl_seat_interface, version);
772                 wl_seat_add_listener(input->wl_seat, &seat_listener, input);
773                 wl_list_insert(&client->inputs, &input->link);
774         } else if (strcmp(interface, "wl_shm") == 0) {
775                 client->wl_shm =
776                         wl_registry_bind(registry, id,
777                                          &wl_shm_interface, version);
778                 wl_shm_add_listener(client->wl_shm, &shm_listener, client);
779         } else if (strcmp(interface, "wl_output") == 0) {
780                 output = xzalloc(sizeof *output);
781                 output->wl_output =
782                         wl_registry_bind(registry, id,
783                                          &wl_output_interface, version);
784                 wl_output_add_listener(output->wl_output,
785                                        &output_listener, output);
786                 wl_list_insert(&client->output_list, &output->link);
787                 client->output = output;
788         } else if (strcmp(interface, "weston_test") == 0) {
789                 test = xzalloc(sizeof *test);
790                 test->weston_test =
791                         wl_registry_bind(registry, id,
792                                          &weston_test_interface, version);
793                 weston_test_add_listener(test->weston_test, &test_listener, test);
794                 client->test = test;
795         } else if (strcmp(interface, "wl_drm") == 0) {
796                 client->has_wl_drm = true;
797         }
798 }
799
800 static struct global *
801 client_find_global_with_name(struct client *client, uint32_t name)
802 {
803         struct global *global;
804
805         wl_list_for_each(global, &client->global_list, link) {
806                 if (global->name == name)
807                         return global;
808         }
809
810         return NULL;
811 }
812
813 static struct input *
814 client_find_input_with_name(struct client *client, uint32_t name)
815 {
816         struct input *input;
817
818         wl_list_for_each(input, &client->inputs, link) {
819                 if (input->global_name == name)
820                         return input;
821         }
822
823         return NULL;
824 }
825
826 static void
827 global_destroy(struct global *global)
828 {
829         wl_list_remove(&global->link);
830         free(global->interface);
831         free(global);
832 }
833
834 static void
835 handle_global_remove(void *data, struct wl_registry *registry, uint32_t name)
836 {
837         struct client *client = data;
838         struct global *global;
839         struct input *input;
840
841         global = client_find_global_with_name(client, name);
842         assert(global && "Request to remove unknown global");
843
844         if (strcmp(global->interface, "wl_seat") == 0) {
845                 input = client_find_input_with_name(client, name);
846                 if (input) {
847                         if (client->input == input)
848                                 client->input = NULL;
849                         input_destroy(input);
850                 }
851         }
852
853         /* XXX: handle wl_output */
854
855         global_destroy(global);
856 }
857
858 static const struct wl_registry_listener registry_listener = {
859         handle_global,
860         handle_global_remove,
861 };
862
863 void
864 skip(const char *fmt, ...)
865 {
866         va_list argp;
867
868         va_start(argp, fmt);
869         vfprintf(stderr, fmt, argp);
870         va_end(argp);
871
872         /* automake tests uses exit code 77. weston-test-runner will see
873          * this and use it, and then weston-test's sigchld handler (in the
874          * weston process) will use that as an exit status, which is what
875          * ninja will see in the end. */
876         exit(77);
877 }
878
879 void
880 expect_protocol_error(struct client *client,
881                       const struct wl_interface *intf,
882                       uint32_t code)
883 {
884         int err;
885         uint32_t errcode, failed = 0;
886         const struct wl_interface *interface;
887         unsigned int id;
888
889         /* if the error has not come yet, make it happen */
890         wl_display_roundtrip(client->wl_display);
891
892         err = wl_display_get_error(client->wl_display);
893
894         assert(err && "Expected protocol error but nothing came");
895         assert(err == EPROTO && "Expected protocol error but got local error");
896
897         errcode = wl_display_get_protocol_error(client->wl_display,
898                                                 &interface, &id);
899
900         /* check error */
901         if (errcode != code) {
902                 testlog("Should get error code %d but got %d\n", code, errcode);
903                 failed = 1;
904         }
905
906         /* this should be definitely set */
907         assert(interface);
908
909         if (strcmp(intf->name, interface->name) != 0) {
910                 testlog("Should get interface '%s' but got '%s'\n",
911                         intf->name, interface->name);
912                 failed = 1;
913         }
914
915         if (failed) {
916                 testlog("Expected other protocol error\n");
917                 abort();
918         }
919
920         /* all OK */
921         testlog("Got expected protocol error on '%s' (object id: %d) "
922                 "with code %d\n", interface->name, id, errcode);
923 }
924
925 static void
926 log_handler(const char *fmt, va_list args)
927 {
928         fprintf(stderr, "libwayland: ");
929         vfprintf(stderr, fmt, args);
930 }
931
932 struct client *
933 create_client(void)
934 {
935         struct client *client;
936
937         wl_log_set_handler_client(log_handler);
938
939         /* connect to display */
940         client = xzalloc(sizeof *client);
941         client->wl_display = wl_display_connect(NULL);
942         assert(client->wl_display);
943         wl_list_init(&client->global_list);
944         wl_list_init(&client->inputs);
945         wl_list_init(&client->output_list);
946
947         /* setup registry so we can bind to interfaces */
948         client->wl_registry = wl_display_get_registry(client->wl_display);
949         wl_registry_add_listener(client->wl_registry, &registry_listener,
950                                  client);
951
952         /* this roundtrip makes sure we have all globals and we bound to them */
953         client_roundtrip(client);
954         /* this roundtrip makes sure we got all wl_shm.format and wl_seat.*
955          * events */
956         client_roundtrip(client);
957
958         /* must have WL_SHM_FORMAT_ARGB32 */
959         assert(client->has_argb);
960
961         /* must have weston_test interface */
962         assert(client->test);
963
964         /* must have an output */
965         assert(client->output);
966
967         /* the output must be initialized */
968         assert(client->output->initialized == 1);
969
970         /* must have seat set */
971         assert(client->input);
972
973         return client;
974 }
975
976 struct surface *
977 create_test_surface(struct client *client)
978 {
979         struct surface *surface;
980
981         surface = xzalloc(sizeof *surface);
982
983         surface->wl_surface =
984                 wl_compositor_create_surface(client->wl_compositor);
985         assert(surface->wl_surface);
986
987         wl_surface_add_listener(surface->wl_surface, &surface_listener,
988                                 surface);
989
990         wl_surface_set_user_data(surface->wl_surface, surface);
991
992         return surface;
993 }
994
995 void
996 surface_destroy(struct surface *surface)
997 {
998         if (surface->wl_surface)
999                 wl_surface_destroy(surface->wl_surface);
1000         if (surface->buffer)
1001                 buffer_destroy(surface->buffer);
1002         free(surface);
1003 }
1004
1005 struct client *
1006 create_client_and_test_surface(int x, int y, int width, int height)
1007 {
1008         struct client *client;
1009         struct surface *surface;
1010         pixman_color_t color = { 16384, 16384, 16384, 16384 }; /* uint16_t */
1011         pixman_image_t *solid;
1012
1013         client = create_client();
1014
1015         /* initialize the client surface */
1016         surface = create_test_surface(client);
1017         client->surface = surface;
1018
1019         surface->width = width;
1020         surface->height = height;
1021         surface->buffer = create_shm_buffer_a8r8g8b8(client, width, height);
1022
1023         solid = pixman_image_create_solid_fill(&color);
1024         pixman_image_composite32(PIXMAN_OP_SRC,
1025                                  solid, /* src */
1026                                  NULL, /* mask */
1027                                  surface->buffer->image, /* dst */
1028                                  0, 0, /* src x,y */
1029                                  0, 0, /* mask x,y */
1030                                  0, 0, /* dst x,y */
1031                                  width, height);
1032         pixman_image_unref(solid);
1033
1034         move_client(client, x, y);
1035
1036         return client;
1037 }
1038
1039 void
1040 client_destroy(struct client *client)
1041 {
1042         if (client->surface)
1043                 surface_destroy(client->surface);
1044
1045         while (!wl_list_empty(&client->inputs)) {
1046                 input_destroy(container_of(client->inputs.next,
1047                                            struct input, link));
1048         }
1049
1050         while (!wl_list_empty(&client->output_list)) {
1051                 output_destroy(container_of(client->output_list.next,
1052                                             struct output, link));
1053         }
1054
1055         while (!wl_list_empty(&client->global_list)) {
1056                 global_destroy(container_of(client->global_list.next,
1057                                             struct global, link));
1058         }
1059
1060         if (client->test) {
1061                 weston_test_destroy(client->test->weston_test);
1062                 free(client->test);
1063         }
1064
1065         if (client->wl_shm)
1066                 wl_shm_destroy(client->wl_shm);
1067         if (client->wl_compositor)
1068                 wl_compositor_destroy(client->wl_compositor);
1069         if (client->wl_registry)
1070                 wl_registry_destroy(client->wl_registry);
1071
1072         client_roundtrip(client);
1073
1074         if (client->wl_display)
1075                 wl_display_disconnect(client->wl_display);
1076         free(client);
1077 }
1078
1079 static const char*
1080 output_path(void)
1081 {
1082         char *path = getenv("WESTON_TEST_OUTPUT_PATH");
1083
1084         if (!path)
1085                 return ".";
1086
1087         return path;
1088 }
1089
1090 char*
1091 screenshot_output_filename(const char *basename, uint32_t seq)
1092 {
1093         char *filename;
1094
1095         if (asprintf(&filename, "%s/%s-%02d.png",
1096                                  output_path(), basename, seq) < 0)
1097                 return NULL;
1098         return filename;
1099 }
1100
1101 static const char*
1102 reference_path(void)
1103 {
1104         char *path = getenv("WESTON_TEST_REFERENCE_PATH");
1105
1106         if (!path)
1107                 return WESTON_TEST_REFERENCE_PATH;
1108         return path;
1109 }
1110
1111 char*
1112 screenshot_reference_filename(const char *basename, uint32_t seq)
1113 {
1114         char *filename;
1115
1116         if (asprintf(&filename, "%s/%s-%02d.png",
1117                                  reference_path(), basename, seq) < 0)
1118                 return NULL;
1119         return filename;
1120 }
1121
1122 char *
1123 image_filename(const char *basename)
1124 {
1125         char *filename;
1126
1127         if (asprintf(&filename, "%s/%s.png", reference_path(), basename) < 0)
1128                 assert(0);
1129         return filename;
1130 }
1131
1132 struct format_map_entry {
1133         cairo_format_t cairo;
1134         pixman_format_code_t pixman;
1135 };
1136
1137 static const struct format_map_entry format_map[] = {
1138         { CAIRO_FORMAT_ARGB32,    PIXMAN_a8r8g8b8 },
1139         { CAIRO_FORMAT_RGB24,     PIXMAN_x8r8g8b8 },
1140         { CAIRO_FORMAT_A8,        PIXMAN_a8 },
1141         { CAIRO_FORMAT_RGB16_565, PIXMAN_r5g6b5 },
1142 };
1143
1144 static pixman_format_code_t
1145 format_cairo2pixman(cairo_format_t fmt)
1146 {
1147         unsigned i;
1148
1149         for (i = 0; i < ARRAY_LENGTH(format_map); i++)
1150                 if (format_map[i].cairo == fmt)
1151                         return format_map[i].pixman;
1152
1153         assert(0 && "unknown Cairo pixel format");
1154 }
1155
1156 static cairo_format_t
1157 format_pixman2cairo(pixman_format_code_t fmt)
1158 {
1159         unsigned i;
1160
1161         for (i = 0; i < ARRAY_LENGTH(format_map); i++)
1162                 if (format_map[i].pixman == fmt)
1163                         return format_map[i].cairo;
1164
1165         assert(0 && "unknown Pixman pixel format");
1166 }
1167
1168 /**
1169  * Validate range
1170  *
1171  * \param r Range to validate or NULL.
1172  * \return The given range, or {0, 0} for NULL.
1173  *
1174  * Will abort if range is invalid, that is a > b.
1175  */
1176 static struct range
1177 range_get(const struct range *r)
1178 {
1179         if (!r)
1180                 return (struct range){ 0, 0 };
1181
1182         assert(r->a <= r->b);
1183         return *r;
1184 }
1185
1186 /**
1187  * Compute the ROI for image comparisons
1188  *
1189  * \param img_a An image.
1190  * \param img_b Another image.
1191  * \param clip_rect Explicit ROI, or NULL for using the whole
1192  * image area.
1193  *
1194  * \return The region of interest (ROI) that is guaranteed to be inside both
1195  * images.
1196  *
1197  * If clip_rect is given, it must fall inside of both images.
1198  * If clip_rect is NULL, the images must be of the same size.
1199  * If any precondition is violated, this function aborts with an error.
1200  *
1201  * The ROI is given as pixman_box32_t, where x2,y2 are non-inclusive.
1202  */
1203 static pixman_box32_t
1204 image_check_get_roi(pixman_image_t *img_a, pixman_image_t *img_b,
1205                    const struct rectangle *clip_rect)
1206 {
1207         int width_a;
1208         int width_b;
1209         int height_a;
1210         int height_b;
1211         pixman_box32_t box;
1212
1213         width_a = pixman_image_get_width(img_a);
1214         height_a = pixman_image_get_height(img_a);
1215
1216         width_b = pixman_image_get_width(img_b);
1217         height_b = pixman_image_get_height(img_b);
1218
1219         if (clip_rect) {
1220                 box.x1 = clip_rect->x;
1221                 box.y1 = clip_rect->y;
1222                 box.x2 = clip_rect->x + clip_rect->width;
1223                 box.y2 = clip_rect->y + clip_rect->height;
1224         } else {
1225                 box.x1 = 0;
1226                 box.y1 = 0;
1227                 box.x2 = max(width_a, width_b);
1228                 box.y2 = max(height_a, height_b);
1229         }
1230
1231         assert(box.x1 >= 0);
1232         assert(box.y1 >= 0);
1233         assert(box.x2 > box.x1);
1234         assert(box.y2 > box.y1);
1235         assert(box.x2 <= width_a);
1236         assert(box.x2 <= width_b);
1237         assert(box.y2 <= height_a);
1238         assert(box.y2 <= height_b);
1239
1240         return box;
1241 }
1242
1243 struct image_iterator {
1244         char *data;
1245         int stride; /* bytes */
1246 };
1247
1248 static void
1249 image_iter_init(struct image_iterator *it, pixman_image_t *image)
1250 {
1251         pixman_format_code_t fmt;
1252
1253         it->stride = pixman_image_get_stride(image);
1254         it->data = (void *)pixman_image_get_data(image);
1255
1256         fmt = pixman_image_get_format(image);
1257         assert(PIXMAN_FORMAT_BPP(fmt) == 32);
1258 }
1259
1260 static uint32_t *
1261 image_iter_get_row(struct image_iterator *it, int y)
1262 {
1263         return (uint32_t *)(it->data + y * it->stride);
1264 }
1265
1266 struct pixel_diff_stat {
1267         struct pixel_diff_stat_channel {
1268                 int min_diff;
1269                 int max_diff;
1270         } ch[4];
1271 };
1272
1273 static void
1274 testlog_pixel_diff_stat(const struct pixel_diff_stat *stat)
1275 {
1276         int i;
1277
1278         testlog("Image difference statistics:\n");
1279         for (i = 0; i < 4; i++) {
1280                 testlog("\tch %d: [%d, %d]\n",
1281                         i, stat->ch[i].min_diff, stat->ch[i].max_diff);
1282         }
1283 }
1284
1285 static bool
1286 fuzzy_match_pixels(uint32_t pix_a, uint32_t pix_b,
1287                    const struct range *fuzz,
1288                    struct pixel_diff_stat *stat)
1289 {
1290         bool ret = true;
1291         int shift;
1292         int i;
1293
1294         for (shift = 0, i = 0; i < 4; shift += 8, i++) {
1295                 int val_a = (pix_a >> shift) & 0xffu;
1296                 int val_b = (pix_b >> shift) & 0xffu;
1297                 int d = val_b - val_a;
1298
1299                 stat->ch[i].min_diff = min(stat->ch[i].min_diff, d);
1300                 stat->ch[i].max_diff = max(stat->ch[i].max_diff, d);
1301
1302                 if (d < fuzz->a || d > fuzz->b)
1303                         ret = false;
1304         }
1305
1306         return ret;
1307 }
1308
1309 /**
1310  * Test if a given region within two images are pixel-identical
1311  *
1312  * Returns true if the two images pixel-wise identical, and false otherwise.
1313  *
1314  * \param img_a First image.
1315  * \param img_b Second image.
1316  * \param clip_rect The region of interest, or NULL for comparing the whole
1317  * images.
1318  * \param prec Per-channel allowed difference, or NULL for identical match
1319  * required.
1320  *
1321  * This function hard-fails if clip_rect is not inside both images. If clip_rect
1322  * is given, the images do not have to match in size, otherwise size mismatch
1323  * will be a hard failure.
1324  *
1325  * The per-pixel, per-channel difference is computed as img_b - img_a which is
1326  * required to be in the range [prec->a, prec->b] inclusive. The difference is
1327  * signed. All four channels are compared the same way, without any special
1328  * meaning on alpha channel.
1329  */
1330 bool
1331 check_images_match(pixman_image_t *img_a, pixman_image_t *img_b,
1332                    const struct rectangle *clip_rect, const struct range *prec)
1333 {
1334         struct range fuzz = range_get(prec);
1335         struct pixel_diff_stat diffstat = {};
1336         struct image_iterator it_a;
1337         struct image_iterator it_b;
1338         pixman_box32_t box;
1339         int x, y;
1340         uint32_t *pix_a;
1341         uint32_t *pix_b;
1342
1343         box = image_check_get_roi(img_a, img_b, clip_rect);
1344
1345         image_iter_init(&it_a, img_a);
1346         image_iter_init(&it_b, img_b);
1347
1348         for (y = box.y1; y < box.y2; y++) {
1349                 pix_a = image_iter_get_row(&it_a, y) + box.x1;
1350                 pix_b = image_iter_get_row(&it_b, y) + box.x1;
1351
1352                 for (x = box.x1; x < box.x2; x++) {
1353                         if (!fuzzy_match_pixels(*pix_a, *pix_b,
1354                                                 &fuzz, &diffstat))
1355                                 return false;
1356
1357                         pix_a++;
1358                         pix_b++;
1359                 }
1360         }
1361
1362         return true;
1363 }
1364
1365 /**
1366  * Tint a color
1367  *
1368  * \param src Source pixel as x8r8g8b8.
1369  * \param add The tint as x8r8g8b8, x8 must be zero; r8, g8 and b8 must be
1370  * no greater than 0xc0 to avoid overflow to another channel.
1371  * \return The tinted pixel color as x8r8g8b8, x8 guaranteed to be 0xff.
1372  *
1373  * The source pixel RGB values are divided by 4, and then the tint is added.
1374  * To achieve colors outside of the range of src, a tint color channel must be
1375  * at least 0x40. (0xff / 4 = 0x3f, 0xff - 0x3f = 0xc0)
1376  */
1377 static uint32_t
1378 tint(uint32_t src, uint32_t add)
1379 {
1380         uint32_t v;
1381
1382         v = ((src & 0xfcfcfcfc) >> 2) | 0xff000000;
1383
1384         return v + add;
1385 }
1386
1387 /**
1388  * Create a visualization of image differences.
1389  *
1390  * \param img_a First image, which is used as the basis for the output.
1391  * \param img_b Second image.
1392  * \param clip_rect The region of interest, or NULL for comparing the whole
1393  * images.
1394  * \param prec Per-channel allowed difference, or NULL for identical match
1395  * required.
1396  * \return A new image with the differences highlighted.
1397  *
1398  * Regions outside of the region of interest are shaded with black, matching
1399  * pixels are shaded with green, and differing pixels are shaded with
1400  * bright red.
1401  *
1402  * This function hard-fails if clip_rect is not inside both images. If clip_rect
1403  * is given, the images do not have to match in size, otherwise size mismatch
1404  * will be a hard failure.
1405  *
1406  * The per-pixel, per-channel difference is computed as img_b - img_a which is
1407  * required to be in the range [prec->a, prec->b] inclusive. The difference is
1408  * signed. All four channels are compared the same way, without any special
1409  * meaning on alpha channel.
1410  */
1411 pixman_image_t *
1412 visualize_image_difference(pixman_image_t *img_a, pixman_image_t *img_b,
1413                            const struct rectangle *clip_rect,
1414                            const struct range *prec)
1415 {
1416         struct range fuzz = range_get(prec);
1417         struct pixel_diff_stat diffstat = {};
1418         pixman_image_t *diffimg;
1419         pixman_image_t *shade;
1420         struct image_iterator it_a;
1421         struct image_iterator it_b;
1422         struct image_iterator it_d;
1423         int width;
1424         int height;
1425         pixman_box32_t box;
1426         int x, y;
1427         uint32_t *pix_a;
1428         uint32_t *pix_b;
1429         uint32_t *pix_d;
1430         pixman_color_t shade_color = { 0, 0, 0, 32768 };
1431
1432         width = pixman_image_get_width(img_a);
1433         height = pixman_image_get_height(img_a);
1434         box = image_check_get_roi(img_a, img_b, clip_rect);
1435
1436         diffimg = pixman_image_create_bits_no_clear(PIXMAN_x8r8g8b8,
1437                                                     width, height, NULL, 0);
1438
1439         /* Fill diffimg with a black-shaded copy of img_a, and then fill
1440          * the clip_rect area with original img_a.
1441          */
1442         shade = pixman_image_create_solid_fill(&shade_color);
1443         pixman_image_composite32(PIXMAN_OP_SRC, img_a, shade, diffimg,
1444                                  0, 0, 0, 0, 0, 0, width, height);
1445         pixman_image_unref(shade);
1446         pixman_image_composite32(PIXMAN_OP_SRC, img_a, NULL, diffimg,
1447                                  box.x1, box.y1, 0, 0, box.x1, box.y1,
1448                                  box.x2 - box.x1, box.y2 - box.y1);
1449
1450         image_iter_init(&it_a, img_a);
1451         image_iter_init(&it_b, img_b);
1452         image_iter_init(&it_d, diffimg);
1453
1454         for (y = box.y1; y < box.y2; y++) {
1455                 pix_a = image_iter_get_row(&it_a, y) + box.x1;
1456                 pix_b = image_iter_get_row(&it_b, y) + box.x1;
1457                 pix_d = image_iter_get_row(&it_d, y) + box.x1;
1458
1459                 for (x = box.x1; x < box.x2; x++) {
1460                         if (fuzzy_match_pixels(*pix_a, *pix_b,
1461                                                &fuzz, &diffstat))
1462                                 *pix_d = tint(*pix_d, 0x00008000); /* green */
1463                         else
1464                                 *pix_d = tint(*pix_d, 0x00c00000); /* red */
1465
1466                         pix_a++;
1467                         pix_b++;
1468                         pix_d++;
1469                 }
1470         }
1471
1472         testlog_pixel_diff_stat(&diffstat);
1473
1474         return diffimg;
1475 }
1476
1477 /**
1478  * Write an image into a PNG file.
1479  *
1480  * \param image The image.
1481  * \param fname The name and path for the file.
1482  *
1483  * \returns true if successfully saved file; false otherwise.
1484  *
1485  * \note Only image formats directly supported by Cairo are accepted, not all
1486  * Pixman formats.
1487  */
1488 bool
1489 write_image_as_png(pixman_image_t *image, const char *fname)
1490 {
1491         cairo_surface_t *cairo_surface;
1492         cairo_status_t status;
1493         cairo_format_t fmt;
1494
1495         fmt = format_pixman2cairo(pixman_image_get_format(image));
1496
1497         cairo_surface = cairo_image_surface_create_for_data(
1498                         (void *)pixman_image_get_data(image),
1499                         fmt,
1500                         pixman_image_get_width(image),
1501                         pixman_image_get_height(image),
1502                         pixman_image_get_stride(image));
1503
1504         status = cairo_surface_write_to_png(cairo_surface, fname);
1505         if (status != CAIRO_STATUS_SUCCESS) {
1506                 testlog("Failed to save image '%s': %s\n", fname,
1507                         cairo_status_to_string(status));
1508
1509                 return false;
1510         }
1511
1512         cairo_surface_destroy(cairo_surface);
1513
1514         return true;
1515 }
1516
1517 static pixman_image_t *
1518 image_convert_to_a8r8g8b8(pixman_image_t *image)
1519 {
1520         pixman_image_t *ret;
1521         int width;
1522         int height;
1523
1524         if (pixman_image_get_format(image) == PIXMAN_a8r8g8b8)
1525                 return pixman_image_ref(image);
1526
1527         width = pixman_image_get_width(image);
1528         height = pixman_image_get_height(image);
1529
1530         ret = pixman_image_create_bits_no_clear(PIXMAN_a8r8g8b8, width, height,
1531                                                 NULL, 0);
1532         assert(ret);
1533
1534         pixman_image_composite32(PIXMAN_OP_SRC, image, NULL, ret,
1535                                  0, 0, 0, 0, 0, 0, width, height);
1536
1537         return ret;
1538 }
1539
1540 static void
1541 destroy_cairo_surface(pixman_image_t *image, void *data)
1542 {
1543         cairo_surface_t *surface = data;
1544
1545         cairo_surface_destroy(surface);
1546 }
1547
1548 /**
1549  * Load an image from a PNG file
1550  *
1551  * Reads a PNG image from disk using the given filename (and path)
1552  * and returns as a Pixman image. Use pixman_image_unref() to free it.
1553  *
1554  * The returned image is always in PIXMAN_a8r8g8b8 format.
1555  *
1556  * @returns Pixman image, or NULL in case of error.
1557  */
1558 pixman_image_t *
1559 load_image_from_png(const char *fname)
1560 {
1561         pixman_image_t *image;
1562         pixman_image_t *converted;
1563         cairo_format_t cairo_fmt;
1564         pixman_format_code_t pixman_fmt;
1565         cairo_surface_t *reference_cairo_surface;
1566         cairo_status_t status;
1567         int width;
1568         int height;
1569         int stride;
1570         void *data;
1571
1572         reference_cairo_surface = cairo_image_surface_create_from_png(fname);
1573         cairo_surface_flush(reference_cairo_surface);
1574         status = cairo_surface_status(reference_cairo_surface);
1575         if (status != CAIRO_STATUS_SUCCESS) {
1576                 testlog("Could not open %s: %s\n", fname,
1577                         cairo_status_to_string(status));
1578                 cairo_surface_destroy(reference_cairo_surface);
1579                 return NULL;
1580         }
1581
1582         cairo_fmt = cairo_image_surface_get_format(reference_cairo_surface);
1583         pixman_fmt = format_cairo2pixman(cairo_fmt);
1584
1585         width = cairo_image_surface_get_width(reference_cairo_surface);
1586         height = cairo_image_surface_get_height(reference_cairo_surface);
1587         stride = cairo_image_surface_get_stride(reference_cairo_surface);
1588         data = cairo_image_surface_get_data(reference_cairo_surface);
1589
1590         /* The Cairo surface will own the data, so we keep it around. */
1591         image = pixman_image_create_bits_no_clear(pixman_fmt,
1592                                                   width, height, data, stride);
1593         assert(image);
1594
1595         pixman_image_set_destroy_function(image, destroy_cairo_surface,
1596                                           reference_cairo_surface);
1597
1598         converted = image_convert_to_a8r8g8b8(image);
1599         pixman_image_unref(image);
1600
1601         return converted;
1602 }
1603
1604 /**
1605  * Take screenshot of a single output
1606  *
1607  * Requests a screenshot from the server of the output that the
1608  * client appears on. This implies that the compositor goes through an output
1609  * repaint to provide the screenshot before this function returns. This
1610  * function is therefore both a server roundtrip and a wait for a repaint.
1611  *
1612  * @returns A new buffer object, that should be freed with buffer_destroy().
1613  */
1614 struct buffer *
1615 capture_screenshot_of_output(struct client *client)
1616 {
1617         struct buffer *buffer;
1618
1619         buffer = create_shm_buffer_a8r8g8b8(client,
1620                                             client->output->width,
1621                                             client->output->height);
1622
1623         client->test->buffer_copy_done = 0;
1624         weston_test_capture_screenshot(client->test->weston_test,
1625                                        client->output->wl_output,
1626                                        buffer->proxy);
1627         while (client->test->buffer_copy_done == 0)
1628                 if (wl_display_dispatch(client->wl_display) < 0)
1629                         break;
1630
1631         /* FIXME: Document somewhere the orientation the screenshot is taken
1632          * and how the clip coords are interpreted, in case of scaling/transform.
1633          * If we're using read_pixels() just make sure it is documented somewhere.
1634          * Protocol docs in the XML, comparison function docs in Doxygen style.
1635          */
1636
1637         return buffer;
1638 }
1639
1640 static void
1641 write_visual_diff(pixman_image_t *ref_image,
1642                   struct buffer *shot,
1643                   const struct rectangle *clip,
1644                   const char *test_name,
1645                   int seq_no,
1646                   const struct range *fuzz)
1647 {
1648         char *fname;
1649         char *ext_test_name;
1650         pixman_image_t *diff;
1651         int ret;
1652
1653         ret = asprintf(&ext_test_name, "%s-diff", test_name);
1654         assert(ret >= 0);
1655
1656         fname = screenshot_output_filename(ext_test_name, seq_no);
1657         diff = visualize_image_difference(ref_image, shot->image, clip, fuzz);
1658         write_image_as_png(diff, fname);
1659
1660         pixman_image_unref(diff);
1661         free(fname);
1662         free(ext_test_name);
1663 }
1664
1665 /**
1666  * Take a screenshot and verify its contents
1667  *
1668  * Takes a screenshot and writes the image into a PNG file named with
1669  * get_test_name() and seq_no. Compares the contents to the given reference
1670  * image over the given clip rectangle, reports whether they match to the
1671  * test log, and if they do not match writes a visual diff into a PNG file.
1672  *
1673  * The compositor output size and the reference image size must both contain
1674  * the clip rectangle.
1675  *
1676  * This function uses the pixel value allowed fuzz approriate for GL-renderer
1677  * with 8 bits per channel data.
1678  *
1679  * \param client The client, for connecting to the compositor.
1680  * \param ref_image The reference image file basename, without sequence number
1681  * and .png suffix.
1682  * \param ref_seq_no The reference image sequence number.
1683  * \param clip The region of interest, or NULL for comparing the whole
1684  * images.
1685  * \param seq_no Test sequence number, for writing output files.
1686  * \return True if the screen contents matches the reference image,
1687  * false otherwise.
1688  *
1689  * For bootstrapping, ref_image can be NULL or the file can be missing.
1690  * In that case the screenshot file is written but no comparison is performed,
1691  * and false is returned.
1692  */
1693 bool
1694 verify_screen_content(struct client *client,
1695                       const char *ref_image,
1696                       int ref_seq_no,
1697                       const struct rectangle *clip,
1698                       int seq_no)
1699 {
1700         const char *test_name = get_test_name();
1701         const struct range gl_fuzz = { -3, 4 };
1702         struct buffer *shot;
1703         pixman_image_t *ref = NULL;
1704         char *ref_fname = NULL;
1705         char *shot_fname;
1706         bool match;
1707
1708         shot = capture_screenshot_of_output(client);
1709         assert(shot);
1710         shot_fname = screenshot_output_filename(test_name, seq_no);
1711         write_image_as_png(shot->image, shot_fname);
1712
1713         if (ref_image) {
1714                 ref_fname = screenshot_reference_filename(ref_image, ref_seq_no);
1715                 ref = load_image_from_png(ref_fname);
1716         }
1717
1718         if (ref) {
1719                 match = check_images_match(ref, shot->image, clip, &gl_fuzz);
1720                 testlog("Verify reference image %s vs. shot %s: %s\n",
1721                         ref_fname, shot_fname, match ? "PASS" : "FAIL");
1722
1723                 if (!match) {
1724                         write_visual_diff(ref, shot, clip,
1725                                           test_name, seq_no, &gl_fuzz);
1726                 }
1727
1728                 pixman_image_unref(ref);
1729         } else {
1730                 testlog("No reference image, shot %s: FAIL\n", shot_fname);
1731                 match = false;
1732         }
1733
1734         free(ref_fname);
1735         buffer_destroy(shot);
1736         free(shot_fname);
1737
1738         return match;
1739 }
1740
1741 /**
1742  * Create a wl_buffer from a PNG file
1743  *
1744  * Loads the named PNG file from the directory of reference images,
1745  * creates a wl_buffer with scale times the image dimensions in pixels,
1746  * and copies the image content into the buffer using nearest-neighbor filter.
1747  *
1748  * \param client The client, for the Wayland connection.
1749  * \param basename The PNG file name without .png suffix.
1750  * \param scale Upscaling factor >= 1.
1751  */
1752 struct buffer *
1753 client_buffer_from_image_file(struct client *client,
1754                               const char *basename,
1755                               int scale)
1756 {
1757         struct buffer *buf;
1758         char *fname;
1759         pixman_image_t *img;
1760         int buf_w, buf_h;
1761         pixman_transform_t scaling;
1762
1763         assert(scale >= 1);
1764
1765         fname = image_filename(basename);
1766         img = load_image_from_png(fname);
1767         free(fname);
1768         assert(img);
1769
1770         buf_w = scale * pixman_image_get_width(img);
1771         buf_h = scale * pixman_image_get_height(img);
1772         buf = create_shm_buffer_a8r8g8b8(client, buf_w, buf_h);
1773
1774         pixman_transform_init_scale(&scaling,
1775                                     pixman_fixed_1 / scale,
1776                                     pixman_fixed_1 / scale);
1777         pixman_image_set_transform(img, &scaling);
1778         pixman_image_set_filter(img, PIXMAN_FILTER_NEAREST, NULL, 0);
1779
1780         pixman_image_composite32(PIXMAN_OP_SRC,
1781                                  img, /* src */
1782                                  NULL, /* mask */
1783                                  buf->image, /* dst */
1784                                  0, 0, /* src x,y */
1785                                  0, 0, /* mask x,y */
1786                                  0, 0, /* dst x,y */
1787                                  buf_w, buf_h);
1788         pixman_image_unref(img);
1789
1790         return buf;
1791 }
1792
1793 /**
1794  * Bind to a singleton global in wl_registry
1795  *
1796  * \param client Client whose registry and globals to use.
1797  * \param iface The Wayland interface to look for.
1798  * \param version The version to bind the interface with.
1799  * \return A struct wl_proxy, which you need to cast to the proper type.
1800  *
1801  * Asserts that the global being searched for is a singleton and is found.
1802  *
1803  * Binds with the exact version given, does not take compositor interface
1804  * version into account.
1805  */
1806 void *
1807 bind_to_singleton_global(struct client *client,
1808                          const struct wl_interface *iface,
1809                          int version)
1810 {
1811         struct global *tmp;
1812         struct global *g = NULL;
1813         struct wl_proxy *proxy;
1814
1815         wl_list_for_each(tmp, &client->global_list, link) {
1816                 if (strcmp(tmp->interface, iface->name))
1817                         continue;
1818
1819                 assert(!g && "multiple singleton objects");
1820                 g = tmp;
1821         }
1822
1823         assert(g && "singleton not found");
1824
1825         proxy = wl_registry_bind(client->wl_registry, g->name, iface, version);
1826         assert(proxy);
1827
1828         return proxy;
1829 }
1830
1831 /**
1832  * Create a wp_viewport for the client surface
1833  *
1834  * \param client The client->surface to use.
1835  * \return A fresh viewport object.
1836  */
1837 struct wp_viewport *
1838 client_create_viewport(struct client *client)
1839 {
1840         struct wp_viewporter *viewporter;
1841         struct wp_viewport *viewport;
1842
1843         viewporter = bind_to_singleton_global(client,
1844                                               &wp_viewporter_interface, 1);
1845         viewport = wp_viewporter_get_viewport(viewporter,
1846                                               client->surface->wl_surface);
1847         assert(viewport);
1848         wp_viewporter_destroy(viewporter);
1849
1850         return viewport;
1851 }
1852
1853 /**
1854  * Fill the image with the given color
1855  *
1856  * \param image The image to write to.
1857  * \param color The color to use.
1858  */
1859 void
1860 fill_image_with_color(pixman_image_t *image, pixman_color_t *color)
1861 {
1862         pixman_image_t *solid;
1863         int width;
1864         int height;
1865
1866         width = pixman_image_get_width(image);
1867         height = pixman_image_get_height(image);
1868
1869         solid = pixman_image_create_solid_fill(color);
1870         pixman_image_composite32(PIXMAN_OP_SRC,
1871                                  solid, /* src */
1872                                  NULL, /* mask */
1873                                  image, /* dst */
1874                                  0, 0, /* src x,y */
1875                                  0, 0, /* mask x,y */
1876                                  0, 0, /* dst x,y */
1877                                  width, height);
1878         pixman_image_unref(solid);
1879 }
1880
1881 /**
1882  * Convert 8-bit RGB to opaque Pixman color
1883  *
1884  * \param tmp Pixman color struct to fill in.
1885  * \param r Red value, 0 - 255.
1886  * \param g Green value, 0 - 255.
1887  * \param b Blue value, 0 - 255.
1888  * \return tmp
1889  */
1890 pixman_color_t *
1891 color_rgb888(pixman_color_t *tmp, uint8_t r, uint8_t g, uint8_t b)
1892 {
1893         tmp->alpha = 65535;
1894         tmp->red = (r << 8) + r;
1895         tmp->green = (g << 8) + g;
1896         tmp->blue = (b << 8) + b;
1897
1898         return tmp;
1899 }