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