blob: 2c91e3f4c5ef1c15616802503a289a399c148176 [file] [log] [blame]
Constantin Kaplinsky729598c2006-05-25 05:12:25 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossman66f1db52019-05-02 12:32:03 +02002 * Copyright 2011-2019 Pierre Ossman for Cendio AB
Constantin Kaplinsky729598c2006-05-25 05:12:25 +00003 *
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 * USA.
18 */
19
20// -=- SDisplay.cxx
21//
22// The SDisplay class encapsulates a particular system display.
23
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +020024#include <assert.h>
25
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000026#include <rfb_win32/SDisplay.h>
27#include <rfb_win32/Service.h>
28#include <rfb_win32/TsSessions.h>
29#include <rfb_win32/CleanDesktop.h>
30#include <rfb_win32/CurrentUser.h>
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000031#include <rfb_win32/MonitorInfo.h>
32#include <rfb_win32/SDisplayCorePolling.h>
33#include <rfb_win32/SDisplayCoreWMHooks.h>
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000034#include <rfb/Exception.h>
35#include <rfb/LogWriter.h>
Rahul Kalec719e4a2017-07-13 00:36:02 +020036#include <rfb/ledStates.h>
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000037
38
39using namespace rdr;
40using namespace rfb;
41using namespace rfb::win32;
42
43static LogWriter vlog("SDisplay");
44
45// - SDisplay-specific configuration options
46
47IntParameter rfb::win32::SDisplay::updateMethod("UpdateMethod",
48 "How to discover desktop updates; 0 - Polling, 1 - Application hooking, 2 - Driver hooking.", 1);
49BoolParameter rfb::win32::SDisplay::disableLocalInputs("DisableLocalInputs",
50 "Disable local keyboard and pointer input while the server is in use", false);
51StringParameter rfb::win32::SDisplay::disconnectAction("DisconnectAction",
52 "Action to perform when all clients have disconnected. (None, Lock, Logoff)", "None");
53StringParameter displayDevice("DisplayDevice",
54 "Display device name of the monitor to be remoted, or empty to export the whole desktop.", "");
55BoolParameter rfb::win32::SDisplay::removeWallpaper("RemoveWallpaper",
56 "Remove the desktop wallpaper when the server is in use.", false);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000057BoolParameter rfb::win32::SDisplay::disableEffects("DisableEffects",
58 "Disable desktop user interface effects when the server is in use.", false);
59
60
61//////////////////////////////////////////////////////////////////////////////
62//
63// SDisplay
64//
65
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000066// -=- Constructor/Destructor
67
68SDisplay::SDisplay()
69 : server(0), pb(0), device(0),
70 core(0), ptr(0), kbd(0), clipboard(0),
71 inputs(0), monitor(0), cleanDesktop(0), cursor(0),
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +020072 statusLocation(0), queryConnectionHandler(0), ledState(0)
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000073{
74 updateEvent.h = CreateEvent(0, TRUE, FALSE, 0);
Pierre Ossman10688ef2018-09-29 11:24:19 +020075 terminateEvent.h = CreateEvent(0, TRUE, FALSE, 0);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000076}
77
78SDisplay::~SDisplay()
79{
80 // XXX when the VNCServer has been deleted with clients active, stop()
81 // doesn't get called - this ought to be fixed in VNCServerST. In any event,
82 // we should never call any methods on VNCServer once we're being deleted.
83 // This is because it is supposed to be guaranteed that the SDesktop exists
84 // throughout the lifetime of the VNCServer. So if we're being deleted, then
85 // the VNCServer ought not to exist and therefore we shouldn't invoke any
86 // methods on it. Setting server to zero here ensures that stop() doesn't
87 // call setPixelBuffer(0) on the server.
88 server = 0;
89 if (core) stop();
90}
91
92
93// -=- SDesktop interface
94
95void SDisplay::start(VNCServer* vs)
96{
97 vlog.debug("starting");
98
99 // Try to make session zero the console session
100 if (!inConsoleSession())
101 setConsoleSession();
102
103 // Start the SDisplay core
104 server = vs;
105 startCore();
106
107 vlog.debug("started");
108
109 if (statusLocation) *statusLocation = true;
110}
111
112void SDisplay::stop()
113{
114 vlog.debug("stopping");
115
116 // If we successfully start()ed then perform the DisconnectAction
117 if (core) {
118 CurrentUserToken cut;
Peter Åstrandb22dbef2008-12-09 14:57:53 +0000119 CharArray action(disconnectAction.getData());
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000120 if (stricmp(action.buf, "Logoff") == 0) {
121 if (!cut.h)
122 vlog.info("ignoring DisconnectAction=Logoff - no current user");
123 else
124 ExitWindowsEx(EWX_LOGOFF, 0);
125 } else if (stricmp(action.buf, "Lock") == 0) {
126 if (!cut.h) {
127 vlog.info("ignoring DisconnectAction=Lock - no current user");
128 } else {
Pierre Ossmanfc08bee2016-01-12 12:32:15 +0100129 LockWorkStation();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000130 }
131 }
132 }
133
134 // Stop the SDisplayCore
135 if (server)
136 server->setPixelBuffer(0);
137 stopCore();
138 server = 0;
139
140 vlog.debug("stopped");
141
142 if (statusLocation) *statusLocation = false;
143}
144
Pierre Ossman10688ef2018-09-29 11:24:19 +0200145void SDisplay::terminate()
146{
147 SetEvent(terminateEvent);
148}
149
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000150
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +0200151void SDisplay::queryConnection(network::Socket* sock,
152 const char* userName)
153{
154 assert(server != NULL);
155
156 if (queryConnectionHandler) {
157 queryConnectionHandler->queryConnection(sock, userName);
158 return;
159 }
160
161 server->approveConnection(sock, true);
162}
163
164
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000165void SDisplay::startCore() {
166
167 // Currently, we just check whether we're in the console session, and
168 // fail if not
169 if (!inConsoleSession())
170 throw rdr::Exception("Console is not session zero - oreconnect to restore Console sessin");
171
172 // Switch to the current input desktop
173 if (rfb::win32::desktopChangeRequired()) {
174 if (!rfb::win32::changeDesktop())
175 throw rdr::Exception("unable to switch into input desktop");
176 }
177
178 // Initialise the change tracker and clipper
179 updates.clear();
180 clipper.setUpdateTracker(server);
181
182 // Create the framebuffer object
183 recreatePixelBuffer(true);
184
185 // Create the SDisplayCore
186 updateMethod_ = updateMethod;
187 int tryMethod = updateMethod_;
188 while (!core) {
189 try {
Pierre Ossman4ab1e5d2016-01-12 12:29:32 +0100190 if (tryMethod == 1)
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000191 core = new SDisplayCoreWMHooks(this, &updates);
192 else
193 core = new SDisplayCorePolling(this, &updates);
194 core->setScreenRect(screenRect);
195 } catch (rdr::Exception& e) {
196 delete core; core = 0;
197 if (tryMethod == 0)
198 throw rdr::Exception("unable to access desktop");
199 tryMethod--;
Pierre Ossmanad8609a2012-04-26 09:04:14 +0000200 vlog.error("%s", e.str());
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000201 }
202 }
203 vlog.info("Started %s", core->methodName());
204
205 // Start display monitor, clipboard handler and input handlers
206 monitor = new WMMonitor;
207 monitor->setNotifier(this);
208 clipboard = new Clipboard;
209 clipboard->setNotifier(this);
210 ptr = new SPointer;
211 kbd = new SKeyboard;
212 inputs = new WMBlockInput;
213 cursor = new WMCursor;
214
215 // Apply desktop optimisations
216 cleanDesktop = new CleanDesktop;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000217 if (removeWallpaper)
218 cleanDesktop->disableWallpaper();
219 if (disableEffects)
220 cleanDesktop->disableEffects();
221 isWallpaperRemoved = removeWallpaper;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000222 areEffectsDisabled = disableEffects;
Rahul Kalec719e4a2017-07-13 00:36:02 +0200223
224 checkLedState();
225 if (server)
226 server->setLEDState(ledState);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000227}
228
229void SDisplay::stopCore() {
230 if (core)
231 vlog.info("Stopping %s", core->methodName());
232 delete core; core = 0;
233 delete pb; pb = 0;
234 delete device; device = 0;
235 delete monitor; monitor = 0;
236 delete clipboard; clipboard = 0;
237 delete inputs; inputs = 0;
238 delete ptr; ptr = 0;
239 delete kbd; kbd = 0;
240 delete cleanDesktop; cleanDesktop = 0;
241 delete cursor; cursor = 0;
242 ResetEvent(updateEvent);
243}
244
245
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000246bool SDisplay::isRestartRequired() {
247 // - We must restart the SDesktop if:
248 // 1. We are no longer in the input desktop.
249 // 2. The any setting has changed.
250
251 // - Check that our session is the Console
252 if (!inConsoleSession())
253 return true;
254
255 // - Check that we are in the input desktop
256 if (rfb::win32::desktopChangeRequired())
257 return true;
258
259 // - Check that the update method setting hasn't changed
260 // NB: updateMethod reflects the *selected* update method, not
261 // necessarily the one in use, since we fall back to simpler
262 // methods if more advanced ones fail!
263 if (updateMethod_ != updateMethod)
264 return true;
265
266 // - Check that the desktop optimisation settings haven't changed
267 // This isn't very efficient, but it shouldn't change very often!
268 if ((isWallpaperRemoved != removeWallpaper) ||
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000269 (areEffectsDisabled != disableEffects))
270 return true;
271
272 return false;
273}
274
275
276void SDisplay::restartCore() {
277 vlog.info("restarting");
278
279 // Stop the existing Core related resources
280 stopCore();
281 try {
282 // Start a new Core if possible
283 startCore();
284 vlog.info("restarted");
285 } catch (rdr::Exception& e) {
286 // If startCore() fails then we MUST disconnect all clients,
287 // to cause the server to stop() the desktop.
288 // Otherwise, the SDesktop is in an inconsistent state
289 // and the server will crash.
290 server->closeClients(e.str());
291 }
292}
293
294
295void SDisplay::pointerEvent(const Point& pos, int buttonmask) {
296 if (pb->getRect().contains(pos)) {
297 Point screenPos = pos.translate(screenRect.tl);
298 // - Check that the SDesktop doesn't need restarting
299 if (isRestartRequired())
300 restartCore();
301 if (ptr)
302 ptr->pointerEvent(screenPos, buttonmask);
303 }
304}
305
Pierre Ossman5ae28212017-05-16 14:30:38 +0200306void SDisplay::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000307 // - Check that the SDesktop doesn't need restarting
308 if (isRestartRequired())
309 restartCore();
310 if (kbd)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200311 kbd->keyEvent(keysym, keycode, down);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000312}
313
Rahul Kalec719e4a2017-07-13 00:36:02 +0200314bool SDisplay::checkLedState() {
315 unsigned state = 0;
316
317 if (GetKeyState(VK_SCROLL) & 0x0001)
318 state |= ledScrollLock;
319 if (GetKeyState(VK_NUMLOCK) & 0x0001)
320 state |= ledNumLock;
321 if (GetKeyState(VK_CAPITAL) & 0x0001)
322 state |= ledCapsLock;
323
324 if (ledState != state) {
325 ledState = state;
326 return true;
327 }
328
329 return false;
330}
331
Pierre Ossman66f1db52019-05-02 12:32:03 +0200332void SDisplay::clientCutText(const char* text) {
333 clipboard->setClipText(text);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000334}
335
336
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000337void
Pierre Ossman66f1db52019-05-02 12:32:03 +0200338SDisplay::notifyClipboardChanged(const char* text) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000339 vlog.debug("clipboard text changed");
340 if (server)
Pierre Ossman66f1db52019-05-02 12:32:03 +0200341 server->serverCutText(text);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000342}
343
344
345void
346SDisplay::notifyDisplayEvent(WMMonitor::Notifier::DisplayEventType evt) {
347 switch (evt) {
348 case WMMonitor::Notifier::DisplaySizeChanged:
349 vlog.debug("desktop size changed");
350 recreatePixelBuffer();
351 break;
352 case WMMonitor::Notifier::DisplayPixelFormatChanged:
353 vlog.debug("desktop format changed");
354 recreatePixelBuffer();
355 break;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000356 default:
357 vlog.error("unknown display event received");
358 }
359}
360
361void
362SDisplay::processEvent(HANDLE event) {
363 if (event == updateEvent) {
364 vlog.write(120, "processEvent");
365 ResetEvent(updateEvent);
366
367 // - If the SDisplay isn't even started then quit now
368 if (!core) {
369 vlog.error("not start()ed");
370 return;
371 }
372
373 // - Ensure that the disableLocalInputs flag is respected
374 inputs->blockInputs(disableLocalInputs);
375
376 // - Only process updates if the server is ready
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000377 if (server) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000378 // - Check that the SDesktop doesn't need restarting
379 if (isRestartRequired()) {
380 restartCore();
381 return;
382 }
383
384 // - Flush any updates from the core
385 try {
386 core->flushUpdates();
387 } catch (rdr::Exception& e) {
Pierre Ossmanad8609a2012-04-26 09:04:14 +0000388 vlog.error("%s", e.str());
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000389 restartCore();
390 return;
391 }
392
393 // Ensure the cursor is up to date
394 WMCursor::Info info = cursor->getCursorInfo();
395 if (old_cursor != info) {
396 // Update the cursor shape if the visibility has changed
397 bool set_cursor = info.visible != old_cursor.visible;
398 // OR if the cursor is visible and the shape has changed.
399 set_cursor |= info.visible && (old_cursor.cursor != info.cursor);
400
401 // Update the cursor shape
402 if (set_cursor)
403 pb->setCursor(info.visible ? info.cursor : 0, server);
404
405 // Update the cursor position
406 // NB: First translate from Screen coordinates to Desktop
407 Point desktopPos = info.position.translate(screenRect.tl.negate());
408 server->setCursorPos(desktopPos);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000409
410 old_cursor = info;
411 }
412
413 // Flush any changes to the server
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000414 flushChangeTracker();
Rahul Kalec719e4a2017-07-13 00:36:02 +0200415
416 // Forward current LED state to the server
417 if (checkLedState())
418 server->setLEDState(ledState);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000419 }
420 return;
421 }
422 throw rdr::Exception("No such event");
423}
424
425
426// -=- Protected methods
427
428void
429SDisplay::recreatePixelBuffer(bool force) {
430 // Open the specified display device
431 // If no device is specified, open entire screen using GetDC().
432 // Opening the whole display with CreateDC doesn't work on multi-monitor
433 // systems for some reason.
434 DeviceContext* new_device = 0;
435 TCharArray deviceName(displayDevice.getData());
436 if (deviceName.buf[0]) {
437 vlog.info("Attaching to device %s", (const char*)CStr(deviceName.buf));
438 new_device = new DeviceDC(deviceName.buf);
439 }
440 if (!new_device) {
441 vlog.info("Attaching to virtual desktop");
442 new_device = new WindowDC(0);
443 }
444
445 // Get the coordinates of the specified dispay device
446 Rect newScreenRect;
447 if (deviceName.buf[0]) {
448 MonitorInfo info(CStr(deviceName.buf));
449 newScreenRect = Rect(info.rcMonitor.left, info.rcMonitor.top,
450 info.rcMonitor.right, info.rcMonitor.bottom);
451 } else {
452 newScreenRect = new_device->getClipBox();
453 }
454
455 // If nothing has changed & a recreate has not been forced, delete
456 // the new device context and return
457 if (pb && !force &&
458 newScreenRect.equals(screenRect) &&
459 new_device->getPF().equal(pb->getPF())) {
460 delete new_device;
461 return;
462 }
463
464 // Flush any existing changes to the server
465 flushChangeTracker();
466
467 // Delete the old pixelbuffer and device context
468 vlog.debug("deleting old pixel buffer & device");
469 if (pb)
470 delete pb;
471 if (device)
472 delete device;
473
474 // Create a DeviceFrameBuffer attached to the new device
475 vlog.debug("creating pixel buffer");
476 DeviceFrameBuffer* new_buffer = new DeviceFrameBuffer(*new_device);
477
478 // Replace the old PixelBuffer
479 screenRect = newScreenRect;
480 pb = new_buffer;
481 device = new_device;
482
483 // Initialise the pixels
484 pb->grabRegion(pb->getRect());
485
486 // Prevent future grabRect operations from throwing exceptions
487 pb->setIgnoreGrabErrors(true);
488
489 // Update the clipping update tracker
490 clipper.setClipRect(pb->getRect());
491
492 // Inform the core of the changes
493 if (core)
494 core->setScreenRect(screenRect);
495
496 // Inform the server of the changes
497 if (server)
498 server->setPixelBuffer(pb);
499}
500
501bool SDisplay::flushChangeTracker() {
502 if (updates.is_empty())
503 return false;
504
505 vlog.write(120, "flushChangeTracker");
506
507 // Translate the update coordinates from Screen coords to Desktop
508 updates.translate(screenRect.tl.negate());
509
510 // Clip the updates & flush them to the server
511 updates.copyTo(&clipper);
512 updates.clear();
513 return true;
514}