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