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