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