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