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