blob: b34b56eba316ce6e4071a9c7b913fe334bfd1b47 [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
Adam Tkac243fd7c2010-12-08 13:47:41 +000019#ifdef HAVE_CONFIG_H
20#include <config.h>
21#endif
22
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000023#include <winsock2.h>
24#include <vncviewer/UserPasswdDialog.h>
25#include <vncviewer/CConn.h>
26#include <vncviewer/CConnThread.h>
27#include <vncviewer/resource.h>
28#include <rfb/encodings.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000029#include <rfb/Security.h>
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000030#include <rfb/CMsgWriter.h>
31#include <rfb/Configuration.h>
Adam Tkac243fd7c2010-12-08 13:47:41 +000032#ifdef HAVE_GNUTLS
33#include <rfb/CSecurityTLS.h>
34#endif
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000035#include <rfb/LogWriter.h>
36#include <rfb_win32/AboutDialog.h>
37
38using namespace rfb;
39using namespace rfb::win32;
40using namespace rdr;
41
42// - Statics & consts
43
44static LogWriter vlog("CConn");
45
46
47const int IDM_FULLSCREEN = ID_FULLSCREEN;
48const int IDM_SEND_MENU_KEY = ID_SEND_MENU_KEY;
49const int IDM_SEND_CAD = ID_SEND_CAD;
50const int IDM_SEND_CTLESC = ID_SEND_CTLESC;
51const int IDM_ABOUT = ID_ABOUT;
52const int IDM_OPTIONS = ID_OPTIONS;
53const int IDM_INFO = ID_INFO;
54const int IDM_NEWCONN = ID_NEW_CONNECTION;
55const int IDM_REQUEST_REFRESH = ID_REQUEST_REFRESH;
56const int IDM_CTRL_KEY = ID_CTRL_KEY;
57const int IDM_ALT_KEY = ID_ALT_KEY;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000058const int IDM_CONN_SAVE_AS = ID_CONN_SAVE_AS;
george824f72ab32006-09-10 05:13:45 +000059const int IDM_ZOOM_IN = ID_ZOOM_IN;
60const int IDM_ZOOM_OUT = ID_ZOOM_OUT;
61const int IDM_ACTUAL_SIZE = ID_ACTUAL_SIZE;
62const int IDM_AUTO_SIZE = ID_AUTO_SIZE;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000063
64
65static IntParameter debugDelay("DebugDelay","Milliseconds to display inverted "
66 "pixel data - a debugging feature", 0);
67
george82b6d87aa2006-09-11 07:00:59 +000068const int scaleValues[9] = {10, 25, 50, 75, 90, 100, 125, 150, 200};
69const int scaleCount = 9;
70
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000071
72//
73// -=- CConn implementation
74//
75
76RegKey CConn::userConfigKey;
77
78
79CConn::CConn()
Peter Åstrand2dd9eea2008-12-11 08:23:55 +000080 : window(0), sameMachine(false), encodingChange(false), formatChange(false),
81 lastUsedEncoding_(encodingRaw), sock(0), sockEvent(CreateEvent(0, TRUE, FALSE, 0)),
Pierre Ossmand6d19942009-03-24 12:29:50 +000082 reverseConnection(false), requestUpdate(false), firstUpdate(true),
83 isClosed_(false) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +000084}
85
86CConn::~CConn() {
87 delete window;
88}
89
90bool CConn::initialise(network::Socket* s, bool reverse) {
91 // Set the server's name for MRU purposes
92 CharArray endpoint(s->getPeerEndpoint());
93 setServerName(endpoint.buf);
94 if (!options.host.buf)
95 options.setHost(endpoint.buf);
96
97 // Initialise the underlying CConnection
98 setStreams(&s->inStream(), &s->outStream());
99
100 // Enable processing of window messages while blocked on I/O
101 s->inStream().setBlockCallback(this);
102
103 // Initialise the viewer options
104 applyOptions(options);
105
Adam Tkacb10489b2010-04-23 14:16:04 +0000106 CSecurity::upg = this;
Adam Tkac243fd7c2010-12-08 13:47:41 +0000107#ifdef HAVE_GNUTLS
108 CSecurityTLS::msg = this;
109#endif
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000110
111 // Start the RFB protocol
112 sock = s;
113 reverseConnection = reverse;
114 initialiseProtocol();
115
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000116 return true;
117}
118
119
120void
121CConn::applyOptions(CConnOptions& opt) {
122 // - If any encoding-related settings have changed then we must
123 // notify the server of the new settings
124 encodingChange |= ((options.useLocalCursor != opt.useLocalCursor) ||
125 (options.useDesktopResize != opt.useDesktopResize) ||
126 (options.customCompressLevel != opt.customCompressLevel) ||
127 (options.compressLevel != opt.compressLevel) ||
128 (options.noJpeg != opt.noJpeg) ||
129 (options.qualityLevel != opt.qualityLevel) ||
130 (options.preferredEncoding != opt.preferredEncoding));
131
132 // - If the preferred pixel format has changed then notify the server
133 formatChange |= (options.fullColour != opt.fullColour);
134 if (!opt.fullColour)
135 formatChange |= (options.lowColourLevel != opt.lowColourLevel);
136
137 // - Save the new set of options
138 options = opt;
139
140 // - Set optional features in ConnParams
141 cp.supportsLocalCursor = options.useLocalCursor;
142 cp.supportsDesktopResize = options.useDesktopResize;
Pierre Ossmand6d19942009-03-24 12:29:50 +0000143 cp.supportsExtendedDesktopSize = options.useDesktopResize;
Peter Åstrandc39e0782009-01-15 12:21:42 +0000144 cp.supportsDesktopRename = true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000145 cp.customCompressLevel = options.customCompressLevel;
146 cp.compressLevel = options.compressLevel;
147 cp.noJpeg = options.noJpeg;
148 cp.qualityLevel = options.qualityLevel;
149
150 // - Configure connection sharing on/off
151 setShared(options.shared);
152
153 // - Whether to use protocol 3.3 for legacy compatibility
154 setProtocol3_3(options.protocol3_3);
155
156 // - Apply settings that affect the window, if it is visible
157 if (window) {
158 window->setMonitor(options.monitor.buf);
159 window->setFullscreen(options.fullScreen);
160 window->setEmulate3(options.emulate3);
161 window->setPointerEventInterval(options.pointerEventInterval);
162 window->setMenuKey(options.menuKey);
163 window->setDisableWinKeys(options.disableWinKeys);
164 window->setShowToolbar(options.showToolbar);
george82770bbbc2007-03-12 10:48:09 +0000165 window->printScale();
george82ffc14a62006-09-05 06:51:41 +0000166 if (options.autoScaling) {
167 window->setAutoScaling(true);
168 } else {
169 window->setAutoScaling(false);
170 window->setDesktopScale(options.scale);
171 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000172 if (!options.useLocalCursor)
173 window->setCursor(0, 0, Point(), 0, 0);
174 }
Adam Tkac1238c042011-02-01 14:33:41 +0000175
176 security->SetSecTypes(options.secTypes);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000177}
178
179
180void
181CConn::displayChanged() {
182 // Display format has changed - recalculate the full-colour pixel format
183 calculateFullColourPF();
184}
185
186void
187CConn::paintCompleted() {
188 // A repaint message has just completed - request next update if necessary
189 requestNewUpdate();
190}
191
192bool
193CConn::sysCommand(WPARAM wParam, LPARAM lParam) {
194 // - If it's one of our (F8 Menu) messages
195 switch (wParam) {
196 case IDM_FULLSCREEN:
197 options.fullScreen = !window->isFullscreen();
198 window->setFullscreen(options.fullScreen);
199 return true;
george824f72ab32006-09-10 05:13:45 +0000200 case IDM_ZOOM_IN:
george824f72ab32006-09-10 05:13:45 +0000201 case IDM_ZOOM_OUT:
george82b6d87aa2006-09-11 07:00:59 +0000202 {
203 if (options.autoScaling) {
204 options.scale = window->getDesktopScale();
205 options.autoScaling = false;
206 window->setAutoScaling(false);
207 }
Peter Åstrand145d1f82010-02-10 07:26:56 +0000208 if (wParam == (unsigned)IDM_ZOOM_IN) {
george82b6d87aa2006-09-11 07:00:59 +0000209 for (int i = 0; i < scaleCount; i++)
210 if (options.scale < scaleValues[i]) {
211 options.scale = scaleValues[i];
212 break;
213 }
214 } else {
215 for (int i = scaleCount-1; i >= 0; i--)
216 if (options.scale > scaleValues[i]) {
217 options.scale = scaleValues[i];
218 break;
219 }
220 }
221 if (options.scale != window->getDesktopScale())
222 window->setDesktopScale(options.scale);
223 }
george824f72ab32006-09-10 05:13:45 +0000224 return true;
225 case IDM_ACTUAL_SIZE:
226 if (options.autoScaling) {
227 options.autoScaling = false;
228 window->setAutoScaling(false);
229 }
george824f72ab32006-09-10 05:13:45 +0000230 options.scale = 100;
231 window->setDesktopScale(100);
232 return true;
233 case IDM_AUTO_SIZE:
george8274ea5f32006-09-11 11:40:12 +0000234 options.autoScaling = !options.autoScaling;
235 window->setAutoScaling(options.autoScaling);
236 if (!options.autoScaling) options.scale = window->getDesktopScale();
george824f72ab32006-09-10 05:13:45 +0000237 return true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000238 case IDM_SHOW_TOOLBAR:
239 options.showToolbar = !window->isToolbarEnabled();
240 window->setShowToolbar(options.showToolbar);
241 return true;
242 case IDM_CTRL_KEY:
243 window->kbd.keyEvent(this, VK_CONTROL, 0, !window->kbd.keyPressed(VK_CONTROL));
244 return true;
245 case IDM_ALT_KEY:
246 window->kbd.keyEvent(this, VK_MENU, 0, !window->kbd.keyPressed(VK_MENU));
247 return true;
248 case IDM_SEND_MENU_KEY:
249 window->kbd.keyEvent(this, options.menuKey, 0, true);
250 window->kbd.keyEvent(this, options.menuKey, 0, false);
251 return true;
252 case IDM_SEND_CAD:
253 window->kbd.keyEvent(this, VK_CONTROL, 0, true);
254 window->kbd.keyEvent(this, VK_MENU, 0, true);
255 window->kbd.keyEvent(this, VK_DELETE, 0x1000000, true);
256 window->kbd.keyEvent(this, VK_DELETE, 0x1000000, false);
257 window->kbd.keyEvent(this, VK_MENU, 0, false);
258 window->kbd.keyEvent(this, VK_CONTROL, 0, false);
259 return true;
260 case IDM_SEND_CTLESC:
261 window->kbd.keyEvent(this, VK_CONTROL, 0, true);
262 window->kbd.keyEvent(this, VK_ESCAPE, 0, true);
263 window->kbd.keyEvent(this, VK_ESCAPE, 0, false);
264 window->kbd.keyEvent(this, VK_CONTROL, 0, false);
265 return true;
266 case IDM_REQUEST_REFRESH:
267 try {
268 writer()->writeFramebufferUpdateRequest(Rect(0,0,cp.width,cp.height), false);
269 requestUpdate = false;
270 } catch (rdr::Exception& e) {
271 close(e.str());
272 }
273 return true;
274 case IDM_NEWCONN:
275 {
Peter Åstrand145d1f82010-02-10 07:26:56 +0000276 new CConnThread;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000277 }
278 return true;
279 case IDM_OPTIONS:
280 // Update the monitor device name in the CConnOptions instance
281 options.monitor.replaceBuf(window->getMonitor());
282 showOptionsDialog();
283 return true;
284 case IDM_INFO:
285 infoDialog.showDialog(this);
286 return true;
287 case IDM_ABOUT:
288 AboutDialog::instance.showDialog();
289 return true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000290 case IDM_CONN_SAVE_AS:
291 return true;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000292 };
293 return false;
294}
295
296
297void
298CConn::closeWindow() {
299 vlog.info("window closed");
300 close();
301}
302
303
304void
305CConn::refreshMenu(bool enableSysItems) {
306 HMENU menu = GetSystemMenu(window->getHandle(), FALSE);
307
308 if (!enableSysItems) {
309 // Gray out menu items that might cause a World Of Pain
310 EnableMenuItem(menu, SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
311 EnableMenuItem(menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
312 EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
313 EnableMenuItem(menu, SC_MINIMIZE, MF_BYCOMMAND | MF_ENABLED);
314 EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_ENABLED);
315 }
316
317 // Update the modifier key menu items
318 UINT ctrlCheckFlags = window->kbd.keyPressed(VK_CONTROL) ? MF_CHECKED : MF_UNCHECKED;
319 UINT altCheckFlags = window->kbd.keyPressed(VK_MENU) ? MF_CHECKED : MF_UNCHECKED;
320 CheckMenuItem(menu, IDM_CTRL_KEY, MF_BYCOMMAND | ctrlCheckFlags);
321 CheckMenuItem(menu, IDM_ALT_KEY, MF_BYCOMMAND | altCheckFlags);
322
323 // Ensure that the Send <MenuKey> menu item has the correct text
324 if (options.menuKey) {
325 TCharArray menuKeyStr(options.menuKeyName());
326 TCharArray tmp(_tcslen(menuKeyStr.buf) + 6);
327 _stprintf(tmp.buf, _T("Send %s"), menuKeyStr.buf);
328 if (!ModifyMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf))
329 InsertMenu(menu, IDM_SEND_CAD, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf);
330 } else {
331 RemoveMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND);
332 }
333
334 // Set the menu fullscreen option tick
335 CheckMenuItem(menu, IDM_FULLSCREEN, (window->isFullscreen() ? MF_CHECKED : 0) | MF_BYCOMMAND);
336
337 // Set the menu toolbar option tick
338 int toolbarFlags = window->isToolbarEnabled() ? MF_CHECKED : 0;
339 CheckMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
340
341 // In the full-screen mode, "Show toolbar" should be grayed.
342 toolbarFlags = window->isFullscreen() ? MF_GRAYED : MF_ENABLED;
343 EnableMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
344}
345
346
347void
348CConn::blockCallback() {
349 // - An InStream has blocked on I/O while processing an RFB message
350 // We re-enable socket event notifications, so we'll know when more
351 // data is available, then we sit and dispatch window events until
352 // the notification arrives.
353 if (!isClosed()) {
354 if (WSAEventSelect(sock->getFd(), sockEvent, FD_READ | FD_CLOSE) == SOCKET_ERROR)
355 throw rdr::SystemException("Unable to wait for sokcet data", WSAGetLastError());
356 }
357 while (true) {
358 // If we have closed then we can't block waiting for data
359 if (isClosed())
360 throw rdr::EndOfStream();
361
362 // Wait for socket data, or a message to process
363 DWORD result = MsgWaitForMultipleObjects(1, &sockEvent.h, FALSE, INFINITE, QS_ALLINPUT);
364 if (result == WAIT_OBJECT_0) {
365 // - Network event notification. Return control to I/O routine.
366 break;
367 } else if (result == WAIT_FAILED) {
368 // - The wait operation failed - raise an exception
369 throw rdr::SystemException("blockCallback wait error", GetLastError());
370 }
371
372 // - There should be a message in the message queue
373 MSG msg;
374 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
375 // IMPORTANT: We mustn't call TranslateMessage() here, because instead we
376 // call ToAscii() in CKeyboard::keyEvent(). ToAscii() stores dead key
377 // state from one call to the next, which would be messed up by calls to
378 // TranslateMessage() (actually it looks like TranslateMessage() calls
379 // ToAscii() internally).
380 DispatchMessage(&msg);
381 }
382 }
383
384 // Before we return control to the InStream, reset the network event
385 WSAEventSelect(sock->getFd(), sockEvent, 0);
386 ResetEvent(sockEvent);
387}
388
389
390void CConn::keyEvent(rdr::U32 key, bool down) {
391 if (!options.sendKeyEvents) return;
392 try {
393 writer()->keyEvent(key, down);
394 } catch (rdr::Exception& e) {
395 close(e.str());
396 }
397}
398void CConn::pointerEvent(const Point& pos, int buttonMask) {
399 if (!options.sendPtrEvents) return;
400 try {
401 writer()->pointerEvent(pos, buttonMask);
402 } catch (rdr::Exception& e) {
403 close(e.str());
404 }
405}
406void CConn::clientCutText(const char* str, int len) {
407 if (!options.clientCutText) return;
408 if (state() != RFBSTATE_NORMAL) return;
409 try {
410 writer()->clientCutText(str, len);
411 } catch (rdr::Exception& e) {
412 close(e.str());
413 }
414}
415
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000416void
417CConn::setColourMapEntries(int first, int count, U16* rgbs) {
418 vlog.debug("setColourMapEntries: first=%d, count=%d", first, count);
419 int i;
420 for (i=0;i<count;i++)
421 window->setColour(i+first, rgbs[i*3], rgbs[i*3+1], rgbs[i*3+2]);
422 // *** change to 0, 256?
423 window->refreshWindowPalette(first, count);
424}
425
426void
427CConn::bell() {
428 if (options.acceptBell)
Peter Åstrand7eb594a2008-12-11 08:27:52 +0000429 MessageBeep((UINT)-1);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000430}
431
432
433void
434CConn::setDesktopSize(int w, int h) {
435 vlog.debug("setDesktopSize %dx%d", w, h);
436
437 // Resize the window's buffer
438 if (window)
439 window->setSize(w, h);
440
441 // Tell the underlying CConnection
442 CConnection::setDesktopSize(w, h);
443}
444
Pierre Ossmand6d19942009-03-24 12:29:50 +0000445
446void
447CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
448 const rfb::ScreenSet& layout) {
Peter Åstrand145d1f82010-02-10 07:26:56 +0000449 if ((reason == (signed)reasonClient) && (result != (signed)resultSuccess)) {
Pierre Ossmand6d19942009-03-24 12:29:50 +0000450 vlog.error("SetDesktopSize failed: %d", result);
451 return;
452 }
453
454 // Resize the window's buffer
455 if (window)
456 window->setSize(w, h);
457
458 // Tell the underlying CConnection
459 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
460}
461
462
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000463void
464CConn::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
465 if (!options.useLocalCursor) return;
466
467 // Set the window to use the new cursor
468 window->setCursor(w, h, hotspot, data, mask);
469}
470
471
472void
473CConn::close(const char* reason) {
474 // If already closed then ignore this
475 if (isClosed())
476 return;
477
478 // Hide the window, if it exists
479 if (window)
480 ShowWindow(window->getHandle(), SW_HIDE);
481
482 // Save the reason & flag that we're closed & shutdown the socket
483 isClosed_ = true;
484 closeReason_.replaceBuf(strDup(reason));
485 sock->shutdown();
486}
487
Adam Tkac243fd7c2010-12-08 13:47:41 +0000488bool CConn::showMsgBox(int flags, const char* title, const char* text)
489{
490 UINT winflags = 0;
491 int ret;
492
493 /* Translate flags */
494 if ((flags & M_OK) != 0)
495 winflags |= MB_OK;
496 if ((flags & M_OKCANCEL) != 0)
497 winflags |= MB_OKCANCEL;
498 if ((flags & M_YESNO) != 0)
499 winflags |= MB_YESNO;
500 if ((flags & M_ICONERROR) != 0)
501 winflags |= MB_ICONERROR;
502 if ((flags & M_ICONQUESTION) != 0)
503 winflags |= MB_ICONQUESTION;
504 if ((flags & M_ICONWARNING) != 0)
505 winflags |= MB_ICONWARNING;
506 if ((flags & M_ICONINFORMATION) != 0)
507 winflags |= MB_ICONINFORMATION;
508 if ((flags & M_DEFBUTTON1) != 0)
509 winflags |= MB_DEFBUTTON1;
510 if ((flags & M_DEFBUTTON2) != 0)
511 winflags |= MB_DEFBUTTON2;
512
513 ret = MessageBox(NULL, text, title, flags);
514 return (ret == IDOK || ret == IDYES) ? true : false;
515}
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000516
517void
518CConn::showOptionsDialog() {
519 optionsDialog.showDialog(this);
520}
521
522
523void
524CConn::framebufferUpdateEnd() {
525 if (debugDelay != 0) {
526 vlog.debug("debug delay %d",(int)debugDelay);
527 UpdateWindow(window->getHandle());
528 Sleep(debugDelay);
529 std::list<rfb::Rect>::iterator i;
530 for (i = debugRects.begin(); i != debugRects.end(); i++) {
531 window->invertRect(*i);
532 }
533 debugRects.clear();
534 }
Pierre Ossmanb2ff1602009-03-25 12:13:28 +0000535 window->framebufferUpdateEnd();
Pierre Ossmand6d19942009-03-24 12:29:50 +0000536
537 if (firstUpdate) {
538 int width, height;
539
540 if (cp.supportsSetDesktopSize &&
541 sscanf(options.desktopSize.buf, "%dx%d", &width, &height) == 2) {
542 ScreenSet layout;
543
544 layout = cp.screenLayout;
545
546 if (layout.num_screens() == 0)
547 layout.add_screen(rfb::Screen());
548 else if (layout.num_screens() != 1) {
549 ScreenSet::iterator iter;
550
551 while (true) {
552 iter = layout.begin();
553 ++iter;
554
555 if (iter == layout.end())
556 break;
557
558 layout.remove_screen(iter->id);
559 }
560 }
561
562 layout.begin()->dimensions.tl.x = 0;
563 layout.begin()->dimensions.tl.y = 0;
564 layout.begin()->dimensions.br.x = width;
565 layout.begin()->dimensions.br.y = height;
566
567 writer()->writeSetDesktopSize(width, height, layout);
568 }
569
570 firstUpdate = false;
571 }
572
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000573 if (options.autoSelect)
574 autoSelectFormatAndEncoding();
575
576 // Always request the next update
577 requestUpdate = true;
578
579 // Check that at least part of the window has changed
580 if (!GetUpdateRect(window->getHandle(), 0, FALSE)) {
581 if (!(GetWindowLong(window->getHandle(), GWL_STYLE) & WS_MINIMIZE))
582 requestNewUpdate();
583 }
584
585 // Make sure the local cursor is shown
586 window->showCursor();
587}
588
589
Pierre Ossman78b23592009-03-12 12:25:11 +0000590// Note: The method below is duplicated in win/vncviewer/CConn.cxx!
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000591
592// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
593// to the connection speed:
594//
Pierre Ossman78b23592009-03-12 12:25:11 +0000595// First we wait for at least one second of bandwidth measurement.
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000596//
Pierre Ossman78b23592009-03-12 12:25:11 +0000597// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
598// which should be perceptually lossless.
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000599//
Pierre Ossman78b23592009-03-12 12:25:11 +0000600// If the bandwidth is below that, we choose a more lossy JPEG quality.
601//
602// If the bandwidth drops below 256 Kbps, we switch to palette mode.
603//
604// Note: The system here is fairly arbitrary and should be replaced
605// with something more intelligent at the server end.
606//
607void CConn::autoSelectFormatAndEncoding()
608{
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000609 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000610 unsigned int timeWaited = sock->inStream().timeWaited();
Pierre Ossman78b23592009-03-12 12:25:11 +0000611 bool newFullColour = options.fullColour;
612 int newQualityLevel = options.qualityLevel;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000613
Pierre Ossman78b23592009-03-12 12:25:11 +0000614 // Always use Tight
615 options.preferredEncoding = encodingTight;
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000616
Pierre Ossman78b23592009-03-12 12:25:11 +0000617 // Check that we have a decent bandwidth measurement
618 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000619 return;
Pierre Ossman78b23592009-03-12 12:25:11 +0000620
621 // Select appropriate quality level
622 if (!options.noJpeg) {
623 if (kbitsPerSecond > 16000)
624 newQualityLevel = 8;
625 else
626 newQualityLevel = 6;
627
628 if (newQualityLevel != options.qualityLevel) {
629 vlog.info("Throughput %d kbit/s - changing to quality %d ",
630 kbitsPerSecond, newQualityLevel);
631 cp.qualityLevel = newQualityLevel;
632 options.qualityLevel = newQualityLevel;
633 encodingChange = true;
634 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000635 }
636
637 if (cp.beforeVersion(3, 8)) {
638 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
639 // cursors "asynchronously". If this happens in the middle of a
640 // pixel format change, the server will encode the cursor with
641 // the old format, but the client will try to decode it
642 // according to the new format. This will lead to a
643 // crash. Therefore, we do not allow automatic format change for
644 // old servers.
645 return;
646 }
647
648 // Select best color level
649 newFullColour = (kbitsPerSecond > 256);
650 if (newFullColour != options.fullColour) {
651 vlog.info("Throughput %d kbit/s - full color is now %s",
Pierre Ossman78b23592009-03-12 12:25:11 +0000652 kbitsPerSecond,
653 newFullColour ? "enabled" : "disabled");
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000654 options.fullColour = newFullColour;
655 formatChange = true;
Pierre Ossman78b23592009-03-12 12:25:11 +0000656 }
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000657}
658
659void
660CConn::requestNewUpdate() {
661 if (!requestUpdate) return;
662
663 if (formatChange) {
664 // Select the required pixel format
665 if (options.fullColour) {
666 window->setPF(fullColourPF);
667 } else {
668 switch (options.lowColourLevel) {
669 case 0:
670 window->setPF(PixelFormat(8,3,0,1,1,1,1,2,1,0));
671 break;
672 case 1:
673 window->setPF(PixelFormat(8,6,0,1,3,3,3,4,2,0));
674 break;
675 case 2:
676 window->setPF(PixelFormat(8,8,0,0,0,0,0,0,0,0));
677 break;
678 }
679 }
680
681 // Print the current pixel format
682 char str[256];
683 window->getPF().print(str, 256);
684 vlog.info("Using pixel format %s",str);
685
686 // Save the connection pixel format and tell server to use it
687 cp.setPF(window->getPF());
688 writer()->writeSetPixelFormat(cp.pf());
689
690 // Correct the local window's palette
691 if (!window->getNativePF().trueColour)
692 window->refreshWindowPalette(0, 1 << cp.pf().depth);
693 }
694
695 if (encodingChange) {
696 vlog.info("Using %s encoding",encodingName(options.preferredEncoding));
697 writer()->writeSetEncodings(options.preferredEncoding, true);
698 }
699
700 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
701 !formatChange);
702
703 encodingChange = formatChange = requestUpdate = false;
704}
705
706
707void
708CConn::calculateFullColourPF() {
709 // If the server is palette based then use palette locally
710 // Also, don't bother doing bgr222
711 if (!serverDefaultPF.trueColour || (serverDefaultPF.depth < 6)) {
712 fullColourPF = serverDefaultPF;
713 options.fullColour = true;
714 } else {
715 // If server is trueColour, use lowest depth PF
716 PixelFormat native = window->getNativePF();
717 if ((serverDefaultPF.bpp < native.bpp) ||
718 ((serverDefaultPF.bpp == native.bpp) &&
719 (serverDefaultPF.depth < native.depth)))
720 fullColourPF = serverDefaultPF;
721 else
722 fullColourPF = window->getNativePF();
723 }
724 formatChange = true;
725}
726
727
728void
729CConn::setName(const char* name) {
730 if (window)
731 window->setName(name);
732 CConnection::setName(name);
733}
734
735
736void CConn::serverInit() {
737 CConnection::serverInit();
738
739 // If using AutoSelect with old servers, start in FullColor
740 // mode. See comment in autoSelectFormatAndEncoding.
741 if (cp.beforeVersion(3, 8) && options.autoSelect) {
742 options.fullColour = true;
743 }
744
745 // Show the window
746 window = new DesktopWindow(this);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000747
748 // Update the window menu
749 HMENU wndmenu = GetSystemMenu(window->getHandle(), FALSE);
750 int toolbarChecked = options.showToolbar ? MF_CHECKED : 0;
751
752 AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
753 AppendMenu(wndmenu, MF_STRING, IDM_FULLSCREEN, _T("&Full screen"));
754 AppendMenu(wndmenu, MF_STRING | toolbarChecked, IDM_SHOW_TOOLBAR,
755 _T("Show tool&bar"));
756 AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
757 AppendMenu(wndmenu, MF_STRING, IDM_CTRL_KEY, _T("Ctr&l"));
758 AppendMenu(wndmenu, MF_STRING, IDM_ALT_KEY, _T("Al&t"));
759 AppendMenu(wndmenu, MF_STRING, IDM_SEND_CAD, _T("Send Ctrl-Alt-&Del"));
760 AppendMenu(wndmenu, MF_STRING, IDM_SEND_CTLESC, _T("Send Ctrl-&Esc"));
761 AppendMenu(wndmenu, MF_STRING, IDM_REQUEST_REFRESH, _T("Refres&h Screen"));
762 AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
763 AppendMenu(wndmenu, MF_STRING, IDM_NEWCONN, _T("Ne&w Connection..."));
764 AppendMenu(wndmenu, MF_STRING, IDM_OPTIONS, _T("&Options..."));
765 AppendMenu(wndmenu, MF_STRING, IDM_INFO, _T("Connection &Info..."));
766 AppendMenu(wndmenu, MF_STRING, IDM_ABOUT, _T("&About..."));
Pierre Ossman0df7c7a2009-04-09 12:00:08 +0000767
768 // Set window attributes
769 window->setName(cp.name());
770 window->setShowToolbar(options.showToolbar);
771 window->setSize(cp.width, cp.height);
772 applyOptions(options);
773
774 // Save the server's current format
775 serverDefaultPF = cp.pf();
776
777 // Calculate the full-colour format to use
778 calculateFullColourPF();
779
780 // Request the initial update
781 vlog.info("requesting initial update");
782 formatChange = encodingChange = requestUpdate = true;
783 requestNewUpdate();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000784}
785
786void
Adam Tkacacf6c6b2009-02-13 12:42:05 +0000787CConn::serverCutText(const char* str, rdr::U32 len) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000788 if (!options.serverCutText) return;
789 window->serverCutText(str, len);
790}
791
792
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000793void CConn::beginRect(const Rect& r, int encoding) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000794 sock->inStream().startTiming();
795}
796
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000797void CConn::endRect(const Rect& r, int encoding) {
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000798 sock->inStream().stopTiming();
799 lastUsedEncoding_ = encoding;
800 if (debugDelay != 0) {
801 window->invertRect(r);
802 debugRects.push_back(r);
803 }
804}
805
806void CConn::fillRect(const Rect& r, Pixel pix) {
807 window->fillRect(r, pix);
808}
809void CConn::imageRect(const Rect& r, void* pixels) {
810 window->imageRect(r, pixels);
811}
812void CConn::copyRect(const Rect& r, int srcX, int srcY) {
813 window->copyRect(r, srcX, srcY);
814}
815
816void CConn::getUserPasswd(char** user, char** password) {
817 if (!user && options.passwordFile.buf[0]) {
818 FILE* fp = fopen(options.passwordFile.buf, "rb");
819 if (fp) {
820 char data[256];
821 int datalen = fread(data, 1, 256, fp);
822 fclose(fp);
823 if (datalen == 8) {
824 ObfuscatedPasswd obfPwd;
825 obfPwd.buf = data;
826 obfPwd.length = datalen;
827 PlainPasswd passwd(obfPwd);
Peter Åstrand8ace9152008-12-03 11:57:18 +0000828 obfPwd.takeBuf();
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000829 *password = strDup(passwd.buf);
Peter Åstrand8ace9152008-12-03 11:57:18 +0000830 memset(data, 0, sizeof(data));
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000831 }
832 }
833 }
834 if (user && options.userName.buf)
835 *user = strDup(options.userName.buf);
836 if (password && options.password.buf)
837 *password = strDup(options.password.buf);
838 if ((user && !*user) || (password && !*password)) {
839 // Missing username or password - prompt the user
840 UserPasswdDialog userPasswdDialog;
Adam Tkacf324dc42010-04-23 14:10:17 +0000841 userPasswdDialog.setCSecurity(csecurity);
Constantin Kaplinsky729598c2006-05-25 05:12:25 +0000842 userPasswdDialog.getUserPasswd(user, password);
843 }
844 if (user) options.setUserName(*user);
845 if (password) options.setPassword(*password);
846}
847