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