aboutsummaryrefslogtreecommitdiffstats
path: root/unix/common/randr.cxx
blob: e4e2d7bed0fc15c1780085e66a58fbbf7c39a1ae (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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/* Copyright (C) 2002-2005 RealVNC Ltd.  All Rights Reserved.
 * Copyright 2009-2017 Pierre Ossman for Cendio AB
 * Copyright 2018 Peter Astrand <astrand@cendio.se> for Cendio AB
 * Copyright 2014 Brian P. Hinz
 * 
 * This 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; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This software 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 software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
 * USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>

#include <unixcommon.h>
#include <rfb/screenTypes.h>
#include <rfb/LogWriter.h>
#include <RandrGlue.h>
static rfb::LogWriter vlog("RandR");

static int ResizeScreen(bool dryrun, int fb_width, int fb_height,
                        std::set<unsigned int>* disabledOutputs)
{
  vlog.debug("Resizing screen framebuffer to %dx%d", fb_width, fb_height);

  /*
   * Disable outputs which are larger than the target size
   */
  for (int i = 0;i < vncRandRGetOutputCount();i++) {
    int x, y, width, height;
    if (vncRandRGetOutputDimensions(i, &x, &y, &width, &height) == 0) {
      if (x + width > fb_width || y + height > fb_height) {
        char *name = vncRandRGetOutputName(i);
        vlog.debug("Temporarily disabling output '%s'", name);
        free(name);
        if (!dryrun) {
          /* Currently ignoring errors */
          /* FIXME: Save output rotation and restore when configuring output */
          vncRandRDisableOutput(i);
          disabledOutputs->insert(vncRandRGetOutputId(i));
        }
      }
    }
  }

  if (!vncRandRIsValidScreenSize(fb_width, fb_height))
    return 0;

  if (dryrun)
    return 1;

  return vncRandRResizeScreen(fb_width, fb_height);
}


/* Return output index of preferred output, -1 on failure */
int getPreferredScreenOutput(OutputIdMap *outputIdMap,
                             const std::set<unsigned int>& disabledOutputs)
{
  int firstDisabled = -1;
  int firstEnabled = -1;
  int firstConnected = -1;
  int firstUsable = -1;

  for (int i = 0;i < vncRandRGetOutputCount();i++) {
    unsigned int output = vncRandRGetOutputId(i);

    /* In use? */
    if (outputIdMap->count(output) == 1) {
      continue;
    }

    /* Can it be used? */
    if (!vncRandRIsOutputUsable(i)) {
      continue;
    }

    /* Temporarily disabled? */
    if (disabledOutputs.count(output)) {
      if (firstDisabled == -1) firstDisabled = i;
    }

    /* Enabled? */
    if (vncRandRIsOutputEnabled(i)) {
      if (firstEnabled == -1) firstEnabled = i;
    }

    /* Connected? */
    if (vncRandRIsOutputConnected(i)) {
      if (firstConnected == -1) firstConnected = i;
    }

    if (firstUsable == -1) firstUsable = i;
  }

  if (firstEnabled != -1) {
    return firstEnabled;
  } else if (firstDisabled != -1) {
    return firstDisabled;
  } else if (firstConnected != -1) {
    return firstConnected;
  } else {
    return firstUsable; /* Possibly -1 */
  }
}


rfb::ScreenSet computeScreenLayout(OutputIdMap *outputIdMap)
{
  rfb::ScreenSet layout;
  OutputIdMap newIdMap;

  for (int i = 0;i < vncRandRGetOutputCount();i++) {
    unsigned int outputId;
    int x, y, width, height;

    /* Disabled? */
    if (!vncRandRIsOutputEnabled(i))
      continue;

    outputId = vncRandRGetOutputId(i);

    /* Known output? */
    if (outputIdMap->count(outputId) == 1)
      newIdMap[outputId] = (*outputIdMap)[outputId];
    else {
      uint32_t id;
      OutputIdMap::const_iterator iter;

      while (true) {
        id = rand();
        for (iter = outputIdMap->begin();iter != outputIdMap->end();++iter) {
          if (iter->second == id)
            break;
        }
        if (iter == outputIdMap->end())
          break;
      }

      newIdMap[outputId] = id;
    }

    if (vncRandRGetOutputDimensions(i, &x, &y, &width, &height) == 0) {
      layout.add_screen(rfb::Screen(newIdMap[outputId], x, y, width, height, 0));
    }
  }

  /* Only keep the entries that are currently active */
  *outputIdMap = newIdMap;

  /*
   * Make sure we have something to display. Hopefully it's just temporary
   * that we have no active outputs...
   */
  if (layout.num_screens() == 0)
    layout.add_screen(rfb::Screen(0, 0, 0, vncGetScreenWidth(),
                                  vncGetScreenHeight(), 0));

  return layout;
}

static unsigned int _setScreenLayout(bool dryrun,
                                     int fb_width, int fb_height, const rfb::ScreenSet& layout,
                                     OutputIdMap *outputIdMap)
{
  int ret;
  int availableOutputs;
  std::set<unsigned int> disabledOutputs;
  /* Printing errors in the dryrun pass might be confusing */
  const bool logErrors = !dryrun || vlog.getLevel() >= vlog.LEVEL_DEBUG;

  // RandR support?
  if (vncRandRGetOutputCount() == 0)
    return rfb::resultProhibited;

  /*
   * First check that we don't have any active clone modes. That's just
   * too messy to deal with.
   */
  if (vncRandRHasOutputClones()) {
    if (logErrors) {
      vlog.error("Clone mode active. Refusing to touch screen layout.");
    }
    return rfb::resultInvalid;
  }

  /* Next count how many useful outputs we have... */
  availableOutputs = vncRandRGetAvailableOutputs();

  /* Try to create more outputs if needed... (only works on Xvnc) */
  if (layout.num_screens() > availableOutputs) {
    vlog.debug("Insufficient screens. Need to create %d more.",
               layout.num_screens() - availableOutputs);

    if (!vncRandRCanCreateOutputs(layout.num_screens() - availableOutputs)) {
      if (logErrors)
        vlog.error("Unable to create more screens, as needed by the new client layout.");
      return rfb::resultInvalid;
    }

    if (!dryrun) {
      ret = vncRandRCreateOutputs(layout.num_screens() - availableOutputs);
      if (!ret) {
        if (logErrors)
          vlog.error("Unable to create more screens, as needed by the new client layout.");
        return rfb::resultInvalid;
      }
    }
  }

  /* First we might need to resize the screen */
  if ((fb_width != vncGetScreenWidth()) ||
      (fb_height != vncGetScreenHeight())) {
    ret = ResizeScreen(dryrun, fb_width, fb_height, &disabledOutputs);
    if (!ret) {
      if (logErrors) {
        vlog.error("Failed to resize screen to %dx%d", fb_width, fb_height);
      }
      return rfb::resultInvalid;
    }
  }

  /* Next, reconfigure all known outputs */
  for (int i = 0;i < vncRandRGetOutputCount();i++) {
    unsigned int output;
    char *name_;
    std::string name;

    rfb::ScreenSet::const_iterator iter;

    output = vncRandRGetOutputId(i);
    name = name_ = vncRandRGetOutputName(i);
    free(name_);

    /* Known? */
    if (outputIdMap->count(output) == 0)
      continue;

    /* Find the corresponding screen... */
    for (iter = layout.begin();iter != layout.end();++iter) {
      if (iter->id == (*outputIdMap)[output])
        break;
    }

    /* Missing? */
    if (iter == layout.end()) {
      outputIdMap->erase(output);
      continue;
    }

    /* Probably not needed, but let's be safe */
    if (!vncRandRIsOutputUsable(i)) {
      if (logErrors)
        vlog.error("Required output '%s' cannot be used", name.c_str());
      return rfb::resultInvalid;
    }

    /* Possible mode? */
    if (!vncRandRCheckOutputMode(i, iter->dimensions.width(),
                                 iter->dimensions.height())) {
      if (logErrors)
        vlog.error("Output '%s' does not support required mode %dx%d",
                   name.c_str(),
                   iter->dimensions.width(), iter->dimensions.height());
      return rfb::resultInvalid;
    }

    vlog.debug("Reconfiguring output '%s' to %dx%d+%d+%d", name.c_str(),
               iter->dimensions.width(), iter->dimensions.height(),
               iter->dimensions.tl.x, iter->dimensions.tl.y);

    if (dryrun)
      continue;

    /* Reconfigure new mode and position */
    ret = vncRandRReconfigureOutput(i,
                                    iter->dimensions.tl.x,
                                    iter->dimensions.tl.y,
                                    iter->dimensions.width(),
                                    iter->dimensions.height());
    if (!ret) {
      if (logErrors)
        vlog.error("Failed to reconfigure output '%s' to %dx%d+%d+%d",
                   name.c_str(),
                   iter->dimensions.width(), iter->dimensions.height(),
                   iter->dimensions.tl.x, iter->dimensions.tl.y);
      return rfb::resultInvalid;
    }
  }

  /* Allocate new outputs for new screens */
  rfb::ScreenSet::const_iterator iter;
  for (iter = layout.begin();iter != layout.end();++iter) {
    OutputIdMap::const_iterator oi;
    unsigned int output;
    char *name_;
    std::string name;
    int i;

    /* Does this screen have an output already? */
    for (oi = outputIdMap->begin();oi != outputIdMap->end();++oi) {
      if (oi->second == iter->id)
        break;
    }

    if (oi != outputIdMap->end())
      continue;

    /* Find an unused output */
    i = getPreferredScreenOutput(outputIdMap, disabledOutputs);

    /* Shouldn't happen */
    if (i == -1) {
      if (logErrors)
        vlog.error("Cannot find an available output for new screen layout");
      return rfb::resultInvalid;
    }
    output = vncRandRGetOutputId(i);
    name = name_ = vncRandRGetOutputName(i);
    free(name_);

    /*
     * Make sure we already have an entry for this, or
     * computeScreenLayout() will think it is a brand new output and
     * assign it a random id.
     */
    (*outputIdMap)[output] = iter->id;

    /* Probably not needed, but let's be safe */
    if (!vncRandRIsOutputUsable(i)) {
      if (logErrors)
        vlog.error("Required new output '%s' cannot be used", name.c_str());
      return rfb::resultInvalid;
    }

    /* Possible mode? */
    if (!vncRandRCheckOutputMode(i, iter->dimensions.width(),
                                 iter->dimensions.height())) {
      if (logErrors)
        vlog.error("New output '%s' does not support required mode %dx%d",
                   name.c_str(),
                   iter->dimensions.width(), iter->dimensions.height());
      return rfb::resultInvalid;
    }

    vlog.debug("Reconfiguring new output '%s' to %dx%d+%d+%d", name.c_str(),
               iter->dimensions.width(), iter->dimensions.height(),
               iter->dimensions.tl.x, iter->dimensions.tl.y);

    if (dryrun)
      continue;

    /* Reconfigure new mode and position */
    ret = vncRandRReconfigureOutput(i,
                                    iter->dimensions.tl.x,
                                    iter->dimensions.tl.y,
                                    iter->dimensions.width(),
                                    iter->dimensions.height());
    if (!ret) {
      if (logErrors)
        vlog.error("Failed to reconfigure new output '%s' to %dx%d+%d+%d",
                   name.c_str(),
                   iter->dimensions.width(), iter->dimensions.height(),
                   iter->dimensions.tl.x, iter->dimensions.tl.y);
      return rfb::resultInvalid;
    }
  }

  /* Turn off unused outputs */
  for (int i = 0;i < vncRandRGetOutputCount();i++) {
    unsigned int output = vncRandRGetOutputId(i);

    /* Known? */
    if (outputIdMap->count(output) == 1)
      continue;

    /* Enabled? */
    if (!vncRandRIsOutputEnabled(i))
      continue;

    /* Disable and move on... */
    ret = vncRandRDisableOutput(i);
    char *name = vncRandRGetOutputName(i);
    if (ret) {
      vlog.debug("Disabled unused output '%s'", name);
    } else {
      if (logErrors) {
        vlog.error("Failed to disable unused output '%s'", name);
      }
      free(name);
      return rfb::resultInvalid;
    }
    free(name);
  }

  /*
   * Update timestamp for when screen layout was last changed.
   * This is normally done in the X11 request handlers, which is
   * why we have to deal with it manually here.
   */
  vncRandRUpdateSetTime();

  return rfb::resultSuccess;
}


unsigned int setScreenLayout(int fb_width, int fb_height, const rfb::ScreenSet& layout,
                             OutputIdMap *outputIdMap)
{
    return _setScreenLayout(false, fb_width, fb_height, layout, outputIdMap);
}


unsigned int tryScreenLayout(int fb_width, int fb_height, const rfb::ScreenSet& layout,
                             OutputIdMap *outputIdMap)
{
    OutputIdMap dryrunIdMap = *outputIdMap;
    return _setScreenLayout(true, fb_width, fb_height, layout, &dryrunIdMap);
}