Import source, backport to libweston 6.0
[src/agl-compositor.git] / src / main.c
1 /*
2  * Copyright © 2012-2019 Collabora, Ltd.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial
14  * portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25
26 #include "ivi-compositor.h"
27
28 #include <assert.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <linux/input.h>
38
39 #include <libweston-6/compositor-drm.h>
40 #include <libweston-6/compositor-wayland.h>
41 #include <libweston-6/compositor-x11.h>
42 #include <libweston-6/compositor.h>
43 #include <libweston-6/windowed-output-api.h>
44 #include <libweston-6/config-parser.h>
45
46 #include "shared/os-compatibility.h"
47
48 #include "agl-shell-server-protocol.h"
49
50 struct ivi_compositor *
51 to_ivi_compositor(struct weston_compositor *ec)
52 {
53         return weston_compositor_get_user_data(ec);
54 }
55
56 static void
57 handle_output_destroy(struct wl_listener *listener, void *data)
58 {
59         struct ivi_output *output;
60
61         output = wl_container_of(listener, output, output_destroy);
62         assert(output->output == data);
63
64         output->output = NULL;
65         wl_list_remove(&output->output_destroy.link);
66 }
67
68 struct ivi_output *
69 to_ivi_output(struct weston_output *o)
70 {
71         struct wl_listener *listener;
72         struct ivi_output *output;
73
74         listener = weston_output_get_destroy_listener(o, handle_output_destroy);
75         output = wl_container_of(listener, output, output_destroy);
76
77         return output;
78 }
79
80 static struct ivi_output *
81 ivi_ensure_output(struct ivi_compositor *ivi, char *name,
82                   struct weston_config_section *config)
83 {
84         struct ivi_output *output = NULL;
85         wl_list_for_each(output, &ivi->outputs, link) {
86                 if (strcmp(output->name, name) == 0) {
87                         free(name);
88                         return output;
89                 }
90         }
91
92         output = zalloc(sizeof *output);
93         if (!output) {
94                 free(name);
95                 return NULL;
96         }
97
98         output->ivi = ivi;
99         output->name = name;
100         output->config = config;
101
102         output->output = weston_compositor_create_output(ivi->compositor, name);
103         if (!output->output) {
104                 free(output->name);
105                 free(output);
106                 return NULL;
107         }
108
109         output->output_destroy.notify = handle_output_destroy;
110         weston_output_add_destroy_listener(output->output,
111                                            &output->output_destroy);
112
113         wl_list_insert(&ivi->outputs, &output->link);
114         return output;
115 }
116
117 static void
118 ivi_output_destroy(struct ivi_output *output)
119 {
120         weston_output_destroy(output->output);
121         free(output->name);
122         wl_list_remove(&output->link);
123         free(output);
124 }
125
126 static int
127 count_heads(struct weston_output *output)
128 {
129         struct weston_head *iter = NULL;
130         int n = 0;
131
132         while ((iter = weston_output_iterate_heads(output, iter)))
133                 ++n;
134
135         return n;
136 }
137
138 static void
139 handle_head_destroy(struct wl_listener *listener, void *data)
140 {
141         struct weston_head *head = data;
142         struct weston_output *output;
143
144         wl_list_remove(&listener->link);
145         free(listener);
146
147         output = weston_head_get_output(head);
148
149         /* On shutdown path, the output might be already gone. */
150         if (!output)
151                 return;
152
153         /* We're the last head */
154         if (count_heads(output) <= 1)
155                 weston_output_destroy(output);
156 }
157
158 static void
159 add_head_destroyed_listener(struct weston_head *head)
160 {
161         /* We already have a destroy listener */
162         if (weston_head_get_destroy_listener(head, handle_head_destroy))
163                 return;
164
165         struct wl_listener *listener = zalloc(sizeof *listener);
166         if (!listener)
167                 return;
168
169         listener->notify = handle_head_destroy;
170         weston_head_add_destroy_listener(head, listener);
171 }
172
173 static int
174 drm_configure_output(struct ivi_output *output)
175 {
176         struct ivi_compositor *ivi = output->ivi;
177         struct weston_config_section *section = output->config;
178         enum weston_drm_backend_output_mode mode =
179                 WESTON_DRM_BACKEND_OUTPUT_PREFERRED;
180         char *modeline = NULL;
181         char *gbm_format = NULL;
182         char *seat = NULL;
183
184         if (section) {
185                 char *m;
186                 weston_config_section_get_string(section, "mode", &m, "preferred");
187
188                 /* This should have been handled earlier */
189                 assert(strcmp(m, "off") != 0);
190
191                 if (ivi->cmdline.use_current_mode || strcmp(m, "current") == 0) {
192                         mode = WESTON_DRM_BACKEND_OUTPUT_CURRENT;
193                 } else if (strcmp(m, "preferred") != 0) {
194                         modeline = m;
195                         m = NULL;
196                 }
197                 free(m);
198
199                 weston_config_section_get_string(section, "gbm-format",
200                                                  &gbm_format, NULL);
201
202                 weston_config_section_get_string(section, "seat", &seat, "");
203         }
204
205         if (ivi->drm_api->set_mode(output->output, mode, modeline) < 0) {
206                 weston_log("Cannot configure output using weston_drm_output_api.\n");
207                 free(modeline);
208                 return -1;
209         }
210         free(modeline);
211
212         ivi->drm_api->set_gbm_format(output->output, gbm_format);
213         free(gbm_format);
214
215         ivi->drm_api->set_seat(output->output, seat);
216         free(seat);
217
218         return 0;
219 }
220
221 #define WINDOWED_DEFAULT_WIDTH 1024
222 #define WINDOWED_DEFAULT_HEIGHT 768
223
224 static int
225 windowed_configure_output(struct ivi_output *output)
226 {
227         struct ivi_compositor *ivi = output->ivi;
228         struct weston_config_section *section = output->config;
229         int width = WINDOWED_DEFAULT_WIDTH;
230         int height = WINDOWED_DEFAULT_HEIGHT;
231
232         if (section) {
233                 char *mode;
234
235                 weston_config_section_get_string(section, "mode", &mode, NULL);
236                 if (!mode || sscanf(mode, "%dx%d", &width, &height) != 2) {
237                         weston_log("Invalid mode for output %s. Using defaults.\n",
238                                    output->name);
239                         width = WINDOWED_DEFAULT_WIDTH;
240                         height = WINDOWED_DEFAULT_HEIGHT;
241                 }
242                 free(mode);
243         }
244
245         if (ivi->cmdline.width)
246                 width = ivi->cmdline.width;
247         if (ivi->cmdline.height)
248                 height = ivi->cmdline.height;
249         if (ivi->cmdline.scale)
250                 weston_output_set_scale(output->output, ivi->cmdline.scale);
251
252         if (ivi->window_api->output_set_size(output->output, width, height) < 0) {
253                 weston_log("Cannot configure output '%s' using weston_windowed_output_api.\n",
254                            output->name);
255                 return -1;
256         }
257
258         return 0;
259 }
260
261 static int
262 parse_transform(const char *transform, uint32_t *out)
263 {
264         static const struct { const char *name; uint32_t token; } transforms[] = {
265                 { "normal",     WL_OUTPUT_TRANSFORM_NORMAL },
266                 { "90",         WL_OUTPUT_TRANSFORM_90 },
267                 { "180",        WL_OUTPUT_TRANSFORM_180 },
268                 { "270",        WL_OUTPUT_TRANSFORM_270 },
269                 { "flipped",    WL_OUTPUT_TRANSFORM_FLIPPED },
270                 { "flipped-90", WL_OUTPUT_TRANSFORM_FLIPPED_90 },
271                 { "flipped-180", WL_OUTPUT_TRANSFORM_FLIPPED_180 },
272                 { "flipped-270", WL_OUTPUT_TRANSFORM_FLIPPED_270 },
273         };
274
275         for (size_t i = 0; i < ARRAY_LENGTH(transforms); i++)
276                 if (strcmp(transforms[i].name, transform) == 0) {
277                         *out = transforms[i].token;
278                         return 0;
279                 }
280
281         *out = WL_OUTPUT_TRANSFORM_NORMAL;
282         return -1;
283 }
284
285 static int
286 configure_output(struct ivi_output *output)
287 {
288         struct ivi_compositor *ivi = output->ivi;
289         struct weston_config_section *section = output->config;
290         int32_t scale = 1;
291         uint32_t transform = WL_OUTPUT_TRANSFORM_NORMAL;
292
293         /*
294          * This can happen with the wayland backend with 'sprawl'. The config
295          * is hard-coded, so we don't need to do anything.
296          */
297         if (!ivi->drm_api && !ivi->window_api)
298                 return 0;
299
300         if (section) {
301                 char *t;
302
303                 weston_config_section_get_int(section, "scale", &scale, 1);
304                 weston_config_section_get_string(section, "transform", &t, "normal");
305                 if (parse_transform(t, &transform) < 0)
306                         weston_log("Invalid transform \"%s\" for output %s\n",
307                                    t, output->name);
308                 free(t);
309         }
310
311         weston_output_set_scale(output->output, scale);
312         weston_output_set_transform(output->output, transform);
313
314         if (ivi->drm_api)
315                 return drm_configure_output(output);
316         else
317                 return windowed_configure_output(output);
318 }
319
320 /*
321  * Reorgainizes the output's add array into two sections.
322  * add[0..ret-1] are the heads that failed to get attached.
323  * add[ret..add_len] are the heads that were successfully attached.
324  *
325  * The order between elements in each section is stable.
326  */
327 static size_t
328 try_attach_heads(struct ivi_output *output)
329 {
330         size_t fail_len = 0;
331
332         for (size_t i = 0; i < output->add_len; ++i) {
333                 if (weston_output_attach_head(output->output, output->add[i]) < 0) {
334                         struct weston_head *tmp = output->add[i];
335                         memmove(&output->add[fail_len + 1], output->add[fail_len],
336                                 sizeof output->add[0] * (i - fail_len));
337                         output->add[fail_len++] = tmp;
338                 }
339         }
340
341         return fail_len;
342 }
343
344 /*
345  * Like try_attach_heads, this reorganizes the output's add array into a failed
346  * and successful section.
347  * i is the number of heads that already failed the previous step.
348  */
349 static size_t
350 try_enable_output(struct ivi_output *output, size_t i)
351 {
352         for (; i < output->add_len; ++i) {
353                 struct weston_head *head;
354
355                 if (weston_output_enable(output->output) == 0)
356                         break;
357
358                 head = output->add[output->add_len - 1];
359                 memmove(&output->add[i + 1], &output->add[i],
360                         sizeof output->add[0] * (output->add_len - i));
361                 output->add[i] = head;
362
363                 weston_head_detach(head);
364         }
365
366         return i;
367 }
368
369 static int
370 try_attach_enable_heads(struct ivi_output *output)
371 {
372         size_t fail_len;
373         assert(!output->output->enabled);
374
375         fail_len = try_attach_heads(output);
376
377         if (configure_output(output) < 0)
378                 return -1;
379
380         fail_len = try_enable_output(output, fail_len);
381
382         /* All heads failed to be attached */
383         if (fail_len == output->add_len)
384                 return -1;
385
386         /* For each successful head attached */
387         for (size_t i = fail_len; i < output->add_len; ++i)
388                 add_head_destroyed_listener(output->add[i]);
389
390         output->add_len = fail_len;
391         return 0;
392 }
393
394 static int
395 process_output(struct ivi_output *output)
396 {
397         if (output->output->enabled) {
398                 output->add_len = try_attach_heads(output);
399                 return output->add_len == 0 ? 0 : -1;
400         }
401
402         return try_attach_enable_heads(output);
403 }
404
405 static void
406 head_disable(struct ivi_compositor *ivi, struct weston_head *head)
407 {
408         struct weston_output *output;
409         struct ivi_output *ivi_output;
410         struct wl_listener *listener;
411
412         output = weston_head_get_output(head);
413         assert(output);
414
415         listener = weston_output_get_destroy_listener(output,
416                                                       handle_output_destroy);
417         assert(listener);
418
419         ivi_output = wl_container_of(listener, ivi_output, output_destroy);
420         assert(ivi_output->output == output);
421
422         weston_head_detach(head);
423         if (count_heads(ivi_output->output) == 0) {
424                 ivi_output_destroy(ivi_output);
425                 weston_output_disable(ivi_output->output);
426         }
427 }
428
429 static struct weston_config_section *
430 find_controlling_output_config(struct weston_config *config,
431                                const char *name)
432 {
433         struct weston_config_section *section;
434         char *same_as;
435         int depth = 0;
436
437         same_as = strdup(name);
438         do {
439                 section = weston_config_get_section(config, "output",
440                                                     "name", same_as);
441                 if (!section && depth > 0)
442                         weston_log("Configuration error: output section reffered"
443                                    "to by same-as=%s not found.\n", same_as);
444                 free(same_as);
445
446                 if (!section)
447                         return NULL;
448
449                 if (depth++ > 8) {
450                         weston_log("Configuration error: same-as nested too "
451                                    "deep for output '%s'.\n", name);
452                         return NULL;
453                 }
454
455                 weston_config_section_get_string(section, "same-as",
456                                                  &same_as, NULL);
457         } while (same_as);
458
459         return section;
460 }
461
462 static void
463 head_prepare_enable(struct ivi_compositor *ivi, struct weston_head *head)
464 {
465         const char *name = weston_head_get_name(head);
466         struct weston_config_section *section;
467         struct ivi_output *output;
468         char *output_name = NULL;
469
470         section = find_controlling_output_config(ivi->config, name);
471         if (section) {
472                 char *mode;
473
474                 weston_config_section_get_string(section, "mode", &mode, NULL);
475                 if (mode && strcmp(mode, "off") == 0) {
476                         free(mode);
477                         return;
478                 }
479                 free(mode);
480
481                 weston_config_section_get_string(section, "name",
482                                                  &output_name, NULL);
483         } else {
484                 output_name = strdup(name);
485         }
486
487         if (!output_name)
488                 return;
489
490         output = ivi_ensure_output(ivi, output_name, section);
491         if (!output)
492                 return;
493
494         if (output->add_len >= ARRAY_LENGTH(output->add))
495                 return;
496
497         output->add[output->add_len++] = head;
498 }
499
500 static void
501 heads_changed(struct wl_listener *listener, void *arg)
502 {
503         struct weston_compositor *compositor = arg;
504         struct weston_head *head = NULL;
505         struct ivi_compositor *ivi = to_ivi_compositor(compositor);
506         struct ivi_output *output;
507
508         while ((head = weston_compositor_iterate_heads(ivi->compositor, head))) {
509                 bool connected = weston_head_is_connected(head);
510                 bool enabled = weston_head_is_enabled(head);
511                 bool changed = weston_head_is_device_changed(head);
512                 bool non_desktop = weston_head_is_non_desktop(head);
513
514                 if (connected && !enabled && !non_desktop)
515                         head_prepare_enable(ivi, head);
516                 else if (!connected && enabled)
517                         head_disable(ivi, head);
518                 else if (enabled && changed)
519                         weston_log("Detected a monitor change on head '%s', "
520                                    "not bothering to do anything about it.\n",
521                                    weston_head_get_name(head));
522
523                 weston_head_reset_device_changed(head);
524         }
525
526         wl_list_for_each(output, &ivi->outputs, link) {
527                 if (output->add_len == 0)
528                         continue;
529
530                 if (process_output(output) < 0) {
531                         output->add_len = 0;
532                         ivi->init_failed = true;
533                 }
534         }
535 }
536
537 static int
538 load_drm_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
539 {
540         struct weston_drm_backend_config config = {
541                 .base = {
542                         .struct_version = WESTON_DRM_BACKEND_CONFIG_VERSION,
543                         .struct_size = sizeof config,
544                 },
545         };
546         struct weston_config_section *section;
547         int use_current_mode = 0;
548         int use_pixman = 0;
549         int use_shadow;
550         int ret;
551
552         const struct weston_option options[] = {
553                 { WESTON_OPTION_STRING, "seat", 0, &config.seat_id },
554                 { WESTON_OPTION_INTEGER, "tty", 0, &config.tty },
555                 { WESTON_OPTION_STRING, "drm-device", 0, &config.specific_device },
556                 { WESTON_OPTION_BOOLEAN, "current-mode", 0, &use_current_mode },
557                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
558         };
559
560         parse_options(options, ARRAY_LENGTH(options), argc, argv);
561         config.use_pixman = use_pixman;
562         ivi->cmdline.use_current_mode = use_current_mode;
563
564         section = weston_config_get_section(ivi->config, "core", NULL, NULL);
565         weston_config_section_get_string(section, "gbm-format",
566                                          &config.gbm_format, NULL);
567         weston_config_section_get_uint(section, "pageflip-timeout",
568                                        &config.pageflip_timeout, 0);
569         weston_config_section_get_bool(section, "pixman-shadow", &use_shadow, 1);
570         config.use_pixman_shadow = use_shadow;
571
572         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_DRM,
573                                              &config.base);
574         if (ret < 0)
575                 return ret;
576
577         ivi->drm_api = weston_drm_output_get_api(ivi->compositor);
578         if (!ivi->drm_api) {
579                 weston_log("Cannot use drm output api.\n");
580                 ret = -1;
581                 goto error;
582         }
583
584 error:
585         free(config.gbm_format);
586         free(config.seat_id);
587         return ret;
588 }
589
590 static void
591 windowed_parse_common_options(struct ivi_compositor *ivi, int *argc, char *argv[],
592                               bool *use_pixman, bool *fullscreen, int *output_count)
593 {
594         struct weston_config_section *section;
595         int pixman;
596         int fs = 0;
597
598         const struct weston_option options[] = {
599                 { WESTON_OPTION_INTEGER, "width", 0, &ivi->cmdline.width },
600                 { WESTON_OPTION_INTEGER, "height", 0, &ivi->cmdline.height },
601                 { WESTON_OPTION_INTEGER, "scale", 0, &ivi->cmdline.scale },
602                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &pixman },
603                 { WESTON_OPTION_BOOLEAN, "fullscreen", 0, &fs },
604                 { WESTON_OPTION_INTEGER, "output-count", 0, output_count },
605         };
606
607         section = weston_config_get_section(ivi->config, "core", NULL, NULL);
608         weston_config_section_get_bool(section, "use-pixman", &pixman, 0);
609
610         *output_count = 1;
611         parse_options(options, ARRAY_LENGTH(options), argc, argv);
612         *use_pixman = pixman;
613         *fullscreen = fs;
614 }
615
616 static int
617 windowed_create_outputs(struct ivi_compositor *ivi, int output_count,
618                         const char *match_prefix, const char *name_prefix)
619 {
620         struct weston_config_section *section = NULL;
621         const char *section_name;
622         char *default_output = NULL;
623         int i = 0;
624         size_t match_len = strlen(match_prefix);
625
626         while (weston_config_next_section(ivi->config, &section, &section_name)) {
627                 char *output_name;
628
629                 if (i >= output_count)
630                         break;
631
632                 if (strcmp(section_name, "output") != 0)
633                         continue;
634
635                 weston_config_section_get_string(section, "name", &output_name, NULL);
636                 if (output_name == NULL)
637                         continue;
638                 if (strncmp(output_name, match_prefix, match_len) != 0) {
639                         free(output_name);
640                         continue;
641                 }
642
643                 if (ivi->window_api->create_head(ivi->compositor, output_name) < 0) {
644                         free(output_name);
645                         return -1;
646                 }
647
648                 free(output_name);
649                 ++i;
650         }
651
652         for (; i < output_count; ++i) {
653                 if (asprintf(&default_output, "%s%d", name_prefix, i) < 0)
654                         return -1;
655
656                 if (ivi->window_api->create_head(ivi->compositor, default_output) < 0) {
657                         free(default_output);
658                         return -1;
659                 }
660
661                 free(default_output);
662         }
663
664         return 0;
665 }
666
667 static int
668 load_wayland_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
669 {
670         struct weston_wayland_backend_config config = {
671                 .base = {
672                         .struct_version = WESTON_WAYLAND_BACKEND_CONFIG_VERSION,
673                         .struct_size = sizeof config,
674                 },
675         };
676         struct weston_config_section *section;
677         int sprawl = 0;
678         int output_count;
679         int ret;
680
681         const struct weston_option options[] = {
682                 { WESTON_OPTION_STRING, "display", 0, &config.display_name },
683                 { WESTON_OPTION_STRING, "sprawl", 0, &sprawl },
684         };
685
686         windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
687                                       &config.fullscreen, &output_count);
688
689         parse_options(options, ARRAY_LENGTH(options), argc, argv);
690         config.sprawl = sprawl;
691
692         section = weston_config_get_section(ivi->config, "shell", NULL, NULL);
693         weston_config_section_get_string(section, "cursor-theme",
694                                          &config.cursor_theme, NULL);
695         weston_config_section_get_int(section, "cursor-size",
696                                       &config.cursor_size, 32);
697
698         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_WAYLAND,
699                                              &config.base);
700
701         free(config.cursor_theme);
702         free(config.display_name);
703
704         if (ret < 0)
705                 return ret;
706
707         ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
708
709         /*
710          * We will just assume if load_backend() finished cleanly and
711          * windowed_output_api is not present that wayland backend is started
712          * with --sprawl or runs on fullscreen-shell. In this case, all values
713          * are hardcoded, so nothing can be configured; simply create and
714          * enable an output.
715          */
716         if (ivi->window_api == NULL)
717                 return 0;
718
719         return windowed_create_outputs(ivi, output_count, "WL", "wayland");
720 }
721
722 static int
723 load_x11_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
724 {
725         struct weston_x11_backend_config config = {
726                 .base = {
727                         .struct_version = WESTON_X11_BACKEND_CONFIG_VERSION,
728                         .struct_size = sizeof config,
729                 },
730         };
731         int no_input = 0;
732         int output_count;
733         int ret;
734
735         const struct weston_option options[] = {
736                { WESTON_OPTION_BOOLEAN, "no-input", 0, &no_input },
737         };
738
739         windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
740                                       &config.fullscreen, &output_count);
741
742         parse_options(options, ARRAY_LENGTH(options), argc, argv);
743         config.no_input = no_input;
744
745         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_X11,
746                                              &config.base);
747
748         if (ret < 0)
749                 return ret;
750
751         ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
752         if (!ivi->window_api) {
753                 weston_log("Cannot use weston_windowed_output_api.\n");
754                 return -1;
755         }
756
757         return windowed_create_outputs(ivi, output_count, "X", "screen");
758 }
759
760 static int
761 load_backend(struct ivi_compositor *ivi, const char *backend,
762              int *argc, char *argv[])
763 {
764         if (strcmp(backend, "drm-backend.so") == 0) {
765                 return load_drm_backend(ivi, argc, argv);
766         } else if (strcmp(backend, "wayland-backend.so") == 0) {
767                 return load_wayland_backend(ivi, argc, argv);
768         } else if (strcmp(backend, "x11-backend.so") == 0) {
769                 return load_x11_backend(ivi, argc, argv);
770         }
771
772         weston_log("fatal: unknown backend '%s'.\n", backend);
773         return -1;
774 }
775
776 static char *
777 choose_default_backend(void)
778 {
779         char *backend = NULL;
780
781         if (getenv("WAYLAND_DISPLAY") || getenv("WAYLAND_SOCKET"))
782                 backend = strdup("wayland-backend.so");
783         else if (getenv("DISPLAY"))
784                 backend = strdup("x11-backend.so");
785         else
786                 backend = strdup("drm-backend.so");
787
788         return backend;
789 }
790
791 static int
792 compositor_init_config(struct weston_compositor *compositor,
793                        struct weston_config *config)
794 {
795         struct xkb_rule_names xkb_names;
796         struct weston_config_section *section;
797         int repaint_msec;
798         int vt_switching;
799         int require_input;
800
801         /* agl-compositor.ini [keyboard] */
802         section = weston_config_get_section(config, "keyboard", NULL, NULL);
803         weston_config_section_get_string(section, "keymap_rules",
804                                          (char **) &xkb_names.rules, NULL);
805         weston_config_section_get_string(section, "keymap_model",
806                                          (char **) &xkb_names.model, NULL);
807         weston_config_section_get_string(section, "keymap_layout",
808                                          (char **) &xkb_names.layout, NULL);
809         weston_config_section_get_string(section, "keymap_variant",
810                                          (char **) &xkb_names.variant, NULL);
811         weston_config_section_get_string(section, "keymap_options",
812                                          (char **) &xkb_names.options, NULL);
813
814         if (weston_compositor_set_xkb_rule_names(compositor, &xkb_names) < 0)
815                 return -1;
816
817         weston_config_section_get_int(section, "repeat-rate",
818                                       &compositor->kb_repeat_rate, 40);
819         weston_config_section_get_int(section, "repeat-delay",
820                                       &compositor->kb_repeat_delay, 400);
821
822         weston_config_section_get_bool(section, "vt-switching",
823                                        &vt_switching, true);
824         compositor->vt_switching = vt_switching;
825
826         /* agl-compositor.ini [core] */
827         section = weston_config_get_section(config, "core", NULL, NULL);
828
829         weston_config_section_get_bool(section, "require-input", &require_input, true);
830         compositor->require_input = require_input;
831
832         weston_config_section_get_int(section, "repaint-window", &repaint_msec,
833                                       compositor->repaint_msec);
834         if (repaint_msec < -10 || repaint_msec > 1000) {
835                 weston_log("Invalid repaint_window value in config: %d\n",
836                            repaint_msec);
837         } else {
838                 compositor->repaint_msec = repaint_msec;
839         }
840         weston_log("Output repaint window is %d ms maximum.\n",
841                    compositor->repaint_msec);
842
843         return 0;
844 }
845
846 struct ivi_surface *
847 to_ivi_surface(struct weston_surface *surface)
848 {
849         struct weston_desktop_surface *dsurface;
850
851         dsurface = weston_surface_get_desktop_surface(surface);
852         if (!dsurface)
853                 return NULL;
854
855         return weston_desktop_surface_get_user_data(dsurface);
856 }
857
858 static void
859 activate_binding(struct weston_seat *seat,
860                  struct weston_view *focus_view)
861 {
862         struct weston_surface *focus = focus_view->surface;
863         struct weston_surface *main_surface =
864                 weston_surface_get_main_surface(focus);
865         struct ivi_surface *surface;
866
867         surface = to_ivi_surface(main_surface);
868         if (!surface || surface->role != IVI_SURFACE_ROLE_DESKTOP)
869                 return;
870
871         weston_seat_set_keyboard_focus(seat, focus);
872 }
873
874 static void
875 click_to_activate_binding(struct weston_pointer *pointer,
876                           const struct timespec *time,
877                           uint32_t button, void *data)
878 {
879         if (pointer->grab != &pointer->default_grab)
880                 return;
881         if (pointer->focus == NULL)
882                 return;
883
884         activate_binding(pointer->seat, pointer->focus);
885 }
886
887 static void
888 touch_to_activate_binding(struct weston_touch *touch,
889                           const struct timespec *time,
890                           void *data)
891 {
892         if (touch->grab != &touch->default_grab)
893                 return;
894         if (touch->focus == NULL)
895                 return;
896
897         activate_binding(touch->seat, touch->focus);
898 }
899
900 static void
901 add_bindings(struct weston_compositor *compositor)
902 {
903         weston_compositor_add_button_binding(compositor, BTN_LEFT, 0,
904                                              click_to_activate_binding,
905                                              NULL);
906         weston_compositor_add_button_binding(compositor, BTN_RIGHT, 0,
907                                              click_to_activate_binding,
908                                              NULL);
909         weston_compositor_add_touch_binding(compositor, 0,
910                                             touch_to_activate_binding,
911                                             NULL);
912 }
913
914 static int
915 create_listening_socket(struct wl_display *display, const char *socket_name)
916 {
917         if (socket_name) {
918                 if (wl_display_add_socket(display, socket_name)) {
919                         weston_log("fatal: failed to add socket: %s\n",
920                                    strerror(errno));
921                         return -1;
922                 }
923         } else {
924                 socket_name = wl_display_add_socket_auto(display);
925                 if (!socket_name) {
926                         weston_log("fatal: failed to add socket: %s\n",
927                                    strerror(errno));
928                         return -1;
929                 }
930         }
931
932         setenv("WAYLAND_DISPLAY", socket_name, 1);
933
934         return 0;
935 }
936
937 static bool
938 global_filter(const struct wl_client *client, const struct wl_global *global,
939               void *data)
940 {
941 #if 0
942         struct ivi_compositor *ivi = data;
943         const struct wl_interface *iface = wl_global_get_interface(global);
944
945         if (iface == &agl_shell_interface)
946                 return client == ivi->shell_client.client;
947 #endif
948
949         return true;
950 }
951
952 static int
953 load_config(struct weston_config **config, bool no_config,
954             const char *config_file)
955 {
956         const char *file = "agl-compositor.ini";
957         const char *full_path;
958
959         if (config_file)
960                 file = config_file;
961
962         if (!no_config)
963                 *config = weston_config_parse(file);
964
965         if (*config) {
966                 full_path = weston_config_get_full_path(*config);
967
968                 weston_log("Using config file '%s'.\n", full_path);
969                 setenv(WESTON_CONFIG_FILE_ENV_VAR, full_path, 1);
970
971                 return 0;
972         }
973
974         if (config_file && !no_config) {
975                 weston_log("fatal: error opening or reading config file '%s'.\n",
976                         config_file);
977
978                 return -1;
979         }
980
981         weston_log("Starting with no config file.\n");
982         setenv(WESTON_CONFIG_FILE_ENV_VAR, "", 1);
983
984         return 0;
985 }
986
987 static FILE *logfile;
988 //static struct weston_log_scope *log_scope;
989 //static struct weston_log_scope *protocol_scope;
990
991 static int
992 log_timestamp(void)
993 {
994         static int cached_tm_mday = -1;
995         struct timespec ts;
996         struct tm brokendown_time;
997         char buf[128];
998
999         clock_gettime(CLOCK_REALTIME, &ts);
1000         if (!localtime_r(&ts.tv_sec, &brokendown_time))
1001                 return fprintf(logfile, "[(NULL)localtime] ");
1002
1003         if (brokendown_time.tm_mday != cached_tm_mday) {
1004                 strftime(buf, sizeof buf, "%Y-%m-%d %Z", &brokendown_time);
1005                 fprintf(logfile, "Date: %s\n", buf);
1006
1007                 cached_tm_mday = brokendown_time.tm_mday;
1008         }
1009
1010         strftime(buf, sizeof buf, "%H:%M:%S", &brokendown_time);
1011
1012         return fprintf(logfile, "[%s.%03ld] ", buf, ts.tv_nsec / 1000000);
1013 }
1014
1015 static void
1016 custom_handler(const char *fmt, va_list arg)
1017 {
1018         log_timestamp();
1019         fprintf(logfile, "libwayland: ");
1020         vfprintf(logfile, fmt, arg);
1021 }
1022
1023 static void
1024 log_file_open(const char *filename)
1025 {
1026         wl_log_set_handler_server(custom_handler);
1027
1028         if (filename)
1029                 logfile = fopen(filename, "a");
1030
1031         if (!logfile) {
1032                 logfile = stderr;
1033         } else {
1034                 os_fd_set_cloexec(fileno(logfile));
1035                 setvbuf(logfile, NULL, _IOLBF, 256);
1036         }
1037 }
1038
1039 static void
1040 log_file_close(void)
1041 {
1042         if (logfile && logfile != stderr)
1043                 fclose(logfile);
1044         logfile = stderr;
1045 }
1046
1047 static int
1048 vlog(const char *fmt, va_list ap)
1049 {
1050         int l;
1051
1052         l = log_timestamp();
1053         l += vfprintf(logfile, fmt, ap);
1054
1055         return l;
1056 }
1057
1058 static int
1059 vlog_continue(const char *fmt, va_list ap)
1060 {
1061         return vfprintf(logfile, fmt, ap);
1062 }
1063
1064 static int
1065 on_term_signal(int signo, void *data)
1066 {
1067         struct wl_display *display = data;
1068
1069         weston_log("caught signal %d\n", signo);
1070         wl_display_terminate(display);
1071
1072         return 1;
1073 }
1074
1075 static void
1076 handle_exit(struct weston_compositor *compositor)
1077 {
1078         wl_display_terminate(compositor->wl_display);
1079 }
1080
1081 static void
1082 usage(int error_code)
1083 {
1084         FILE *out = error_code == EXIT_SUCCESS ? stdout : stderr;
1085         fprintf(out,
1086                 "Usage: agl-compositor [OPTIONS]\n"
1087                 "\n"
1088                 "This is " PACKAGE_STRING ", the reference compositor for\n"
1089                 "Automotive Grade Linux. Weston-ivi supports multiple backends, and depending\n"
1090                 "on which backend is in use different options will be accepted.\n"
1091                 "\n"
1092                 "Core options:\n"
1093                 "\n"
1094                 "  --version\t\tPrint agl-compositor version\n"
1095                 "  -B, --backend=MODULE\tBackend module, one of\n"
1096                         "\t\t\t\tdrm-backend.so\n"
1097                         "\t\t\t\twayland-backend.so\n"
1098                         "\t\t\t\tx11-backend.so\n"
1099                 "  -S, --socket=NAME\tName of socket to listen on\n"
1100                 "  --log=FILE\t\tLog to the given file\n"
1101                 "  -c, --config=FILE\tConfig file to load, defaults to agl-compositor.ini\n"
1102                 "  --no-config\t\tDo not read agl-compositor.ini\n"
1103                 "  --debug\t\tEnable debug extension\n"
1104                 "  -h, --help\t\tThis help message\n"
1105                 "\n");
1106         exit(error_code);
1107 }
1108
1109 int main(int argc, char *argv[])
1110 {
1111         struct ivi_compositor ivi = { 0 };
1112         struct wl_display *display;
1113         struct wl_event_loop *loop;
1114         struct wl_event_source *signals[3] = { 0 };
1115         struct weston_config_section *section;
1116         /* Command line options */
1117         char *backend = NULL;
1118         char *socket_name = NULL;
1119         char *log = NULL;
1120         int help = 0;
1121         int version = 0;
1122         int no_config = 0;
1123         char *config_file = NULL;
1124         int debug_protocol = 0;
1125
1126         const struct weston_option core_options[] = {
1127                 { WESTON_OPTION_STRING, "backend", 'B', &backend },
1128                 { WESTON_OPTION_STRING, "socket", 'S', &socket_name },
1129                 { WESTON_OPTION_STRING, "log", 0, &log },
1130                 { WESTON_OPTION_BOOLEAN, "help", 'h', &help },
1131                 { WESTON_OPTION_BOOLEAN, "version", 0, &version },
1132                 { WESTON_OPTION_BOOLEAN, "no-config", 0, &no_config },
1133                 { WESTON_OPTION_STRING, "config", 'c', &config_file },
1134                 { WESTON_OPTION_BOOLEAN, "debug", 0, &debug_protocol },
1135         };
1136
1137         wl_list_init(&ivi.outputs);
1138         wl_list_init(&ivi.surfaces);
1139         wl_list_init(&ivi.shell_clients);
1140         wl_list_init(&ivi.pending_surfaces);
1141
1142         /* Prevent any clients we spawn getting our stdin */
1143         os_fd_set_cloexec(STDIN_FILENO);
1144
1145         parse_options(core_options, ARRAY_LENGTH(core_options), &argc, argv);
1146
1147         if (help)
1148                 usage(EXIT_SUCCESS);
1149
1150         if (version) {
1151                 printf(PACKAGE_STRING "\n");
1152                 return EXIT_SUCCESS;
1153         }
1154
1155         log_file_open(log);
1156         weston_log_set_handler(vlog, vlog_continue);
1157
1158         if (load_config(&ivi.config, no_config, config_file) < 0)
1159                 goto error_signals;
1160         section = weston_config_get_section(ivi.config, "core", NULL, NULL);
1161         if (!backend) {
1162                 weston_config_section_get_string(section, "backend", &backend,
1163                                                  NULL);
1164                 if (!backend)
1165                         backend = choose_default_backend();
1166         }
1167
1168         display = wl_display_create();
1169         loop = wl_display_get_event_loop(display);
1170
1171         wl_display_set_global_filter(display,
1172                                      global_filter, &ivi);
1173
1174         /* Register signal handlers so we shut down cleanly */
1175
1176         signals[0] = wl_event_loop_add_signal(loop, SIGTERM, on_term_signal,
1177                                               display);
1178         signals[1] = wl_event_loop_add_signal(loop, SIGINT, on_term_signal,
1179                                               display);
1180         signals[2] = wl_event_loop_add_signal(loop, SIGQUIT, on_term_signal,
1181                                               display);
1182
1183         for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
1184                 if (!signals[i])
1185                         goto error_signals;
1186
1187 #if 0
1188         log_ctx = weston_log_ctx_compositor_create();
1189         if (!log_ctx) {
1190                 weston_log("Failed to initialize weston debug framework.\n");
1191                 goto error_signals;
1192         }
1193 #endif
1194
1195         ivi.compositor = weston_compositor_create(display, &ivi);
1196         if (!ivi.compositor) {
1197                 weston_log("fatal: failed to create compositor.\n");
1198                 goto error_signals;
1199         }
1200
1201 #if 0
1202         if (debug_protocol)
1203                 weston_compositor_enable_debug_protocol(ivi.compositor);
1204 #endif
1205
1206         if (compositor_init_config(ivi.compositor, ivi.config) < 0)
1207                 goto error_compositor;
1208
1209         if (load_backend(&ivi, backend, &argc, argv) < 0) {
1210                 weston_log("fatal: failed to create compositor backend.\n");
1211                 goto error_compositor;
1212         }
1213
1214         ivi.heads_changed.notify = heads_changed;
1215         weston_compositor_add_heads_changed_listener(ivi.compositor,
1216                                                      &ivi.heads_changed);
1217
1218         if (ivi_desktop_init(&ivi) < 0)
1219                 goto error_compositor;
1220
1221         if (ivi_shell_init(&ivi) < 0)
1222                 goto error_compositor;
1223
1224         add_bindings(ivi.compositor);
1225
1226         weston_compositor_flush_heads_changed(ivi.compositor);
1227
1228         if (create_listening_socket(display, socket_name) < 0)
1229                 goto error_compositor;
1230
1231         ivi.compositor->exit = handle_exit;
1232
1233         weston_compositor_wake(ivi.compositor);
1234
1235         ivi_shell_create_global(&ivi);
1236         ivi_launch_shell_client(&ivi);
1237
1238         wl_display_run(display);
1239
1240         wl_display_destroy_clients(display);
1241
1242 error_compositor:
1243         weston_compositor_destroy(ivi.compositor);
1244
1245 error_signals:
1246         for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
1247                 if (signals[i])
1248                         wl_event_source_remove(signals[i]);
1249
1250         wl_display_destroy(display);
1251
1252         log_file_close();
1253         if (ivi.config)
1254                 weston_config_destroy(ivi.config);
1255 }