Import source, backport to libweston 6.0 42/23042/1 8.99.2 8.99.3 8.99.4 8.99.5 icefish/8.99.2 icefish/8.99.3 icefish/8.99.4 icefish/8.99.5 icefish_8.99.2 icefish_8.99.3 icefish_8.99.4 icefish_8.99.5
authorDaniel Stone <daniels@collabora.com>
Mon, 25 Nov 2019 12:26:36 +0000 (12:26 +0000)
committerDaniel Stone <daniels@collabora.com>
Mon, 25 Nov 2019 14:41:45 +0000 (14:41 +0000)
Signed-off-by: Daniel Stone <daniels@collabora.com>
Change-Id: I7705fa82dab29a27e4913cd548a2f5c3247dc5ad

COPYING [new file with mode: 0644]
meson.build [new file with mode: 0644]
protocol/agl-shell.xml [new file with mode: 0644]
shared/option-parser.c [new file with mode: 0644]
shared/os-compatibility.c [new file with mode: 0644]
shared/os-compatibility.h [new file with mode: 0644]
shared/string-helpers.h [new file with mode: 0644]
src/desktop.c [new file with mode: 0644]
src/ivi-compositor.h [new file with mode: 0644]
src/main.c [new file with mode: 0644]
src/shell.c [new file with mode: 0644]

diff --git a/COPYING b/COPYING
new file mode 100644 (file)
index 0000000..7f47b2d
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,24 @@
+Copyright © 2012, 2019 Collabora, Ltd.
+Copyright © 2012 Kristian Høgsberg
+Copyright © 2016 Samsung Electronics Co., Ltd
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice (including the
+next paragraph) shall be included in all copies or substantial
+portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/meson.build b/meson.build
new file mode 100644 (file)
index 0000000..a7e1bfc
--- /dev/null
@@ -0,0 +1,108 @@
+project('agl-compositor',
+  'c',
+  version: '0.0.13',
+  default_options: [
+    'warning_level=3',
+    'c_std=gnu99',
+  ],
+  meson_version: '>= 0.47',
+  license: 'MIT/Expat',
+)
+
+cc = meson.get_compiler('c')
+add_project_arguments(
+  cc.get_supported_arguments([
+    '-Wno-unused-parameter',
+    '-Wno-pedantic',
+  ]),
+  language: 'c'
+)
+
+add_project_arguments([
+    '-DPACKAGE_STRING="agl-compositor @0@"'.format(meson.project_version()),
+    '-D_GNU_SOURCE',
+    '-D_ALL_SOURCE',
+  ],
+  language: 'c'
+)
+
+optional_libc_funcs = [ 'memfd_create', 'strchrnul' ]
+foreach func: optional_libc_funcs
+    if cc.has_function(func)
+        add_project_arguments('-DHAVE_@0@=1'.format(func.to_upper()), language: 'c')
+    endif
+endforeach
+
+dep_scanner = dependency('wayland-scanner', native: true)
+prog_scanner = find_program(dep_scanner.get_pkgconfig_variable('wayland_scanner'))
+dep_wp = dependency('wayland-protocols', version: '>= 1.12')
+dir_wp_base = dep_wp.get_pkgconfig_variable('pkgdatadir')
+
+agl_shell_xml = files('protocol/agl-shell.xml')
+xdg_shell_xml = join_paths(dir_wp_base, 'stable', 'xdg-shell', 'xdg-shell.xml')
+
+protocols = [
+  { 'name': 'agl-shell', 'source': 'internal' },
+  { 'name': 'xdg-shell', 'source': 'wp-stable' },
+]
+
+foreach proto: protocols
+    proto_name = proto['name']
+    if proto['source'] == 'internal'
+        base_file = proto_name
+       xml_path = join_paths('protocol', '@0@.xml'.format(base_file))
+    elif proto['source'] == 'wp-stable'
+        base_file = proto_name
+       xml_path = join_paths(dir_wp_base, 'stable', proto_name, '@0@.xml'.format(base_file))
+    else
+        base_file = '@0@-unstable-@1@'.format(proto_name, proto['version'])
+       xml_path = join_paths(dir_wp_base, 'unstable', proto_name, '@0@.xml'.format(base_file))
+    endif
+
+    foreach output_type: [ 'client-header', 'server-header', 'private-code' ]
+       if output_type == 'client-header'
+           output_file = '@0@-client-protocol.h'.format(base_file)
+       elif output_type == 'server-header'
+           output_file = '@0@-server-protocol.h'.format(base_file)
+       else
+           output_file = '@0@-protocol.c'.format(base_file)
+           if dep_scanner.version().version_compare('< 1.14.91')
+               output_type = 'code'
+           endif
+       endif
+
+       var_name = output_file.underscorify()
+       target = custom_target(
+           '@0@ @1@'.format(base_file, output_type),
+           command: [ prog_scanner, output_type, '@INPUT@', '@OUTPUT@' ],
+           input: xml_path,
+           output: output_file,
+       )
+
+        set_variable(var_name, target)
+    endforeach
+endforeach
+
+deps_libweston = [
+  dependency('wayland-server'),
+  dependency('libweston-6'),
+  dependency('libweston-desktop-6'),
+]
+
+srcs_agl_compositor = [
+       'src/main.c',
+       'src/desktop.c',
+       'src/shell.c',
+       'shared/option-parser.c',
+       'shared/os-compatibility.c',
+       agl_shell_server_protocol_h,
+       agl_shell_protocol_c,
+       xdg_shell_protocol_c,
+]
+
+exe_agl_compositor = executable(
+       'agl-compositor',
+       srcs_agl_compositor,
+       dependencies: deps_libweston,
+       install: true
+)
diff --git a/protocol/agl-shell.xml b/protocol/agl-shell.xml
new file mode 100644 (file)
index 0000000..59548e7
--- /dev/null
@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="agl_shell">
+  <copyright>
+    Copyright © 2019 Collabora, Ltd.
+
+    Permission is hereby granted, free of charge, to any person obtaining a
+    copy of this software and associated documentation files (the "Software"),
+    to deal in the Software without restriction, including without limitation
+    the rights to use, copy, modify, merge, publish, distribute, sublicense,
+    and/or sell copies of the Software, and to permit persons to whom the
+    Software is furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice (including the next
+    paragraph) shall be included in all copies or substantial portions of the
+    Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+    DEALINGS IN THE SOFTWARE.
+  </copyright>
+  <interface name="agl_shell" version="1">
+    <description summary="user interface for weston-ivi">
+    </description>
+
+    <enum name="error">
+      <entry name="invalid_argument" value="0"/>
+      <entry name="background_exists" value="1"/>
+      <entry name="panel_exists" value="2"/>
+    </enum>
+
+    <enum name="edge">
+      <entry name="top" value="0"/>
+      <entry name="bottom" value="1"/>
+      <entry name="left" value="2"/>
+      <entry name="right" value="3"/>
+    </enum>
+
+    <request name="ready">
+      <description summary="client is ready to be shown">
+        Tell the server that this client is ready to be shown. The server
+        will delay presentation during start-up until all shell clients are
+        ready to be shown, and will display a black screen instead.
+        This gives the client an oppurtunity to set up and configure several
+        surfaces into a coherent interface.
+
+        The client that binds to this interface must send this request, otherwise
+        they may stall the compositor unnecessarily.
+
+        If this request is called after the compositor has already finished
+        start-up, no operation is performed.
+      </description>
+    </request>
+
+    <request name="set_background">
+      <description summary="set surface as output's background">
+        Set the surface to act as the background of an output. After this
+        request, the server will immediately send a configure event with
+        the dimensions the client should use to cover the entire output.
+
+        The surface must have a "desktop" surface role, as supported by
+        libweston-desktop.
+
+        Only a single surface may be the background for any output. If a
+        background surface already exists, a protocol error is raised.
+      </description>
+      <arg name="surface" type="object" interface="wl_surface"/>
+      <arg name="output" type="object" interface="wl_output"/>
+    </request>
+
+    <request name="set_panel">
+      <description summary="set surface as panel">
+        Set the surface to act as a panel of an output. The 'edge' argument
+        says what edge of the output the surface will be anchored to.
+        After this request, the server will send a configure event with the
+        correponding width/height that the client should use, and 0 for the
+        other dimension. E.g. if the edge is 'top', the width will be the
+        output's width, and the height will be 0.
+
+        The surface must have a "desktop" surface role, as supported by
+        libweston-desktop.
+
+        The compositor will take the panel's window geometry into account when
+        positioning other windows, so the panels are not covered.
+
+        XXX: What happens if e.g. both top and left are used at the same time?
+        Who gets to have the corner?
+
+        Only a single surface may be the panel for an output's edge. If a
+        surface already exists on an edge, a protocol error is raised.
+      </description>
+      <arg name="surface" type="object" interface="wl_surface"/>
+      <arg name="output" type="object" interface="wl_output"/>
+      <arg name="edge" type="uint" enum="edge"/>
+    </request>
+  </interface>
+</protocol>
diff --git a/shared/option-parser.c b/shared/option-parser.c
new file mode 100644 (file)
index 0000000..81222f3
--- /dev/null
@@ -0,0 +1,202 @@
+/*
+ * Copyright © 2012 Kristian Høgsberg
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <libweston-6/config-parser.h>
+#include "shared/string-helpers.h"
+
+static bool
+handle_option(const struct weston_option *option, char *value)
+{
+       char* p;
+
+       switch (option->type) {
+       case WESTON_OPTION_INTEGER:
+               if (!safe_strtoint(value, option->data))
+                       return false;
+               return true;
+       case WESTON_OPTION_UNSIGNED_INTEGER:
+               errno = 0;
+               * (uint32_t *) option->data = strtoul(value, &p, 10);
+               if (errno != 0 || p == value || *p != '\0')
+                       return false;
+               return true;
+       case WESTON_OPTION_STRING:
+               * (char **) option->data = strdup(value);
+               return true;
+       default:
+               assert(0);
+               return false;
+       }
+}
+
+static bool
+long_option(const struct weston_option *options, int count, char *arg)
+{
+       int k, len;
+
+       for (k = 0; k < count; k++) {
+               if (!options[k].name)
+                       continue;
+
+               len = strlen(options[k].name);
+               if (strncmp(options[k].name, arg + 2, len) != 0)
+                       continue;
+
+               if (options[k].type == WESTON_OPTION_BOOLEAN) {
+                       if (!arg[len + 2]) {
+                               * (int32_t *) options[k].data = 1;
+
+                               return true;
+                       }
+               } else if (arg[len+2] == '=') {
+                       return handle_option(options + k, arg + len + 3);
+               }
+       }
+
+       return false;
+}
+
+static bool
+long_option_with_arg(const struct weston_option *options, int count, char *arg,
+                    char *param)
+{
+       int k, len;
+
+       for (k = 0; k < count; k++) {
+               if (!options[k].name)
+                       continue;
+
+               len = strlen(options[k].name);
+               if (strncmp(options[k].name, arg + 2, len) != 0)
+                       continue;
+
+               /* Since long_option() should handle all booleans, we should
+                * never reach this
+                */
+               assert(options[k].type != WESTON_OPTION_BOOLEAN);
+
+               return handle_option(options + k, param);
+       }
+
+       return false;
+}
+
+static bool
+short_option(const struct weston_option *options, int count, char *arg)
+{
+       int k;
+
+       if (!arg[1])
+               return false;
+
+       for (k = 0; k < count; k++) {
+               if (options[k].short_name != arg[1])
+                       continue;
+
+               if (options[k].type == WESTON_OPTION_BOOLEAN) {
+                       if (!arg[2]) {
+                               * (int32_t *) options[k].data = 1;
+
+                               return true;
+                       }
+               } else if (arg[2]) {
+                       return handle_option(options + k, arg + 2);
+               } else {
+                       return false;
+               }
+       }
+
+       return false;
+}
+
+static bool
+short_option_with_arg(const struct weston_option *options, int count, char *arg, char *param)
+{
+       int k;
+
+       if (!arg[1])
+               return false;
+
+       for (k = 0; k < count; k++) {
+               if (options[k].short_name != arg[1])
+                       continue;
+
+               if (options[k].type == WESTON_OPTION_BOOLEAN)
+                       continue;
+
+               return handle_option(options + k, param);
+       }
+
+       return false;
+}
+
+int
+parse_options(const struct weston_option *options,
+             int count, int *argc, char *argv[])
+{
+       int i, j;
+
+       for (i = 1, j = 1; i < *argc; i++) {
+               if (argv[i][0] == '-') {
+                       if (argv[i][1] == '-') {
+                               /* Long option, e.g. --foo or --foo=bar */
+                               if (long_option(options, count, argv[i]))
+                                       continue;
+
+                               /* ...also handle --foo bar */
+                               if (i + 1 < *argc &&
+                                   long_option_with_arg(options, count,
+                                                        argv[i], argv[i+1])) {
+                                       i++;
+                                       continue;
+                               }
+                       } else {
+                               /* Short option, e.g -f or -f42 */
+                               if (short_option(options, count, argv[i]))
+                                       continue;
+
+                               /* ...also handle -f 42 */
+                               if (i+1 < *argc &&
+                                   short_option_with_arg(options, count, argv[i], argv[i+1])) {
+                                       i++;
+                                       continue;
+                               }
+                       }
+               }
+               argv[j++] = argv[i];
+       }
+       argv[j] = NULL;
+       *argc = j;
+
+       return j;
+}
diff --git a/shared/os-compatibility.c b/shared/os-compatibility.c
new file mode 100644 (file)
index 0000000..3013f1f
--- /dev/null
@@ -0,0 +1,405 @@
+/*
+ * Copyright © 2012 Collabora, Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <sys/epoll.h>
+#include <string.h>
+#include <stdlib.h>
+#include <libweston-6/zalloc.h>
+
+#ifdef HAVE_MEMFD_CREATE
+#include <sys/mman.h>
+#endif
+
+#include "os-compatibility.h"
+
+#define READONLY_SEALS (F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE)
+
+int
+os_fd_set_cloexec(int fd)
+{
+       long flags;
+
+       if (fd == -1)
+               return -1;
+
+       flags = fcntl(fd, F_GETFD);
+       if (flags == -1)
+               return -1;
+
+       if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
+               return -1;
+
+       return 0;
+}
+
+static int
+set_cloexec_or_close(int fd)
+{
+       if (os_fd_set_cloexec(fd) != 0) {
+               close(fd);
+               return -1;
+       }
+       return fd;
+}
+
+int
+os_socketpair_cloexec(int domain, int type, int protocol, int *sv)
+{
+       int ret;
+
+#ifdef SOCK_CLOEXEC
+       ret = socketpair(domain, type | SOCK_CLOEXEC, protocol, sv);
+       if (ret == 0 || errno != EINVAL)
+               return ret;
+#endif
+
+       ret = socketpair(domain, type, protocol, sv);
+       if (ret < 0)
+               return ret;
+
+       sv[0] = set_cloexec_or_close(sv[0]);
+       sv[1] = set_cloexec_or_close(sv[1]);
+
+       if (sv[0] != -1 && sv[1] != -1)
+               return 0;
+
+       close(sv[0]);
+       close(sv[1]);
+       return -1;
+}
+
+int
+os_epoll_create_cloexec(void)
+{
+       int fd;
+
+#ifdef EPOLL_CLOEXEC
+       fd = epoll_create1(EPOLL_CLOEXEC);
+       if (fd >= 0)
+               return fd;
+       if (errno != EINVAL)
+               return -1;
+#endif
+
+       fd = epoll_create(1);
+       return set_cloexec_or_close(fd);
+}
+
+static int
+create_tmpfile_cloexec(char *tmpname)
+{
+       int fd;
+
+#ifdef HAVE_MKOSTEMP
+       fd = mkostemp(tmpname, O_CLOEXEC);
+       if (fd >= 0)
+               unlink(tmpname);
+#else
+       fd = mkstemp(tmpname);
+       if (fd >= 0) {
+               fd = set_cloexec_or_close(fd);
+               unlink(tmpname);
+       }
+#endif
+
+       return fd;
+}
+
+/*
+ * Create a new, unique, anonymous file of the given size, and
+ * return the file descriptor for it. The file descriptor is set
+ * CLOEXEC. The file is immediately suitable for mmap()'ing
+ * the given size at offset zero.
+ *
+ * The file should not have a permanent backing store like a disk,
+ * but may have if XDG_RUNTIME_DIR is not properly implemented in OS.
+ *
+ * The file name is deleted from the file system.
+ *
+ * The file is suitable for buffer sharing between processes by
+ * transmitting the file descriptor over Unix sockets using the
+ * SCM_RIGHTS methods.
+ *
+ * If the C library implements posix_fallocate(), it is used to
+ * guarantee that disk space is available for the file at the
+ * given size. If disk space is insufficient, errno is set to ENOSPC.
+ * If posix_fallocate() is not supported, program may receive
+ * SIGBUS on accessing mmap()'ed file contents instead.
+ *
+ * If the C library implements memfd_create(), it is used to create the
+ * file purely in memory, without any backing file name on the file
+ * system, and then sealing off the possibility of shrinking it.  This
+ * can then be checked before accessing mmap()'ed file contents, to
+ * make sure SIGBUS can't happen.  It also avoids requiring
+ * XDG_RUNTIME_DIR.
+ */
+int
+os_create_anonymous_file(off_t size)
+{
+       static const char template[] = "/weston-shared-XXXXXX";
+       const char *path;
+       char *name;
+       int fd;
+       int ret;
+
+#ifdef HAVE_MEMFD_CREATE
+       fd = memfd_create("weston-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING);
+       if (fd >= 0) {
+               /* We can add this seal before calling posix_fallocate(), as
+                * the file is currently zero-sized anyway.
+                *
+                * There is also no need to check for the return value, we
+                * couldn't do anything with it anyway.
+                */
+               fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK);
+       } else
+#endif
+       {
+               path = getenv("XDG_RUNTIME_DIR");
+               if (!path) {
+                       errno = ENOENT;
+                       return -1;
+               }
+
+               name = malloc(strlen(path) + sizeof(template));
+               if (!name)
+                       return -1;
+
+               strcpy(name, path);
+               strcat(name, template);
+
+               fd = create_tmpfile_cloexec(name);
+
+               free(name);
+
+               if (fd < 0)
+                       return -1;
+       }
+
+#ifdef HAVE_POSIX_FALLOCATE
+       do {
+               ret = posix_fallocate(fd, 0, size);
+       } while (ret == EINTR);
+       if (ret != 0) {
+               close(fd);
+               errno = ret;
+               return -1;
+       }
+#else
+       do {
+               ret = ftruncate(fd, size);
+       } while (ret < 0 && errno == EINTR);
+       if (ret < 0) {
+               close(fd);
+               return -1;
+       }
+#endif
+
+       return fd;
+}
+
+#ifndef HAVE_STRCHRNUL
+char *
+strchrnul(const char *s, int c)
+{
+       while (*s && *s != c)
+               s++;
+       return (char *)s;
+}
+#endif
+
+struct ro_anonymous_file {
+       int fd;
+       size_t size;
+};
+
+/** Create a new anonymous read-only file of the given size and the given data
+ *
+ * \param size The size of \p data.
+ * \param data The data of the file with the size \p size.
+ * \return A new \c ro_anonymous_file, or NULL on failure.
+ *
+ * The intended use-case is for sending mid-sized data from the compositor
+ * to clients.
+ * If the function fails errno is set.
+ */
+struct ro_anonymous_file *
+os_ro_anonymous_file_create(size_t size,
+                           const char *data)
+{
+       struct ro_anonymous_file *file;
+       void *map;
+
+       file = zalloc(sizeof *file);
+       if (!file) {
+               errno = ENOMEM;
+               return NULL;
+       }
+
+       file->size = size;
+       file->fd = os_create_anonymous_file(size);
+       if (file->fd == -1)
+               goto err_free;
+
+       map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, file->fd, 0);
+       if (map == MAP_FAILED)
+               goto err_close;
+
+       memcpy(map, data, size);
+
+       munmap(map, size);
+
+#ifdef HAVE_MEMFD_CREATE
+       /* try to put seals on the file to make it read-only so that we can
+        * return the fd later directly when support_shared is not set.
+        * os_ro_anonymous_file_get_fd can handle the fd even if it is not
+        * sealed read-only and will instead create a new anonymous file on
+        * each invocation.
+        */
+       fcntl(file->fd, F_ADD_SEALS, READONLY_SEALS);
+#endif
+
+       return file;
+
+err_close:
+       close(file->fd);
+err_free:
+       free(file);
+       return NULL;
+}
+
+/** Destroy an anonymous read-only file
+ *
+ * \param file The file to destroy.
+ */
+void
+os_ro_anonymous_file_destroy(struct ro_anonymous_file *file)
+{
+       close(file->fd);
+       free(file);
+}
+
+/** Get the size of an anonymous read-only file
+ *
+ * \param file The file to get the size of.
+ * \return The size of the file.
+ */
+size_t
+os_ro_anonymous_file_size(struct ro_anonymous_file *file)
+{
+       return file->size;
+}
+
+/** Returns a file descriptor for the given file, ready to be send to a client.
+ *
+ * \param file The file for which to get a file descriptor.
+ * \param mapmode Describes the ways in which the returned file descriptor can
+ * be used with mmap.
+ * \return A file descriptor for the given file that can be send to a client
+ * or -1 on failure.
+ *
+ * The returned file descriptor must not be shared between multiple clients.
+ * When \p mapmode is RO_ANONYMOUS_FILE_MAPMODE_PRIVATE the file descriptor is
+ * only guaranteed to be mmapable with \c MAP_PRIVATE, when \p mapmode is
+ * RO_ANONYMOUS_FILE_MAPMODE_SHARED the file descriptor can be mmaped with
+ * either MAP_PRIVATE or MAP_SHARED.
+ * When you're done with the fd you must call \c os_ro_anonymous_file_put_fd
+ * instead of calling \c close.
+ * If the function fails errno is set.
+ */
+int
+os_ro_anonymous_file_get_fd(struct ro_anonymous_file *file,
+                           enum ro_anonymous_file_mapmode mapmode)
+{
+       void *src, *dst;
+       int seals, fd;
+
+       seals = fcntl(file->fd, F_GET_SEALS);
+
+       /* file was sealed for read-only and we don't have to support MAP_SHARED
+        * so we can simply pass the memfd fd
+        */
+       if (seals != -1 && mapmode == RO_ANONYMOUS_FILE_MAPMODE_PRIVATE &&
+           (seals & READONLY_SEALS) == READONLY_SEALS)
+               return file->fd;
+
+       /* for all other cases we create a new anonymous file that can be mapped
+        * with MAP_SHARED and copy the contents to it and return that instead
+        */
+       fd = os_create_anonymous_file(file->size);
+       if (fd == -1)
+               return fd;
+
+       src = mmap(NULL, file->size, PROT_READ, MAP_PRIVATE, file->fd, 0);
+       if (src == MAP_FAILED) {
+               close(fd);
+               return -1;
+       }
+
+       dst = mmap(NULL, file->size, PROT_WRITE, MAP_SHARED, fd, 0);
+       if (dst == MAP_FAILED) {
+               close(fd);
+               munmap(src, file->size);
+               return -1;
+       }
+
+       memcpy(dst, src, file->size);
+       munmap(src, file->size);
+       munmap(dst, file->size);
+
+       return fd;
+}
+
+/** Release a file descriptor returned by \c os_ro_anonymous_file_get_fd
+ *
+ * \param fd A file descriptor returned by \c os_ro_anonymous_file_get_fd.
+ * \return 0 on success, or -1 on failure.
+ *
+ * This function must be called for every file descriptor created with
+ * \c os_ro_anonymous_file_get_fd to not leake any resources.
+ * If the function fails errno is set.
+ */
+int
+os_ro_anonymous_file_put_fd(int fd)
+{
+       int seals = fcntl(fd, F_GET_SEALS);
+       if (seals == -1 && errno != EINVAL)
+               return -1;
+
+       /* If the fd cannot be sealed seals is -1 at this point
+        * or the file can be sealed but has not been sealed for writing.
+        * In both cases we created a new anonymous file that we have to
+        * close.
+        */
+       if (seals == -1 || !(seals & F_SEAL_WRITE))
+               close(fd);
+
+       return 0;
+}
diff --git a/shared/os-compatibility.h b/shared/os-compatibility.h
new file mode 100644 (file)
index 0000000..1ad45d7
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright © 2012 Collabora, Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef OS_COMPATIBILITY_H
+#define OS_COMPATIBILITY_H
+
+#include <sys/types.h>
+
+int
+os_fd_set_cloexec(int fd);
+
+int
+os_socketpair_cloexec(int domain, int type, int protocol, int *sv);
+
+int
+os_epoll_create_cloexec(void);
+
+int
+os_create_anonymous_file(off_t size);
+
+#ifndef HAVE_STRCHRNUL
+char *
+strchrnul(const char *s, int c);
+#endif
+
+struct ro_anonymous_file;
+
+enum ro_anonymous_file_mapmode {
+       RO_ANONYMOUS_FILE_MAPMODE_PRIVATE,
+       RO_ANONYMOUS_FILE_MAPMODE_SHARED,
+};
+
+struct ro_anonymous_file *
+os_ro_anonymous_file_create(size_t size,
+                           const char *data);
+
+void
+os_ro_anonymous_file_destroy(struct ro_anonymous_file *file);
+
+size_t
+os_ro_anonymous_file_size(struct ro_anonymous_file *file);
+
+int
+os_ro_anonymous_file_get_fd(struct ro_anonymous_file *file,
+                           enum ro_anonymous_file_mapmode mapmode);
+
+int
+os_ro_anonymous_file_put_fd(int fd);
+
+#endif /* OS_COMPATIBILITY_H */
diff --git a/shared/string-helpers.h b/shared/string-helpers.h
new file mode 100644 (file)
index 0000000..c8ce449
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright © 2016 Samsung Electronics Co., Ltd
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef WESTON_STRING_HELPERS_H
+#define WESTON_STRING_HELPERS_H
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <errno.h>
+#include <assert.h>
+
+/* Convert string to integer
+ *
+ * Parses a base-10 number from the given string.  Checks that the
+ * string is not blank, contains only numerical characters, and is
+ * within the range of INT32_MIN to INT32_MAX.  If the validation is
+ * successful the result is stored in *value; otherwise *value is
+ * unchanged and errno is set appropriately.
+ *
+ * \return true if the number parsed successfully, false on error
+ */
+static inline bool
+safe_strtoint(const char *str, int32_t *value)
+{
+       long ret;
+       char *end;
+
+       assert(str != NULL);
+
+       errno = 0;
+       ret = strtol(str, &end, 10);
+       if (errno != 0) {
+               return false;
+       } else if (end == str || *end != '\0') {
+               errno = EINVAL;
+               return false;
+       }
+
+       if ((long)((int32_t)ret) != ret) {
+               errno = ERANGE;
+               return false;
+       }
+       *value = (int32_t)ret;
+
+       return true;
+}
+
+#endif /* WESTON_STRING_HELPERS_H */
diff --git a/src/desktop.c b/src/desktop.c
new file mode 100644 (file)
index 0000000..fbeefec
--- /dev/null
@@ -0,0 +1,319 @@
+/*
+ * Copyright © 2019 Collabora, Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "ivi-compositor.h"
+
+#include <libweston-6/compositor.h>
+#include <libweston-6/libweston-desktop.h>
+
+#if 0
+static struct weston_output *
+get_default_output(struct weston_compositor *compositor)
+{
+       if (wl_list_empty(&compositor->output_list))
+               return NULL;
+
+       return wl_container_of(compositor->output_list.next,
+                              struct weston_output, link);
+}
+#endif
+
+static void
+desktop_ping_timeout(struct weston_desktop_client *dclient, void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_pong(struct weston_desktop_client *dclient, void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_surface_added(struct weston_desktop_surface *dsurface, void *userdata)
+{
+       struct ivi_compositor *ivi = userdata;
+       struct weston_desktop_client *dclient;
+       struct wl_client *client;
+       struct ivi_surface *surface;
+
+       dclient = weston_desktop_surface_get_client(dsurface);
+       client = weston_desktop_client_get_client(dclient);
+
+       surface = zalloc(sizeof *surface);
+       if (!surface) {
+               wl_client_post_no_memory(client);
+               return;
+       }
+
+       surface->ivi = ivi;
+       surface->dsurface = dsurface;
+       surface->role = IVI_SURFACE_ROLE_NONE;
+       surface->old_geom.width = -1;
+       surface->old_geom.height = -1;
+
+       weston_desktop_surface_set_user_data(dsurface, surface);
+
+       if (ivi->shell_client.ready) {
+               ivi_set_desktop_surface(surface);
+
+               ivi_reflow_outputs(ivi);
+       } else {
+               /*
+                * We delay creating "normal" desktop surfaces until later, to
+                * give the shell-client an oppurtunity to set the surface as a
+                * background/panel.
+                */
+               wl_list_insert(&ivi->pending_surfaces, &surface->link);
+       }
+}
+
+static void
+desktop_surface_removed(struct weston_desktop_surface *dsurface, void *userdata)
+{
+       struct ivi_surface *surface =
+               weston_desktop_surface_get_user_data(dsurface);
+       struct weston_surface *wsurface =
+               weston_desktop_surface_get_surface(dsurface);
+       struct ivi_compositor *ivi = surface->ivi;
+
+       /* TODO */
+       if (surface->role != IVI_SURFACE_ROLE_DESKTOP)
+               return;
+
+       if (weston_surface_is_mapped(wsurface)) {
+               weston_desktop_surface_unlink_view(surface->desktop.view);
+               weston_view_destroy(surface->desktop.view);
+               wl_list_remove(&surface->link);
+       }
+       free(surface);
+
+       ivi_reflow_outputs(ivi);
+}
+
+static void
+surface_committed(struct ivi_surface *surface)
+{
+       struct ivi_compositor *ivi = surface->ivi;
+       struct weston_desktop_surface *dsurface = surface->dsurface;
+       struct weston_geometry geom, old_geom;
+
+       old_geom = surface->old_geom;
+       geom = weston_desktop_surface_get_geometry(dsurface);
+
+       surface->old_geom = geom;
+
+       if (geom.width != old_geom.width || geom.height != old_geom.height) {
+               ivi_reflow_outputs(ivi);
+       }
+
+       //wl_list_insert(&ivi->surfaces, &surface->link);
+}
+
+static void
+background_committed(struct ivi_surface *surface)
+{
+       struct ivi_compositor *ivi = surface->ivi;
+       struct ivi_output *output = surface->bg.output;
+       struct weston_output *woutput = output->output;
+       struct weston_desktop_surface *dsurface = surface->dsurface;
+       struct weston_surface *wsurface =
+               weston_desktop_surface_get_surface(dsurface);
+
+       if (wsurface->is_mapped)
+               return;
+
+       surface->bg.view = weston_desktop_surface_create_view(dsurface);
+
+       weston_view_set_output(surface->bg.view, woutput);
+       weston_view_set_position(surface->bg.view,
+                                woutput->x,
+                                woutput->y);
+       weston_layer_entry_insert(&ivi->background.view_list,
+                                 &surface->bg.view->layer_link);
+
+       weston_view_update_transform(surface->bg.view);
+       weston_view_schedule_repaint(surface->bg.view);
+
+       wsurface->is_mapped = true;
+}
+
+static void
+panel_committed(struct ivi_surface *surface)
+{
+       struct ivi_compositor *ivi = surface->ivi;
+       struct ivi_output *output = surface->bg.output;
+       struct weston_output *woutput = output->output;
+       struct weston_desktop_surface *dsurface = surface->dsurface;
+       struct weston_surface *wsurface =
+               weston_desktop_surface_get_surface(dsurface);
+       struct weston_geometry geom;
+       int32_t x = woutput->x;
+       int32_t y = woutput->y;
+
+       if (wsurface->is_mapped)
+               return;
+
+       surface->panel.view = weston_desktop_surface_create_view(dsurface);
+
+       geom = weston_desktop_surface_get_geometry(dsurface);
+       switch (surface->panel.edge) {
+       case AGL_SHELL_EDGE_TOP:
+               /* Do nothing */
+               break;
+       case AGL_SHELL_EDGE_BOTTOM:
+               y += woutput->height - geom.height;
+               break;
+       case AGL_SHELL_EDGE_LEFT:
+               /* Do nothing */
+               break;
+       case AGL_SHELL_EDGE_RIGHT:
+               x += woutput->width - geom.width;
+               break;
+       }
+
+       weston_view_set_output(surface->panel.view, woutput);
+       weston_view_set_position(surface->panel.view, x, y);
+       weston_layer_entry_insert(&ivi->normal.view_list,
+                                 &surface->panel.view->layer_link);
+
+       weston_view_update_transform(surface->panel.view);
+       weston_view_schedule_repaint(surface->panel.view);
+
+       wsurface->is_mapped = true;
+}
+
+static void
+desktop_committed(struct weston_desktop_surface *dsurface, 
+                 int32_t sx, int32_t sy, void *userdata)
+{
+       struct ivi_surface *surface =
+               weston_desktop_surface_get_user_data(dsurface);
+
+       weston_compositor_schedule_repaint(surface->ivi->compositor);
+
+       switch (surface->role) {
+       case IVI_SURFACE_ROLE_NONE:
+               break;
+       case IVI_SURFACE_ROLE_DESKTOP:
+               surface_committed(surface);
+               break;
+       case IVI_SURFACE_ROLE_BACKGROUND:
+               background_committed(surface);
+               break;
+       case IVI_SURFACE_ROLE_PANEL:
+               panel_committed(surface);
+               break;
+       }
+}
+
+static void
+desktop_show_window_menu(struct weston_desktop_surface *dsurface,
+                        struct weston_seat *seat, int32_t x, int32_t y,
+                        void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_set_parent(struct weston_desktop_surface *dsurface,
+                  struct weston_desktop_surface *parent, void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_move(struct weston_desktop_surface *dsurface,
+            struct weston_seat *seat, uint32_t serial, void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_resize(struct weston_desktop_surface *dsurface,
+              struct weston_seat *seat, uint32_t serial,
+              enum weston_desktop_surface_edge edges, void *user_data)
+{
+       /* not supported */
+}
+
+static void
+desktop_fullscreen_requested(struct weston_desktop_surface *dsurface,
+                            bool fullscreen, struct weston_output *output,
+                            void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_maximized_requested(struct weston_desktop_surface *dsurface,
+                           bool maximized, void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_minimized_requested(struct weston_desktop_surface *dsurface,
+                           void *userdata)
+{
+       /* not supported */
+}
+
+static void
+desktop_set_xwayland_position(struct weston_desktop_surface *dsurface,
+                             int32_t x, int32_t y, void *userdata)
+{
+       /* not supported */
+}
+
+static const struct weston_desktop_api desktop_api = {
+       .struct_size = sizeof desktop_api,
+       .ping_timeout = desktop_ping_timeout,
+       .pong = desktop_pong,
+       .surface_added = desktop_surface_added,
+       .surface_removed = desktop_surface_removed,
+       .committed = desktop_committed,
+       .show_window_menu = desktop_show_window_menu,
+       .set_parent = desktop_set_parent,
+       .move = desktop_move,
+       .resize = desktop_resize,
+       .fullscreen_requested = desktop_fullscreen_requested,
+       .maximized_requested = desktop_maximized_requested,
+       .minimized_requested = desktop_minimized_requested,
+       .set_xwayland_position = desktop_set_xwayland_position,
+};
+
+int
+ivi_desktop_init(struct ivi_compositor *ivi)
+{
+       ivi->desktop = weston_desktop_create(ivi->compositor, &desktop_api, ivi);
+       if (!ivi->desktop) {
+               weston_log("Failed to create desktop globals");
+               return -1;
+       }
+
+       return 0;
+}
diff --git a/src/ivi-compositor.h b/src/ivi-compositor.h
new file mode 100644 (file)
index 0000000..65e06ad
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+ * Copyright © 2019 Collabora, Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#ifndef IVI_COMPOSITOR_H
+#define IVI_COMPOSITOR_H
+
+#include <stdbool.h>
+
+#include <libweston-6/compositor-drm.h>
+#include <libweston-6/compositor.h>
+#include <libweston-6/windowed-output-api.h>
+#include <libweston-6/libweston-desktop.h>
+
+#include "agl-shell-server-protocol.h"
+
+#define ARRAY_LENGTH(x) (sizeof(x) / sizeof((x)[0]))
+
+struct ivi_compositor {
+       struct weston_compositor *compositor;
+       struct weston_config *config;
+
+       struct wl_listener heads_changed;
+
+       bool init_failed;
+
+       /*
+        * Options parsed from command line arugments.
+        * Overrides what is found in the config file.
+        */
+       struct {
+               /* drm */
+               bool use_current_mode;
+               /* wayland/x11 */
+               int width;
+               int height;
+               int scale;
+       } cmdline;
+       const struct weston_windowed_output_api *window_api;
+       const struct weston_drm_output_api *drm_api;
+
+       struct wl_global *agl_shell;
+       struct {
+               struct wl_client *client;
+               struct wl_resource *resource;
+               bool ready;
+       } shell_client;
+
+       struct wl_list outputs; /* ivi_output.link */
+       struct wl_list surfaces; /* ivi_desktop_surface.link */
+
+       struct weston_desktop *desktop;
+
+       struct wl_list pending_surfaces;
+
+       struct weston_layer background;
+       struct weston_layer normal;
+       struct weston_layer panel;
+       struct weston_layer fullscreen;
+
+       struct wl_list shell_clients; /* ivi_shell_client.link */
+};
+
+struct ivi_surface;
+
+struct ivi_output {
+       struct wl_list link; /* ivi_compositor.outputs */
+       struct ivi_compositor *ivi;
+
+       char *name;
+       struct weston_config_section *config;
+       struct weston_output *output;
+
+       struct ivi_surface *background;
+       /* Panels */
+       struct ivi_surface *top;
+       struct ivi_surface *bottom;
+       struct ivi_surface *left;
+       struct ivi_surface *right;
+
+       struct wl_listener output_destroy;
+
+       /*
+        * Usable area for normal clients, i.e. with panels removed.
+        * In output-coorrdinate space.
+        */
+       struct weston_geometry area;
+
+       //int32_t width;
+       //int32_t height;
+
+       /* Temporary: only used during configuration */
+       size_t add_len;
+       struct weston_head *add[8];
+};
+
+enum ivi_surface_role {
+       IVI_SURFACE_ROLE_NONE,
+       IVI_SURFACE_ROLE_DESKTOP,
+       IVI_SURFACE_ROLE_BACKGROUND,
+       IVI_SURFACE_ROLE_PANEL,
+};
+
+struct ivi_desktop_surface {
+       struct weston_view *view;
+};
+
+struct ivi_background_surface {
+       struct ivi_output *output;
+       struct weston_view *view;
+};
+
+struct ivi_panel_surface {
+       struct ivi_output *output;
+       enum agl_shell_edge edge;
+       struct weston_view *view;
+};
+
+enum ivi_surface_flags {
+       IVI_SURFACE_PROP_MAP = (1 << 0),
+       /* x, y, width, height */
+       IVI_SURFACE_PROP_POSITION = (1 << 1),
+};
+
+struct ivi_surface {
+       struct ivi_compositor *ivi;
+       struct weston_desktop_surface *dsurface;
+
+       struct wl_list link;
+
+       struct {
+               enum ivi_surface_flags flags;
+               int32_t x, y;
+               int32_t width, height;
+       } pending;
+
+       struct weston_geometry old_geom;
+
+       enum ivi_surface_role role;
+       union {
+               struct ivi_desktop_surface desktop;
+               struct ivi_background_surface bg;
+               struct ivi_panel_surface panel;
+       };
+};
+
+struct ivi_shell_client {
+       struct wl_list link;
+       char *command;
+       bool require_ready;
+
+       pid_t pid;
+       struct wl_client *client;
+
+       struct wl_listener client_destroy;
+};
+
+struct ivi_compositor *
+to_ivi_compositor(struct weston_compositor *ec);
+
+int
+ivi_shell_init(struct ivi_compositor *ivi);
+
+int
+ivi_shell_create_global(struct ivi_compositor *ivi);
+
+int
+ivi_launch_shell_client(struct ivi_compositor *ivi);
+
+int
+ivi_desktop_init(struct ivi_compositor *ivi);
+
+struct ivi_shell_client *
+ivi_shell_client_from_wl(struct wl_client *client);
+
+struct ivi_output *
+to_ivi_output(struct weston_output *o);
+
+void
+ivi_set_desktop_surface(struct ivi_surface *surface);
+
+void
+ivi_reflow_outputs(struct ivi_compositor *ivi);
+
+struct ivi_surface *
+to_ivi_surface(struct weston_surface *surface);
+
+void
+ivi_layout_set_mapped(struct ivi_surface *surface);
+
+void
+ivi_layout_set_position(struct ivi_surface *surface,
+                       int32_t x, int32_t y,
+                       int32_t width, int32_t height);
+
+void
+ivi_layout_commit(struct ivi_compositor *ivi);
+
+#endif
diff --git a/src/main.c b/src/main.c
new file mode 100644 (file)
index 0000000..71a99ea
--- /dev/null
@@ -0,0 +1,1255 @@
+/*
+ * Copyright © 2012-2019 Collabora, Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "ivi-compositor.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <linux/input.h>
+
+#include <libweston-6/compositor-drm.h>
+#include <libweston-6/compositor-wayland.h>
+#include <libweston-6/compositor-x11.h>
+#include <libweston-6/compositor.h>
+#include <libweston-6/windowed-output-api.h>
+#include <libweston-6/config-parser.h>
+
+#include "shared/os-compatibility.h"
+
+#include "agl-shell-server-protocol.h"
+
+struct ivi_compositor *
+to_ivi_compositor(struct weston_compositor *ec)
+{
+       return weston_compositor_get_user_data(ec);
+}
+
+static void
+handle_output_destroy(struct wl_listener *listener, void *data)
+{
+       struct ivi_output *output;
+
+       output = wl_container_of(listener, output, output_destroy);
+       assert(output->output == data);
+
+       output->output = NULL;
+       wl_list_remove(&output->output_destroy.link);
+}
+
+struct ivi_output *
+to_ivi_output(struct weston_output *o)
+{
+       struct wl_listener *listener;
+       struct ivi_output *output;
+
+       listener = weston_output_get_destroy_listener(o, handle_output_destroy);
+       output = wl_container_of(listener, output, output_destroy);
+
+       return output;
+}
+
+static struct ivi_output *
+ivi_ensure_output(struct ivi_compositor *ivi, char *name,
+                 struct weston_config_section *config)
+{
+       struct ivi_output *output = NULL;
+       wl_list_for_each(output, &ivi->outputs, link) {
+               if (strcmp(output->name, name) == 0) {
+                       free(name);
+                       return output;
+               }
+       }
+
+       output = zalloc(sizeof *output);
+       if (!output) {
+               free(name);
+               return NULL;
+       }
+
+       output->ivi = ivi;
+       output->name = name;
+       output->config = config;
+
+       output->output = weston_compositor_create_output(ivi->compositor, name);
+       if (!output->output) {
+               free(output->name);
+               free(output);
+               return NULL;
+       }
+
+       output->output_destroy.notify = handle_output_destroy;
+       weston_output_add_destroy_listener(output->output,
+                                          &output->output_destroy);
+
+       wl_list_insert(&ivi->outputs, &output->link);
+       return output;
+}
+
+static void
+ivi_output_destroy(struct ivi_output *output)
+{
+       weston_output_destroy(output->output);
+       free(output->name);
+       wl_list_remove(&output->link);
+       free(output);
+}
+
+static int
+count_heads(struct weston_output *output)
+{
+       struct weston_head *iter = NULL;
+       int n = 0;
+
+       while ((iter = weston_output_iterate_heads(output, iter)))
+               ++n;
+
+       return n;
+}
+
+static void
+handle_head_destroy(struct wl_listener *listener, void *data)
+{
+       struct weston_head *head = data;
+       struct weston_output *output;
+
+       wl_list_remove(&listener->link);
+       free(listener);
+
+       output = weston_head_get_output(head);
+
+       /* On shutdown path, the output might be already gone. */
+       if (!output)
+               return;
+
+       /* We're the last head */
+       if (count_heads(output) <= 1)
+               weston_output_destroy(output);
+}
+
+static void
+add_head_destroyed_listener(struct weston_head *head)
+{
+       /* We already have a destroy listener */
+       if (weston_head_get_destroy_listener(head, handle_head_destroy))
+               return;
+
+       struct wl_listener *listener = zalloc(sizeof *listener);
+       if (!listener)
+               return;
+
+       listener->notify = handle_head_destroy;
+       weston_head_add_destroy_listener(head, listener);
+}
+
+static int
+drm_configure_output(struct ivi_output *output)
+{
+       struct ivi_compositor *ivi = output->ivi;
+       struct weston_config_section *section = output->config;
+       enum weston_drm_backend_output_mode mode =
+               WESTON_DRM_BACKEND_OUTPUT_PREFERRED;
+       char *modeline = NULL;
+       char *gbm_format = NULL;
+       char *seat = NULL;
+
+       if (section) {
+               char *m;
+               weston_config_section_get_string(section, "mode", &m, "preferred");
+
+               /* This should have been handled earlier */
+               assert(strcmp(m, "off") != 0);
+
+               if (ivi->cmdline.use_current_mode || strcmp(m, "current") == 0) {
+                       mode = WESTON_DRM_BACKEND_OUTPUT_CURRENT;
+               } else if (strcmp(m, "preferred") != 0) {
+                       modeline = m;
+                       m = NULL;
+               }
+               free(m);
+
+               weston_config_section_get_string(section, "gbm-format",
+                                                &gbm_format, NULL);
+
+               weston_config_section_get_string(section, "seat", &seat, "");
+       }
+
+       if (ivi->drm_api->set_mode(output->output, mode, modeline) < 0) {
+               weston_log("Cannot configure output using weston_drm_output_api.\n");
+               free(modeline);
+               return -1;
+       }
+       free(modeline);
+
+       ivi->drm_api->set_gbm_format(output->output, gbm_format);
+       free(gbm_format);
+
+       ivi->drm_api->set_seat(output->output, seat);
+       free(seat);
+
+       return 0;
+}
+
+#define WINDOWED_DEFAULT_WIDTH 1024
+#define WINDOWED_DEFAULT_HEIGHT 768
+
+static int
+windowed_configure_output(struct ivi_output *output)
+{
+       struct ivi_compositor *ivi = output->ivi;
+       struct weston_config_section *section = output->config;
+       int width = WINDOWED_DEFAULT_WIDTH;
+       int height = WINDOWED_DEFAULT_HEIGHT;
+
+       if (section) {
+               char *mode;
+
+               weston_config_section_get_string(section, "mode", &mode, NULL);
+               if (!mode || sscanf(mode, "%dx%d", &width, &height) != 2) {
+                       weston_log("Invalid mode for output %s. Using defaults.\n",
+                                  output->name);
+                       width = WINDOWED_DEFAULT_WIDTH;
+                       height = WINDOWED_DEFAULT_HEIGHT;
+               }
+               free(mode);
+       }
+
+       if (ivi->cmdline.width)
+               width = ivi->cmdline.width;
+       if (ivi->cmdline.height)
+               height = ivi->cmdline.height;
+       if (ivi->cmdline.scale)
+               weston_output_set_scale(output->output, ivi->cmdline.scale);
+
+       if (ivi->window_api->output_set_size(output->output, width, height) < 0) {
+               weston_log("Cannot configure output '%s' using weston_windowed_output_api.\n",
+                          output->name);
+               return -1;
+       }
+
+       return 0;
+}
+
+static int
+parse_transform(const char *transform, uint32_t *out)
+{
+       static const struct { const char *name; uint32_t token; } transforms[] = {
+               { "normal",     WL_OUTPUT_TRANSFORM_NORMAL },
+               { "90",         WL_OUTPUT_TRANSFORM_90 },
+               { "180",        WL_OUTPUT_TRANSFORM_180 },
+               { "270",        WL_OUTPUT_TRANSFORM_270 },
+               { "flipped",    WL_OUTPUT_TRANSFORM_FLIPPED },
+               { "flipped-90", WL_OUTPUT_TRANSFORM_FLIPPED_90 },
+               { "flipped-180", WL_OUTPUT_TRANSFORM_FLIPPED_180 },
+               { "flipped-270", WL_OUTPUT_TRANSFORM_FLIPPED_270 },
+       };
+
+       for (size_t i = 0; i < ARRAY_LENGTH(transforms); i++)
+               if (strcmp(transforms[i].name, transform) == 0) {
+                       *out = transforms[i].token;
+                       return 0;
+               }
+
+       *out = WL_OUTPUT_TRANSFORM_NORMAL;
+       return -1;
+}
+
+static int
+configure_output(struct ivi_output *output)
+{
+       struct ivi_compositor *ivi = output->ivi;
+       struct weston_config_section *section = output->config;
+       int32_t scale = 1;
+       uint32_t transform = WL_OUTPUT_TRANSFORM_NORMAL;
+
+       /*
+        * This can happen with the wayland backend with 'sprawl'. The config
+        * is hard-coded, so we don't need to do anything.
+        */
+       if (!ivi->drm_api && !ivi->window_api)
+               return 0;
+
+       if (section) {
+               char *t;
+
+               weston_config_section_get_int(section, "scale", &scale, 1);
+               weston_config_section_get_string(section, "transform", &t, "normal");
+               if (parse_transform(t, &transform) < 0)
+                       weston_log("Invalid transform \"%s\" for output %s\n",
+                                  t, output->name);
+               free(t);
+       }
+
+       weston_output_set_scale(output->output, scale);
+       weston_output_set_transform(output->output, transform);
+
+       if (ivi->drm_api)
+               return drm_configure_output(output);
+       else
+               return windowed_configure_output(output);
+}
+
+/*
+ * Reorgainizes the output's add array into two sections.
+ * add[0..ret-1] are the heads that failed to get attached.
+ * add[ret..add_len] are the heads that were successfully attached.
+ *
+ * The order between elements in each section is stable.
+ */
+static size_t
+try_attach_heads(struct ivi_output *output)
+{
+       size_t fail_len = 0;
+
+       for (size_t i = 0; i < output->add_len; ++i) {
+               if (weston_output_attach_head(output->output, output->add[i]) < 0) {
+                       struct weston_head *tmp = output->add[i];
+                       memmove(&output->add[fail_len + 1], output->add[fail_len],
+                               sizeof output->add[0] * (i - fail_len));
+                       output->add[fail_len++] = tmp;
+               }
+       }
+
+       return fail_len;
+}
+
+/*
+ * Like try_attach_heads, this reorganizes the output's add array into a failed
+ * and successful section.
+ * i is the number of heads that already failed the previous step.
+ */
+static size_t
+try_enable_output(struct ivi_output *output, size_t i)
+{
+       for (; i < output->add_len; ++i) {
+               struct weston_head *head;
+
+               if (weston_output_enable(output->output) == 0)
+                       break;
+
+               head = output->add[output->add_len - 1];
+               memmove(&output->add[i + 1], &output->add[i],
+                       sizeof output->add[0] * (output->add_len - i));
+               output->add[i] = head;
+
+               weston_head_detach(head);
+       }
+
+       return i;
+}
+
+static int
+try_attach_enable_heads(struct ivi_output *output)
+{
+       size_t fail_len;
+       assert(!output->output->enabled);
+
+       fail_len = try_attach_heads(output);
+
+       if (configure_output(output) < 0)
+               return -1;
+
+       fail_len = try_enable_output(output, fail_len);
+
+       /* All heads failed to be attached */
+       if (fail_len == output->add_len)
+               return -1;
+
+       /* For each successful head attached */
+       for (size_t i = fail_len; i < output->add_len; ++i)
+               add_head_destroyed_listener(output->add[i]);
+
+       output->add_len = fail_len;
+       return 0;
+}
+
+static int
+process_output(struct ivi_output *output)
+{
+       if (output->output->enabled) {
+               output->add_len = try_attach_heads(output);
+               return output->add_len == 0 ? 0 : -1;
+       }
+
+       return try_attach_enable_heads(output);
+}
+
+static void
+head_disable(struct ivi_compositor *ivi, struct weston_head *head)
+{
+       struct weston_output *output;
+       struct ivi_output *ivi_output;
+       struct wl_listener *listener;
+
+       output = weston_head_get_output(head);
+       assert(output);
+
+       listener = weston_output_get_destroy_listener(output,
+                                                     handle_output_destroy);
+       assert(listener);
+
+       ivi_output = wl_container_of(listener, ivi_output, output_destroy);
+       assert(ivi_output->output == output);
+
+       weston_head_detach(head);
+       if (count_heads(ivi_output->output) == 0) {
+               ivi_output_destroy(ivi_output);
+               weston_output_disable(ivi_output->output);
+       }
+}
+
+static struct weston_config_section *
+find_controlling_output_config(struct weston_config *config,
+                              const char *name)
+{
+       struct weston_config_section *section;
+       char *same_as;
+       int depth = 0;
+
+       same_as = strdup(name);
+       do {
+               section = weston_config_get_section(config, "output",
+                                                   "name", same_as);
+               if (!section && depth > 0)
+                       weston_log("Configuration error: output section reffered"
+                                  "to by same-as=%s not found.\n", same_as);
+               free(same_as);
+
+               if (!section)
+                       return NULL;
+
+               if (depth++ > 8) {
+                       weston_log("Configuration error: same-as nested too "
+                                  "deep for output '%s'.\n", name);
+                       return NULL;
+               }
+
+               weston_config_section_get_string(section, "same-as",
+                                                &same_as, NULL);
+       } while (same_as);
+
+       return section;
+}
+
+static void
+head_prepare_enable(struct ivi_compositor *ivi, struct weston_head *head)
+{
+       const char *name = weston_head_get_name(head);
+       struct weston_config_section *section;
+       struct ivi_output *output;
+       char *output_name = NULL;
+
+       section = find_controlling_output_config(ivi->config, name);
+       if (section) {
+               char *mode;
+
+               weston_config_section_get_string(section, "mode", &mode, NULL);
+               if (mode && strcmp(mode, "off") == 0) {
+                       free(mode);
+                       return;
+               }
+               free(mode);
+
+               weston_config_section_get_string(section, "name",
+                                                &output_name, NULL);
+       } else {
+               output_name = strdup(name);
+       }
+
+       if (!output_name)
+               return;
+
+       output = ivi_ensure_output(ivi, output_name, section);
+       if (!output)
+               return;
+
+       if (output->add_len >= ARRAY_LENGTH(output->add))
+               return;
+
+       output->add[output->add_len++] = head;
+}
+
+static void
+heads_changed(struct wl_listener *listener, void *arg)
+{
+       struct weston_compositor *compositor = arg;
+       struct weston_head *head = NULL;
+       struct ivi_compositor *ivi = to_ivi_compositor(compositor);
+       struct ivi_output *output;
+
+       while ((head = weston_compositor_iterate_heads(ivi->compositor, head))) {
+               bool connected = weston_head_is_connected(head);
+               bool enabled = weston_head_is_enabled(head);
+               bool changed = weston_head_is_device_changed(head);
+               bool non_desktop = weston_head_is_non_desktop(head);
+
+               if (connected && !enabled && !non_desktop)
+                       head_prepare_enable(ivi, head);
+               else if (!connected && enabled)
+                       head_disable(ivi, head);
+               else if (enabled && changed)
+                       weston_log("Detected a monitor change on head '%s', "
+                                  "not bothering to do anything about it.\n",
+                                  weston_head_get_name(head));
+
+               weston_head_reset_device_changed(head);
+       }
+
+       wl_list_for_each(output, &ivi->outputs, link) {
+               if (output->add_len == 0)
+                       continue;
+
+               if (process_output(output) < 0) {
+                       output->add_len = 0;
+                       ivi->init_failed = true;
+               }
+       }
+}
+
+static int
+load_drm_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
+{
+       struct weston_drm_backend_config config = {
+               .base = {
+                       .struct_version = WESTON_DRM_BACKEND_CONFIG_VERSION,
+                       .struct_size = sizeof config,
+               },
+       };
+       struct weston_config_section *section;
+       int use_current_mode = 0;
+       int use_pixman = 0;
+       int use_shadow;
+       int ret;
+
+       const struct weston_option options[] = {
+               { WESTON_OPTION_STRING, "seat", 0, &config.seat_id },
+               { WESTON_OPTION_INTEGER, "tty", 0, &config.tty },
+               { WESTON_OPTION_STRING, "drm-device", 0, &config.specific_device },
+               { WESTON_OPTION_BOOLEAN, "current-mode", 0, &use_current_mode },
+               { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &use_pixman },
+       };
+
+       parse_options(options, ARRAY_LENGTH(options), argc, argv);
+       config.use_pixman = use_pixman;
+       ivi->cmdline.use_current_mode = use_current_mode;
+
+       section = weston_config_get_section(ivi->config, "core", NULL, NULL);
+       weston_config_section_get_string(section, "gbm-format",
+                                        &config.gbm_format, NULL);
+       weston_config_section_get_uint(section, "pageflip-timeout",
+                                      &config.pageflip_timeout, 0);
+       weston_config_section_get_bool(section, "pixman-shadow", &use_shadow, 1);
+       config.use_pixman_shadow = use_shadow;
+
+       ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_DRM,
+                                            &config.base);
+       if (ret < 0)
+               return ret;
+
+       ivi->drm_api = weston_drm_output_get_api(ivi->compositor);
+       if (!ivi->drm_api) {
+               weston_log("Cannot use drm output api.\n");
+               ret = -1;
+               goto error;
+       }
+
+error:
+       free(config.gbm_format);
+       free(config.seat_id);
+       return ret;
+}
+
+static void
+windowed_parse_common_options(struct ivi_compositor *ivi, int *argc, char *argv[],
+                             bool *use_pixman, bool *fullscreen, int *output_count)
+{
+       struct weston_config_section *section;
+       int pixman;
+       int fs = 0;
+
+       const struct weston_option options[] = {
+               { WESTON_OPTION_INTEGER, "width", 0, &ivi->cmdline.width },
+               { WESTON_OPTION_INTEGER, "height", 0, &ivi->cmdline.height },
+               { WESTON_OPTION_INTEGER, "scale", 0, &ivi->cmdline.scale },
+               { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &pixman },
+               { WESTON_OPTION_BOOLEAN, "fullscreen", 0, &fs },
+               { WESTON_OPTION_INTEGER, "output-count", 0, output_count },
+       };
+
+       section = weston_config_get_section(ivi->config, "core", NULL, NULL);
+       weston_config_section_get_bool(section, "use-pixman", &pixman, 0);
+
+       *output_count = 1;
+       parse_options(options, ARRAY_LENGTH(options), argc, argv);
+       *use_pixman = pixman;
+       *fullscreen = fs;
+}
+
+static int
+windowed_create_outputs(struct ivi_compositor *ivi, int output_count,
+                       const char *match_prefix, const char *name_prefix)
+{
+       struct weston_config_section *section = NULL;
+       const char *section_name;
+       char *default_output = NULL;
+       int i = 0;
+       size_t match_len = strlen(match_prefix);
+
+       while (weston_config_next_section(ivi->config, &section, &section_name)) {
+               char *output_name;
+
+               if (i >= output_count)
+                       break;
+
+               if (strcmp(section_name, "output") != 0)
+                       continue;
+
+               weston_config_section_get_string(section, "name", &output_name, NULL);
+               if (output_name == NULL)
+                       continue;
+               if (strncmp(output_name, match_prefix, match_len) != 0) {
+                       free(output_name);
+                       continue;
+               }
+
+               if (ivi->window_api->create_head(ivi->compositor, output_name) < 0) {
+                       free(output_name);
+                       return -1;
+               }
+
+               free(output_name);
+               ++i;
+       }
+
+       for (; i < output_count; ++i) {
+               if (asprintf(&default_output, "%s%d", name_prefix, i) < 0)
+                       return -1;
+
+               if (ivi->window_api->create_head(ivi->compositor, default_output) < 0) {
+                       free(default_output);
+                       return -1;
+               }
+
+               free(default_output);
+       }
+
+       return 0;
+}
+
+static int
+load_wayland_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
+{
+       struct weston_wayland_backend_config config = {
+               .base = {
+                       .struct_version = WESTON_WAYLAND_BACKEND_CONFIG_VERSION,
+                       .struct_size = sizeof config,
+               },
+       };
+       struct weston_config_section *section;
+       int sprawl = 0;
+       int output_count;
+       int ret;
+
+       const struct weston_option options[] = {
+               { WESTON_OPTION_STRING, "display", 0, &config.display_name },
+               { WESTON_OPTION_STRING, "sprawl", 0, &sprawl },
+       };
+
+       windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
+                                     &config.fullscreen, &output_count);
+
+       parse_options(options, ARRAY_LENGTH(options), argc, argv);
+       config.sprawl = sprawl;
+
+       section = weston_config_get_section(ivi->config, "shell", NULL, NULL);
+       weston_config_section_get_string(section, "cursor-theme",
+                                        &config.cursor_theme, NULL);
+       weston_config_section_get_int(section, "cursor-size",
+                                     &config.cursor_size, 32);
+
+       ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_WAYLAND,
+                                            &config.base);
+
+       free(config.cursor_theme);
+       free(config.display_name);
+
+       if (ret < 0)
+               return ret;
+
+       ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
+
+       /*
+        * We will just assume if load_backend() finished cleanly and
+        * windowed_output_api is not present that wayland backend is started
+        * with --sprawl or runs on fullscreen-shell. In this case, all values
+        * are hardcoded, so nothing can be configured; simply create and
+        * enable an output.
+        */
+       if (ivi->window_api == NULL)
+               return 0;
+
+       return windowed_create_outputs(ivi, output_count, "WL", "wayland");
+}
+
+static int
+load_x11_backend(struct ivi_compositor *ivi, int *argc, char *argv[])
+{
+       struct weston_x11_backend_config config = {
+               .base = {
+                       .struct_version = WESTON_X11_BACKEND_CONFIG_VERSION,
+                       .struct_size = sizeof config,
+               },
+       };
+       int no_input = 0;
+       int output_count;
+       int ret;
+
+       const struct weston_option options[] = {
+              { WESTON_OPTION_BOOLEAN, "no-input", 0, &no_input },
+       };
+
+       windowed_parse_common_options(ivi, argc, argv, &config.use_pixman,
+                                     &config.fullscreen, &output_count);
+
+       parse_options(options, ARRAY_LENGTH(options), argc, argv);
+       config.no_input = no_input;
+
+       ret = weston_compositor_load_backend(ivi->compositor, WESTON_BACKEND_X11,
+                                            &config.base);
+
+       if (ret < 0)
+               return ret;
+
+       ivi->window_api = weston_windowed_output_get_api(ivi->compositor);
+       if (!ivi->window_api) {
+               weston_log("Cannot use weston_windowed_output_api.\n");
+               return -1;
+       }
+
+       return windowed_create_outputs(ivi, output_count, "X", "screen");
+}
+
+static int
+load_backend(struct ivi_compositor *ivi, const char *backend,
+            int *argc, char *argv[])
+{
+       if (strcmp(backend, "drm-backend.so") == 0) {
+               return load_drm_backend(ivi, argc, argv);
+       } else if (strcmp(backend, "wayland-backend.so") == 0) {
+               return load_wayland_backend(ivi, argc, argv);
+       } else if (strcmp(backend, "x11-backend.so") == 0) {
+               return load_x11_backend(ivi, argc, argv);
+       }
+
+       weston_log("fatal: unknown backend '%s'.\n", backend);
+       return -1;
+}
+
+static char *
+choose_default_backend(void)
+{
+       char *backend = NULL;
+
+       if (getenv("WAYLAND_DISPLAY") || getenv("WAYLAND_SOCKET"))
+               backend = strdup("wayland-backend.so");
+       else if (getenv("DISPLAY"))
+               backend = strdup("x11-backend.so");
+       else
+               backend = strdup("drm-backend.so");
+
+       return backend;
+}
+
+static int
+compositor_init_config(struct weston_compositor *compositor,
+                      struct weston_config *config)
+{
+       struct xkb_rule_names xkb_names;
+       struct weston_config_section *section;
+       int repaint_msec;
+       int vt_switching;
+       int require_input;
+
+       /* agl-compositor.ini [keyboard] */
+       section = weston_config_get_section(config, "keyboard", NULL, NULL);
+       weston_config_section_get_string(section, "keymap_rules",
+                                        (char **) &xkb_names.rules, NULL);
+       weston_config_section_get_string(section, "keymap_model",
+                                        (char **) &xkb_names.model, NULL);
+       weston_config_section_get_string(section, "keymap_layout",
+                                        (char **) &xkb_names.layout, NULL);
+       weston_config_section_get_string(section, "keymap_variant",
+                                        (char **) &xkb_names.variant, NULL);
+       weston_config_section_get_string(section, "keymap_options",
+                                        (char **) &xkb_names.options, NULL);
+
+       if (weston_compositor_set_xkb_rule_names(compositor, &xkb_names) < 0)
+               return -1;
+
+       weston_config_section_get_int(section, "repeat-rate",
+                                     &compositor->kb_repeat_rate, 40);
+       weston_config_section_get_int(section, "repeat-delay",
+                                     &compositor->kb_repeat_delay, 400);
+
+       weston_config_section_get_bool(section, "vt-switching",
+                                      &vt_switching, true);
+       compositor->vt_switching = vt_switching;
+
+       /* agl-compositor.ini [core] */
+       section = weston_config_get_section(config, "core", NULL, NULL);
+
+       weston_config_section_get_bool(section, "require-input", &require_input, true);
+       compositor->require_input = require_input;
+
+       weston_config_section_get_int(section, "repaint-window", &repaint_msec,
+                                     compositor->repaint_msec);
+       if (repaint_msec < -10 || repaint_msec > 1000) {
+               weston_log("Invalid repaint_window value in config: %d\n",
+                          repaint_msec);
+       } else {
+               compositor->repaint_msec = repaint_msec;
+       }
+       weston_log("Output repaint window is %d ms maximum.\n",
+                  compositor->repaint_msec);
+
+       return 0;
+}
+
+struct ivi_surface *
+to_ivi_surface(struct weston_surface *surface)
+{
+       struct weston_desktop_surface *dsurface;
+
+       dsurface = weston_surface_get_desktop_surface(surface);
+       if (!dsurface)
+               return NULL;
+
+       return weston_desktop_surface_get_user_data(dsurface);
+}
+
+static void
+activate_binding(struct weston_seat *seat,
+                struct weston_view *focus_view)
+{
+       struct weston_surface *focus = focus_view->surface;
+       struct weston_surface *main_surface =
+               weston_surface_get_main_surface(focus);
+       struct ivi_surface *surface;
+
+       surface = to_ivi_surface(main_surface);
+       if (!surface || surface->role != IVI_SURFACE_ROLE_DESKTOP)
+               return;
+
+       weston_seat_set_keyboard_focus(seat, focus);
+}
+
+static void
+click_to_activate_binding(struct weston_pointer *pointer,
+                         const struct timespec *time,
+                         uint32_t button, void *data)
+{
+       if (pointer->grab != &pointer->default_grab)
+               return;
+       if (pointer->focus == NULL)
+               return;
+
+       activate_binding(pointer->seat, pointer->focus);
+}
+
+static void
+touch_to_activate_binding(struct weston_touch *touch,
+                         const struct timespec *time,
+                         void *data)
+{
+       if (touch->grab != &touch->default_grab)
+               return;
+       if (touch->focus == NULL)
+               return;
+
+       activate_binding(touch->seat, touch->focus);
+}
+
+static void
+add_bindings(struct weston_compositor *compositor)
+{
+       weston_compositor_add_button_binding(compositor, BTN_LEFT, 0,
+                                            click_to_activate_binding,
+                                            NULL);
+       weston_compositor_add_button_binding(compositor, BTN_RIGHT, 0,
+                                            click_to_activate_binding,
+                                            NULL);
+       weston_compositor_add_touch_binding(compositor, 0,
+                                           touch_to_activate_binding,
+                                           NULL);
+}
+
+static int
+create_listening_socket(struct wl_display *display, const char *socket_name)
+{
+       if (socket_name) {
+               if (wl_display_add_socket(display, socket_name)) {
+                       weston_log("fatal: failed to add socket: %s\n",
+                                  strerror(errno));
+                       return -1;
+               }
+       } else {
+               socket_name = wl_display_add_socket_auto(display);
+               if (!socket_name) {
+                       weston_log("fatal: failed to add socket: %s\n",
+                                  strerror(errno));
+                       return -1;
+               }
+       }
+
+       setenv("WAYLAND_DISPLAY", socket_name, 1);
+
+       return 0;
+}
+
+static bool
+global_filter(const struct wl_client *client, const struct wl_global *global,
+             void *data)
+{
+#if 0
+       struct ivi_compositor *ivi = data;
+       const struct wl_interface *iface = wl_global_get_interface(global);
+
+       if (iface == &agl_shell_interface)
+               return client == ivi->shell_client.client;
+#endif
+
+       return true;
+}
+
+static int
+load_config(struct weston_config **config, bool no_config,
+           const char *config_file)
+{
+       const char *file = "agl-compositor.ini";
+       const char *full_path;
+
+       if (config_file)
+               file = config_file;
+
+       if (!no_config)
+               *config = weston_config_parse(file);
+
+       if (*config) {
+               full_path = weston_config_get_full_path(*config);
+
+               weston_log("Using config file '%s'.\n", full_path);
+               setenv(WESTON_CONFIG_FILE_ENV_VAR, full_path, 1);
+
+               return 0;
+       }
+
+       if (config_file && !no_config) {
+               weston_log("fatal: error opening or reading config file '%s'.\n",
+                       config_file);
+
+               return -1;
+       }
+
+       weston_log("Starting with no config file.\n");
+       setenv(WESTON_CONFIG_FILE_ENV_VAR, "", 1);
+
+       return 0;
+}
+
+static FILE *logfile;
+//static struct weston_log_scope *log_scope;
+//static struct weston_log_scope *protocol_scope;
+
+static int
+log_timestamp(void)
+{
+       static int cached_tm_mday = -1;
+       struct timespec ts;
+       struct tm brokendown_time;
+       char buf[128];
+
+       clock_gettime(CLOCK_REALTIME, &ts);
+       if (!localtime_r(&ts.tv_sec, &brokendown_time))
+               return fprintf(logfile, "[(NULL)localtime] ");
+
+       if (brokendown_time.tm_mday != cached_tm_mday) {
+               strftime(buf, sizeof buf, "%Y-%m-%d %Z", &brokendown_time);
+               fprintf(logfile, "Date: %s\n", buf);
+
+               cached_tm_mday = brokendown_time.tm_mday;
+       }
+
+       strftime(buf, sizeof buf, "%H:%M:%S", &brokendown_time);
+
+       return fprintf(logfile, "[%s.%03ld] ", buf, ts.tv_nsec / 1000000);
+}
+
+static void
+custom_handler(const char *fmt, va_list arg)
+{
+       log_timestamp();
+       fprintf(logfile, "libwayland: ");
+       vfprintf(logfile, fmt, arg);
+}
+
+static void
+log_file_open(const char *filename)
+{
+       wl_log_set_handler_server(custom_handler);
+
+       if (filename)
+               logfile = fopen(filename, "a");
+
+       if (!logfile) {
+               logfile = stderr;
+       } else {
+               os_fd_set_cloexec(fileno(logfile));
+               setvbuf(logfile, NULL, _IOLBF, 256);
+       }
+}
+
+static void
+log_file_close(void)
+{
+       if (logfile && logfile != stderr)
+               fclose(logfile);
+       logfile = stderr;
+}
+
+static int
+vlog(const char *fmt, va_list ap)
+{
+       int l;
+
+       l = log_timestamp();
+       l += vfprintf(logfile, fmt, ap);
+
+       return l;
+}
+
+static int
+vlog_continue(const char *fmt, va_list ap)
+{
+       return vfprintf(logfile, fmt, ap);
+}
+
+static int
+on_term_signal(int signo, void *data)
+{
+       struct wl_display *display = data;
+
+       weston_log("caught signal %d\n", signo);
+       wl_display_terminate(display);
+
+       return 1;
+}
+
+static void
+handle_exit(struct weston_compositor *compositor)
+{
+       wl_display_terminate(compositor->wl_display);
+}
+
+static void
+usage(int error_code)
+{
+       FILE *out = error_code == EXIT_SUCCESS ? stdout : stderr;
+       fprintf(out,
+               "Usage: agl-compositor [OPTIONS]\n"
+               "\n"
+               "This is " PACKAGE_STRING ", the reference compositor for\n"
+               "Automotive Grade Linux. Weston-ivi supports multiple backends, and depending\n"
+               "on which backend is in use different options will be accepted.\n"
+               "\n"
+               "Core options:\n"
+               "\n"
+               "  --version\t\tPrint agl-compositor version\n"
+               "  -B, --backend=MODULE\tBackend module, one of\n"
+                       "\t\t\t\tdrm-backend.so\n"
+                       "\t\t\t\twayland-backend.so\n"
+                       "\t\t\t\tx11-backend.so\n"
+               "  -S, --socket=NAME\tName of socket to listen on\n"
+               "  --log=FILE\t\tLog to the given file\n"
+               "  -c, --config=FILE\tConfig file to load, defaults to agl-compositor.ini\n"
+               "  --no-config\t\tDo not read agl-compositor.ini\n"
+               "  --debug\t\tEnable debug extension\n"
+               "  -h, --help\t\tThis help message\n"
+               "\n");
+       exit(error_code);
+}
+
+int main(int argc, char *argv[])
+{
+       struct ivi_compositor ivi = { 0 };
+       struct wl_display *display;
+       struct wl_event_loop *loop;
+       struct wl_event_source *signals[3] = { 0 };
+       struct weston_config_section *section;
+       /* Command line options */
+       char *backend = NULL;
+       char *socket_name = NULL;
+       char *log = NULL;
+       int help = 0;
+       int version = 0;
+       int no_config = 0;
+       char *config_file = NULL;
+       int debug_protocol = 0;
+
+       const struct weston_option core_options[] = {
+               { WESTON_OPTION_STRING, "backend", 'B', &backend },
+               { WESTON_OPTION_STRING, "socket", 'S', &socket_name },
+               { WESTON_OPTION_STRING, "log", 0, &log },
+               { WESTON_OPTION_BOOLEAN, "help", 'h', &help },
+               { WESTON_OPTION_BOOLEAN, "version", 0, &version },
+               { WESTON_OPTION_BOOLEAN, "no-config", 0, &no_config },
+               { WESTON_OPTION_STRING, "config", 'c', &config_file },
+               { WESTON_OPTION_BOOLEAN, "debug", 0, &debug_protocol },
+       };
+
+       wl_list_init(&ivi.outputs);
+       wl_list_init(&ivi.surfaces);
+       wl_list_init(&ivi.shell_clients);
+       wl_list_init(&ivi.pending_surfaces);
+
+       /* Prevent any clients we spawn getting our stdin */
+       os_fd_set_cloexec(STDIN_FILENO);
+
+       parse_options(core_options, ARRAY_LENGTH(core_options), &argc, argv);
+
+       if (help)
+               usage(EXIT_SUCCESS);
+
+       if (version) {
+               printf(PACKAGE_STRING "\n");
+               return EXIT_SUCCESS;
+       }
+
+       log_file_open(log);
+       weston_log_set_handler(vlog, vlog_continue);
+
+       if (load_config(&ivi.config, no_config, config_file) < 0)
+               goto error_signals;
+       section = weston_config_get_section(ivi.config, "core", NULL, NULL);
+       if (!backend) {
+               weston_config_section_get_string(section, "backend", &backend,
+                                                NULL);
+               if (!backend)
+                       backend = choose_default_backend();
+       }
+
+       display = wl_display_create();
+       loop = wl_display_get_event_loop(display);
+
+       wl_display_set_global_filter(display,
+                                    global_filter, &ivi);
+
+       /* Register signal handlers so we shut down cleanly */
+
+       signals[0] = wl_event_loop_add_signal(loop, SIGTERM, on_term_signal,
+                                             display);
+       signals[1] = wl_event_loop_add_signal(loop, SIGINT, on_term_signal,
+                                             display);
+       signals[2] = wl_event_loop_add_signal(loop, SIGQUIT, on_term_signal,
+                                             display);
+
+       for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
+               if (!signals[i])
+                       goto error_signals;
+
+#if 0
+       log_ctx = weston_log_ctx_compositor_create();
+       if (!log_ctx) {
+               weston_log("Failed to initialize weston debug framework.\n");
+               goto error_signals;
+       }
+#endif
+
+       ivi.compositor = weston_compositor_create(display, &ivi);
+       if (!ivi.compositor) {
+               weston_log("fatal: failed to create compositor.\n");
+               goto error_signals;
+       }
+
+#if 0
+       if (debug_protocol)
+               weston_compositor_enable_debug_protocol(ivi.compositor);
+#endif
+
+       if (compositor_init_config(ivi.compositor, ivi.config) < 0)
+               goto error_compositor;
+
+       if (load_backend(&ivi, backend, &argc, argv) < 0) {
+               weston_log("fatal: failed to create compositor backend.\n");
+               goto error_compositor;
+       }
+
+       ivi.heads_changed.notify = heads_changed;
+       weston_compositor_add_heads_changed_listener(ivi.compositor,
+                                                    &ivi.heads_changed);
+
+       if (ivi_desktop_init(&ivi) < 0)
+               goto error_compositor;
+
+       if (ivi_shell_init(&ivi) < 0)
+               goto error_compositor;
+
+       add_bindings(ivi.compositor);
+
+       weston_compositor_flush_heads_changed(ivi.compositor);
+
+       if (create_listening_socket(display, socket_name) < 0)
+               goto error_compositor;
+
+       ivi.compositor->exit = handle_exit;
+
+       weston_compositor_wake(ivi.compositor);
+
+       ivi_shell_create_global(&ivi);
+       ivi_launch_shell_client(&ivi);
+
+       wl_display_run(display);
+
+       wl_display_destroy_clients(display);
+
+error_compositor:
+       weston_compositor_destroy(ivi.compositor);
+
+error_signals:
+       for (size_t i = 0; i < ARRAY_LENGTH(signals); ++i)
+               if (signals[i])
+                       wl_event_source_remove(signals[i]);
+
+       wl_display_destroy(display);
+
+       log_file_close();
+       if (ivi.config)
+               weston_config_destroy(ivi.config);
+}
diff --git a/src/shell.c b/src/shell.c
new file mode 100644 (file)
index 0000000..cac8fa2
--- /dev/null
@@ -0,0 +1,533 @@
+/*
+ * Copyright © 2019 Collabora, Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+#include "ivi-compositor.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <libweston-6/compositor.h>
+#include <libweston-6/config-parser.h>
+
+#include "shared/os-compatibility.h"
+
+#include "agl-shell-server-protocol.h"
+
+void
+ivi_set_desktop_surface(struct ivi_surface *surface)
+{
+       assert(surface->role == IVI_SURFACE_ROLE_NONE);
+
+       surface->role = IVI_SURFACE_ROLE_DESKTOP;
+       wl_list_insert(&surface->ivi->surfaces, &surface->link);
+}
+
+/* TODO: Replace this with some callback or similar, to have
+ * adjustable window management policy.
+ */
+void
+ivi_reflow_outputs(struct ivi_compositor *ivi)
+{
+       struct ivi_surface *surface;
+       struct ivi_output *output;
+       int i = 0;
+
+       if (wl_list_empty(&ivi->outputs))
+               return;
+
+       output = wl_container_of(ivi->outputs.next, output, link);
+
+       wl_list_for_each(surface, &ivi->surfaces, link) {
+               struct weston_desktop_surface *dsurface = surface->dsurface;
+
+               int32_t w = output->area.width / 4;
+               int32_t h = output->area.height / 2;
+               int32_t x = output->output->x + output->area.x + w * (i % 4);
+               int32_t y = output->output->y + output->area.y + h * (i / 4);
+
+               if (surface->old_geom.width == -1) {
+                       weston_desktop_surface_set_size(dsurface, w, h);
+                       continue;
+               } else {
+                       ivi_layout_set_mapped(surface);
+                       ivi_layout_set_position(surface, x, y, w, h);
+               }
+
+               if (++i == 8) {
+                       if (output->link.next == &ivi->outputs)
+                               break;
+
+                       output = wl_container_of(output->link.next,
+                                                output, link);
+                       i = 0;
+               }
+       }
+
+       ivi_layout_commit(ivi);
+}
+
+void
+ivi_layout_set_mapped(struct ivi_surface *surface)
+{
+       surface->pending.flags |= IVI_SURFACE_PROP_MAP;
+}
+
+void
+ivi_layout_set_position(struct ivi_surface *surface,
+                       int32_t x, int32_t y,
+                       int32_t width, int32_t height)
+{
+       surface->pending.flags |= IVI_SURFACE_PROP_POSITION;
+       surface->pending.x = x;
+       surface->pending.y = y;
+       surface->pending.width = width;
+       surface->pending.height = height;
+}
+
+void
+ivi_layout_commit(struct ivi_compositor *ivi)
+{
+       struct ivi_surface *surface;
+
+       wl_list_for_each(surface, &ivi->surfaces, link) {
+               struct weston_desktop_surface *dsurface = surface->dsurface;
+               struct weston_surface *wsurface =
+                       weston_desktop_surface_get_surface(dsurface);
+               struct weston_geometry geom;
+               struct weston_view *view;
+
+               /*
+                * TODO: Hoist view into ivi_struct. It doesn't need ot be part
+                * of the tagged union.
+                */
+               switch (surface->role) {
+               case IVI_SURFACE_ROLE_DESKTOP:
+                       view = surface->desktop.view;
+                       break;
+               case IVI_SURFACE_ROLE_BACKGROUND:
+                       view = surface->bg.view;
+                       break;
+               case IVI_SURFACE_ROLE_PANEL:
+                       view = surface->panel.view;
+                       break;
+               default:
+                       continue;
+               }
+
+               if (surface->pending.flags & IVI_SURFACE_PROP_MAP) {
+                       view = weston_desktop_surface_create_view(dsurface);
+                       wsurface->is_mapped = true;
+
+                       surface->desktop.view = view;
+                       weston_layer_entry_insert(&ivi->normal.view_list,
+                                                 &view->layer_link);
+                       weston_view_update_transform(view);
+                       weston_view_set_mask_infinite(view);
+                       weston_view_schedule_repaint(view);
+               }
+
+               geom = weston_desktop_surface_get_geometry(dsurface);
+
+               if (surface->pending.flags & IVI_SURFACE_PROP_POSITION) {
+                       weston_desktop_surface_set_size(dsurface,
+                                                       surface->pending.width,
+                                                       surface->pending.height);
+                       weston_view_set_position(view,
+                                                surface->pending.x - geom.x,
+                                                surface->pending.y - geom.y);
+               }
+
+               surface->pending.flags = 0;
+       }
+}
+
+int
+ivi_shell_init(struct ivi_compositor *ivi)
+{
+       weston_layer_init(&ivi->background, ivi->compositor);
+       weston_layer_init(&ivi->normal, ivi->compositor);
+       weston_layer_init(&ivi->panel, ivi->compositor);
+       weston_layer_init(&ivi->fullscreen, ivi->compositor);
+
+       weston_layer_set_position(&ivi->background,
+                                 WESTON_LAYER_POSITION_BACKGROUND);
+       weston_layer_set_position(&ivi->normal,
+                                 WESTON_LAYER_POSITION_NORMAL);
+       weston_layer_set_position(&ivi->panel,
+                                 WESTON_LAYER_POSITION_UI);
+       weston_layer_set_position(&ivi->fullscreen,
+                                 WESTON_LAYER_POSITION_FULLSCREEN);
+
+       return 0;
+}
+
+static void
+client_exec(const char *command, int fd)
+{
+       sigset_t sig;
+       char s[32];
+
+       /* Don't give the child our signal mask */
+       sigfillset(&sig);
+       sigprocmask(SIG_UNBLOCK, &sig, NULL);
+
+       /* Launch clients as the user; don't give them the wrong euid */
+       if (seteuid(getuid()) == -1) {
+               weston_log("seteuid failed: %s\n", strerror(errno));
+               return;
+       }
+
+       /* Duplicate fd to unset the CLOEXEC flag. We don't need to worry about
+        * clobbering fd, as we'll exit/exec either way.
+        */
+       fd = dup(fd);
+       if (fd == -1) {
+               weston_log("dup failed: %s\n", strerror(errno));
+               return;
+       }
+
+       snprintf(s, sizeof s, "%d", fd);
+       setenv("WAYLAND_SOCKET", s, 1);
+
+       execl("/bin/sh", "/bin/sh", "-c", command, NULL);
+       weston_log("executing '%s' failed: %s", command, strerror(errno));
+}
+
+static struct wl_client *
+launch_shell_client(struct ivi_compositor *ivi, const char *command)
+{
+       struct wl_client *client;
+       int sock[2];
+       pid_t pid;
+
+       weston_log("launching' %s'\n", command);
+
+       if (os_socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, sock) < 0) {
+               weston_log("socketpair failed while launching '%s': %s\n",
+                          command, strerror(errno));
+               return NULL;
+       }
+
+       pid = fork();
+       if (pid == -1) {
+               close(sock[0]);
+               close(sock[1]);
+               weston_log("fork failed while launching '%s': %s\n",
+                          command, strerror(errno));
+               return NULL;
+       }
+
+       if (pid == 0) {
+               client_exec(command, sock[1]);
+               _Exit(EXIT_FAILURE);
+       }
+       close(sock[1]);
+
+       client = wl_client_create(ivi->compositor->wl_display, sock[0]);
+       if (!client) {
+               close(sock[0]);
+               weston_log("Failed to create wayland client for '%s'",
+                          command);
+               return NULL;
+       }
+
+       return client;
+}
+
+int
+ivi_launch_shell_client(struct ivi_compositor *ivi)
+{
+       struct weston_config_section *section;
+       char *command = NULL;
+
+       section = weston_config_get_section(ivi->config, "shell-client",
+                                           NULL, NULL);
+       if (section)
+               weston_config_section_get_string(section, "command",
+                                                &command, NULL);
+
+       if (!command)
+               return -1;
+
+       ivi->shell_client.client = launch_shell_client(ivi, command);
+       if (!ivi->shell_client.client)
+               return -1;
+
+       return 0;
+}
+
+static void
+shell_ready(struct wl_client *client, struct wl_resource *shell_res)
+{
+       struct ivi_compositor *ivi = wl_resource_get_user_data(shell_res);
+       struct ivi_output *output;
+       struct ivi_surface *surface, *tmp;
+
+       /* Init already finished. Do nothing */
+       if (ivi->shell_client.ready)
+               return;
+
+       ivi->shell_client.ready = true;
+       /* TODO: Create a black screen and remove it here */
+
+       wl_list_for_each(output, &ivi->outputs, link) {
+               struct weston_desktop_surface *dsurf;
+               struct weston_geometry geom;
+
+               output->area.x = 0;
+               output->area.y = 0;
+               output->area.width = output->output->width;
+               output->area.height = output->output->height;
+
+               if (output->top) {
+                       dsurf = output->top->dsurface;
+                       geom = weston_desktop_surface_get_geometry(dsurf);
+
+                       output->area.y += geom.height;
+                       output->area.height -= geom.height;
+               }
+               if (output->bottom) {
+                       dsurf = output->bottom->dsurface;
+                       geom = weston_desktop_surface_get_geometry(dsurf);
+
+                       output->area.height -= geom.height;
+               }
+               if (output->left) {
+                       dsurf = output->left->dsurface;
+                       geom = weston_desktop_surface_get_geometry(dsurf);
+
+                       output->area.x += geom.width;
+                       output->area.width -= geom.width;
+               }
+               if (output->right) {
+                       dsurf = output->right->dsurface;
+                       geom = weston_desktop_surface_get_geometry(dsurf);
+
+                       output->area.width -= geom.width;
+               }
+
+               weston_log("Usable area: %dx%d+%d,%d\n",
+                          output->area.width, output->area.height,
+                          output->area.x, output->area.y);
+       }
+
+       wl_list_for_each_safe(surface, tmp, &ivi->pending_surfaces, link) {
+               wl_list_remove(&surface->link);
+               ivi_set_desktop_surface(surface);
+       }
+}
+
+static void
+shell_set_background(struct wl_client *client,
+                    struct wl_resource *shell_res,
+                    struct wl_resource *surface_res,
+                    struct wl_resource *output_res)
+{
+       struct weston_head *head = weston_head_from_resource(output_res);
+       struct weston_output *woutput = weston_head_get_output(head);
+       struct ivi_output *output = to_ivi_output(woutput);
+       struct weston_surface *wsurface = wl_resource_get_user_data(surface_res);
+       struct weston_desktop_surface *dsurface;
+       struct ivi_surface *surface;
+
+       dsurface = weston_surface_get_desktop_surface(wsurface);
+       if (!dsurface) {
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_INVALID_ARGUMENT,
+                                      "surface must be a desktop surface");
+               return;
+       }
+
+       surface = weston_desktop_surface_get_user_data(dsurface);
+       if (surface->role != IVI_SURFACE_ROLE_NONE) {
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_INVALID_ARGUMENT,
+                                      "surface already has another ivi role");
+               return;
+       }
+
+       if (output->background) {
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_BACKGROUND_EXISTS,
+                                      "output already has background");
+               return;
+       }
+
+       surface->role = IVI_SURFACE_ROLE_BACKGROUND;
+       surface->bg.output = output;
+       wl_list_remove(&surface->link);
+       wl_list_init(&surface->link);
+
+       output->background = surface;
+
+       weston_desktop_surface_set_maximized(dsurface, true);
+       weston_desktop_surface_set_size(dsurface,
+                                       output->output->width,
+                                       output->output->height);
+}
+
+static void
+shell_set_panel(struct wl_client *client,
+               struct wl_resource *shell_res,
+               struct wl_resource *surface_res,
+               struct wl_resource *output_res,
+               uint32_t edge)
+{
+       struct weston_head *head = weston_head_from_resource(output_res);
+       struct weston_output *woutput = weston_head_get_output(head);
+       struct ivi_output *output = to_ivi_output(woutput);
+       struct weston_surface *wsurface = wl_resource_get_user_data(surface_res);
+       struct weston_desktop_surface *dsurface;
+       struct ivi_surface *surface;
+       struct ivi_surface **member;
+       int32_t width = 0, height = 0;
+
+       dsurface = weston_surface_get_desktop_surface(wsurface);
+       if (!dsurface) {
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_INVALID_ARGUMENT,
+                                      "surface must be a desktop surface");
+               return;
+       }
+
+       surface = weston_desktop_surface_get_user_data(dsurface);
+       if (surface->role != IVI_SURFACE_ROLE_NONE) {
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_INVALID_ARGUMENT,
+                                      "surface already has another ivi role");
+               return;
+       }
+
+       switch (edge) {
+       case AGL_SHELL_EDGE_TOP:
+               member = &output->top;
+               break;
+       case AGL_SHELL_EDGE_BOTTOM:
+               member = &output->bottom;
+               break;
+       case AGL_SHELL_EDGE_LEFT:
+               member = &output->left;
+               break;
+       case AGL_SHELL_EDGE_RIGHT:
+               member = &output->right;
+               break;
+       default:
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_INVALID_ARGUMENT,
+                                      "invalid edge for panel");
+               return;
+       }
+
+       if (*member) {
+               wl_resource_post_error(shell_res,
+                                      AGL_SHELL_ERROR_BACKGROUND_EXISTS,
+                                      "output already has panel on this edge");
+               return;
+       }
+
+       surface->role = IVI_SURFACE_ROLE_PANEL;
+       surface->panel.output = output;
+       surface->panel.edge = edge;
+       wl_list_remove(&surface->link);
+       wl_list_init(&surface->link);
+
+       *member = surface;
+
+       switch (surface->panel.edge) {
+       case AGL_SHELL_EDGE_TOP:
+       case AGL_SHELL_EDGE_BOTTOM:
+               width = woutput->width;
+               break;
+       case AGL_SHELL_EDGE_LEFT:
+       case AGL_SHELL_EDGE_RIGHT:
+               height = woutput->height;
+               break;
+       }
+
+       weston_desktop_surface_set_size(dsurface, width, height);
+}
+
+static const struct agl_shell_interface agl_shell_implementation = {
+       .ready = shell_ready,
+       .set_background = shell_set_background,
+       .set_panel = shell_set_panel,
+};
+
+static void
+unbind_agl_shell(struct wl_resource *resource)
+{
+}
+
+static void
+bind_agl_shell(struct wl_client *client,
+              void *data, uint32_t version, uint32_t id)
+{
+       struct ivi_compositor *ivi = data;
+       struct wl_resource *resource;
+
+       resource = wl_resource_create(client, &agl_shell_interface,
+                                     1, id);
+       if (!resource) {
+               wl_client_post_no_memory(client);
+               return;
+       }
+
+#if 0
+       if (ivi->shell_client.client != client) {
+               wl_resource_post_error(resource, WL_DISPLAY_ERROR_INVALID_OBJECT,
+                                      "client not authorized to use agl_shell");
+               return;
+       }
+#endif
+
+       if (ivi->shell_client.resource) {
+               wl_resource_post_error(resource, WL_DISPLAY_ERROR_INVALID_OBJECT,
+                                      "agl_shell has already been bound");
+               return;
+       }
+
+       wl_resource_set_implementation(resource, &agl_shell_implementation,
+                                      ivi, unbind_agl_shell);
+       ivi->shell_client.resource = resource;
+}
+
+int
+ivi_shell_create_global(struct ivi_compositor *ivi)
+{
+       ivi->agl_shell = wl_global_create(ivi->compositor->wl_display,
+                                         &agl_shell_interface, 1,
+                                         ivi, bind_agl_shell);
+       if (!ivi->agl_shell) {
+               weston_log("Failed to create wayland global.\n");
+               return -1;
+       }
+
+       return 0;
+}