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