src: Allow to start other clients
[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                 weston_output_disable(ivi_output->output);
491         }
492 }
493
494 static struct weston_config_section *
495 find_controlling_output_config(struct weston_config *config,
496                                const char *name)
497 {
498         struct weston_config_section *section;
499         char *same_as;
500         int depth = 0;
501
502         same_as = strdup(name);
503         do {
504                 section = weston_config_get_section(config, "output",
505                                                     "name", same_as);
506                 if (!section && depth > 0)
507                         weston_log("Configuration error: output section reffered"
508                                    "to by same-as=%s not found.\n", same_as);
509                 free(same_as);
510
511                 if (!section)
512                         return NULL;
513
514                 if (depth++ > 8) {
515                         weston_log("Configuration error: same-as nested too "
516                                    "deep for output '%s'.\n", name);
517                         return NULL;
518                 }
519
520                 weston_config_section_get_string(section, "same-as",
521                                                  &same_as, NULL);
522         } while (same_as);
523
524         return section;
525 }
526
527 static void
528 head_prepare_enable(struct ivi_compositor *ivi, struct weston_head *head)
529 {
530         const char *name = weston_head_get_name(head);
531         struct weston_config_section *section;
532         struct ivi_output *output;
533         char *output_name = NULL;
534
535         section = find_controlling_output_config(ivi->config, name);
536         if (section) {
537                 char *mode;
538
539                 weston_config_section_get_string(section, "mode", &mode, NULL);
540                 if (mode && strcmp(mode, "off") == 0) {
541                         free(mode);
542                         return;
543                 }
544                 free(mode);
545
546                 weston_config_section_get_string(section, "name",
547                                                  &output_name, NULL);
548         } else {
549                 output_name = strdup(name);
550         }
551
552         if (!output_name)
553                 return;
554
555         output = ivi_ensure_output(ivi, output_name, section);
556         if (!output)
557                 return;
558
559         if (output->add_len >= ARRAY_LENGTH(output->add))
560                 return;
561
562         output->add[output->add_len++] = head;
563 }
564
565 static void
566 heads_changed(struct wl_listener *listener, void *arg)
567 {
568         struct weston_compositor *compositor = arg;
569         struct weston_head *head = NULL;
570         struct ivi_compositor *ivi = to_ivi_compositor(compositor);
571         struct ivi_output *output;
572
573         while ((head = weston_compositor_iterate_heads(ivi->compositor, head))) {
574                 bool connected = weston_head_is_connected(head);
575                 bool enabled = weston_head_is_enabled(head);
576                 bool changed = weston_head_is_device_changed(head);
577                 bool non_desktop = weston_head_is_non_desktop(head);
578
579                 if (connected && !enabled && !non_desktop)
580                         head_prepare_enable(ivi, head);
581                 else if (!connected && enabled)
582                         head_disable(ivi, head);
583                 else if (enabled && changed)
584                         weston_log("Detected a monitor change on head '%s', "
585                                    "not bothering to do anything about it.\n",
586                                    weston_head_get_name(head));
587
588                 weston_head_reset_device_changed(head);
589         }
590
591         wl_list_for_each(output, &ivi->outputs, link) {
592                 if (output->add_len == 0)
593                         continue;
594
595                 if (process_output(output) < 0) {
596                         output->add_len = 0;
597                         ivi->init_failed = true;
598                 }
599         }
600 }
601
602 #ifdef HAVE_WALTHAM
603 static int
604 load_waltham_plugin(struct ivi_compositor *ivi, struct weston_config *config)
605 {
606         struct weston_compositor *compositor = ivi->compositor;
607         int (*module_init)(struct weston_compositor *wc);
608
609         module_init = weston_load_module("waltham-transmitter.so",
610                                          "wet_module_init");
611         if (!module_init)
612                 return -1;
613
614         if (module_init(compositor) < 0)
615                 return -1;
616
617         ivi->waltham_transmitter_api = weston_get_transmitter_api(compositor);
618         if (!ivi->waltham_transmitter_api) {
619                 weston_log("Failed to load waltham-transmitter plugin.\n");
620                 return -1;
621         }
622
623         weston_log("waltham-transmitter plug-in loaded\n");
624         return 0;
625 }
626 #else
627 static int
628 load_waltham_plugin(struct ivi_compositor *ivi, struct weston_config *config)
629 {
630         return -1;
631 }
632 #endif
633
634 #ifdef HAVE_REMOTING
635 static int
636 drm_backend_remoted_output_configure(struct weston_output *output,
637                                      struct weston_config_section *section,
638                                      char *modeline,
639                                      const struct weston_remoting_api *api)
640 {
641         char *gbm_format = NULL;
642         char *seat = NULL;
643         char *host = NULL;
644         char *pipeline = NULL;
645         int port, ret;
646         int32_t scale = 1;
647         uint32_t transform = WL_OUTPUT_TRANSFORM_NORMAL;
648         char *trans;
649
650         ret = api->set_mode(output, modeline);
651         if (ret < 0) {
652                 weston_log("Cannot configure an output \"%s\" using "
653                                 "weston_remoting_api. Invalid mode\n",
654                                 output->name);
655                 return -1;
656         }
657
658         weston_config_section_get_int(section, "scale", &scale, 1);
659         weston_output_set_scale(output, scale);
660
661         weston_config_section_get_string(section, "transform", &trans, "normal");
662         if (parse_transform(trans, &transform) < 0) {
663                 weston_log("Invalid transform \"%s\" for output %s\n",
664                            trans, output->name);
665         }
666         weston_output_set_transform(output, transform);
667
668         weston_config_section_get_string(section, "gbm-format",
669                                          &gbm_format, NULL);
670         api->set_gbm_format(output, gbm_format);
671         free(gbm_format);
672
673         weston_config_section_get_string(section, "seat", &seat, "");
674
675         api->set_seat(output, seat);
676         free(seat);
677
678         weston_config_section_get_string(section, "gst-pipeline", &pipeline,
679                         NULL);
680         if (pipeline) {
681                 api->set_gst_pipeline(output, pipeline);
682                 free(pipeline);
683                 return 0;
684         }
685
686         weston_config_section_get_string(section, "host", &host, NULL);
687         weston_config_section_get_int(section, "port", &port, 0);
688         if (!host || port <= 0 || 65533 < port) {
689                 weston_log("Cannot configure an output \"%s\". "
690                                 "Need to specify gst-pipeline or "
691                                 "host and port (1-65533).\n", output->name);
692         }
693         api->set_host(output, host);
694         free(host);
695         api->set_port(output, port);
696
697         return 0;
698 }
699
700
701 static int
702 remote_output_init(struct ivi_output *ivi_output,
703                    struct weston_compositor *compositor,
704                    struct weston_config_section *section,
705                    const struct weston_remoting_api *api)
706 {
707         char *output_name, *modeline = NULL;
708         int ret = -1;
709
710         weston_config_section_get_string(section, "name", &output_name, NULL);
711         if (!output_name)
712                 return ret;
713
714         weston_config_section_get_string(section, "mode", &modeline, "off");
715         if (strcmp(modeline, "off") == 0)
716                 goto err;
717
718         ivi_output->output = api->create_output(compositor, output_name);
719         if (!ivi_output->output) {
720                 weston_log("Cannot create remoted output \"%s\".\n",
721                                 output_name);
722                 goto err;
723         }
724
725         ret = drm_backend_remoted_output_configure(ivi_output->output, section,
726                                                    modeline, api);
727         if (ret < 0) {
728                 weston_log("Cannot configure remoted output \"%s\".\n",
729                                 output_name);
730                 goto err;
731         }
732
733         if (weston_output_enable(ivi_output->output) < 0) {
734                 weston_log("Enabling remoted output \"%s\" failed.\n",
735                                 output_name);
736                 goto err;
737         }
738
739         free(modeline);
740         free(output_name);
741         weston_log("remoted output '%s' enabled\n", ivi_output->output->name);
742
743         return 0;
744
745 err:
746         free(modeline);
747         free(output_name);
748         if (ivi_output->output)
749                 weston_output_destroy(ivi_output->output);
750
751         return ret;
752 }
753
754 static void
755 ivi_enable_remote_outputs(struct ivi_compositor *ivi)
756 {
757         struct weston_config_section *remote_section = NULL;
758         const char *section_name;
759         struct weston_config *config = ivi->config;
760
761         while (weston_config_next_section(config, &remote_section, &section_name)) {
762                 if (strcmp(section_name, "remote-output"))
763                         continue;
764
765                 struct ivi_output *ivi_output = NULL;
766                 bool output_found = false;
767                 char *_name = NULL;
768
769                 weston_config_section_get_string(remote_section,
770                                                  "name", &_name, NULL);
771                 wl_list_for_each(ivi_output, &ivi->outputs, link) {
772                         if (!strcmp(ivi_output->name, _name)) {
773                                 output_found = true;
774                                 break;
775                         }
776                 }
777
778                 if (output_found) {
779                         free(_name);
780                         continue;
781                 }
782
783                 ivi_output = zalloc(sizeof(*ivi_output));
784                 if (!ivi_output) {
785                         free(_name);
786                         continue;
787                 }
788
789                 ivi_output->ivi = ivi;
790                 ivi_output->name = _name;
791                 ivi_output->config = remote_section;
792                 ivi_output->type = OUTPUT_REMOTE;
793
794                 if (remote_output_init(ivi_output, ivi->compositor,
795                                        remote_section, ivi->remoting_api)) {
796                         free(ivi_output->name);
797                         free(ivi_output);
798                         continue;
799                 }
800
801                 ivi_output->output_destroy.notify = handle_output_destroy;
802                 weston_output_add_destroy_listener(ivi_output->output,
803                                                    &ivi_output->output_destroy);
804
805                 wl_list_insert(&ivi->outputs, &ivi_output->link);
806                 ivi_output_configure_app_id(ivi_output);
807         }
808 }
809
810 static void
811 ivi_enable_waltham_outputs(struct ivi_compositor *ivi)
812 {
813         struct weston_config_section *transmitter_section = NULL;
814         const char *sect_name;
815         struct weston_config *config = ivi->config;
816
817         while (weston_config_next_section(config, &transmitter_section, &sect_name)) {
818                 if (strcmp(sect_name, "transmitter-output"))
819                         continue;
820
821                 struct ivi_output *ivi_output = NULL;
822                 bool output_found = false;
823                 char *_name = NULL;
824
825                 weston_config_section_get_string(transmitter_section,
826                                 "name", &_name, NULL);
827                 wl_list_for_each(ivi_output, &ivi->outputs, link) {
828                         if (!strcmp(ivi_output->name, _name)) {
829                                 output_found = true;
830                                 break;
831                         }
832                 }
833
834                 if (output_found) {
835                         free(_name);
836                         continue;
837                 }
838
839                 ivi_output = zalloc(sizeof(*ivi_output));
840                 if (!ivi_output) {
841                         free(_name);
842                         continue;
843                 }
844
845                 ivi_output->ivi = ivi;
846                 ivi_output->name = _name;
847                 ivi_output->config = transmitter_section;
848
849                 if (remote_output_init(ivi_output, ivi->compositor,
850                                         transmitter_section, ivi->remoting_api)) {
851                         free(ivi_output->name);
852                         free(ivi_output);
853                         continue;
854                 }
855
856                 ivi_output->type = OUTPUT_WALTHAM;
857                 ivi_output->output_destroy.notify = handle_output_destroy;
858                 weston_output_add_destroy_listener(ivi_output->output,
859                                 &ivi_output->output_destroy);
860
861                 wl_list_insert(&ivi->outputs, &ivi_output->link);
862                 ivi_output_configure_app_id(ivi_output);
863         }
864 }
865
866 static int
867 load_remoting_plugin(struct ivi_compositor *ivi, struct weston_config *config)
868 {
869         struct weston_compositor *compositor = ivi->compositor;
870         int (*module_init)(struct weston_compositor *wc);
871
872         module_init = weston_load_module("remoting-plugin.so",
873                                          "weston_module_init");
874         if (!module_init)
875                 return -1;
876
877         if (module_init(compositor) < 0)
878                 return -1;
879
880         ivi->remoting_api = weston_remoting_get_api(compositor);
881         if (!ivi->remoting_api)
882                 return -1;
883         return 0;
884 }
885 #else
886 static int
887 load_remoting_plugin(struct weston_compositor *compositor, struct weston_config *config)
888 {
889         return -1;
890 }
891 #endif
892
893 static int
894 load_drm_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
895 {
896         struct weston_drm_backend_config config = {
897                 .base = {
898                         .struct_version = WESTON_DRM_BACKEND_CONFIG_VERSION,
899                         .struct_size = sizeof config,
900                 },
901         };
902         struct weston_config_section *section;
903         int use_current_mode = 0;
904         int use_pixman = 0;
905         bool use_shadow;
906         bool without_input = false;
907         int ret;
908
909         const struct weston_option options[] = {
910                 { WESTON_OPTION_STRING, "seat", 0, &config.seat_id },
911                 { WESTON_OPTION_STRING, "drm-device", 0, &config.specific_device },
912                 { WESTON_OPTION_BOOLEAN, "current-mode", 0, &use_current_mode },
913                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
914                 { WESTON_OPTION_BOOLEAN, "continue-without-input", false, &without_input }
915         };
916
917         parse_options(options, ARRAY_LENGTH(options), argc, argv);
918         config.use_pixman = use_pixman;
919         ivi->cmdline.use_current_mode = use_current_mode;
920
921         section = weston_config_get_section(ivi->config, "core", NULL, NULL);
922         weston_config_section_get_string(section, "gbm-format",
923                                          &config.gbm_format, NULL);
924         weston_config_section_get_uint(section, "pageflip-timeout",
925                                        &config.pageflip_timeout, 0);
926         weston_config_section_get_bool(section, "pixman-shadow", &use_shadow, 1);
927         config.use_pixman_shadow = use_shadow;
928
929         if (without_input)
930                 ivi->compositor->require_input = !without_input;
931
932         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_DRM,
933                                              &config.base);
934         if (ret < 0)
935                 return ret;
936
937         ivi->drm_api = weston_drm_output_get_api(ivi->compositor);
938         if (!ivi->drm_api) {
939                 weston_log("Cannot use drm output api.\n");
940                 ret = -1;
941                 goto error;
942         }
943
944         load_remoting_plugin(ivi, ivi->config);
945         load_waltham_plugin(ivi, ivi->config);
946
947 error:
948         free(config.gbm_format);
949         free(config.seat_id);
950         return ret;
951 }
952
953 static void
954 windowed_parse_common_options(struct ivi_compositor *ivi, int *argc, char *argv[],
955                               bool *use_pixman, bool *fullscreen, int *output_count)
956 {
957         struct weston_config_section *section;
958         bool pixman;
959         int fs = 0;
960
961         const struct weston_option options[] = {
962                 { WESTON_OPTION_INTEGER, "width", 0, &ivi->cmdline.width },
963                 { WESTON_OPTION_INTEGER, "height", 0, &ivi->cmdline.height },
964                 { WESTON_OPTION_INTEGER, "scale", 0, &ivi->cmdline.scale },
965                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &pixman },
966                 { WESTON_OPTION_BOOLEAN, "fullscreen", 0, &fs },
967                 { WESTON_OPTION_INTEGER, "output-count", 0, output_count },
968         };
969
970         section = weston_config_get_section(ivi->config, "core", NULL, NULL);
971         weston_config_section_get_bool(section, "use-pixman", &pixman, 0);
972
973         *output_count = 1;
974         parse_options(options, ARRAY_LENGTH(options), argc, argv);
975         *use_pixman = pixman;
976         *fullscreen = fs;
977 }
978
979 static int
980 windowed_create_outputs(struct ivi_compositor *ivi, int output_count,
981                         const char *match_prefix, const char *name_prefix)
982 {
983         struct weston_config_section *section = NULL;
984         const char *section_name;
985         char *default_output = NULL;
986         int i = 0;
987         size_t match_len = strlen(match_prefix);
988
989         while (weston_config_next_section(ivi->config, &section, &section_name)) {
990                 char *output_name;
991
992                 if (i >= output_count)
993                         break;
994
995                 if (strcmp(section_name, "output") != 0)
996                         continue;
997
998                 weston_config_section_get_string(section, "name", &output_name, NULL);
999                 if (output_name == NULL)
1000                         continue;
1001                 if (strncmp(output_name, match_prefix, match_len) != 0) {
1002                         free(output_name);
1003                         continue;
1004                 }
1005
1006                 if (ivi->window_api->create_head(ivi->compositor, output_name) < 0) {
1007                         free(output_name);
1008                         return -1;
1009                 }
1010
1011                 free(output_name);
1012                 ++i;
1013         }
1014
1015         for (; i < output_count; ++i) {
1016                 if (asprintf(&default_output, "%s%d", name_prefix, i) < 0)
1017                         return -1;
1018
1019                 if (ivi->window_api->create_head(ivi->compositor, default_output) < 0) {
1020                         free(default_output);
1021                         return -1;
1022                 }
1023
1024                 free(default_output);
1025         }
1026
1027         return 0;
1028 }
1029
1030 static int
1031 load_wayland_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
1032 {
1033         struct weston_wayland_backend_config config = {
1034                 .base = {
1035                         .struct_version = WESTON_WAYLAND_BACKEND_CONFIG_VERSION,
1036                         .struct_size = sizeof config,
1037                 },
1038         };
1039         struct weston_config_section *section;
1040         int sprawl = 0;
1041         int output_count;
1042         int ret;
1043
1044         const struct weston_option options[] = {
1045                 { WESTON_OPTION_STRING, "display", 0, &config.display_name },
1046                 { WESTON_OPTION_STRING, "sprawl", 0, &sprawl },
1047         };
1048
1049         windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
1050                                       &config.fullscreen, &output_count);
1051
1052         parse_options(options, ARRAY_LENGTH(options), argc, argv);
1053         config.sprawl = sprawl;
1054
1055         section = weston_config_get_section(ivi->config, "shell", NULL, NULL);
1056         weston_config_section_get_string(section, "cursor-theme",
1057                                          &config.cursor_theme, NULL);
1058         weston_config_section_get_int(section, "cursor-size",
1059                                       &config.cursor_size, 32);
1060
1061         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_WAYLAND,
1062                                              &config.base);
1063
1064         free(config.cursor_theme);
1065         free(config.display_name);
1066
1067         if (ret < 0)
1068                 return ret;
1069
1070         ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
1071
1072         /*
1073          * We will just assume if load_backend() finished cleanly and
1074          * windowed_output_api is not present that wayland backend is started
1075          * with --sprawl or runs on fullscreen-shell. In this case, all values
1076          * are hardcoded, so nothing can be configured; simply create and
1077          * enable an output.
1078          */
1079         if (ivi->window_api == NULL)
1080                 return 0;
1081
1082         return windowed_create_outputs(ivi, output_count, "WL", "wayland");
1083 }
1084
1085 #ifdef HAVE_BACKEND_X11
1086 static int
1087 load_x11_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
1088 {
1089         struct weston_x11_backend_config config = {
1090                 .base = {
1091                         .struct_version = WESTON_X11_BACKEND_CONFIG_VERSION,
1092                         .struct_size = sizeof config,
1093                 },
1094         };
1095         int no_input = 0;
1096         int output_count;
1097         int ret;
1098
1099         const struct weston_option options[] = {
1100                { WESTON_OPTION_BOOLEAN, "no-input", 0, &no_input },
1101         };
1102
1103         windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
1104                                       &config.fullscreen, &output_count);
1105
1106         parse_options(options, ARRAY_LENGTH(options), argc, argv);
1107         config.no_input = no_input;
1108
1109         ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_X11,
1110                                              &config.base);
1111
1112         if (ret < 0)
1113                 return ret;
1114
1115         ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
1116         if (!ivi->window_api) {
1117                 weston_log("Cannot use weston_windowed_output_api.\n");
1118                 return -1;
1119         }
1120
1121         return windowed_create_outputs(ivi, output_count, "X", "screen");
1122 }
1123 #else
1124 static int
1125 load_x11_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
1126 {
1127         return -1;
1128 }
1129 #endif
1130
1131 #ifdef HAVE_BACKEND_HEADLESS
1132 static int
1133 load_headless_backend(struct ivi_compositor *ivi, int *argc, char **argv)
1134 {
1135         struct weston_headless_backend_config config = {};
1136         int ret = 0;
1137
1138         bool use_pixman;
1139         bool fullscreen;
1140         bool use_gl;
1141         int output_count;
1142
1143         struct weston_compositor *c = ivi->compositor;
1144
1145         const struct weston_option options[] = {
1146                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
1147                 { WESTON_OPTION_BOOLEAN, "use-gl", 0, &use_gl },
1148         };
1149
1150         windowed_parse_common_options(ivi, argc, argv, &use_pixman,
1151                         &fullscreen, &output_count);
1152
1153         parse_options(options, ARRAY_LENGTH(options), argc, argv);
1154         config.use_pixman = use_pixman;
1155         config.use_gl = use_gl;
1156
1157         config.base.struct_version = WESTON_HEADLESS_BACKEND_CONFIG_VERSION;
1158         config.base.struct_size = sizeof(struct weston_headless_backend_config);
1159
1160         /* load the actual headless-backend and configure it */
1161         ret = weston_compositor_load_backend(c, WESTON_BACKEND_HEADLESS,
1162                                              &config.base);
1163         if (ret < 0)
1164                 return ret;
1165
1166         ivi->window_api = weston_windowed_output_get_api(c);
1167         if (!ivi->window_api) {
1168                 weston_log("Cannot use weston_windowed_output_api.\n");
1169                 return -1;
1170         }
1171
1172         if (ivi->window_api->create_head(c, "headless") < 0) {
1173                 weston_log("Cannot create headless back-end\n");
1174                 return -1;
1175         }
1176
1177         return 0;
1178 }
1179 #else
1180 static int
1181 load_headless_backend(struct ivi_compositor *ivi, int *argc, char **argv)
1182 {
1183         return -1;
1184 }
1185 #endif
1186
1187 static int
1188 load_backend(struct ivi_compositor *ivi, const char *backend,
1189              int *argc, char *argv[])
1190 {
1191         if (strcmp(backend, "drm-backend.so") == 0) {
1192                 return load_drm_backend(ivi, argc, argv);
1193         } else if (strcmp(backend, "wayland-backend.so") == 0) {
1194                 return load_wayland_backend(ivi, argc, argv);
1195         } else if (strcmp(backend, "x11-backend.so") == 0) {
1196                 return load_x11_backend(ivi, argc, argv);
1197         } else if (strcmp(backend, "headless-backend.so") == 0) {
1198                 return load_headless_backend(ivi, argc, argv);
1199         }
1200
1201         weston_log("fatal: unknown backend '%s'.\n", backend);
1202         return -1;
1203 }
1204
1205 static int
1206 load_modules(struct ivi_compositor *ivi, const char *modules,
1207              int *argc, char *argv[], bool *xwayland)
1208 {
1209         const char *p, *end;
1210         char buffer[256];
1211         int (*module_init)(struct weston_compositor *wc, int argc, char *argv[]);
1212
1213         if (modules == NULL)
1214                 return 0;
1215
1216         p = modules;
1217         while (*p) {
1218                 end = strchrnul(p, ',');
1219                 snprintf(buffer, sizeof buffer, "%.*s", (int) (end - p), p);
1220
1221                 if (strstr(buffer, "xwayland.so")) {
1222                         weston_log("Xwayland plug-in not supported!\n");
1223                         p = end;
1224                         while (*p == ',')
1225                                 p++;
1226                         continue;
1227                 }
1228
1229                 if (strstr(buffer, "systemd-notify.so")) {
1230                         weston_log("systemd-notify plug-in already loaded!\n");
1231                         p = end;
1232                         while (*p == ',')
1233                                 p++;
1234                         continue;
1235                 }
1236
1237                 module_init = weston_load_module(buffer, "wet_module_init");
1238                 if (!module_init)
1239                         return -1;
1240
1241                 if (module_init(ivi->compositor, *argc, argv) < 0)
1242                         return -1;
1243
1244                 p = end;
1245                 while (*p == ',')
1246                         p++;
1247         }
1248
1249         return 0;
1250 }
1251
1252
1253 static char *
1254 choose_default_backend(void)
1255 {
1256         char *backend = NULL;
1257
1258         if (getenv("WAYLAND_DISPLAY") || getenv("WAYLAND_SOCKET"))
1259                 backend = strdup("wayland-backend.so");
1260         else if (getenv("DISPLAY"))
1261                 backend = strdup("x11-backend.so");
1262         else
1263                 backend = strdup("drm-backend.so");
1264
1265         return backend;
1266 }
1267
1268 static int
1269 compositor_init_config(struct weston_compositor *compositor,
1270                        struct weston_config *config)
1271 {
1272         struct xkb_rule_names xkb_names;
1273         struct weston_config_section *section;
1274         int repaint_msec;
1275         bool vt_switching;
1276         bool require_input;
1277
1278         /* agl-compositor.ini [keyboard] */
1279         section = weston_config_get_section(config, "keyboard", NULL, NULL);
1280         weston_config_section_get_string(section, "keymap_rules",
1281                                          (char **) &xkb_names.rules, NULL);
1282         weston_config_section_get_string(section, "keymap_model",
1283                                          (char **) &xkb_names.model, NULL);
1284         weston_config_section_get_string(section, "keymap_layout",
1285                                          (char **) &xkb_names.layout, NULL);
1286         weston_config_section_get_string(section, "keymap_variant",
1287                                          (char **) &xkb_names.variant, NULL);
1288         weston_config_section_get_string(section, "keymap_options",
1289                                          (char **) &xkb_names.options, NULL);
1290
1291         if (weston_compositor_set_xkb_rule_names(compositor, &xkb_names) < 0)
1292                 return -1;
1293
1294         weston_config_section_get_int(section, "repeat-rate",
1295                                       &compositor->kb_repeat_rate, 40);
1296         weston_config_section_get_int(section, "repeat-delay",
1297                                       &compositor->kb_repeat_delay, 400);
1298
1299         weston_config_section_get_bool(section, "vt-switching",
1300                                        &vt_switching, false);
1301         compositor->vt_switching = vt_switching;
1302
1303         /* agl-compositor.ini [core] */
1304         section = weston_config_get_section(config, "core", NULL, NULL);
1305
1306         weston_config_section_get_bool(section, "require-input", &require_input, true);
1307         compositor->require_input = require_input;
1308
1309         weston_config_section_get_int(section, "repaint-window", &repaint_msec,
1310                                       compositor->repaint_msec);
1311         if (repaint_msec < -10 || repaint_msec > 1000) {
1312                 weston_log("Invalid repaint_window value in config: %d\n",
1313                            repaint_msec);
1314         } else {
1315                 compositor->repaint_msec = repaint_msec;
1316         }
1317         weston_log("Output repaint window is %d ms maximum.\n",
1318                    compositor->repaint_msec);
1319
1320         return 0;
1321 }
1322
1323 struct ivi_surface *
1324 to_ivi_surface(struct weston_surface *surface)
1325 {
1326         struct weston_desktop_surface *dsurface;
1327
1328         dsurface = weston_surface_get_desktop_surface(surface);
1329         if (!dsurface)
1330                 return NULL;
1331
1332         return weston_desktop_surface_get_user_data(dsurface);
1333 }
1334
1335 static void
1336 activate_binding(struct weston_seat *seat,
1337                  struct weston_view *focus_view, uint32_t flags)
1338 {
1339         struct weston_surface *focus_surface;
1340         struct weston_surface *main_surface;
1341         struct ivi_surface *ivi_surface;
1342         struct ivi_shell_seat *ivi_seat = get_ivi_shell_seat(seat);
1343
1344         if (!focus_view)
1345                 return;
1346
1347         focus_surface = focus_view->surface;
1348         main_surface = weston_surface_get_main_surface(focus_surface);
1349
1350         ivi_surface = to_ivi_surface(main_surface);
1351         if (!ivi_surface)
1352                 return;
1353
1354         if (ivi_seat)
1355                 ivi_shell_activate_surface(ivi_surface, ivi_seat, flags);
1356 }
1357
1358 static void
1359 click_to_activate_binding(struct weston_pointer *pointer,
1360                           const struct timespec *time,
1361                           uint32_t button, void *data)
1362 {
1363         if (pointer->grab != &pointer->default_grab)
1364                 return;
1365         if (pointer->focus == NULL)
1366                 return;
1367
1368         activate_binding(pointer->seat, pointer->focus,
1369                          WESTON_ACTIVATE_FLAG_CLICKED);
1370 }
1371
1372 static void
1373 touch_to_activate_binding(struct weston_touch *touch,
1374                           const struct timespec *time,
1375                           void *data)
1376 {
1377         if (touch->grab != &touch->default_grab)
1378                 return;
1379         if (touch->focus == NULL)
1380                 return;
1381
1382         activate_binding(touch->seat, touch->focus,
1383                          WESTON_ACTIVATE_FLAG_NONE);
1384 }
1385
1386 static void
1387 add_bindings(struct weston_compositor *compositor)
1388 {
1389         weston_compositor_add_button_binding(compositor, BTN_LEFT, 0,
1390                                              click_to_activate_binding,
1391                                              NULL);
1392         weston_compositor_add_button_binding(compositor, BTN_RIGHT, 0,
1393                                              click_to_activate_binding,
1394                                              NULL);
1395         weston_compositor_add_touch_binding(compositor, 0,
1396                                             touch_to_activate_binding,
1397                                             NULL);
1398 }
1399
1400 static int
1401 create_listening_socket(struct wl_display *display, const char *socket_name)
1402 {
1403         if (socket_name) {
1404                 if (wl_display_add_socket(display, socket_name)) {
1405                         weston_log("fatal: failed to add socket: %s\n",
1406                                    strerror(errno));
1407                         return -1;
1408                 }
1409         } else {
1410                 socket_name = wl_display_add_socket_auto(display);
1411                 if (!socket_name) {
1412                         weston_log("fatal: failed to add socket: %s\n",
1413                                    strerror(errno));
1414                         return -1;
1415                 }
1416         }
1417
1418         setenv("WAYLAND_DISPLAY", socket_name, 1);
1419
1420         return 0;
1421 }
1422
1423 static bool
1424 global_filter(const struct wl_client *client, const struct wl_global *global,
1425               void *data)
1426 {
1427         return true;
1428 }
1429
1430 static int
1431 load_config(struct weston_config **config, bool no_config,
1432             const char *config_file)
1433 {
1434         const char *file = "agl-compositor.ini";
1435         const char *full_path;
1436
1437         if (config_file)
1438                 file = config_file;
1439
1440         if (!no_config)
1441                 *config = weston_config_parse(file);
1442
1443         if (*config) {
1444                 full_path = weston_config_get_full_path(*config);
1445
1446                 weston_log("Using config file '%s'.\n", full_path);
1447                 setenv(WESTON_CONFIG_FILE_ENV_VAR, full_path, 1);
1448
1449                 return 0;
1450         }
1451
1452         if (config_file && !no_config) {
1453                 weston_log("fatal: error opening or reading config file '%s'.\n",
1454                         config_file);
1455
1456                 return -1;
1457         }
1458
1459         weston_log("Starting with no config file.\n");
1460         setenv(WESTON_CONFIG_FILE_ENV_VAR, "", 1);
1461
1462         return 0;
1463 }
1464
1465 static FILE *logfile;
1466
1467 static char *
1468 log_timestamp(char *buf, size_t len)
1469 {
1470         struct timeval tv;
1471         struct tm *brokendown_time;
1472         char datestr[128];
1473         char timestr[128];
1474
1475         gettimeofday(&tv, NULL);
1476
1477         brokendown_time = localtime(&tv.tv_sec);
1478         if (brokendown_time == NULL) {
1479                 snprintf(buf, len, "%s", "[(NULL)localtime] ");
1480                 return buf;
1481         }
1482
1483         memset(datestr, 0, sizeof(datestr));
1484         if (brokendown_time->tm_mday != cached_tm_mday) {
1485                 strftime(datestr, sizeof(datestr), "Date: %Y-%m-%d %Z\n",
1486                                 brokendown_time);
1487                 cached_tm_mday = brokendown_time->tm_mday;
1488         }
1489
1490         strftime(timestr, sizeof(timestr), "%H:%M:%S", brokendown_time);
1491         /* if datestr is empty it prints only timestr*/
1492         snprintf(buf, len, "%s[%s.%03li]", datestr,
1493                         timestr, (tv.tv_usec / 1000));
1494
1495         return buf;
1496 }
1497
1498 static void
1499 custom_handler(const char *fmt, va_list arg)
1500 {
1501         char timestr[512];
1502
1503         weston_log_scope_printf(log_scope, "%s libwayland: ",
1504                         log_timestamp(timestr, sizeof(timestr)));
1505         weston_log_scope_vprintf(log_scope, fmt, arg);
1506 }
1507
1508 static void
1509 log_file_open(const char *filename)
1510 {
1511         wl_log_set_handler_server(custom_handler);
1512
1513         if (filename)
1514                 logfile = fopen(filename, "a");
1515
1516         if (!logfile) {
1517                 logfile = stderr;
1518         } else {
1519                 os_fd_set_cloexec(fileno(logfile));
1520                 setvbuf(logfile, NULL, _IOLBF, 256);
1521         }
1522 }
1523
1524 static void
1525 log_file_close(void)
1526 {
1527         if (logfile && logfile != stderr)
1528                 fclose(logfile);
1529         logfile = stderr;
1530 }
1531
1532 static int
1533 vlog(const char *fmt, va_list ap)
1534 {
1535         const char *oom = "Out of memory";
1536         char timestr[128];
1537         int len = 0;
1538         char *str;
1539
1540         if (weston_log_scope_is_enabled(log_scope)) {
1541                 int len_va;
1542                 char *xlog_timestamp = log_timestamp(timestr, sizeof(timestr));
1543                 len_va = vasprintf(&str, fmt, ap);
1544                 if (len_va >= 0) {
1545                         len = weston_log_scope_printf(log_scope, "%s %s",
1546                                         xlog_timestamp, str);
1547                         free(str);
1548                 } else {
1549                         len = weston_log_scope_printf(log_scope, "%s %s",
1550                                         xlog_timestamp, oom);
1551                 }
1552         }
1553
1554         return len;
1555 }
1556
1557
1558 static int
1559 vlog_continue(const char *fmt, va_list ap)
1560 {
1561         return weston_log_scope_vprintf(log_scope, fmt, ap);
1562 }
1563
1564 static int
1565 on_term_signal(int signo, void *data)
1566 {
1567         struct wl_display *display = data;
1568
1569         weston_log("caught signal %d\n", signo);
1570         wl_display_terminate(display);
1571
1572         return 1;
1573 }
1574
1575 static void
1576 handle_exit(struct weston_compositor *compositor)
1577 {
1578         wl_display_terminate(compositor->wl_display);
1579 }
1580
1581 static void
1582 usage(int error_code)
1583 {
1584         FILE *out = error_code == EXIT_SUCCESS ? stdout : stderr;
1585         fprintf(out,
1586                 "Usage: agl-compositor [OPTIONS]\n"
1587                 "\n"
1588                 "This is " PACKAGE_STRING ", the reference compositor for\n"
1589                 "Automotive Grade Linux. " PACKAGE_STRING " supports multiple "
1590                 "backends,\nand depending on which backend is in use different "
1591                 "options will be accepted.\n"
1592                 "\n"
1593                 "Core options:\n"
1594                 "\n"
1595                 "  --version\t\tPrint agl-compositor version\n"
1596                 "  -B, --backend=MODULE\tBackend module, one of\n"
1597                         "\t\t\t\tdrm-backend.so\n"
1598                         "\t\t\t\twayland-backend.so\n"
1599                         "\t\t\t\tx11-backend.so\n"
1600                         "\t\t\t\theadless-backend.so\n"
1601                 "  -S, --socket=NAME\tName of socket to listen on\n"
1602                 "  --log=FILE\t\tLog to the given file\n"
1603                 "  -c, --config=FILE\tConfig file to load, defaults to agl-compositor.ini\n"
1604                 "  --no-config\t\tDo not read agl-compositor.ini\n"
1605                 "  --debug\t\tEnable debug extension(s)\n"
1606                 "  -h, --help\t\tThis help message\n"
1607                 "\n");
1608         exit(error_code);
1609 }
1610
1611 static char *
1612 copy_command_line(int argc, char * const argv[])
1613 {
1614         FILE *fp;
1615         char *str = NULL;
1616         size_t size = 0;
1617         int i;
1618
1619         fp = open_memstream(&str, &size);
1620         if (!fp)
1621                 return NULL;
1622
1623         fprintf(fp, "%s", argv[0]);
1624         for (i = 1; i < argc; i++)
1625                 fprintf(fp, " %s", argv[i]);
1626         fclose(fp);
1627
1628         return str;
1629 }
1630
1631 WL_EXPORT
1632 int wet_main(int argc, char *argv[], const struct weston_testsuite_data *test_data)
1633 {
1634         struct ivi_compositor ivi = { 0 };
1635         char *cmdline;
1636         struct wl_display *display = NULL;
1637         struct wl_event_loop *loop;
1638         struct wl_event_source *signals[3] = { 0 };
1639         struct weston_config_section *section;
1640         /* Command line options */
1641         char *backend = NULL;
1642         char *socket_name = NULL;
1643         char *log = NULL;
1644         char *modules = NULL;
1645         char *option_modules = NULL;
1646         int help = 0;
1647         int version = 0;
1648         int no_config = 0;
1649         int debug = 0;
1650         char *config_file = NULL;
1651         struct weston_log_context *log_ctx = NULL;
1652         struct weston_log_subscriber *logger;
1653         int ret = EXIT_FAILURE;
1654         bool xwayland = false;
1655         struct sigaction action;
1656
1657         const struct weston_option core_options[] = {
1658                 { WESTON_OPTION_STRING, "backend", 'B', &backend },
1659                 { WESTON_OPTION_STRING, "socket", 'S', &socket_name },
1660                 { WESTON_OPTION_STRING, "log", 0, &log },
1661                 { WESTON_OPTION_BOOLEAN, "help", 'h', &help },
1662                 { WESTON_OPTION_BOOLEAN, "version", 0, &version },
1663                 { WESTON_OPTION_BOOLEAN, "no-config", 0, &no_config },
1664                 { WESTON_OPTION_BOOLEAN, "debug", 0, &debug },
1665                 { WESTON_OPTION_STRING, "config", 'c', &config_file },
1666                 { WESTON_OPTION_STRING, "modules", 0, &option_modules },
1667         };
1668
1669         wl_list_init(&ivi.outputs);
1670         wl_list_init(&ivi.surfaces);
1671         wl_list_init(&ivi.pending_surfaces);
1672         wl_list_init(&ivi.popup_pending_apps);
1673         wl_list_init(&ivi.fullscreen_pending_apps);
1674         wl_list_init(&ivi.split_pending_apps);
1675         wl_list_init(&ivi.remote_pending_apps);
1676         wl_list_init(&ivi.desktop_clients);
1677         wl_list_init(&ivi.child_process_list);
1678
1679         /* Prevent any clients we spawn getting our stdin */
1680         os_fd_set_cloexec(STDIN_FILENO);
1681
1682         cmdline = copy_command_line(argc, argv);
1683         parse_options(core_options, ARRAY_LENGTH(core_options), &argc, argv);
1684
1685         if (help)
1686                 usage(EXIT_SUCCESS);
1687
1688         if (version) {
1689                 printf(PACKAGE_STRING "\n");
1690                 ret = EXIT_SUCCESS;
1691                 goto exit_signals;
1692         }
1693
1694         log_ctx = weston_log_ctx_create();
1695         if (!log_ctx) {
1696                 fprintf(stderr, "Failed to initialize weston debug framework.\n");
1697                 goto exit_signals;
1698         }
1699
1700         log_scope = weston_log_ctx_add_log_scope(log_ctx, "log",
1701                                                  "agl-compositor log\n",
1702                                                  NULL, NULL, NULL);
1703
1704         log_file_open(log);
1705         weston_log_set_handler(vlog, vlog_continue);
1706
1707         logger = weston_log_subscriber_create_log(logfile);
1708         weston_log_subscribe(log_ctx, logger, "log");
1709
1710         weston_log("Command line: %s\n", cmdline);
1711         free(cmdline);
1712
1713         if (load_config(&ivi.config, no_config, config_file) < 0)
1714                 goto error_signals;
1715         section = weston_config_get_section(ivi.config, "core", NULL, NULL);
1716         if (!backend) {
1717                 weston_config_section_get_string(section, "backend", &backend,
1718                                                  NULL);
1719                 if (!backend)
1720                         backend = choose_default_backend();
1721         }
1722         /* from [core] */
1723         weston_config_section_get_bool(section, "hide-cursor",
1724                                        &ivi.hide_cursor, false);
1725         weston_config_section_get_bool(section, "activate-by-default",
1726                                        &ivi.activate_by_default, true);
1727
1728         display = wl_display_create();
1729         loop = wl_display_get_event_loop(display);
1730
1731         wl_display_set_global_filter(display,
1732                                      global_filter, &ivi);
1733
1734         /* Register signal handlers so we shut down cleanly */
1735
1736         signals[0] = wl_event_loop_add_signal(loop, SIGTERM, on_term_signal,
1737                                               display);
1738         signals[1] = wl_event_loop_add_signal(loop, SIGUSR2, on_term_signal,
1739                                               display);
1740         signals[2] = wl_event_loop_add_signal(loop, SIGCHLD, sigchld_handler,
1741                                               display);
1742
1743         /* When debugging the compositor, if use wl_event_loop_add_signal() to
1744          * catch SIGINT, the debugger can't catch it, and attempting to stop
1745          * the compositor from within the debugger results in weston exiting
1746          * cleanly.
1747          *
1748          * Instead, use the sigaction() function, which sets up the signal in a
1749          * way that gdb can successfully catch, but have the handler for SIGINT
1750          * send SIGUSR2 (xwayland uses SIGUSR1), which we catch via
1751          * wl_event_loop_add_signal().
1752          */
1753         action.sa_handler = sigint_helper;
1754         sigemptyset(&action.sa_mask);
1755         action.sa_flags = 0;
1756         sigaction(SIGINT, &action, NULL);
1757
1758         for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
1759                 if (!signals[i])
1760                         goto error_signals;
1761
1762         ivi.compositor = weston_compositor_create(display, log_ctx, &ivi, test_data);
1763         if (!ivi.compositor) {
1764                 weston_log("fatal: failed to create compositor.\n");
1765                 goto error_signals;
1766         }
1767
1768         if (compositor_init_config(ivi.compositor, ivi.config) < 0)
1769                 goto error_compositor;
1770
1771         if (load_backend(&ivi, backend, &argc, argv) < 0) {
1772                 weston_log("fatal: failed to create compositor backend.\n");
1773                 goto error_compositor;
1774         }
1775
1776         ivi.heads_changed.notify = heads_changed;
1777         weston_compositor_add_heads_changed_listener(ivi.compositor,
1778                                                      &ivi.heads_changed);
1779
1780         if (ivi_desktop_init(&ivi) < 0)
1781                 goto error_compositor;
1782
1783         ivi_seat_init(&ivi);
1784
1785         /* load additional modules */
1786         weston_config_section_get_string(section, "modules", &modules, "");
1787         if (load_modules(&ivi, modules, &argc, argv, &xwayland) < 0)
1788                 goto error_compositor;
1789
1790         if (load_modules(&ivi, option_modules, &argc, argv, &xwayland) < 0)
1791                 goto error_compositor;
1792
1793         if (ivi_policy_init(&ivi) < 0)
1794                 goto error_compositor;
1795
1796         if (ivi_shell_init(&ivi) < 0)
1797                 goto error_compositor;
1798
1799         add_bindings(ivi.compositor);
1800
1801         weston_compositor_flush_heads_changed(ivi.compositor);
1802
1803         if (ivi.remoting_api)
1804                 ivi_enable_remote_outputs(&ivi);
1805
1806         if (ivi.waltham_transmitter_api)
1807                 ivi_enable_waltham_outputs(&ivi);
1808
1809         if (create_listening_socket(display, socket_name) < 0)
1810                 goto error_compositor;
1811
1812         ivi_shell_init_black_fs(&ivi);
1813
1814         ivi.compositor->exit = handle_exit;
1815
1816         weston_compositor_wake(ivi.compositor);
1817
1818         ivi_shell_create_global(&ivi);
1819
1820         ivi_launch_shell_client(&ivi, "shell-client",
1821                                 &ivi.shell_client.client);
1822         ivi_launch_shell_client(&ivi, "shell-client-ext",
1823                                 &ivi.shell_client_ext.client);
1824
1825         if (debug)
1826                 ivi_screenshooter_create(&ivi);
1827         ivi_agl_systemd_notify(&ivi);
1828
1829         wl_display_run(display);
1830
1831         ret = ivi.compositor->exit_code;
1832
1833         wl_display_destroy_clients(display);
1834
1835 error_compositor:
1836         free(backend);
1837         backend = NULL;
1838         free(modules);
1839         modules = NULL;
1840
1841         weston_compositor_destroy(ivi.compositor);
1842
1843         weston_log_scope_destroy(log_scope);
1844         log_scope = NULL;
1845
1846         weston_log_subscriber_destroy(logger);
1847         weston_log_ctx_destroy(log_ctx);
1848
1849         ivi_policy_destroy(ivi.policy);
1850
1851 error_signals:
1852         for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
1853                 if (signals[i])
1854                         wl_event_source_remove(signals[i]);
1855
1856         wl_display_destroy(display);
1857
1858         log_file_close();
1859         if (ivi.config)
1860                 weston_config_destroy(ivi.config);
1861
1862 exit_signals:
1863         free(log);
1864         free(config_file);
1865         free(socket_name);
1866         free(option_modules);
1867         return ret;
1868 }