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