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