blob: 2e0c3a41f3ee5ac7a3c6683d591e00062260d8ae [file] [log] [blame]
Constantin Kaplinsky729598c2006-05-25 05:12:25 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18
19#include <windows.h>
20#include <winsock2.h>
21#include <vncviewer/UserPasswdDialog.h>
22#include <vncviewer/CConn.h>
23#include <vncviewer/CConnThread.h>
24#include <vncviewer/resource.h>
25#include <rfb/encodings.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000026#include <rfb/Security.h>
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000027#include <rfb/CSecurityNone.h>
28#include <rfb/CSecurityVncAuth.h>
29#include <rfb/CMsgWriter.h>
30#include <rfb/Configuration.h>
31#include <rfb/LogWriter.h>
32#include <rfb_win32/AboutDialog.h>
33
34using namespace rfb;
35using namespace rfb::win32;
36using namespace rdr;
37
38// - Statics & consts
39
40static LogWriter vlog("CConn");
41
42
43const int IDM_FULLSCREEN = ID_FULLSCREEN;
44const int IDM_SEND_MENU_KEY = ID_SEND_MENU_KEY;
45const int IDM_SEND_CAD = ID_SEND_CAD;
46const int IDM_SEND_CTLESC = ID_SEND_CTLESC;
47const int IDM_ABOUT = ID_ABOUT;
48const int IDM_OPTIONS = ID_OPTIONS;
49const int IDM_INFO = ID_INFO;
50const int IDM_NEWCONN = ID_NEW_CONNECTION;
51const int IDM_REQUEST_REFRESH = ID_REQUEST_REFRESH;
52const int IDM_CTRL_KEY = ID_CTRL_KEY;
53const int IDM_ALT_KEY = ID_ALT_KEY;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000054const int IDM_CONN_SAVE_AS = ID_CONN_SAVE_AS;
george824f72ab32006-09-10 05:13:45 +000055const int IDM_ZOOM_IN = ID_ZOOM_IN;
56const int IDM_ZOOM_OUT = ID_ZOOM_OUT;
57const int IDM_ACTUAL_SIZE = ID_ACTUAL_SIZE;
58const int IDM_AUTO_SIZE = ID_AUTO_SIZE;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000059
60
61static IntParameter debugDelay("DebugDelay","Milliseconds to display inverted "
62 "pixel data - a debugging feature", 0);
63
george82b6d87aa2006-09-11 07:00:59 +000064const int scaleValues[9] = {10, 25, 50, 75, 90, 100, 125, 150, 200};
65const int scaleCount = 9;
66
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000067
68//
69// -=- CConn implementation
70//
71
72RegKey CConn::userConfigKey;
73
74
75CConn::CConn()
Peter Åstrand2dd9eea2008-12-11 08:23:55 +000076 : window(0), sameMachine(false), encodingChange(false), formatChange(false),
77 lastUsedEncoding_(encodingRaw), sock(0), sockEvent(CreateEvent(0, TRUE, FALSE, 0)),
Pierre Ossmand6d19942009-03-24 12:29:50 +000078 reverseConnection(false), requestUpdate(false), firstUpdate(true),
79 isClosed_(false) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000080}
81
82CConn::~CConn() {
83 delete window;
84}
85
86bool CConn::initialise(network::Socket* s, bool reverse) {
87 // Set the server's name for MRU purposes
88 CharArray endpoint(s->getPeerEndpoint());
89 setServerName(endpoint.buf);
90 if (!options.host.buf)
91 options.setHost(endpoint.buf);
92
93 // Initialise the underlying CConnection
94 setStreams(&s->inStream(), &s->outStream());
95
96 // Enable processing of window messages while blocked on I/O
97 s->inStream().setBlockCallback(this);
98
99 // Initialise the viewer options
100 applyOptions(options);
101
102 // - Set which auth schemes we support, in order of preference
103 addSecType(secTypeVncAuth);
104 addSecType(secTypeNone);
Adam Tkacb10489b2010-04-23 14:16:04 +0000105 CSecurity::upg = this;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000106
107 // Start the RFB protocol
108 sock = s;
109 reverseConnection = reverse;
110 initialiseProtocol();
111
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000112 return true;
113}
114
115
116void
117CConn::applyOptions(CConnOptions& opt) {
118 // - If any encoding-related settings have changed then we must
119 // notify the server of the new settings
120 encodingChange |= ((options.useLocalCursor != opt.useLocalCursor) ||
121 (options.useDesktopResize != opt.useDesktopResize) ||
122 (options.customCompressLevel != opt.customCompressLevel) ||
123 (options.compressLevel != opt.compressLevel) ||
124 (options.noJpeg != opt.noJpeg) ||
125 (options.qualityLevel != opt.qualityLevel) ||
126 (options.preferredEncoding != opt.preferredEncoding));
127
128 // - If the preferred pixel format has changed then notify the server
129 formatChange |= (options.fullColour != opt.fullColour);
130 if (!opt.fullColour)
131 formatChange |= (options.lowColourLevel != opt.lowColourLevel);
132
133 // - Save the new set of options
134 options = opt;
135
136 // - Set optional features in ConnParams
137 cp.supportsLocalCursor = options.useLocalCursor;
138 cp.supportsDesktopResize = options.useDesktopResize;
Pierre Ossmand6d19942009-03-24 12:29:50 +0000139 cp.supportsExtendedDesktopSize = options.useDesktopResize;
Peter Åstrandc39e0782009-01-15 12:21:42 +0000140 cp.supportsDesktopRename = true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000141 cp.customCompressLevel = options.customCompressLevel;
142 cp.compressLevel = options.compressLevel;
143 cp.noJpeg = options.noJpeg;
144 cp.qualityLevel = options.qualityLevel;
145
146 // - Configure connection sharing on/off
147 setShared(options.shared);
148
149 // - Whether to use protocol 3.3 for legacy compatibility
150 setProtocol3_3(options.protocol3_3);
151
152 // - Apply settings that affect the window, if it is visible
153 if (window) {
154 window->setMonitor(options.monitor.buf);
155 window->setFullscreen(options.fullScreen);
156 window->setEmulate3(options.emulate3);
157 window->setPointerEventInterval(options.pointerEventInterval);
158 window->setMenuKey(options.menuKey);
159 window->setDisableWinKeys(options.disableWinKeys);
160 window->setShowToolbar(options.showToolbar);
george82770bbbc2007-03-12 10:48:09 +0000161 window->printScale();
george82ffc14a62006-09-05 06:51:41 +0000162 if (options.autoScaling) {
163 window->setAutoScaling(true);
164 } else {
165 window->setAutoScaling(false);
166 window->setDesktopScale(options.scale);
167 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000168 if (!options.useLocalCursor)
169 window->setCursor(0, 0, Point(), 0, 0);
170 }
171}
172
173
174void
175CConn::displayChanged() {
176 // Display format has changed - recalculate the full-colour pixel format
177 calculateFullColourPF();
178}
179
180void
181CConn::paintCompleted() {
182 // A repaint message has just completed - request next update if necessary
183 requestNewUpdate();
184}
185
186bool
187CConn::sysCommand(WPARAM wParam, LPARAM lParam) {
188 // - If it's one of our (F8 Menu) messages
189 switch (wParam) {
190 case IDM_FULLSCREEN:
191 options.fullScreen = !window->isFullscreen();
192 window->setFullscreen(options.fullScreen);
193 return true;
george824f72ab32006-09-10 05:13:45 +0000194 case IDM_ZOOM_IN:
george824f72ab32006-09-10 05:13:45 +0000195 case IDM_ZOOM_OUT:
george82b6d87aa2006-09-11 07:00:59 +0000196 {
197 if (options.autoScaling) {
198 options.scale = window->getDesktopScale();
199 options.autoScaling = false;
200 window->setAutoScaling(false);
201 }
Peter Åstrand145d1f82010-02-10 07:26:56 +0000202 if (wParam == (unsigned)IDM_ZOOM_IN) {
george82b6d87aa2006-09-11 07:00:59 +0000203 for (int i = 0; i < scaleCount; i++)
204 if (options.scale < scaleValues[i]) {
205 options.scale = scaleValues[i];
206 break;
207 }
208 } else {
209 for (int i = scaleCount-1; i >= 0; i--)
210 if (options.scale > scaleValues[i]) {
211 options.scale = scaleValues[i];
212 break;
213 }
214 }
215 if (options.scale != window->getDesktopScale())
216 window->setDesktopScale(options.scale);
217 }
george824f72ab32006-09-10 05:13:45 +0000218 return true;
219 case IDM_ACTUAL_SIZE:
220 if (options.autoScaling) {
221 options.autoScaling = false;
222 window->setAutoScaling(false);
223 }
george824f72ab32006-09-10 05:13:45 +0000224 options.scale = 100;
225 window->setDesktopScale(100);
226 return true;
227 case IDM_AUTO_SIZE:
george8274ea5f32006-09-11 11:40:12 +0000228 options.autoScaling = !options.autoScaling;
229 window->setAutoScaling(options.autoScaling);
230 if (!options.autoScaling) options.scale = window->getDesktopScale();
george824f72ab32006-09-10 05:13:45 +0000231 return true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000232 case IDM_SHOW_TOOLBAR:
233 options.showToolbar = !window->isToolbarEnabled();
234 window->setShowToolbar(options.showToolbar);
235 return true;
236 case IDM_CTRL_KEY:
237 window->kbd.keyEvent(this, VK_CONTROL, 0, !window->kbd.keyPressed(VK_CONTROL));
238 return true;
239 case IDM_ALT_KEY:
240 window->kbd.keyEvent(this, VK_MENU, 0, !window->kbd.keyPressed(VK_MENU));
241 return true;
242 case IDM_SEND_MENU_KEY:
243 window->kbd.keyEvent(this, options.menuKey, 0, true);
244 window->kbd.keyEvent(this, options.menuKey, 0, false);
245 return true;
246 case IDM_SEND_CAD:
247 window->kbd.keyEvent(this, VK_CONTROL, 0, true);
248 window->kbd.keyEvent(this, VK_MENU, 0, true);
249 window->kbd.keyEvent(this, VK_DELETE, 0x1000000, true);
250 window->kbd.keyEvent(this, VK_DELETE, 0x1000000, false);
251 window->kbd.keyEvent(this, VK_MENU, 0, false);
252 window->kbd.keyEvent(this, VK_CONTROL, 0, false);
253 return true;
254 case IDM_SEND_CTLESC:
255 window->kbd.keyEvent(this, VK_CONTROL, 0, true);
256 window->kbd.keyEvent(this, VK_ESCAPE, 0, true);
257 window->kbd.keyEvent(this, VK_ESCAPE, 0, false);
258 window->kbd.keyEvent(this, VK_CONTROL, 0, false);
259 return true;
260 case IDM_REQUEST_REFRESH:
261 try {
262 writer()->writeFramebufferUpdateRequest(Rect(0,0,cp.width,cp.height), false);
263 requestUpdate = false;
264 } catch (rdr::Exception& e) {
265 close(e.str());
266 }
267 return true;
268 case IDM_NEWCONN:
269 {
Peter Åstrand145d1f82010-02-10 07:26:56 +0000270 new CConnThread;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000271 }
272 return true;
273 case IDM_OPTIONS:
274 // Update the monitor device name in the CConnOptions instance
275 options.monitor.replaceBuf(window->getMonitor());
276 showOptionsDialog();
277 return true;
278 case IDM_INFO:
279 infoDialog.showDialog(this);
280 return true;
281 case IDM_ABOUT:
282 AboutDialog::instance.showDialog();
283 return true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000284 case IDM_CONN_SAVE_AS:
285 return true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000286 };
287 return false;
288}
289
290
291void
292CConn::closeWindow() {
293 vlog.info("window closed");
294 close();
295}
296
297
298void
299CConn::refreshMenu(bool enableSysItems) {
300 HMENU menu = GetSystemMenu(window->getHandle(), FALSE);
301
302 if (!enableSysItems) {
303 // Gray out menu items that might cause a World Of Pain
304 EnableMenuItem(menu, SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
305 EnableMenuItem(menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
306 EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
307 EnableMenuItem(menu, SC_MINIMIZE, MF_BYCOMMAND | MF_ENABLED);
308 EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_ENABLED);
309 }
310
311 // Update the modifier key menu items
312 UINT ctrlCheckFlags = window->kbd.keyPressed(VK_CONTROL) ? MF_CHECKED : MF_UNCHECKED;
313 UINT altCheckFlags = window->kbd.keyPressed(VK_MENU) ? MF_CHECKED : MF_UNCHECKED;
314 CheckMenuItem(menu, IDM_CTRL_KEY, MF_BYCOMMAND | ctrlCheckFlags);
315 CheckMenuItem(menu, IDM_ALT_KEY, MF_BYCOMMAND | altCheckFlags);
316
317 // Ensure that the Send <MenuKey> menu item has the correct text
318 if (options.menuKey) {
319 TCharArray menuKeyStr(options.menuKeyName());
320 TCharArray tmp(_tcslen(menuKeyStr.buf) + 6);
321 _stprintf(tmp.buf, _T("Send %s"), menuKeyStr.buf);
322 if (!ModifyMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf))
323 InsertMenu(menu, IDM_SEND_CAD, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf);
324 } else {
325 RemoveMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND);
326 }
327
328 // Set the menu fullscreen option tick
329 CheckMenuItem(menu, IDM_FULLSCREEN, (window->isFullscreen() ? MF_CHECKED : 0) | MF_BYCOMMAND);
330
331 // Set the menu toolbar option tick
332 int toolbarFlags = window->isToolbarEnabled() ? MF_CHECKED : 0;
333 CheckMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
334
335 // In the full-screen mode, "Show toolbar" should be grayed.
336 toolbarFlags = window->isFullscreen() ? MF_GRAYED : MF_ENABLED;
337 EnableMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
338}
339
340
341void
342CConn::blockCallback() {
343 // - An InStream has blocked on I/O while processing an RFB message
344 // We re-enable socket event notifications, so we'll know when more
345 // data is available, then we sit and dispatch window events until
346 // the notification arrives.
347 if (!isClosed()) {
348 if (WSAEventSelect(sock->getFd(), sockEvent, FD_READ | FD_CLOSE) == SOCKET_ERROR)
349 throw rdr::SystemException("Unable to wait for sokcet data", WSAGetLastError());
350 }
351 while (true) {
352 // If we have closed then we can't block waiting for data
353 if (isClosed())
354 throw rdr::EndOfStream();
355
356 // Wait for socket data, or a message to process
357 DWORD result = MsgWaitForMultipleObjects(1, &sockEvent.h, FALSE, INFINITE, QS_ALLINPUT);
358 if (result == WAIT_OBJECT_0) {
359 // - Network event notification. Return control to I/O routine.
360 break;
361 } else if (result == WAIT_FAILED) {
362 // - The wait operation failed - raise an exception
363 throw rdr::SystemException("blockCallback wait error", GetLastError());
364 }
365
366 // - There should be a message in the message queue
367 MSG msg;
368 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
369 // IMPORTANT: We mustn't call TranslateMessage() here, because instead we
370 // call ToAscii() in CKeyboard::keyEvent(). ToAscii() stores dead key
371 // state from one call to the next, which would be messed up by calls to
372 // TranslateMessage() (actually it looks like TranslateMessage() calls
373 // ToAscii() internally).
374 DispatchMessage(&msg);
375 }
376 }
377
378 // Before we return control to the InStream, reset the network event
379 WSAEventSelect(sock->getFd(), sockEvent, 0);
380 ResetEvent(sockEvent);
381}
382
383
384void CConn::keyEvent(rdr::U32 key, bool down) {
385 if (!options.sendKeyEvents) return;
386 try {
387 writer()->keyEvent(key, down);
388 } catch (rdr::Exception& e) {
389 close(e.str());
390 }
391}
392void CConn::pointerEvent(const Point& pos, int buttonMask) {
393 if (!options.sendPtrEvents) return;
394 try {
395 writer()->pointerEvent(pos, buttonMask);
396 } catch (rdr::Exception& e) {
397 close(e.str());
398 }
399}
400void CConn::clientCutText(const char* str, int len) {
401 if (!options.clientCutText) return;
402 if (state() != RFBSTATE_NORMAL) return;
403 try {
404 writer()->clientCutText(str, len);
405 } catch (rdr::Exception& e) {
406 close(e.str());
407 }
408}
409
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000410void
411CConn::setColourMapEntries(int first, int count, U16* rgbs) {
412 vlog.debug("setColourMapEntries: first=%d, count=%d", first, count);
413 int i;
414 for (i=0;i<count;i++)
415 window->setColour(i+first, rgbs[i*3], rgbs[i*3+1], rgbs[i*3+2]);
416 // *** change to 0, 256?
417 window->refreshWindowPalette(first, count);
418}
419
420void
421CConn::bell() {
422 if (options.acceptBell)
Peter Åstrand7eb594a2008-12-11 08:27:52 +0000423 MessageBeep((UINT)-1);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000424}
425
426
427void
428CConn::setDesktopSize(int w, int h) {
429 vlog.debug("setDesktopSize %dx%d", w, h);
430
431 // Resize the window's buffer
432 if (window)
433 window->setSize(w, h);
434
435 // Tell the underlying CConnection
436 CConnection::setDesktopSize(w, h);
437}
438
Pierre Ossmand6d19942009-03-24 12:29:50 +0000439
440void
441CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
442 const rfb::ScreenSet& layout) {
Peter Åstrand145d1f82010-02-10 07:26:56 +0000443 if ((reason == (signed)reasonClient) && (result != (signed)resultSuccess)) {
Pierre Ossmand6d19942009-03-24 12:29:50 +0000444 vlog.error("SetDesktopSize failed: %d", result);
445 return;
446 }
447
448 // Resize the window's buffer
449 if (window)
450 window->setSize(w, h);
451
452 // Tell the underlying CConnection
453 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
454}
455
456
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000457void
458CConn::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
459 if (!options.useLocalCursor) return;
460
461 // Set the window to use the new cursor
462 window->setCursor(w, h, hotspot, data, mask);
463}
464
465
466void
467CConn::close(const char* reason) {
468 // If already closed then ignore this
469 if (isClosed())
470 return;
471
472 // Hide the window, if it exists
473 if (window)
474 ShowWindow(window->getHandle(), SW_HIDE);
475
476 // Save the reason & flag that we're closed & shutdown the socket
477 isClosed_ = true;
478 closeReason_.replaceBuf(strDup(reason));
479 sock->shutdown();
480}
481
482
483void
484CConn::showOptionsDialog() {
485 optionsDialog.showDialog(this);
486}
487
488
489void
490CConn::framebufferUpdateEnd() {
491 if (debugDelay != 0) {
492 vlog.debug("debug delay %d",(int)debugDelay);
493 UpdateWindow(window->getHandle());
494 Sleep(debugDelay);
495 std::list<rfb::Rect>::iterator i;
496 for (i = debugRects.begin(); i != debugRects.end(); i++) {
497 window->invertRect(*i);
498 }
499 debugRects.clear();
500 }
Pierre Ossmanb2ff1602009-03-25 12:13:28 +0000501 window->framebufferUpdateEnd();
Pierre Ossmand6d19942009-03-24 12:29:50 +0000502
503 if (firstUpdate) {
504 int width, height;
505
506 if (cp.supportsSetDesktopSize &&
507 sscanf(options.desktopSize.buf, "%dx%d", &width, &height) == 2) {
508 ScreenSet layout;
509
510 layout = cp.screenLayout;
511
512 if (layout.num_screens() == 0)
513 layout.add_screen(rfb::Screen());
514 else if (layout.num_screens() != 1) {
515 ScreenSet::iterator iter;
516
517 while (true) {
518 iter = layout.begin();
519 ++iter;
520
521 if (iter == layout.end())
522 break;
523
524 layout.remove_screen(iter->id);
525 }
526 }
527
528 layout.begin()->dimensions.tl.x = 0;
529 layout.begin()->dimensions.tl.y = 0;
530 layout.begin()->dimensions.br.x = width;
531 layout.begin()->dimensions.br.y = height;
532
533 writer()->writeSetDesktopSize(width, height, layout);
534 }
535
536 firstUpdate = false;
537 }
538
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000539 if (options.autoSelect)
540 autoSelectFormatAndEncoding();
541
542 // Always request the next update
543 requestUpdate = true;
544
545 // Check that at least part of the window has changed
546 if (!GetUpdateRect(window->getHandle(), 0, FALSE)) {
547 if (!(GetWindowLong(window->getHandle(), GWL_STYLE) & WS_MINIMIZE))
548 requestNewUpdate();
549 }
550
551 // Make sure the local cursor is shown
552 window->showCursor();
553}
554
555
Pierre Ossman78b23592009-03-12 12:25:11 +0000556// Note: The method below is duplicated in win/vncviewer/CConn.cxx!
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000557
558// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
559// to the connection speed:
560//
Pierre Ossman78b23592009-03-12 12:25:11 +0000561// First we wait for at least one second of bandwidth measurement.
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000562//
Pierre Ossman78b23592009-03-12 12:25:11 +0000563// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
564// which should be perceptually lossless.
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000565//
Pierre Ossman78b23592009-03-12 12:25:11 +0000566// If the bandwidth is below that, we choose a more lossy JPEG quality.
567//
568// If the bandwidth drops below 256 Kbps, we switch to palette mode.
569//
570// Note: The system here is fairly arbitrary and should be replaced
571// with something more intelligent at the server end.
572//
573void CConn::autoSelectFormatAndEncoding()
574{
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000575 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000576 unsigned int timeWaited = sock->inStream().timeWaited();
Pierre Ossman78b23592009-03-12 12:25:11 +0000577 bool newFullColour = options.fullColour;
578 int newQualityLevel = options.qualityLevel;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000579
Pierre Ossman78b23592009-03-12 12:25:11 +0000580 // Always use Tight
581 options.preferredEncoding = encodingTight;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000582
Pierre Ossman78b23592009-03-12 12:25:11 +0000583 // Check that we have a decent bandwidth measurement
584 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000585 return;
Pierre Ossman78b23592009-03-12 12:25:11 +0000586
587 // Select appropriate quality level
588 if (!options.noJpeg) {
589 if (kbitsPerSecond > 16000)
590 newQualityLevel = 8;
591 else
592 newQualityLevel = 6;
593
594 if (newQualityLevel != options.qualityLevel) {
595 vlog.info("Throughput %d kbit/s - changing to quality %d ",
596 kbitsPerSecond, newQualityLevel);
597 cp.qualityLevel = newQualityLevel;
598 options.qualityLevel = newQualityLevel;
599 encodingChange = true;
600 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000601 }
602
603 if (cp.beforeVersion(3, 8)) {
604 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
605 // cursors "asynchronously". If this happens in the middle of a
606 // pixel format change, the server will encode the cursor with
607 // the old format, but the client will try to decode it
608 // according to the new format. This will lead to a
609 // crash. Therefore, we do not allow automatic format change for
610 // old servers.
611 return;
612 }
613
614 // Select best color level
615 newFullColour = (kbitsPerSecond > 256);
616 if (newFullColour != options.fullColour) {
617 vlog.info("Throughput %d kbit/s - full color is now %s",
Pierre Ossman78b23592009-03-12 12:25:11 +0000618 kbitsPerSecond,
619 newFullColour ? "enabled" : "disabled");
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000620 options.fullColour = newFullColour;
621 formatChange = true;
Pierre Ossman78b23592009-03-12 12:25:11 +0000622 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000623}
624
625void
626CConn::requestNewUpdate() {
627 if (!requestUpdate) return;
628
629 if (formatChange) {
630 // Select the required pixel format
631 if (options.fullColour) {
632 window->setPF(fullColourPF);
633 } else {
634 switch (options.lowColourLevel) {
635 case 0:
636 window->setPF(PixelFormat(8,3,0,1,1,1,1,2,1,0));
637 break;
638 case 1:
639 window->setPF(PixelFormat(8,6,0,1,3,3,3,4,2,0));
640 break;
641 case 2:
642 window->setPF(PixelFormat(8,8,0,0,0,0,0,0,0,0));
643 break;
644 }
645 }
646
647 // Print the current pixel format
648 char str[256];
649 window->getPF().print(str, 256);
650 vlog.info("Using pixel format %s",str);
651
652 // Save the connection pixel format and tell server to use it
653 cp.setPF(window->getPF());
654 writer()->writeSetPixelFormat(cp.pf());
655
656 // Correct the local window's palette
657 if (!window->getNativePF().trueColour)
658 window->refreshWindowPalette(0, 1 << cp.pf().depth);
659 }
660
661 if (encodingChange) {
662 vlog.info("Using %s encoding",encodingName(options.preferredEncoding));
663 writer()->writeSetEncodings(options.preferredEncoding, true);
664 }
665
666 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
667 !formatChange);
668
669 encodingChange = formatChange = requestUpdate = false;
670}
671
672
673void
674CConn::calculateFullColourPF() {
675 // If the server is palette based then use palette locally
676 // Also, don't bother doing bgr222
677 if (!serverDefaultPF.trueColour || (serverDefaultPF.depth < 6)) {
678 fullColourPF = serverDefaultPF;
679 options.fullColour = true;
680 } else {
681 // If server is trueColour, use lowest depth PF
682 PixelFormat native = window->getNativePF();
683 if ((serverDefaultPF.bpp < native.bpp) ||
684 ((serverDefaultPF.bpp == native.bpp) &&
685 (serverDefaultPF.depth < native.depth)))
686 fullColourPF = serverDefaultPF;
687 else
688 fullColourPF = window->getNativePF();
689 }
690 formatChange = true;
691}
692
693
694void
695CConn::setName(const char* name) {
696 if (window)
697 window->setName(name);
698 CConnection::setName(name);
699}
700
701
702void CConn::serverInit() {
703 CConnection::serverInit();
704
705 // If using AutoSelect with old servers, start in FullColor
706 // mode. See comment in autoSelectFormatAndEncoding.
707 if (cp.beforeVersion(3, 8) && options.autoSelect) {
708 options.fullColour = true;
709 }
710
711 // Show the window
712 window = new DesktopWindow(this);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000713
714 // Update the window menu
715 HMENU wndmenu = GetSystemMenu(window->getHandle(), FALSE);
716 int toolbarChecked = options.showToolbar ? MF_CHECKED : 0;
717
718 AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
719 AppendMenu(wndmenu, MF_STRING, IDM_FULLSCREEN, _T("&Full screen"));
720 AppendMenu(wndmenu, MF_STRING | toolbarChecked, IDM_SHOW_TOOLBAR,
721 _T("Show tool&bar"));
722 AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
723 AppendMenu(wndmenu, MF_STRING, IDM_CTRL_KEY, _T("Ctr&l"));
724 AppendMenu(wndmenu, MF_STRING, IDM_ALT_KEY, _T("Al&t"));
725 AppendMenu(wndmenu, MF_STRING, IDM_SEND_CAD, _T("Send Ctrl-Alt-&Del"));
726 AppendMenu(wndmenu, MF_STRING, IDM_SEND_CTLESC, _T("Send Ctrl-&Esc"));
727 AppendMenu(wndmenu, MF_STRING, IDM_REQUEST_REFRESH, _T("Refres&h Screen"));
728 AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
729 AppendMenu(wndmenu, MF_STRING, IDM_NEWCONN, _T("Ne&w Connection..."));
730 AppendMenu(wndmenu, MF_STRING, IDM_OPTIONS, _T("&Options..."));
731 AppendMenu(wndmenu, MF_STRING, IDM_INFO, _T("Connection &Info..."));
732 AppendMenu(wndmenu, MF_STRING, IDM_ABOUT, _T("&About..."));
Pierre Ossman0df7c7a2009-04-09 12:00:08 +0000733
734 // Set window attributes
735 window->setName(cp.name());
736 window->setShowToolbar(options.showToolbar);
737 window->setSize(cp.width, cp.height);
738 applyOptions(options);
739
740 // Save the server's current format
741 serverDefaultPF = cp.pf();
742
743 // Calculate the full-colour format to use
744 calculateFullColourPF();
745
746 // Request the initial update
747 vlog.info("requesting initial update");
748 formatChange = encodingChange = requestUpdate = true;
749 requestNewUpdate();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000750}
751
752void
Adam Tkacacf6c6b2009-02-13 12:42:05 +0000753CConn::serverCutText(const char* str, rdr::U32 len) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000754 if (!options.serverCutText) return;
755 window->serverCutText(str, len);
756}
757
758
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000759void CConn::beginRect(const Rect& r, int encoding) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000760 sock->inStream().startTiming();
761}
762
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000763void CConn::endRect(const Rect& r, int encoding) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000764 sock->inStream().stopTiming();
765 lastUsedEncoding_ = encoding;
766 if (debugDelay != 0) {
767 window->invertRect(r);
768 debugRects.push_back(r);
769 }
770}
771
772void CConn::fillRect(const Rect& r, Pixel pix) {
773 window->fillRect(r, pix);
774}
775void CConn::imageRect(const Rect& r, void* pixels) {
776 window->imageRect(r, pixels);
777}
778void CConn::copyRect(const Rect& r, int srcX, int srcY) {
779 window->copyRect(r, srcX, srcY);
780}
781
782void CConn::getUserPasswd(char** user, char** password) {
783 if (!user && options.passwordFile.buf[0]) {
784 FILE* fp = fopen(options.passwordFile.buf, "rb");
785 if (fp) {
786 char data[256];
787 int datalen = fread(data, 1, 256, fp);
788 fclose(fp);
789 if (datalen == 8) {
790 ObfuscatedPasswd obfPwd;
791 obfPwd.buf = data;
792 obfPwd.length = datalen;
793 PlainPasswd passwd(obfPwd);
Peter Åstrand8ace9152008-12-03 11:57:18 +0000794 obfPwd.takeBuf();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000795 *password = strDup(passwd.buf);
Peter Åstrand8ace9152008-12-03 11:57:18 +0000796 memset(data, 0, sizeof(data));
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000797 }
798 }
799 }
800 if (user && options.userName.buf)
801 *user = strDup(options.userName.buf);
802 if (password && options.password.buf)
803 *password = strDup(options.password.buf);
804 if ((user && !*user) || (password && !*password)) {
805 // Missing username or password - prompt the user
806 UserPasswdDialog userPasswdDialog;
Adam Tkacf324dc42010-04-23 14:10:17 +0000807 userPasswdDialog.setCSecurity(csecurity);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000808 userPasswdDialog.getUserPasswd(user, password);
809 }
810 if (user) options.setUserName(*user);
811 if (password) options.setPassword(*password);
812}
813