827ef7a403313acf57ade63040d4cf1d52935cda
[src/agl-compositor.git] / src / compositor.c
1 /*
2  * Copyright © 2012-2021 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_HEADLESS
43 #include <libweston/backend-headless.h>
44 #endif
45 #ifdef HAVE_BACKEND_X11
46 #include <libweston/backend-x11.h>
47 #endif
48 #include <libweston/libweston.h>
49 #include <libweston/windowed-output-api.h>
50 #include <libweston/config-parser.h>
51 #include <libweston/weston-log.h>
52 #include <weston.h>
53
54 #include "shared/os-compatibility.h"
55 #include "shared/helpers.h"
56
57 #include "agl-shell-server-protocol.h"
58
59 #ifdef HAVE_REMOTING
60 #include "remote.h"
61 #endif
62
63 static int cached_tm_mday = -1;
64 static struct weston_log_scope *log_scope;
65
66 struct ivi_compositor *
67 to_ivi_compositor(struct weston_compositor *ec)
68 {
69         return weston_compositor_get_user_data(ec);
70 }
71
72 static void
73 sigint_helper(int sig)
74 {
75        raise(SIGUSR2);
76 }
77
78 void
79 ivi_layout_save(struct ivi_compositor *ivi, struct ivi_output *output)
80 {
81         struct ivi_output *new_output;
82         ivi->need_ivi_output_relayout = true;
83
84         new_output = zalloc(sizeof(*new_output));
85
86         new_output->ivi = ivi;
87         new_output->background = output->background;
88
89         new_output->top = output->top;
90         new_output->bottom = output->bottom;
91         new_output->left = output->left;
92         new_output->right = output->right;
93
94         new_output->active = output->active;
95         new_output->previous_active = output->previous_active;
96         new_output->name = strdup(output->name);
97         if (output->app_ids)
98                 new_output->app_ids = strdup(output->app_ids);
99
100         new_output->area = output->area;
101         new_output->area_saved = output->area_saved;
102         new_output->area_activation = output->area_activation;
103
104         weston_log("saving output layout for output %s\n", new_output->name);
105
106         wl_list_insert(&ivi->saved_outputs, &new_output->link);
107 }
108
109 void
110 ivi_layout_restore(struct ivi_compositor *ivi, struct ivi_output *n_output)
111 {
112         struct ivi_output *output = NULL;
113         struct ivi_output *iter_output;
114
115         if (!ivi->need_ivi_output_relayout)
116                 return;
117
118         ivi->need_ivi_output_relayout = false;
119
120         wl_list_for_each(iter_output, &ivi->saved_outputs, link) {
121                 if (strcmp(n_output->name, iter_output->name) == 0) {
122                         output = iter_output;
123                         break;
124                 }
125         }
126
127         if (!output)
128                 return;
129
130         weston_log("restoring output layout for output %s\n", output->name);
131         n_output->background = output->background;
132
133         n_output->top = output->top;
134         n_output->bottom = output->bottom;
135         n_output->left = output->left;
136         n_output->right = output->right;
137
138         n_output->active = output->active;
139         n_output->previous_active = output->previous_active;
140         if (output->app_ids)
141                 n_output->app_ids = strdup(output->app_ids);
142
143         n_output->area = output->area;
144         n_output->area_saved = output->area_saved;
145         n_output->area_activation = output->area_activation;
146
147         free(output->app_ids);
148         free(output->name);
149         wl_list_remove(&output->link);
150         free(output);
151 }
152
153 void
154 ivi_layout_destroy_saved_outputs(struct ivi_compositor *ivi)
155 {
156         struct ivi_output *output, *output_next;
157
158         wl_list_for_each_safe(output, output_next, &ivi->saved_outputs, link) {
159                 free(output->app_ids);
160                 free(output->name);
161
162                 wl_list_remove(&output->link);
163                 free(output);
164         }
165 }
166
167 static void
168 handle_output_destroy(struct wl_listener *listener, void *data)
169 {
170         struct ivi_output *output;
171
172         output = wl_container_of(listener, output, output_destroy);
173         assert(output->output == data);
174
175         if (output->fullscreen_view.fs &&
176             output->fullscreen_view.fs->view) {
177                 weston_surface_destroy(output->fullscreen_view.fs->view->surface);
178                 output->fullscreen_view.fs->view = NULL;
179         }
180
181         ivi_layout_save(output->ivi, output);
182
183         output->output = NULL;
184         wl_list_remove(&output->output_destroy.link);
185 }
186
187 struct ivi_output *
188 to_ivi_output(struct weston_output *o)
189 {
190         struct wl_listener *listener;
191         struct ivi_output *output;
192
193         listener = weston_output_get_destroy_listener(o, handle_output_destroy);
194         output = wl_container_of(listener, output, output_destroy);
195
196         return output;
197 }
198
199 static void
200 ivi_output_configure_app_id(struct ivi_output *ivi_output)
201 {
202         if (ivi_output->config) {
203                 if (ivi_output->app_ids != NULL)
204                         return;
205
206                 weston_config_section_get_string(ivi_output->config,
207                                                  "agl-shell-app-id",
208                                                  &ivi_output->app_ids,
209                                                  NULL);
210
211                 if (ivi_output->app_ids == NULL)
212                         return;
213
214                 weston_log("Will place app_id %s on output %s\n",
215                                 ivi_output->app_ids, ivi_output->name);
216         }
217 }
218
219 static struct ivi_output *
220 ivi_ensure_output(struct ivi_compositor *ivi, char *name,
221                   struct weston_config_section *config)
222 {
223         struct ivi_output *output = NULL;
224         wl_list_for_each(output, &ivi->outputs, link) {
225                 if (strcmp(output->name, name) == 0) {
226                         free(name);
227                         return output;
228                 }
229         }
230
231         output = zalloc(sizeof *output);
232         if (!output) {
233                 free(name);
234                 return NULL;
235         }
236
237         output->ivi = ivi;
238         output->name = name;
239         output->config = config;
240
241         output->output = weston_compositor_create_output(ivi->compositor, name);
242         if (!output->output) {
243                 free(output->name);
244                 free(output);
245                 return NULL;
246         }
247
248         output->output_destroy.notify = handle_output_destroy;
249         weston_output_add_destroy_listener(output->output,
250                                            &output->output_destroy);
251
252         wl_list_insert(&ivi->outputs, &output->link);
253         ivi_output_configure_app_id(output);
254         return output;
255 }
256
257 static int
258 count_heads(struct weston_output *output)
259 {
260         struct weston_head *iter = NULL;
261         int n = 0;
262
263         while ((iter = weston_output_iterate_heads(output, iter)))
264                 ++n;
265
266         return n;
267 }
268
269 static void
270 handle_head_destroy(struct wl_listener *listener, void *data)
271 {
272         struct weston_head *head = data;
273         struct weston_output *output;
274
275         wl_list_remove(&listener->link);
276         free(listener);
277
278         output = weston_head_get_output(head);
279
280         /* On shutdown path, the output might be already gone. */
281         if (!output)
282                 return;
283
284         /* We're the last head */
285         if (count_heads(output) <= 1)
286                 weston_output_destroy(output);
287 }
288
289 static void
290 add_head_destroyed_listener(struct weston_head *head)
291 {
292         /* We already have a destroy listener */
293         if (weston_head_get_destroy_listener(head, handle_head_destroy))
294                 return;
295
296         struct wl_listener *listener = zalloc(sizeof *listener);
297         if (!listener)
298                 return;
299
300         listener->notify = handle_head_destroy;
301         weston_head_add_destroy_listener(head, listener);
302 }
303
304 static int
305 drm_configure_output(struct ivi_output *output)
306 {
307         struct ivi_compositor *ivi = output->ivi;
308         struct weston_config_section *section = output->config;
309         enum weston_drm_backend_output_mode mode =
310                 WESTON_DRM_BACKEND_OUTPUT_PREFERRED;
311         char *modeline = NULL;
312         char *gbm_format = NULL;
313         char *seat = NULL;
314
315         if (section) {
316                 char *m;
317                 weston_config_section_get_string(section, "mode", &m, "preferred");
318
319                 /* This should have been handled earlier */
320                 assert(strcmp(m, "off") != 0);
321
322                 if (ivi->cmdline.use_current_mode || strcmp(m, "current") == 0) {
323                         mode = WESTON_DRM_BACKEND_OUTPUT_CURRENT;
324                 } else if (strcmp(m, "preferred") != 0) {
325                         modeline = m;
326                         m = NULL;
327                 }
328                 free(m);
329
330                 weston_config_section_get_string(section, "gbm-format",
331                                                  &gbm_format, NULL);
332
333                 weston_config_section_get_string(section, "seat", &seat, "");
334         }
335
336         if (ivi->drm_api->set_mode(output->output, mode, modeline) < 0) {
337                 weston_log("Cannot configure output using weston_drm_output_api.\n");
338                 free(modeline);
339                 return -1;
340         }
341         free(modeline);
342
343         ivi->drm_api->set_gbm_format(output->output, gbm_format);
344         free(gbm_format);
345
346         ivi->drm_api->set_seat(output->output, seat);
347         free(seat);
348
349         return 0;
350 }
351
352 #define WINDOWED_DEFAULT_WIDTH 1024
353 #define WINDOWED_DEFAULT_HEIGHT 768
354
355 static int
356 windowed_configure_output(struct ivi_output *output)
357 {
358         struct ivi_compositor *ivi = output->ivi;
359         struct weston_config_section *section = output->config;
360         int width = WINDOWED_DEFAULT_WIDTH;
361         int height = WINDOWED_DEFAULT_HEIGHT;
362
363         if (section) {
364                 char *mode;
365
366                 weston_config_section_get_string(section, "mode", &mode, NULL);
367                 if (!mode || sscanf(mode, "%dx%d", &width, &height) != 2) {
368                         weston_log("Invalid mode for output %s. Using defaults.\n",
369                                    output->name);
370                         width = WINDOWED_DEFAULT_WIDTH;
371                         height = WINDOWED_DEFAULT_HEIGHT;
372                 }
373                 free(mode);
374         }
375
376         if (ivi->cmdline.width)
377                 width = ivi->cmdline.width;
378         if (ivi->cmdline.height)
379                 height = ivi->cmdline.height;
380         if (ivi->cmdline.scale)
381                 weston_output_set_scale(output->output, ivi->cmdline.scale);
382
383         if (ivi->window_api->output_set_size(output->output, width, height) < 0) {
384                 weston_log("Cannot configure output '%s' using weston_windowed_output_api.\n",
385                            output->name);
386                 return -1;
387         }
388
389         weston_log("Configured windowed_output_api to %dx%d\n", width, height);
390
391         return 0;
392 }
393
394 static int
395 parse_transform(const char *transform, uint32_t *out)
396 {
397         static const struct { const char *name; uint32_t token; } transforms[] = {
398                 { "normal",             WL_OUTPUT_TRANSFORM_NORMAL },
399                 { "rotate-90",          WL_OUTPUT_TRANSFORM_90 },
400                 { "rotate-180",         WL_OUTPUT_TRANSFORM_180 },
401                 { "rotate-270",         WL_OUTPUT_TRANSFORM_270 },
402                 { "flipped",            WL_OUTPUT_TRANSFORM_FLIPPED },
403                 { "flipped-rotate-90",  WL_OUTPUT_TRANSFORM_FLIPPED_90 },
404                 { "flipped-rotate-180", WL_OUTPUT_TRANSFORM_FLIPPED_180 },
405                 { "flipped-rotate-270", WL_OUTPUT_TRANSFORM_FLIPPED_270 },
406         };
407
408         for (size_t i = 0; i < ARRAY_LENGTH(transforms); i++)
409                 if (strcmp(transforms[i].name, transform) == 0) {
410                         *out = transforms[i].token;
411                         return 0;
412                 }
413
414         *out = WL_OUTPUT_TRANSFORM_NORMAL;
415         return -1;
416 }
417
418 int
419 parse_activation_area(const char *geometry, struct ivi_output *output)
420 {
421         int n;
422         unsigned width, height, x, y;
423
424         n = sscanf(geometry, "%ux%u+%u,%u", &width, &height, &x, &y);
425         if (n != 4) {
426                 return -1;
427         }
428         output->area_activation.width = width;
429         output->area_activation.height = height;
430         output->area_activation.x = x;
431         output->area_activation.y = y;
432         return 0;
433 }
434
435 static int
436 configure_output(struct ivi_output *output)
437 {
438         struct ivi_compositor *ivi = output->ivi;
439         struct weston_config_section *section = output->config;
440         int32_t scale = 1;
441         uint32_t transform = WL_OUTPUT_TRANSFORM_NORMAL;
442
443         /*
444          * This can happen with the wayland backend with 'sprawl'. The config
445          * is hard-coded, so we don't need to do anything.
446          */
447         if (!ivi->drm_api && !ivi->window_api)
448                 return 0;
449
450         if (section) {
451                 char *t;
452
453                 weston_config_section_get_int(section, "scale", &scale, 1);
454                 weston_config_section_get_string(section, "transform", &t, "normal");
455                 if (parse_transform(t, &transform) < 0)
456                         weston_log("Invalid transform \"%s\" for output %s\n",
457                                    t, output->name);
458                 weston_config_section_get_string(section, "activation-area", &t, "");
459                 if (parse_activation_area(t, output) < 0)
460                         weston_log("Invalid activation-area \"%s\" for output %s\n",
461                                    t, output->name);
462                 free(t);
463         }
464
465         weston_output_set_scale(output->output, scale);
466         weston_output_set_transform(output->output, transform);
467
468         if (ivi->drm_api)
469                 return drm_configure_output(output);
470         else
471                 return windowed_configure_output(output);
472 }
473
474 /*
475  * Reorgainizes the output's add array into two sections.
476  * add[0..ret-1] are the heads that failed to get attached.
477  * add[ret..add_len] are the heads that were successfully attached.
478  *
479  * The order between elements in each section is stable.
480  */
481 static size_t
482 try_attach_heads(struct ivi_output *output)
483 {
484         size_t fail_len = 0;
485
486         for (size_t i = 0; i < output->add_len; ++i) {
487                 if (weston_output_attach_head(output->output, output->add[i]) < 0) {
488                         struct weston_head *tmp = output->add[i];
489                         memmove(&output->add[fail_len + 1], output->add[fail_len],
490                                 sizeof output->add[0] * (i - fail_len));
491                         output->add[fail_len++] = tmp;
492                 }
493         }
494
495         return fail_len;
496 }
497
498 /*
499  * Like try_attach_heads, this reorganizes the output's add array into a failed
500  * and successful section.
501  * i is the number of heads that already failed the previous step.
502  */
503 static size_t
504 try_enable_output(struct ivi_output *output, size_t i)
505 {
506         for (; i < output->add_len; ++i) {
507                 struct weston_head *head;
508
509                 if (weston_output_enable(output->output) == 0)
510                         break;
511
512                 head = output->add[output->add_len - 1];
513                 memmove(&output->add[i + 1], &output->add[i],
514                         sizeof output->add[0] * (output->add_len - i));
515                 output->add[i] = head;
516
517                 weston_head_detach(head);
518         }
519
520         return i;
521 }
522
523 static int
524 try_attach_enable_heads(struct ivi_output *output)
525 {
526         size_t fail_len;
527         assert(!output->output->enabled);
528
529         fail_len = try_attach_heads(output);
530
531         if (configure_output(output) < 0)
532                 return -1;
533
534         fail_len = try_enable_output(output, fail_len);
535
536         /* All heads failed to be attached */
537         if (fail_len == output->add_len)
538                 return -1;
539
540         /* For each successful head attached */
541         for (size_t i = fail_len; i < output->add_len; ++i)
542                 add_head_destroyed_listener(output->add[i]);
543
544         ivi_layout_restore(output->ivi, output);
545
546         output->add_len = fail_len;
547         return 0;
548 }
549
550 static int
551 process_output(struct ivi_output *output)
552 {
553         if (output->output->enabled) {
554                 output->add_len = try_attach_heads(output);
555                 return output->add_len == 0 ? 0 : -1;
556         }
557
558         return try_attach_enable_heads(output);
559 }
560
561 static void
562 head_disable(struct ivi_compositor *ivi, struct weston_head *head)
563 {
564         struct weston_output *output;
565         struct ivi_output *ivi_output;
566         struct wl_listener *listener;
567
568         output = weston_head_get_output(head);
569         assert(output);
570
571         listener = weston_output_get_destroy_listener(output,
572                                                       handle_output_destroy);
573         assert(listener);
574
575         ivi_output = wl_container_of(listener, ivi_output, output_destroy);
576         assert(ivi_output->output == output);
577
578         weston_head_detach(head);
579         if (count_heads(ivi_output->output) == 0) {
580                 if (ivi_output->output) {
581                         /* ivi_output->output destruction may be deferred in
582                          * some cases (see drm_output_destroy()), so we need to
583                          * forcibly trigger the destruction callback now, or
584                          * otherwise would later access data that we are about
585                          * to free
586                          */
587                         struct weston_output *save = ivi_output->output;
588
589                         handle_output_destroy(&ivi_output->output_destroy, save);
590                         weston_output_destroy(save);
591                 }
592         }
593         wl_list_remove(&ivi_output->link);
594         free(ivi_output->app_ids);
595         free(ivi_output);
596 }
597
598 static struct weston_config_section *
599 find_controlling_output_config(struct weston_config *config,
600                                const char *name)
601 {
602         struct weston_config_section *section;
603         char *same_as;
604         int depth = 0;
605
606         same_as = strdup(name);
607         do {
608                 section = weston_config_get_section(config, "output",
609                                                     "name", same_as);
610                 if (!section && depth > 0)
611                         weston_log("Configuration error: output section reffered"
612                                    "to by same-as=%s not found.\n", same_as);
613                 free(same_as);
614
615                 if (!section)
616                         return NULL;
617
618                 if (depth++ > 8) {
619                         weston_log("Configuration error: same-as nested too "
620                                    "deep for output '%s'.\n", name);
621                         return NULL;
622                 }
623
624                 weston_config_section_get_string(section, "same-as",
625                                                  &same_as, NULL);
626         } while (same_as);
627
628         return section;
629 }
630
631 static void
632 head_prepare_enable(struct ivi_compositor *ivi, struct weston_head *head)
633 {
634         const char *name = weston_head_get_name(head);
635         struct weston_config_section *section;
636         struct ivi_output *output;
637         char *output_name = NULL;
638
639         section = find_controlling_output_config(ivi->config, name);
640         if (section) {
641                 char *mode;
642
643                 weston_config_section_get_string(section, "mode", &mode, NULL);
644                 if (mode && strcmp(mode, "off") == 0) {
645                         free(mode);
646                         return;
647                 }
648                 free(mode);
649
650                 weston_config_section_get_string(section, "name",
651                                                  &output_name, NULL);
652         } else {
653                 output_name = strdup(name);
654         }
655
656         if (!output_name)
657                 return;
658
659         output = ivi_ensure_output(ivi, output_name, section);
660         if (!output)
661                 return;
662
663         if (output->add_len >= ARRAY_LENGTH(output->add))
664                 return;
665
666         output->add[output->add_len++] = head;
667 }
668
669 static void
670 heads_changed(struct wl_listener *listener, void *arg)
671 {
672         struct weston_compositor *compositor = arg;
673         struct weston_head *head = NULL;
674         struct ivi_compositor *ivi = to_ivi_compositor(compositor);
675         struct ivi_output *output;
676
677         while ((head = weston_compositor_iterate_heads(ivi->compositor, head))) {
678                 bool connected = weston_head_is_connected(head);
679                 bool enabled = weston_head_is_enabled(head);
680                 bool changed = weston_head_is_device_changed(head);
681                 bool non_desktop = weston_head_is_non_desktop(head);
682
683                 if (connected && !enabled && !non_desktop)
684                         head_prepare_enable(ivi, head);
685                 else if (!connected && enabled)
686                         head_disable(ivi, head);
687                 else if (enabled && changed)
688                         weston_log("Detected a monitor change on head '%s', "
689                                    "not bothering to do anything about it.\n",
690                                    weston_head_get_name(head));
691
692                 weston_head_reset_device_changed(head);
693         }
694
695         wl_list_for_each(output, &ivi->outputs, link) {
696                 if (output->add_len == 0)
697                         continue;
698
699                 if (process_output(output) < 0) {
700                         output->add_len = 0;
701                         ivi->init_failed = true;
702                 }
703         }
704 }
705
706 #ifdef HAVE_REMOTING
707 static int
708 drm_backend_remoted_output_configure(struct weston_output *output,
709                                      struct weston_config_section *section,
710                                      char *modeline,
711                                      const struct weston_remoting_api *api)
712 {
713         char *gbm_format = NULL;
714         char *seat = NULL;
715         char *host = NULL;
716         char *pipeline = NULL;
717         int port, ret;
718         int32_t scale = 1;
719         uint32_t transform = WL_OUTPUT_TRANSFORM_NORMAL;
720         char *trans;
721
722         ret = api->set_mode(output, modeline);
723         if (ret < 0) {
724                 weston_log("Cannot configure an output \"%s\" using "
725                                 "weston_remoting_api. Invalid mode\n",
726                                 output->name);
727                 return -1;
728         }
729
730         weston_config_section_get_int(section, "scale", &scale, 1);
731         weston_output_set_scale(output, scale);
732
733         weston_config_section_get_string(section, "transform", &trans, "normal");
734         if (parse_transform(trans, &transform) < 0) {
735                 weston_log("Invalid transform \"%s\" for output %s\n",
736                            trans, output->name);
737         }
738         weston_output_set_transform(output, transform);
739
740         weston_config_section_get_string(section, "gbm-format",
741                                          &gbm_format, NULL);
742         api->set_gbm_format(output, gbm_format);
743         free(gbm_format);
744
745         weston_config_section_get_string(section, "seat", &seat, "");
746
747         api->set_seat(output, seat);
748         free(seat);
749
750         weston_config_section_get_string(section, "gst-pipeline", &pipeline,
751                         NULL);
752         if (pipeline) {
753                 api->set_gst_pipeline(output, pipeline);
754                 free(pipeline);
755                 return 0;
756         }
757
758         weston_config_section_get_string(section, "host", &host, NULL);
759         weston_config_section_get_int(section, "port", &port, 0);
760         if (!host || port <= 0 || 65533 < port) {
761                 weston_log("Cannot configure an output \"%s\". "
762                                 "Need to specify gst-pipeline or "
763                                 "host and port (1-65533).\n", output->name);
764         }
765         api->set_host(output, host);
766         free(host);
767         api->set_port(output, port);
768
769         return 0;
770 }
771
772
773 static int
774 remote_output_init(struct ivi_output *ivi_output,
775                    struct weston_compositor *compositor,
776                    struct weston_config_section *section,
777                    const struct weston_remoting_api *api)
778 {
779         char *output_name, *modeline = NULL;
780         int ret = -1;
781
782         weston_config_section_get_string(section, "name", &output_name, NULL);
783         if (!output_name)
784                 return ret;
785
786         weston_config_section_get_string(section, "mode", &modeline, "off");
787         if (strcmp(modeline, "off") == 0)
788                 goto err;
789
790         ivi_output->output = api->create_output(compositor, output_name);
791         if (!ivi_output->output) {
792                 weston_log("Cannot create remoted output \"%s\".\n",
793                                 output_name);
794                 goto err;
795         }
796
797         ret = drm_backend_remoted_output_configure(ivi_output->output, section,
798                                                    modeline, api);
799         if (ret < 0) {
800                 weston_log("Cannot configure remoted output \"%s\".\n",
801                                 output_name);
802                 goto err;
803         }
804
805         if ((ret = weston_output_enable(ivi_output->output)) < 0) {
806                 weston_log("Enabling remoted output \"%s\" failed.\n",
807                                 output_name);
808                 goto err;
809         }
810
811         free(modeline);
812         free(output_name);
813         weston_log("remoted output '%s' enabled\n", ivi_output->output->name);
814
815         return 0;
816
817 err:
818         free(modeline);
819         free(output_name);
820         if (ivi_output->output)
821                 weston_output_destroy(ivi_output->output);
822
823         return ret;
824 }
825
826 static void
827 ivi_enable_remote_outputs(struct ivi_compositor *ivi)
828 {
829         struct weston_config_section *remote_section = NULL;
830         const char *section_name;
831         struct weston_config *config = ivi->config;
832
833         while (weston_config_next_section(config, &remote_section, &section_name)) {
834                 if (strcmp(section_name, "remote-output"))
835                         continue;
836
837                 struct ivi_output *ivi_output = NULL;
838                 bool output_found = false;
839                 char *_name = NULL;
840
841                 weston_config_section_get_string(remote_section,
842                                                  "name", &_name, NULL);
843                 wl_list_for_each(ivi_output, &ivi->outputs, link) {
844                         if (!strcmp(ivi_output->name, _name)) {
845                                 output_found = true;
846                                 break;
847                         }
848                 }
849
850                 if (output_found) {
851                         free(_name);
852                         continue;
853                 }
854
855                 ivi_output = zalloc(sizeof(*ivi_output));
856                 if (!ivi_output) {
857                         free(_name);
858                         continue;
859                 }
860
861                 ivi_output->ivi = ivi;
862                 ivi_output->name = _name;
863                 ivi_output->config = remote_section;
864                 ivi_output->type = OUTPUT_REMOTE;
865
866                 if (remote_output_init(ivi_output, ivi->compositor,
867                                        remote_section, ivi->remoting_api)) {
868                         free(ivi_output->name);
869                         free(ivi_output);
870                         continue;
871                 }
872
873                 ivi_output->output_destroy.notify = handle_output_destroy;
874                 weston_output_add_destroy_listener(ivi_output->output,
875                                                    &ivi_output->output_destroy);
876
877                 wl_list_insert(&ivi->outputs, &ivi_output->link);
878                 ivi_output_configure_app_id(ivi_output);
879         }
880 }
881
882 static int
883 load_remoting_plugin(struct ivi_compositor *ivi, struct weston_config *config)
884 {
885         struct weston_compositor *compositor = ivi->compositor;
886         int (*module_init)(struct weston_compositor *wc);
887
888         module_init = weston_load_module("remoting-plugin.so",
889                                          "weston_module_init");
890         if (!module_init)
891                 return -1;
892
893         if (module_init(compositor) < 0)
894                 return -1;
895
896         ivi->remoting_api = weston_remoting_get_api(compositor);
897         if (!ivi->remoting_api)
898                 return -1;
899         return 0;
900 }
901 #else
902 static int
903 load_remoting_plugin(struct weston_compositor *compositor, struct weston_config *config)
904 {
905         return -1;
906 }
907 #endif
908
909 static int
910 load_drm_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
911 {
912         struct weston_drm_backend_config config = {
913                 .base = {
914                         .struct_version = WESTON_DRM_BACKEND_CONFIG_VERSION,
915                         .struct_size = sizeof config,
916                 },
917         };
918         struct weston_config_section *section;
919         int use_current_mode = 0;
920         int use_pixman = 0;
921         bool use_shadow;
922         bool without_input = false;
923         int ret;
924
925         const struct weston_option options[] = {
926                 { WESTON_OPTION_STRING, "seat", 0, &config.seat_id },
927                 { WESTON_OPTION_STRING, "drm-device", 0, &config.specific_device },
928                 { WESTON_OPTION_BOOLEAN, "current-mode", 0, &use_current_mode },
929                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
930                 { WESTON_OPTION_BOOLEAN, "continue-without-input", false, &without_input }
931         };
932
933         parse_options(options, ARRAY_LENGTH(options), argc, argv);
934         config.use_pixman = use_pixman;
935         ivi->cmdline.use_current_mode = use_current_mode;
936
937         section = weston_config_get_section(ivi->config, "core", NULL, NULL);
938         weston_config_section_get_string(section, "gbm-format",
939                                          &config.gbm_format, NULL);
940         weston_config_section_get_uint(section, "pageflip-timeout",
941                                        &config.pageflip_timeout, 0);
942         weston_config_section_get_bool(section, "pixman-shadow", &use_shadow, 1);
943         config.use_pixman_shadow = use_shadow;
944
945         if (without_input)
946                 ivi->compositor->require_input = !without_input;
947
948         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_DRM,
949                                              &config.base);
950         if (ret < 0)
951                 return ret;
952
953         ivi->drm_api = weston_drm_output_get_api(ivi->compositor);
954         if (!ivi->drm_api) {
955                 weston_log("Cannot use drm output api.\n");
956                 ret = -1;
957                 goto error;
958         }
959
960         load_remoting_plugin(ivi, ivi->config);
961
962 error:
963         free(config.gbm_format);
964         free(config.seat_id);
965         return ret;
966 }
967
968 static void
969 windowed_parse_common_options(struct ivi_compositor *ivi, int *argc, char *argv[],
970                               bool *use_pixman, bool *fullscreen, int *output_count)
971 {
972         struct weston_config_section *section;
973         bool pixman;
974         int fs = 0;
975
976         const struct weston_option options[] = {
977                 { WESTON_OPTION_INTEGER, "width", 0, &ivi->cmdline.width },
978                 { WESTON_OPTION_INTEGER, "height", 0, &ivi->cmdline.height },
979                 { WESTON_OPTION_INTEGER, "scale", 0, &ivi->cmdline.scale },
980                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &pixman },
981                 { WESTON_OPTION_BOOLEAN, "fullscreen", 0, &fs },
982                 { WESTON_OPTION_INTEGER, "output-count", 0, output_count },
983         };
984
985         section = weston_config_get_section(ivi->config, "core", NULL, NULL);
986         weston_config_section_get_bool(section, "use-pixman", &pixman, 0);
987
988         *output_count = 1;
989         parse_options(options, ARRAY_LENGTH(options), argc, argv);
990         *use_pixman = pixman;
991         *fullscreen = fs;
992 }
993
994 static int
995 windowed_create_outputs(struct ivi_compositor *ivi, int output_count,
996                         const char *match_prefix, const char *name_prefix)
997 {
998         struct weston_config_section *section = NULL;
999         const char *section_name;
1000         char *default_output = NULL;
1001         int i = 0;
1002         size_t match_len = strlen(match_prefix);
1003
1004         while (weston_config_next_section(ivi->config, &section, &section_name)) {
1005                 char *output_name;
1006
1007                 if (i >= output_count)
1008                         break;
1009
1010                 if (strcmp(section_name, "output") != 0)
1011                         continue;
1012
1013                 weston_config_section_get_string(section, "name", &output_name, NULL);
1014                 if (output_name == NULL)
1015                         continue;
1016                 if (strncmp(output_name, match_prefix, match_len) != 0) {
1017                         free(output_name);
1018                         continue;
1019                 }
1020
1021                 if (ivi->window_api->create_head(ivi->compositor, output_name) < 0) {
1022                         free(output_name);
1023                         return -1;
1024                 }
1025
1026                 free(output_name);
1027                 ++i;
1028         }
1029
1030         for (; i < output_count; ++i) {
1031                 if (asprintf(&default_output, "%s%d", name_prefix, i) < 0)
1032                         return -1;
1033
1034                 if (ivi->window_api->create_head(ivi->compositor, default_output) < 0) {
1035                         free(default_output);
1036                         return -1;
1037                 }
1038
1039                 free(default_output);
1040         }
1041
1042         return 0;
1043 }
1044
1045 static int
1046 load_wayland_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
1047 {
1048         struct weston_wayland_backend_config config = {
1049                 .base = {
1050                         .struct_version = WESTON_WAYLAND_BACKEND_CONFIG_VERSION,
1051                         .struct_size = sizeof config,
1052                 },
1053         };
1054         struct weston_config_section *section;
1055         int sprawl = 0;
1056         int output_count;
1057         int ret;
1058
1059         const struct weston_option options[] = {
1060                 { WESTON_OPTION_STRING, "display", 0, &config.display_name },
1061                 { WESTON_OPTION_STRING, "sprawl", 0, &sprawl },
1062         };
1063
1064         windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
1065                                       &config.fullscreen, &output_count);
1066
1067         parse_options(options, ARRAY_LENGTH(options), argc, argv);
1068         config.sprawl = sprawl;
1069
1070         section = weston_config_get_section(ivi->config, "shell", NULL, NULL);
1071         weston_config_section_get_string(section, "cursor-theme",
1072                                          &config.cursor_theme, NULL);
1073         weston_config_section_get_int(section, "cursor-size",
1074                                       &config.cursor_size, 32);
1075
1076         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_WAYLAND,
1077                                              &config.base);
1078
1079         free(config.cursor_theme);
1080         free(config.display_name);
1081
1082         if (ret < 0)
1083                 return ret;
1084
1085         ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
1086
1087         /*
1088          * We will just assume if load_backend() finished cleanly and
1089          * windowed_output_api is not present that wayland backend is started
1090          * with --sprawl or runs on fullscreen-shell. In this case, all values
1091          * are hardcoded, so nothing can be configured; simply create and
1092          * enable an output.
1093          */
1094         if (ivi->window_api == NULL)
1095                 return 0;
1096
1097         return windowed_create_outputs(ivi, output_count, "WL", "wayland");
1098 }
1099
1100 #ifdef HAVE_BACKEND_X11
1101 static int
1102 load_x11_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
1103 {
1104         struct weston_x11_backend_config config = {
1105                 .base = {
1106                         .struct_version = WESTON_X11_BACKEND_CONFIG_VERSION,
1107                         .struct_size = sizeof config,
1108                 },
1109         };
1110         int no_input = 0;
1111         int output_count;
1112         int ret;
1113
1114         const struct weston_option options[] = {
1115                { WESTON_OPTION_BOOLEAN, "no-input", 0, &no_input },
1116         };
1117
1118         windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
1119                                       &config.fullscreen, &output_count);
1120
1121         parse_options(options, ARRAY_LENGTH(options), argc, argv);
1122         config.no_input = no_input;
1123
1124         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_X11,
1125                                              &config.base);
1126
1127         if (ret < 0)
1128                 return ret;
1129
1130         ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
1131         if (!ivi->window_api) {
1132                 weston_log("Cannot use weston_windowed_output_api.\n");
1133                 return -1;
1134         }
1135
1136         return windowed_create_outputs(ivi, output_count, "X", "screen");
1137 }
1138 #else
1139 static int
1140 load_x11_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
1141 {
1142         return -1;
1143 }
1144 #endif
1145
1146 #ifdef HAVE_BACKEND_HEADLESS
1147 static int
1148 load_headless_backend(struct ivi_compositor *ivi, int *argc, char **argv)
1149 {
1150         struct weston_headless_backend_config config = {};
1151         int ret = 0;
1152
1153         bool use_pixman;
1154         bool fullscreen;
1155         bool use_gl;
1156         int output_count;
1157
1158         struct weston_compositor *c = ivi->compositor;
1159
1160         const struct weston_option options[] = {
1161                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
1162                 { WESTON_OPTION_BOOLEAN, "use-gl", 0, &use_gl },
1163         };
1164
1165         windowed_parse_common_options(ivi, argc, argv, &use_pixman,
1166                         &fullscreen, &output_count);
1167
1168         parse_options(options, ARRAY_LENGTH(options), argc, argv);
1169         config.use_pixman = use_pixman;
1170         config.use_gl = use_gl;
1171
1172         config.base.struct_version = WESTON_HEADLESS_BACKEND_CONFIG_VERSION;
1173         config.base.struct_size = sizeof(struct weston_headless_backend_config);
1174
1175         /* load the actual headless-backend and configure it */
1176         ret = weston_compositor_load_backend(c, WESTON_BACKEND_HEADLESS,
1177                                              &config.base);
1178         if (ret < 0)
1179                 return ret;
1180
1181         ivi->window_api = weston_windowed_output_get_api(c);
1182         if (!ivi->window_api) {
1183                 weston_log("Cannot use weston_windowed_output_api.\n");
1184                 return -1;
1185         }
1186
1187         if (ivi->window_api->create_head(c, "headless") < 0) {
1188                 weston_log("Cannot create headless back-end\n");
1189                 return -1;
1190         }
1191
1192         return 0;
1193 }
1194 #else
1195 static int
1196 load_headless_backend(struct ivi_compositor *ivi, int *argc, char **argv)
1197 {
1198         return -1;
1199 }
1200 #endif
1201
1202 static int
1203 load_backend(struct ivi_compositor *ivi, const char *backend,
1204              int *argc, char *argv[])
1205 {
1206         if (strcmp(backend, "drm-backend.so") == 0) {
1207                 return load_drm_backend(ivi, argc, argv);
1208         } else if (strcmp(backend, "wayland-backend.so") == 0) {
1209                 return load_wayland_backend(ivi, argc, argv);
1210         } else if (strcmp(backend, "x11-backend.so") == 0) {
1211                 return load_x11_backend(ivi, argc, argv);
1212         } else if (strcmp(backend, "headless-backend.so") == 0) {
1213                 return load_headless_backend(ivi, argc, argv);
1214         }
1215
1216         weston_log("fatal: unknown backend '%s'.\n", backend);
1217         return -1;
1218 }
1219
1220 static int
1221 load_modules(struct ivi_compositor *ivi, const char *modules,
1222              int *argc, char *argv[], bool *xwayland)
1223 {
1224         const char *p, *end;
1225         char buffer[256];
1226         int (*module_init)(struct weston_compositor *wc, int argc, char *argv[]);
1227
1228         if (modules == NULL)
1229                 return 0;
1230
1231         p = modules;
1232         while (*p) {
1233                 end = strchrnul(p, ',');
1234                 snprintf(buffer, sizeof buffer, "%.*s", (int) (end - p), p);
1235
1236                 if (strstr(buffer, "xwayland.so")) {
1237                         *xwayland = true;
1238                 } else if (strstr(buffer, "systemd-notify.so")) {
1239                         weston_log("systemd-notify plug-in already loaded!\n");
1240                 } else {
1241                         module_init = weston_load_module(buffer, "wet_module_init");
1242                         if (!module_init)
1243                                 return -1;
1244
1245                         if (module_init(ivi->compositor, *argc, argv) < 0)
1246                                 return -1;
1247
1248                 }
1249
1250                 p = end;
1251                 while (*p == ',')
1252                         p++;
1253         }
1254
1255         return 0;
1256 }
1257
1258
1259 static char *
1260 choose_default_backend(void)
1261 {
1262         char *backend = NULL;
1263
1264         if (getenv("WAYLAND_DISPLAY") || getenv("WAYLAND_SOCKET"))
1265                 backend = strdup("wayland-backend.so");
1266         else if (getenv("DISPLAY"))
1267                 backend = strdup("x11-backend.so");
1268         else
1269                 backend = strdup("drm-backend.so");
1270
1271         return backend;
1272 }
1273
1274 static int
1275 compositor_init_config(struct ivi_compositor *ivi)
1276 {
1277         struct xkb_rule_names xkb_names;
1278         struct weston_config_section *section;
1279         struct weston_compositor *compositor = ivi->compositor;
1280         struct weston_config *config = ivi->config;
1281         int repaint_msec;
1282         bool vt_switching;
1283         bool require_input;
1284
1285         /* agl-compositor.ini [keyboard] */
1286         section = weston_config_get_section(config, "keyboard", NULL, NULL);
1287         weston_config_section_get_string(section, "keymap_rules",
1288                                          (char **) &xkb_names.rules, NULL);
1289         weston_config_section_get_string(section, "keymap_model",
1290                                          (char **) &xkb_names.model, NULL);
1291         weston_config_section_get_string(section, "keymap_layout",
1292                                          (char **) &xkb_names.layout, NULL);
1293         weston_config_section_get_string(section, "keymap_variant",
1294                                          (char **) &xkb_names.variant, NULL);
1295         weston_config_section_get_string(section, "keymap_options",
1296                                          (char **) &xkb_names.options, NULL);
1297
1298         if (weston_compositor_set_xkb_rule_names(compositor, &xkb_names) < 0)
1299                 return -1;
1300
1301         weston_config_section_get_int(section, "repeat-rate",
1302                                       &compositor->kb_repeat_rate, 40);
1303         weston_config_section_get_int(section, "repeat-delay",
1304                                       &compositor->kb_repeat_delay, 400);
1305
1306         weston_config_section_get_bool(section, "vt-switching",
1307                                        &vt_switching, false);
1308         compositor->vt_switching = vt_switching;
1309
1310         /* agl-compositor.ini [core] */
1311         section = weston_config_get_section(config, "core", NULL, NULL);
1312
1313         weston_config_section_get_bool(section, "disable-cursor",
1314                                        &ivi->disable_cursor, false);
1315         weston_config_section_get_bool(section, "activate-by-default",
1316                                        &ivi->activate_by_default, true);
1317
1318         weston_config_section_get_bool(section, "require-input", &require_input, true);
1319         compositor->require_input = require_input;
1320
1321         weston_config_section_get_int(section, "repaint-window", &repaint_msec,
1322                                       compositor->repaint_msec);
1323         if (repaint_msec < -10 || repaint_msec > 1000) {
1324                 weston_log("Invalid repaint_window value in config: %d\n",
1325                            repaint_msec);
1326         } else {
1327                 compositor->repaint_msec = repaint_msec;
1328         }
1329         weston_log("Output repaint window is %d ms maximum.\n",
1330                    compositor->repaint_msec);
1331
1332         return 0;
1333 }
1334
1335 struct ivi_surface *
1336 to_ivi_surface(struct weston_surface *surface)
1337 {
1338         struct weston_desktop_surface *dsurface;
1339
1340         dsurface = weston_surface_get_desktop_surface(surface);
1341         if (!dsurface)
1342                 return NULL;
1343
1344         return weston_desktop_surface_get_user_data(dsurface);
1345 }
1346
1347 static void
1348 activate_binding(struct weston_seat *seat,
1349                  struct weston_view *focus_view, uint32_t flags)
1350 {
1351         struct weston_surface *focus_surface;
1352         struct weston_surface *main_surface;
1353         struct ivi_surface *ivi_surface;
1354         struct ivi_shell_seat *ivi_seat = get_ivi_shell_seat(seat);
1355
1356         if (!focus_view)
1357                 return;
1358
1359         focus_surface = focus_view->surface;
1360         main_surface = weston_surface_get_main_surface(focus_surface);
1361
1362         ivi_surface = to_ivi_surface(main_surface);
1363         if (!ivi_surface)
1364                 return;
1365
1366         if (ivi_seat)
1367                 ivi_shell_activate_surface(ivi_surface, ivi_seat, flags);
1368 }
1369
1370 static void
1371 click_to_activate_binding(struct weston_pointer *pointer,
1372                           const struct timespec *time,
1373                           uint32_t button, void *data)
1374 {
1375         if (pointer->grab != &pointer->default_grab)
1376                 return;
1377         if (pointer->focus == NULL)
1378                 return;
1379
1380         activate_binding(pointer->seat, pointer->focus,
1381                          WESTON_ACTIVATE_FLAG_CLICKED);
1382 }
1383
1384 static void
1385 touch_to_activate_binding(struct weston_touch *touch,
1386                           const struct timespec *time,
1387                           void *data)
1388 {
1389         if (touch->grab != &touch->default_grab)
1390                 return;
1391         if (touch->focus == NULL)
1392                 return;
1393
1394         activate_binding(touch->seat, touch->focus,
1395                          WESTON_ACTIVATE_FLAG_NONE);
1396 }
1397
1398 static void
1399 add_bindings(struct weston_compositor *compositor)
1400 {
1401         weston_compositor_add_button_binding(compositor, BTN_LEFT, 0,
1402                                              click_to_activate_binding,
1403                                              NULL);
1404         weston_compositor_add_button_binding(compositor, BTN_RIGHT, 0,
1405                                              click_to_activate_binding,
1406                                              NULL);
1407         weston_compositor_add_touch_binding(compositor, 0,
1408                                             touch_to_activate_binding,
1409                                             NULL);
1410 }
1411
1412 static int
1413 create_listening_socket(struct wl_display *display, const char *socket_name)
1414 {
1415         if (socket_name) {
1416                 if (wl_display_add_socket(display, socket_name)) {
1417                         weston_log("fatal: failed to add socket: %s\n",
1418                                    strerror(errno));
1419                         return -1;
1420                 }
1421         } else {
1422                 socket_name = wl_display_add_socket_auto(display);
1423                 if (!socket_name) {
1424                         weston_log("fatal: failed to add socket: %s\n",
1425                                    strerror(errno));
1426                         return -1;
1427                 }
1428         }
1429
1430         setenv("WAYLAND_DISPLAY", socket_name, 1);
1431
1432         return 0;
1433 }
1434
1435 static bool
1436 global_filter(const struct wl_client *client, const struct wl_global *global,
1437               void *data)
1438 {
1439         return true;
1440 }
1441
1442 static int
1443 load_config(struct weston_config **config, bool no_config,
1444             const char *config_file)
1445 {
1446         const char *file = "agl-compositor.ini";
1447         const char *full_path;
1448
1449         if (config_file)
1450                 file = config_file;
1451
1452         if (!no_config)
1453                 *config = weston_config_parse(file);
1454
1455         if (*config) {
1456                 full_path = weston_config_get_full_path(*config);
1457
1458                 weston_log("Using config file '%s'.\n", full_path);
1459                 setenv(WESTON_CONFIG_FILE_ENV_VAR, full_path, 1);
1460
1461                 return 0;
1462         }
1463
1464         if (config_file && !no_config) {
1465                 weston_log("fatal: error opening or reading config file '%s'.\n",
1466                         config_file);
1467
1468                 return -1;
1469         }
1470
1471         weston_log("Starting with no config file.\n");
1472         setenv(WESTON_CONFIG_FILE_ENV_VAR, "", 1);
1473
1474         return 0;
1475 }
1476
1477 static FILE *logfile;
1478
1479 static char *
1480 log_timestamp(char *buf, size_t len)
1481 {
1482         struct timeval tv;
1483         struct tm *brokendown_time;
1484         char datestr[128];
1485         char timestr[128];
1486
1487         gettimeofday(&tv, NULL);
1488
1489         brokendown_time = localtime(&tv.tv_sec);
1490         if (brokendown_time == NULL) {
1491                 snprintf(buf, len, "%s", "[(NULL)localtime] ");
1492                 return buf;
1493         }
1494
1495         memset(datestr, 0, sizeof(datestr));
1496         if (brokendown_time->tm_mday != cached_tm_mday) {
1497                 strftime(datestr, sizeof(datestr), "Date: %Y-%m-%d %Z\n",
1498                                 brokendown_time);
1499                 cached_tm_mday = brokendown_time->tm_mday;
1500         }
1501
1502         strftime(timestr, sizeof(timestr), "%H:%M:%S", brokendown_time);
1503         /* if datestr is empty it prints only timestr*/
1504         snprintf(buf, len, "%s[%s.%03li]", datestr,
1505                         timestr, (tv.tv_usec / 1000));
1506
1507         return buf;
1508 }
1509
1510 static void
1511 custom_handler(const char *fmt, va_list arg)
1512 {
1513         char timestr[512];
1514
1515         weston_log_scope_printf(log_scope, "%s libwayland: ",
1516                         log_timestamp(timestr, sizeof(timestr)));
1517         weston_log_scope_vprintf(log_scope, fmt, arg);
1518 }
1519
1520 static void
1521 log_file_open(const char *filename)
1522 {
1523         wl_log_set_handler_server(custom_handler);
1524
1525         if (filename)
1526                 logfile = fopen(filename, "a");
1527
1528         if (!logfile) {
1529                 logfile = stderr;
1530         } else {
1531                 os_fd_set_cloexec(fileno(logfile));
1532                 setvbuf(logfile, NULL, _IOLBF, 256);
1533         }
1534 }
1535
1536 static void
1537 log_file_close(void)
1538 {
1539         if (logfile && logfile != stderr)
1540                 fclose(logfile);
1541         logfile = stderr;
1542 }
1543
1544 static int
1545 vlog(const char *fmt, va_list ap)
1546 {
1547         const char *oom = "Out of memory";
1548         char timestr[128];
1549         int len = 0;
1550         char *str;
1551
1552         if (weston_log_scope_is_enabled(log_scope)) {
1553                 int len_va;
1554                 char *xlog_timestamp = log_timestamp(timestr, sizeof(timestr));
1555                 len_va = vasprintf(&str, fmt, ap);
1556                 if (len_va >= 0) {
1557                         len = weston_log_scope_printf(log_scope, "%s %s",
1558                                         xlog_timestamp, str);
1559                         free(str);
1560                 } else {
1561                         len = weston_log_scope_printf(log_scope, "%s %s",
1562                                         xlog_timestamp, oom);
1563                 }
1564         }
1565
1566         return len;
1567 }
1568
1569
1570 static int
1571 vlog_continue(const char *fmt, va_list ap)
1572 {
1573         return weston_log_scope_vprintf(log_scope, fmt, ap);
1574 }
1575
1576 static int
1577 on_term_signal(int signo, void *data)
1578 {
1579         struct wl_display *display = data;
1580
1581         weston_log("caught signal %d\n", signo);
1582         wl_display_terminate(display);
1583
1584         return 1;
1585 }
1586
1587 static void
1588 handle_exit(struct weston_compositor *compositor)
1589 {
1590         wl_display_terminate(compositor->wl_display);
1591 }
1592
1593 static void
1594 usage(int error_code)
1595 {
1596         FILE *out = error_code == EXIT_SUCCESS ? stdout : stderr;
1597         fprintf(out,
1598                 "Usage: agl-compositor [OPTIONS]\n"
1599                 "\n"
1600                 "This is " PACKAGE_STRING ", the reference compositor for\n"
1601                 "Automotive Grade Linux. " PACKAGE_STRING " supports multiple "
1602                 "backends,\nand depending on which backend is in use different "
1603                 "options will be accepted.\n"
1604                 "\n"
1605                 "Core options:\n"
1606                 "\n"
1607                 "  --version\t\tPrint agl-compositor version\n"
1608                 "  -B, --backend=MODULE\tBackend module, one of\n"
1609                         "\t\t\t\tdrm-backend.so\n"
1610                         "\t\t\t\twayland-backend.so\n"
1611                         "\t\t\t\tx11-backend.so\n"
1612                         "\t\t\t\theadless-backend.so\n"
1613                 "  -S, --socket=NAME\tName of socket to listen on\n"
1614                 "  --log=FILE\t\tLog to the given file\n"
1615                 "  -c, --config=FILE\tConfig file to load, defaults to agl-compositor.ini\n"
1616                 "  --no-config\t\tDo not read agl-compositor.ini\n"
1617                 "  --debug\t\tEnable debug extension(s)\n"
1618                 "  -h, --help\t\tThis help message\n"
1619                 "\n");
1620         exit(error_code);
1621 }
1622
1623 static char *
1624 copy_command_line(int argc, char * const argv[])
1625 {
1626         FILE *fp;
1627         char *str = NULL;
1628         size_t size = 0;
1629         int i;
1630
1631         fp = open_memstream(&str, &size);
1632         if (!fp)
1633                 return NULL;
1634
1635         fprintf(fp, "%s", argv[0]);
1636         for (i = 1; i < argc; i++)
1637                 fprintf(fp, " %s", argv[i]);
1638         fclose(fp);
1639
1640         return str;
1641 }
1642
1643 #if !defined(BUILD_XWAYLAND)
1644 int
1645 wet_load_xwayland(struct weston_compositor *comp)
1646 {
1647         weston_log("Attempted to load xwayland library but compositor "
1648                    "was *not* built with xwayland support!\n");
1649         return -1;
1650 }
1651 #endif
1652
1653 static void
1654 weston_log_setup_scopes(struct weston_log_context *log_ctx,
1655                         struct weston_log_subscriber *subscriber,
1656                         const char *names)
1657 {
1658         assert(log_ctx);
1659         assert(subscriber);
1660
1661         char *tokenize = strdup(names);
1662         char *token = strtok(tokenize, ",");
1663         while (token) {
1664                 weston_log_subscribe(log_ctx, subscriber, token);
1665                 token = strtok(NULL, ",");
1666         }
1667         free(tokenize);
1668 }
1669
1670 static void
1671 weston_log_subscribe_to_scopes(struct weston_log_context *log_ctx,
1672                                struct weston_log_subscriber *logger,
1673                                const char *debug_scopes)
1674 {
1675         if (logger && debug_scopes)
1676                 weston_log_setup_scopes(log_ctx, logger, debug_scopes);
1677         else
1678                 weston_log_subscribe(log_ctx, logger, "log");
1679 }
1680
1681 WL_EXPORT
1682 int wet_main(int argc, char *argv[], const struct weston_testsuite_data *test_data)
1683 {
1684         struct ivi_compositor ivi = { 0 };
1685         char *cmdline;
1686         struct wl_display *display = NULL;
1687         struct wl_event_loop *loop;
1688         struct wl_event_source *signals[3] = { 0 };
1689         struct weston_config_section *section;
1690         /* Command line options */
1691         char *backend = NULL;
1692         char *socket_name = NULL;
1693         char *log = NULL;
1694         char *modules = NULL;
1695         char *option_modules = NULL;
1696         char *debug_scopes = NULL;
1697         int help = 0;
1698         int version = 0;
1699         int no_config = 0;
1700         int debug = 0;
1701         bool list_debug_scopes = false;
1702         char *config_file = NULL;
1703         struct weston_log_context *log_ctx = NULL;
1704         struct weston_log_subscriber *logger;
1705         int ret = EXIT_FAILURE;
1706         bool xwayland = false;
1707         struct sigaction action;
1708
1709         const struct weston_option core_options[] = {
1710                 { WESTON_OPTION_STRING, "backend", 'B', &backend },
1711                 { WESTON_OPTION_STRING, "socket", 'S', &socket_name },
1712                 { WESTON_OPTION_STRING, "log", 0, &log },
1713                 { WESTON_OPTION_BOOLEAN, "help", 'h', &help },
1714                 { WESTON_OPTION_BOOLEAN, "version", 0, &version },
1715                 { WESTON_OPTION_BOOLEAN, "no-config", 0, &no_config },
1716                 { WESTON_OPTION_BOOLEAN, "debug", 0, &debug },
1717                 { WESTON_OPTION_STRING, "config", 'c', &config_file },
1718                 { WESTON_OPTION_STRING, "modules", 0, &option_modules },
1719                 { WESTON_OPTION_STRING, "debug-scopes", 'l', &debug_scopes },
1720                 { WESTON_OPTION_STRING, "list-debug-scopes", 'L', &list_debug_scopes },
1721         };
1722
1723         wl_list_init(&ivi.outputs);
1724         wl_list_init(&ivi.saved_outputs);
1725         wl_list_init(&ivi.surfaces);
1726         wl_list_init(&ivi.pending_surfaces);
1727         wl_list_init(&ivi.popup_pending_apps);
1728         wl_list_init(&ivi.fullscreen_pending_apps);
1729         wl_list_init(&ivi.split_pending_apps);
1730         wl_list_init(&ivi.remote_pending_apps);
1731         wl_list_init(&ivi.desktop_clients);
1732         wl_list_init(&ivi.child_process_list);
1733         wl_list_init(&ivi.pending_apps);
1734
1735         /* Prevent any clients we spawn getting our stdin */
1736         os_fd_set_cloexec(STDIN_FILENO);
1737
1738         cmdline = copy_command_line(argc, argv);
1739         parse_options(core_options, ARRAY_LENGTH(core_options), &argc, argv);
1740
1741         if (help)
1742                 usage(EXIT_SUCCESS);
1743
1744         if (version) {
1745                 printf(PACKAGE_STRING "\n");
1746                 ret = EXIT_SUCCESS;
1747                 goto exit_signals;
1748         }
1749
1750         log_ctx = weston_log_ctx_create();
1751         if (!log_ctx) {
1752                 fprintf(stderr, "Failed to initialize weston debug framework.\n");
1753                 goto exit_signals;
1754         }
1755
1756         log_scope = weston_log_ctx_add_log_scope(log_ctx, "log",
1757                                                  "agl-compositor log\n",
1758                                                  NULL, NULL, NULL);
1759
1760         log_file_open(log);
1761         weston_log_set_handler(vlog, vlog_continue);
1762
1763         logger = weston_log_subscriber_create_log(logfile);
1764         weston_log_subscribe_to_scopes(log_ctx, logger, debug_scopes);
1765
1766         weston_log("Command line: %s\n", cmdline);
1767         free(cmdline);
1768
1769         if (load_config(&ivi.config, no_config, config_file) < 0)
1770                 goto error_signals;
1771         section = weston_config_get_section(ivi.config, "core", NULL, NULL);
1772         if (!backend) {
1773                 weston_config_section_get_string(section, "backend", &backend,
1774                                                  NULL);
1775                 if (!backend)
1776                         backend = choose_default_backend();
1777         }
1778
1779         display = wl_display_create();
1780         loop = wl_display_get_event_loop(display);
1781
1782         wl_display_set_global_filter(display,
1783                                      global_filter, &ivi);
1784
1785         /* Register signal handlers so we shut down cleanly */
1786
1787         signals[0] = wl_event_loop_add_signal(loop, SIGTERM, on_term_signal,
1788                                               display);
1789         signals[1] = wl_event_loop_add_signal(loop, SIGUSR2, on_term_signal,
1790                                               display);
1791         signals[2] = wl_event_loop_add_signal(loop, SIGCHLD, sigchld_handler,
1792                                               display);
1793
1794         /* When debugging the compositor, if use wl_event_loop_add_signal() to
1795          * catch SIGINT, the debugger can't catch it, and attempting to stop
1796          * the compositor from within the debugger results in weston exiting
1797          * cleanly.
1798          *
1799          * Instead, use the sigaction() function, which sets up the signal in a
1800          * way that gdb can successfully catch, but have the handler for SIGINT
1801          * send SIGUSR2 (xwayland uses SIGUSR1), which we catch via
1802          * wl_event_loop_add_signal().
1803          */
1804         action.sa_handler = sigint_helper;
1805         sigemptyset(&action.sa_mask);
1806         action.sa_flags = 0;
1807         sigaction(SIGINT, &action, NULL);
1808
1809         for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
1810                 if (!signals[i])
1811                         goto error_signals;
1812
1813         ivi.compositor = weston_compositor_create(display, log_ctx, &ivi, test_data);
1814         if (!ivi.compositor) {
1815                 weston_log("fatal: failed to create compositor.\n");
1816                 goto error_signals;
1817         }
1818
1819         if (compositor_init_config(&ivi) < 0)
1820                 goto error_compositor;
1821
1822         if (load_backend(&ivi, backend, &argc, argv) < 0) {
1823                 weston_log("fatal: failed to create compositor backend.\n");
1824                 goto error_compositor;
1825         }
1826
1827         ivi.heads_changed.notify = heads_changed;
1828         weston_compositor_add_heads_changed_listener(ivi.compositor,
1829                                                      &ivi.heads_changed);
1830
1831         if (ivi_desktop_init(&ivi) < 0)
1832                 goto error_compositor;
1833
1834         ivi_seat_init(&ivi);
1835
1836         /* load additional modules */
1837         weston_config_section_get_string(section, "modules", &modules, "");
1838         if (load_modules(&ivi, modules, &argc, argv, &xwayland) < 0)
1839                 goto error_compositor;
1840
1841         if (load_modules(&ivi, option_modules, &argc, argv, &xwayland) < 0)
1842                 goto error_compositor;
1843
1844         if (!xwayland) {
1845                 weston_config_section_get_bool(section, "xwayland", &xwayland,
1846                                                false);
1847         }
1848
1849         if (ivi_shell_init(&ivi) < 0)
1850                 goto error_compositor;
1851
1852         if (xwayland) {
1853                 if (wet_load_xwayland(ivi.compositor) < 0)
1854                         goto error_compositor;
1855         }
1856
1857         if (ivi_policy_init(&ivi) < 0)
1858                 goto error_compositor;
1859
1860
1861         if (list_debug_scopes) {
1862                 struct weston_log_scope *nscope = NULL;
1863
1864                 weston_log("Printing available debug scopes:\n");
1865
1866                 while ((nscope = weston_log_scopes_iterate(log_ctx, nscope))) {
1867                         weston_log("\tscope name: %s, desc: %s",
1868                                         weston_log_scope_get_name(nscope),
1869                                         weston_log_scope_get_description(nscope));
1870                 }
1871
1872                 weston_log("\n");
1873
1874                 goto error_compositor;
1875         }
1876
1877         add_bindings(ivi.compositor);
1878
1879         weston_compositor_flush_heads_changed(ivi.compositor);
1880
1881         if (ivi.remoting_api)
1882                 ivi_enable_remote_outputs(&ivi);
1883
1884         if (create_listening_socket(display, socket_name) < 0)
1885                 goto error_compositor;
1886
1887         ivi_shell_init_black_fs(&ivi);
1888
1889         ivi.compositor->exit = handle_exit;
1890
1891         weston_compositor_wake(ivi.compositor);
1892
1893         ivi_shell_create_global(&ivi);
1894
1895         ivi_launch_shell_client(&ivi, "shell-client",
1896                                 &ivi.shell_client.client);
1897         ivi_launch_shell_client(&ivi, "shell-client-ext",
1898                                 &ivi.shell_client_ext.client);
1899
1900         if (debug)
1901                 ivi_screenshooter_create(&ivi);
1902         ivi_agl_systemd_notify(&ivi);
1903
1904         wl_display_run(display);
1905
1906         ret = ivi.compositor->exit_code;
1907
1908         wl_display_destroy_clients(display);
1909
1910 error_compositor:
1911         free(backend);
1912         backend = NULL;
1913         free(modules);
1914         modules = NULL;
1915
1916         weston_compositor_destroy(ivi.compositor);
1917
1918         weston_log_scope_destroy(log_scope);
1919         log_scope = NULL;
1920
1921         weston_log_subscriber_destroy(logger);
1922         weston_log_ctx_destroy(log_ctx);
1923
1924         ivi_policy_destroy(ivi.policy);
1925
1926 error_signals:
1927         for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
1928                 if (signals[i])
1929                         wl_event_source_remove(signals[i]);
1930
1931         wl_display_destroy(display);
1932
1933         log_file_close();
1934         if (ivi.config)
1935                 weston_config_destroy(ivi.config);
1936
1937 exit_signals:
1938         free(log);
1939         free(config_file);
1940         free(socket_name);
1941         free(option_modules);
1942         return ret;
1943 }