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