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