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