summaryrefslogtreecommitdiffstats
path: root/src/VBox/Additions/x11/VBoxClient/display.cpp
blob: 3edbfd3106d88121cebe93d97ae26bee5f6fd2f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/* $Id: display.cpp $ */
/** @file
 * X11 guest client - display management.
 */

/*
 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "VBoxClient.h"

#include <iprt/errcore.h>
#include <iprt/file.h>
#include <iprt/mem.h>
#include <iprt/string.h>
#include <iprt/asm.h>

#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xrandr.h>

/** @todo this should probably be replaced by something IPRT */
/* For system() and WEXITSTATUS() */
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <limits.h>
#include <poll.h>
#include <time.h>
#include <dlfcn.h>

/* TESTING: Dynamic resizing and mouse integration toggling should work
 * correctly with a range of X servers (pre-1.3, 1.3 and later under Linux, 1.3
 * and later under Solaris) with Guest Additions installed.  Switching to a
 * virtual terminal while a user session is in place should disable dynamic
 * resizing and cursor integration, switching back should re-enable them. */

/** State information needed for the service.  The main VBoxClient code provides
 *  the daemon logic needed by all services. */
struct DISPLAYSTATE
{
    /** Are we initialised yet? */
    bool mfInit;
    /** The connection to the server. */
    Display *pDisplay;
    /** The RandR extension base event number. */
    int cRREventBase;
    /** Can we use version 1.2 or later of the RandR protocol here? */
    bool fHaveRandR12;
    /** The command argument to use for the xrandr binary.  Currently only
     * used to support the non-standard location on some Solaris systems -
     * would it make sense to use absolute paths on all systems? */
    const char *pcszXrandr;
    /** Was there a recent mode hint with no following root window resize, and
     *  if so, have we waited for a reasonable time? */
    time_t timeLastModeHint;
    /** Handle to libXrandr. */
    void *pRandLibraryHandle;
    /** Handle to pXRRSelectInput. */
    void (*pXRRSelectInput) (Display *, Window, int);
    /** Handle to pXRRQueryExtension. */
    Bool (*pXRRQueryExtension) (Display *, int *, int *);
};

static struct DISPLAYSTATE g_DisplayState;

static unsigned char *getRootProperty(struct DISPLAYSTATE *pState, const char *pszName,
                                      long cItems, Atom type)
{
    Atom actualType = None;
    int iFormat = 0;
    unsigned long cReturned = 0;
    unsigned long cAfter = 0;
    unsigned char *pData = 0;

    if (XGetWindowProperty(pState->pDisplay, DefaultRootWindow(pState->pDisplay),
                           XInternAtom(pState->pDisplay, pszName, 0), 0, cItems,
                           False /* delete */, type, &actualType, &iFormat,
                           &cReturned, &cAfter, &pData))
        return NULL;
    return pData;
}

static void doResize(struct DISPLAYSTATE *pState)
{
    /** @note The xrandr command can fail if something else accesses RandR at
     *  the same time.  We just ignore failure for now as we do not know what
     *  someone else is doing. */
    if (!pState->fHaveRandR12)
    {
        char szCommand[256];
        unsigned char *pData;

        pData = getRootProperty(pState, "VBOXVIDEO_PREFERRED_MODE", 1, XA_INTEGER);
        if (pData != NULL)
        {
            RTStrPrintf(szCommand, sizeof(szCommand), "%s -s %ux%u",
                        pState->pcszXrandr, ((unsigned long *)pData)[0] >> 16, ((unsigned long *)pData)[0] & 0xFFFF);
            int rcShutUpGcc = system(szCommand); RT_NOREF_PV(rcShutUpGcc);
            XFree(pData);
        }
    }
    else
    {
        const char szCommandBase[] =
            "%s --output VGA-0 --auto --output VGA-1 --auto --right-of VGA-0 "
               "--output VGA-2 --auto --right-of VGA-1 --output VGA-3 --auto --right-of VGA-2 "
               "--output VGA-4 --auto --right-of VGA-3 --output VGA-5 --auto --right-of VGA-4 "
               "--output VGA-6 --auto --right-of VGA-5 --output VGA-7 --auto --right-of VGA-6 "
               "--output VGA-8 --auto --right-of VGA-7 --output VGA-9 --auto --right-of VGA-8 "
               "--output VGA-10 --auto --right-of VGA-9 --output VGA-11 --auto --right-of VGA-10 "
               "--output VGA-12 --auto --right-of VGA-11 --output VGA-13 --auto --right-of VGA-12 "
               "--output VGA-14 --auto --right-of VGA-13 --output VGA-15 --auto --right-of VGA-14 "
               "--output VGA-16 --auto --right-of VGA-15 --output VGA-17 --auto --right-of VGA-16 "
               "--output VGA-18 --auto --right-of VGA-17 --output VGA-19 --auto --right-of VGA-18 "
               "--output VGA-20 --auto --right-of VGA-19 --output VGA-21 --auto --right-of VGA-20 "
               "--output VGA-22 --auto --right-of VGA-21 --output VGA-23 --auto --right-of VGA-22 "
               "--output VGA-24 --auto --right-of VGA-23 --output VGA-25 --auto --right-of VGA-24 "
               "--output VGA-26 --auto --right-of VGA-25 --output VGA-27 --auto --right-of VGA-26 "
               "--output VGA-28 --auto --right-of VGA-27 --output VGA-29 --auto --right-of VGA-28 "
               "--output VGA-30 --auto --right-of VGA-29 --output VGA-31 --auto --right-of VGA-30";
        char szCommand[sizeof(szCommandBase) + 256];
        RTStrPrintf(szCommand, sizeof(szCommand), szCommandBase, pState->pcszXrandr);
        int rcShutUpGcc = system(szCommand); RT_NOREF_PV(rcShutUpGcc);
    }
}

/** Main loop: handle display hot-plug events, property updates (which can
 *  signal VT switches hot-plug in old X servers). */
static void runDisplay(struct DISPLAYSTATE *pState, bool volatile *pfShutdown)
{
    Display *pDisplay = pState->pDisplay;
    long cValue = 1;

    /* One way or another we want the preferred mode at server start-up. */
    doResize(pState);
    XSelectInput(pDisplay, DefaultRootWindow(pDisplay), PropertyChangeMask | StructureNotifyMask);
    if (pState->fHaveRandR12)
        pState->pXRRSelectInput(pDisplay, DefaultRootWindow(pDisplay), RRScreenChangeNotifyMask);
    /* Semantics: when VBOXCLIENT_STARTED is set, pre-1.3 X.Org Server driver
     * assumes that a client capable of handling mode hints will be present for the
     * rest of the X session.  If we crash things will not work as they should.
     * I thought that preferable to implementing complex crash-handling logic.
     */
    XChangeProperty(pState->pDisplay, DefaultRootWindow(pState->pDisplay), XInternAtom(pState->pDisplay, "VBOXCLIENT_STARTED", 0),
                    XA_INTEGER, 32, PropModeReplace, (unsigned char *)&cValue, 1);
    /* Interrupting this cleanly will be more work than making it robust
     * against spontaneous termination, especially as it will never get
     * properly tested, so I will go for the second. */
    while (!ASMAtomicReadBool(pfShutdown))
    {
        XEvent event;
        struct pollfd PollFd;
        int pollTimeOut = -1;
        int cFds;

        /* Do not handle overflow. */
        if (pState->timeLastModeHint > 0 && pState->timeLastModeHint < INT_MAX - 2)
            pollTimeOut = 2 - (time(0) - pState->timeLastModeHint);
        PollFd.fd = ConnectionNumber(pDisplay);
        PollFd.events = POLLIN;  /* Hang-up is always reported. */
        XFlush(pDisplay);
        cFds = poll(&PollFd, 1, pollTimeOut >= 0 ? pollTimeOut * 1000 : -1);
        while (XPending(pDisplay))
        {
            XNextEvent(pDisplay, &event);
            /* This property is deleted when the server regains the virtual
             * terminal.  Force the main thread to call xrandr again, as old X
             * servers could not handle it while switched out. */
            if (   !pState->fHaveRandR12
                && event.type == PropertyNotify
                && event.xproperty.state == PropertyDelete
                && event.xproperty.window == DefaultRootWindow(pDisplay)
                && event.xproperty.atom == XInternAtom(pDisplay, "VBOXVIDEO_NO_VT", False))
                doResize(pState);
            if (   !pState->fHaveRandR12
                && event.type == PropertyNotify
                && event.xproperty.state == PropertyNewValue
                && event.xproperty.window == DefaultRootWindow(pDisplay)
                && event.xproperty.atom == XInternAtom(pDisplay, "VBOXVIDEO_PREFERRED_MODE", False))
                doResize(pState);
            if (   pState->fHaveRandR12
                && event.type == pState->cRREventBase + RRScreenChangeNotify)
                pState->timeLastModeHint = time(0);
            if (   event.type == ConfigureNotify
                && event.xproperty.window == DefaultRootWindow(pDisplay))
                pState->timeLastModeHint = 0;
        }
        if (cFds == 0 && pState->timeLastModeHint > 0)
            doResize(pState);
    }
}

static int initDisplay(struct DISPLAYSTATE *pState)
{
    char szCommand[256];
    int status;

    pState->pRandLibraryHandle = dlopen("libXrandr.so", RTLD_LAZY /*| RTLD_LOCAL */);
    if (!pState->pRandLibraryHandle)
        pState->pRandLibraryHandle = dlopen("libXrandr.so.2", RTLD_LAZY /*| RTLD_LOCAL */);
    if (!pState->pRandLibraryHandle)
        pState->pRandLibraryHandle = dlopen("libXrandr.so.2.2.0", RTLD_LAZY /*| RTLD_LOCAL */);

    if (!RT_VALID_PTR(pState->pRandLibraryHandle))
    {
        VBClLogFatalError("Could not locate libXrandr for dlopen\n");
        return VERR_NOT_FOUND;
    }

    *(void **)(&pState->pXRRSelectInput) = dlsym(pState->pRandLibraryHandle, "XRRSelectInput");
    *(void **)(&pState->pXRRQueryExtension) = dlsym(pState->pRandLibraryHandle, "XRRQueryExtension");

    if (   !RT_VALID_PTR(pState->pXRRSelectInput)
        || !RT_VALID_PTR(pState->pXRRQueryExtension))
    {
        VBClLogFatalError("Could not load required libXrandr symbols\n");
        dlclose(pState->pRandLibraryHandle);
        pState->pRandLibraryHandle = NULL;
        return VERR_NOT_FOUND;
    }

    pState->pDisplay = XOpenDisplay(NULL);
    if (!pState->pDisplay)
        return VERR_NOT_FOUND;
    if (!pState->pXRRQueryExtension(pState->pDisplay, &pState->cRREventBase, &status))
        return VERR_NOT_FOUND;
    pState->fHaveRandR12 = false;
    pState->pcszXrandr = "xrandr";
    if (RTFileExists("/usr/X11/bin/xrandr"))
        pState->pcszXrandr = "/usr/X11/bin/xrandr";
    status = system(pState->pcszXrandr);
    if (WEXITSTATUS(status) != 0)  /* Utility or extension not available. */
        VBClLogFatalError("Failed to execute the xrandr utility\n");
    RTStrPrintf(szCommand, sizeof(szCommand), "%s --q12", pState->pcszXrandr);
    status = system(szCommand);
    if (WEXITSTATUS(status) == 0)
        pState->fHaveRandR12 = true;
    return VINF_SUCCESS;
}

/**
 * @interface_method_impl{VBCLSERVICE,pfnInit}
 */
static DECLCALLBACK(int) init(void)
{
    struct DISPLAYSTATE *pSelf = &g_DisplayState;
    int rc;

    if (pSelf->mfInit)
        return VERR_WRONG_ORDER;
    rc = initDisplay(pSelf);
    if (RT_FAILURE(rc))
        return rc;
    if (RT_SUCCESS(rc))
        pSelf->mfInit = true;
    return rc;
}

/**
 * @interface_method_impl{VBCLSERVICE,pfnWorker}
 */
static DECLCALLBACK(int) run(bool volatile *pfShutdown)
{
    struct DISPLAYSTATE *pSelf = &g_DisplayState;

    if (!pSelf->mfInit)
        return VERR_WRONG_ORDER;

    runDisplay(pSelf, pfShutdown);

    return VINF_SUCCESS;
}

/**
 * @interface_method_impl{VBCLSERVICE,pfnStop}
 */
static DECLCALLBACK(void) stop(void)
{
    /* Nothing to do here. Implement empty callback, so
     * main thread can set pfShutdown=true on process termination. */
}

VBCLSERVICE g_SvcDisplayLegacy =
{
    "dp-legacy-x11",                    /* szName */
    "Legacy display assistant",         /* pszDescription */
    ".vboxclient-display",              /* pszPidFilePathTemplate */
    NULL,                               /* pszUsage */
    NULL,                               /* pszOptions */
    NULL,                               /* pfnOption */
    init,                               /* pfnInit */
    run,                                /* pfnWorker */
    stop,                               /* pfnStop */
    NULL,                               /* pfnTerm */
};