blob: 79195a8b6eef4e0f7c5b7c0a31936cae4b83b8bd [file] [log] [blame]
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossman49f88222009-03-20 13:02:50 +00002 * Copyright 2009 Pierre Ossman for Cendio AB
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +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// CConn.cxx
21//
22
23#include <unistd.h>
24#include "CConn.h"
25#include <rfb/CMsgWriter.h>
26#include <rfb/encodings.h>
27#include <rfb/secTypes.h>
28#include <rfb/CSecurityNone.h>
29#include <rfb/CSecurityVncAuth.h>
30#include <rfb/Hostname.h>
31#include <rfb/LogWriter.h>
32#include <rfb/util.h>
33#include <rfb/Password.h>
Pierre Ossman49f88222009-03-20 13:02:50 +000034#include <rfb/screenTypes.h>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000035#include <network/TcpSocket.h>
36
37#include "TXViewport.h"
38#include "DesktopWindow.h"
39#include "ServerDialog.h"
40#include "PasswdDialog.h"
41#include "parameters.h"
42
43using namespace rfb;
44
45static rfb::LogWriter vlog("CConn");
46
47IntParameter debugDelay("DebugDelay","Milliseconds to display inverted "
48 "pixel data - a debugging feature", 0);
49
50StringParameter menuKey("MenuKey", "The key which brings up the popup menu",
51 "F8");
52StringParameter windowName("name", "The X window name", "");
53
54CConn::CConn(Display* dpy_, int argc_, char** argv_, network::Socket* sock_,
55 char* vncServerName, bool reverse)
56 : dpy(dpy_), argc(argc_),
57 argv(argv_), serverHost(0), serverPort(0), sock(sock_), viewport(0),
58 desktop(0), desktopEventHandler(0),
Pierre Ossman7dfa22e2009-03-12 13:03:22 +000059 currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000060 fullColour(::fullColour),
61 autoSelect(::autoSelect), shared(::shared), formatChange(false),
62 encodingChange(false), sameMachine(false), fullScreen(::fullScreen),
63 ctrlDown(false), altDown(false),
64 menuKeysym(0), menu(dpy, this), options(dpy, this), about(dpy), info(dpy),
65 reverseConnection(reverse)
66{
67 CharArray menuKeyStr(menuKey.getData());
68 menuKeysym = XStringToKeysym(menuKeyStr.buf);
69
70 setShared(shared);
71 addSecType(secTypeNone);
72 addSecType(secTypeVncAuth);
73 CharArray encStr(preferredEncoding.getData());
74 int encNum = encodingNum(encStr.buf);
75 if (encNum != -1) {
76 currentEncoding = encNum;
77 }
78 cp.supportsDesktopResize = true;
Pierre Ossman49f88222009-03-20 13:02:50 +000079 cp.supportsExtendedDesktopSize = true;
Peter Åstrandc39e0782009-01-15 12:21:42 +000080 cp.supportsDesktopRename = true;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000081 cp.supportsLocalCursor = useLocalCursor;
82 cp.customCompressLevel = customCompressLevel;
83 cp.compressLevel = compressLevel;
84 cp.noJpeg = noJpeg;
85 cp.qualityLevel = qualityLevel;
86 initMenu();
87
88 if (sock) {
89 char* name = sock->getPeerEndpoint();
90 vlog.info("Accepted connection from %s", name);
91 if (name) free(name);
92 } else {
93 if (vncServerName) {
94 getHostAndPort(vncServerName, &serverHost, &serverPort);
95 } else {
96 ServerDialog dlg(dpy, &options, &about);
97 if (!dlg.show() || dlg.entry.getText()[0] == 0) {
98 exit(1);
99 }
100 getHostAndPort(dlg.entry.getText(), &serverHost, &serverPort);
101 }
102
103 sock = new network::TcpSocket(serverHost, serverPort);
104 vlog.info("connected to host %s port %d", serverHost, serverPort);
105 }
106
107 sameMachine = sock->sameMachine();
108 sock->inStream().setBlockCallback(this);
109 setServerName(sock->getPeerEndpoint());
110 setStreams(&sock->inStream(), &sock->outStream());
111 initialiseProtocol();
112}
113
114CConn::~CConn() {
115 free(serverHost);
116 delete desktop;
117 delete viewport;
118 delete sock;
119}
120
121// deleteWindow() is called when the user closes the desktop or menu windows.
122
123void CConn::deleteWindow(TXWindow* w) {
124 if (w == &menu) {
125 menu.unmap();
126 } else if (w == viewport) {
127 exit(1);
128 }
129}
130
131// handleEvent() filters all events on the desktop and menu. Most are passed
132// straight through. The exception is the F8 key. When pressed on the
133// desktop, it is used to bring up the menu. An F8 press or release on the
134// menu is passed through as if it were on the desktop.
135
136void CConn::handleEvent(TXWindow* w, XEvent* ev)
137{
138 KeySym ks;
139 char str[256];
140
141 switch (ev->type) {
142 case KeyPress:
143 case KeyRelease:
144 XLookupString(&ev->xkey, str, 256, &ks, NULL);
145 if (ks == menuKeysym && (ev->xkey.state & (ShiftMask|ControlMask)) == 0) {
146 if (w == desktop && ev->type == KeyPress) {
147 showMenu(ev->xkey.x_root, ev->xkey.y_root);
148 break;
149 } else if (w == &menu) {
150 if (ev->type == KeyPress) menu.unmap();
151 desktopEventHandler->handleEvent(w, ev);
152 break;
153 }
154 }
155 // drop through
156
157 default:
158 if (w == desktop) desktopEventHandler->handleEvent(w, ev);
159 else if (w == &menu) menuEventHandler->handleEvent(w, ev);
160 }
161}
162
163// blockCallback() is called when reading from the socket would block. We
164// process X events until the socket is ready for reading again.
165
166void CConn::blockCallback() {
167 fd_set rfds;
168 do {
169 struct timeval tv;
170 struct timeval* tvp = 0;
171
172 // Process any incoming X events
173 TXWindow::handleXEvents(dpy);
174
175 // Process expired timers and get the time until the next one
176 int timeoutMs = Timer::checkTimeouts();
177 if (timeoutMs) {
178 tv.tv_sec = timeoutMs / 1000;
179 tv.tv_usec = (timeoutMs % 1000) * 1000;
180 tvp = &tv;
181 }
182
183 // If there are X requests pending then poll, don't wait!
184 if (XPending(dpy)) {
185 tv.tv_usec = tv.tv_sec = 0;
186 tvp = &tv;
187 }
188
189 // Wait for X events, VNC traffic, or the next timer expiry
190 FD_ZERO(&rfds);
191 FD_SET(ConnectionNumber(dpy), &rfds);
192 FD_SET(sock->getFd(), &rfds);
193 int n = select(FD_SETSIZE, &rfds, 0, 0, tvp);
194 if (n < 0) throw rdr::SystemException("select",errno);
195 } while (!(FD_ISSET(sock->getFd(), &rfds)));
196}
197
198
199// getPasswd() is called by the CSecurity object when it needs us to read a
200// password from the user.
201
202void CConn::getUserPasswd(char** user, char** password)
203{
204 CharArray passwordFileStr(passwordFile.getData());
205 if (!user && passwordFileStr.buf[0]) {
206 FILE* fp = fopen(passwordFileStr.buf, "r");
207 if (!fp) throw rfb::Exception("Opening password file failed");
208 ObfuscatedPasswd obfPwd(256);
209 obfPwd.length = fread(obfPwd.buf, 1, obfPwd.length, fp);
210 fclose(fp);
211 PlainPasswd passwd(obfPwd);
212 *password = passwd.takeBuf();
213 return;
214 }
215
216 const char* secType = secTypeName(getCurrentCSecurity()->getType());
217 const char* titlePrefix = _("VNC authentication");
218 unsigned int titleLen = strlen(titlePrefix) + strlen(secType) + 4;
219 CharArray title(titleLen);
220 snprintf(title.buf, titleLen, "%s [%s]", titlePrefix, secType);
221 PasswdDialog dlg(dpy, title.buf, !user);
222 if (!dlg.show()) throw rfb::Exception("Authentication cancelled");
223 if (user)
224 *user = strDup(dlg.userEntry.getText());
225 *password = strDup(dlg.passwdEntry.getText());
226}
227
228
229// CConnection callback methods
230
231// getCSecurity() gets the appropriate CSecurity object for the security
232// types which we support.
233CSecurity* CConn::getCSecurity(int secType) {
234 switch (secType) {
235 case secTypeNone:
236 return new CSecurityNone();
237 case secTypeVncAuth:
238 return new CSecurityVncAuth(this);
239 default:
240 throw rfb::Exception("Unsupported secType?");
241 }
242}
243
244// serverInit() is called when the serverInit message has been received. At
245// this point we create the desktop window and display it. We also tell the
246// server the pixel format and encodings to use and request the first update.
247void CConn::serverInit() {
248 CConnection::serverInit();
249
250 // If using AutoSelect with old servers, start in FullColor
251 // mode. See comment in autoSelectFormatAndEncoding.
252 if (cp.beforeVersion(3, 8) && autoSelect) {
253 fullColour = true;
254 }
255
256 serverPF = cp.pf();
257 desktop = new DesktopWindow(dpy, cp.width, cp.height, serverPF, this);
258 desktopEventHandler = desktop->setEventHandler(this);
259 desktop->addEventMask(KeyPressMask | KeyReleaseMask);
260 fullColourPF = desktop->getPF();
261 if (!serverPF.trueColour)
262 fullColour = true;
263 recreateViewport();
264 formatChange = encodingChange = true;
265 requestNewUpdate();
266}
267
268// setDesktopSize() is called when the desktop size changes (including when
269// it is set initially).
270void CConn::setDesktopSize(int w, int h) {
271 CConnection::setDesktopSize(w,h);
Pierre Ossman49f88222009-03-20 13:02:50 +0000272 resizeFramebuffer();
273}
274
275// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
276void CConn::setExtendedDesktopSize(int reason, int result, int w, int h) {
277 CConnection::setExtendedDesktopSize(reason, result, w,h);
278
279 if ((reason == reasonClient) && (result != resultSuccess))
280 return;
281
282 resizeFramebuffer();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000283}
284
Peter Åstrandc39e0782009-01-15 12:21:42 +0000285// setName() is called when the desktop name changes
286void CConn::setName(const char* name) {
287 CConnection::setName(name);
Peter Åstrand051a83a2009-01-15 13:36:03 +0000288
289 CharArray windowNameStr(windowName.getData());
290 if (!windowNameStr.buf[0]) {
291 windowNameStr.replaceBuf(new char[256]);
Peter Åstrand4eacc022009-02-27 10:12:14 +0000292 snprintf(windowNameStr.buf, 256, _("TigerVNC: %.240s"), cp.name());
Peter Åstrand051a83a2009-01-15 13:36:03 +0000293 }
294
Peter Åstrandc39e0782009-01-15 12:21:42 +0000295 if (viewport) {
Peter Åstrand051a83a2009-01-15 13:36:03 +0000296 viewport->setName(windowNameStr.buf);
Peter Åstrandc39e0782009-01-15 12:21:42 +0000297 }
298}
299
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000300// framebufferUpdateEnd() is called at the end of an update.
301// For each rectangle, the FdInStream will have timed the speed
302// of the connection, allowing us to select format and encoding
303// appropriately, and then request another incremental update.
304void CConn::framebufferUpdateEnd() {
305 if (debugDelay != 0) {
306 XSync(dpy, False);
307 struct timeval tv;
308 tv.tv_sec = debugDelay / 1000;
309 tv.tv_usec = (debugDelay % 1000) * 1000;
310 select(0, 0, 0, 0, &tv);
311 std::list<rfb::Rect>::iterator i;
312 for (i = debugRects.begin(); i != debugRects.end(); i++) {
313 desktop->invertRect(*i);
314 }
315 debugRects.clear();
316 }
317 desktop->framebufferUpdateEnd();
318 if (autoSelect)
319 autoSelectFormatAndEncoding();
320 requestNewUpdate();
321}
322
323// The rest of the callbacks are fairly self-explanatory...
324
325void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
326{
327 desktop->setColourMapEntries(firstColour, nColours, rgbs);
328}
329
330void CConn::bell() { XBell(dpy, 0); }
331
332void CConn::serverCutText(const char* str, int len) {
333 desktop->serverCutText(str,len);
334}
335
336// We start timing on beginRect and stop timing on endRect, to
337// avoid skewing the bandwidth estimation as a result of the server
338// being slow or the network having high latency
339void CConn::beginRect(const Rect& r, unsigned int encoding)
340{
341 sock->inStream().startTiming();
342 if (encoding != encodingCopyRect) {
343 lastServerEncoding = encoding;
344 }
345}
346
347void CConn::endRect(const Rect& r, unsigned int encoding)
348{
349 sock->inStream().stopTiming();
350 if (debugDelay != 0) {
351 desktop->invertRect(r);
352 debugRects.push_back(r);
353 }
354}
355
356void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p) {
357 desktop->fillRect(r,p);
358}
359void CConn::imageRect(const rfb::Rect& r, void* p) {
360 desktop->imageRect(r,p);
361}
362void CConn::copyRect(const rfb::Rect& r, int sx, int sy) {
363 desktop->copyRect(r,sx,sy);
364}
365void CConn::setCursor(int width, int height, const Point& hotspot,
366 void* data, void* mask) {
367 desktop->setCursor(width, height, hotspot, data, mask);
368}
369
370
371// Menu stuff - menuSelect() is called when the user selects a menu option.
372
373enum { ID_OPTIONS, ID_INFO, ID_FULLSCREEN, ID_REFRESH, ID_F8, ID_CTRLALTDEL,
374 ID_ABOUT, ID_DISMISS, ID_EXIT, ID_NEWCONN, ID_CTRL, ID_ALT };
375
376void CConn::initMenu() {
377 menuEventHandler = menu.setEventHandler(this);
378 menu.addEventMask(KeyPressMask | KeyReleaseMask);
379 menu.addEntry(_("Exit viewer"), ID_EXIT);
380 menu.addEntry(0, 0);
381 menu.addEntry(_("Full screen"), ID_FULLSCREEN);
382 menu.check(ID_FULLSCREEN, fullScreen);
383 menu.addEntry(0, 0);
384 menu.addEntry(_("Ctrl"), ID_CTRL);
385 menu.addEntry(_("Alt"), ID_ALT);
386 CharArray menuKeyStr(menuKey.getData());
387 CharArray sendMenuKey(64);
388 snprintf(sendMenuKey.buf, 64, _("Send %s"), menuKeyStr.buf);
389 menu.addEntry(sendMenuKey.buf, ID_F8);
390 menu.addEntry(_("Send Ctrl-Alt-Del"), ID_CTRLALTDEL);
391 menu.addEntry(0, 0);
392 menu.addEntry(_("Refresh screen"), ID_REFRESH);
393 menu.addEntry(0, 0);
394 menu.addEntry(_("New connection..."), ID_NEWCONN);
395 menu.addEntry(_("Options..."), ID_OPTIONS);
396 menu.addEntry(_("Connection info..."), ID_INFO);
397 menu.addEntry(_("About VNCviewer..."), ID_ABOUT);
398 menu.addEntry(0, 0);
399 menu.addEntry(_("Dismiss menu"), ID_DISMISS);
400 menu.toplevel(_("VNC Menu"), this);
401 menu.setBorderWidth(1);
402}
403
404void CConn::showMenu(int x, int y) {
405 menu.check(ID_FULLSCREEN, fullScreen);
406 if (x + menu.width() > viewport->width())
407 x = viewport->width() - menu.width();
408 if (y + menu.height() > viewport->height())
409 y = viewport->height() - menu.height();
410 menu.move(x, y);
411 menu.raise();
412 menu.map();
413}
414
415void CConn::menuSelect(long id, TXMenu* m) {
416 switch (id) {
417 case ID_NEWCONN:
418 {
419 menu.unmap();
420 if (fullScreen) {
421 fullScreen = false;
422 if (viewport) recreateViewport();
423 }
424 int pid = fork();
425 if (pid < 0) { perror("fork"); exit(1); }
426 if (pid == 0) {
427 delete sock;
428 close(ConnectionNumber(dpy));
429 struct timeval tv;
430 tv.tv_sec = 0;
431 tv.tv_usec = 200*1000;
432 select(0, 0, 0, 0, &tv);
Adam Tkacfee32e32008-10-10 15:48:22 +0000433 execlp(programName, programName, NULL);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000434 perror("execlp"); exit(1);
435 }
436 break;
437 }
438 case ID_OPTIONS:
439 menu.unmap();
440 options.show();
441 break;
442 case ID_INFO:
443 {
444 menu.unmap();
445 char pfStr[100];
446 char spfStr[100];
447 cp.pf().print(pfStr, 100);
448 serverPF.print(spfStr, 100);
449 int secType = getCurrentCSecurity()->getType();
450 char infoText[1024];
451 snprintf(infoText, sizeof(infoText),
452 _("Desktop name: %.80s\n"
453 "Host: %.80s port: %d\n"
454 "Size: %d x %d\n"
455 "Pixel format: %s\n"
456 "(server default %s)\n"
457 "Requested encoding: %s\n"
458 "Last used encoding: %s\n"
459 "Line speed estimate: %d kbit/s\n"
460 "Protocol version: %d.%d\n"
461 "Security method: %s\n"),
462 cp.name(), serverHost, serverPort, cp.width, cp.height,
463 pfStr, spfStr, encodingName(currentEncoding),
464 encodingName(lastServerEncoding),
465 sock->inStream().kbitsPerSecond(),
466 cp.majorVersion, cp.minorVersion,
467 secTypeName(secType));
468 info.setText(infoText);
469 info.show();
470 break;
471 }
472 case ID_FULLSCREEN:
473 menu.unmap();
474 fullScreen = !fullScreen;
475 if (viewport) recreateViewport();
476 break;
477 case ID_REFRESH:
478 menu.unmap();
479 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
480 false);
481 break;
482 case ID_F8:
483 menu.unmap();
484 if (!viewOnly) {
485 writer()->keyEvent(menuKeysym, true);
486 writer()->keyEvent(menuKeysym, false);
487 }
488 break;
489 case ID_CTRLALTDEL:
490 menu.unmap();
491 if (!viewOnly) {
492 writer()->keyEvent(XK_Control_L, true);
493 writer()->keyEvent(XK_Alt_L, true);
494 writer()->keyEvent(XK_Delete, true);
495 writer()->keyEvent(XK_Delete, false);
496 writer()->keyEvent(XK_Alt_L, false);
497 writer()->keyEvent(XK_Control_L, false);
498 }
499 break;
500 case ID_CTRL:
501 menu.unmap();
502 if (!viewOnly) {
503 ctrlDown = !ctrlDown;
504 writer()->keyEvent(XK_Control_L, ctrlDown);
505 menu.check(ID_CTRL, ctrlDown);
506 }
507 break;
508 case ID_ALT:
509 menu.unmap();
510 if (!viewOnly) {
511 altDown = !altDown;
512 writer()->keyEvent(XK_Alt_L, altDown);
513 menu.check(ID_ALT, altDown);
514 }
515 break;
516 case ID_ABOUT:
517 menu.unmap();
518 about.show();
519 break;
520 case ID_DISMISS:
521 menu.unmap();
522 break;
523 case ID_EXIT:
524 exit(1);
525 break;
526 }
527}
528
529
530// OptionsDialogCallback. setOptions() sets the options dialog's checkboxes
531// etc to reflect our flags. getOptions() sets our flags according to the
532// options dialog's checkboxes.
533
534void CConn::setOptions() {
535 char digit[2] = "0";
536 options.autoSelect.checked(autoSelect);
537 options.fullColour.checked(fullColour);
538 options.veryLowColour.checked(!fullColour && lowColourLevel == 0);
539 options.lowColour.checked(!fullColour && lowColourLevel == 1);
540 options.mediumColour.checked(!fullColour && lowColourLevel == 2);
541 options.tight.checked(currentEncoding == encodingTight);
542 options.zrle.checked(currentEncoding == encodingZRLE);
543 options.hextile.checked(currentEncoding == encodingHextile);
544 options.raw.checked(currentEncoding == encodingRaw);
545
546 options.customCompressLevel.checked(customCompressLevel);
547 digit[0] = '0' + compressLevel;
548 options.compressLevel.setText(digit);
549 options.noJpeg.checked(!noJpeg);
550 digit[0] = '0' + qualityLevel;
551 options.qualityLevel.setText(digit);
552
553 options.viewOnly.checked(viewOnly);
554 options.acceptClipboard.checked(acceptClipboard);
555 options.sendClipboard.checked(sendClipboard);
556 options.sendPrimary.checked(sendPrimary);
557 if (state() == RFBSTATE_NORMAL)
558 options.shared.disabled(true);
559 else
560 options.shared.checked(shared);
561 options.fullScreen.checked(fullScreen);
562 options.useLocalCursor.checked(useLocalCursor);
563 options.dotWhenNoCursor.checked(dotWhenNoCursor);
564}
565
566void CConn::getOptions() {
567 autoSelect = options.autoSelect.checked();
568 if (fullColour != options.fullColour.checked())
569 formatChange = true;
570 fullColour = options.fullColour.checked();
571 if (!fullColour) {
572 int newLowColourLevel = (options.veryLowColour.checked() ? 0 :
573 options.lowColour.checked() ? 1 : 2);
574 if (newLowColourLevel != lowColourLevel) {
575 lowColourLevel.setParam(newLowColourLevel);
576 formatChange = true;
577 }
578 }
579 unsigned int newEncoding = (options.tight.checked() ? encodingTight :
580 options.zrle.checked() ? encodingZRLE :
581 options.hextile.checked() ? encodingHextile :
582 encodingRaw);
583 if (newEncoding != currentEncoding) {
584 currentEncoding = newEncoding;
585 encodingChange = true;
586 }
587
588 customCompressLevel.setParam(options.customCompressLevel.checked());
589 if (cp.customCompressLevel != customCompressLevel) {
590 cp.customCompressLevel = customCompressLevel;
591 encodingChange = true;
592 }
593 compressLevel.setParam(options.compressLevel.getText());
594 if (cp.compressLevel != compressLevel) {
595 cp.compressLevel = compressLevel;
596 encodingChange = true;
597 }
598 noJpeg.setParam(!options.noJpeg.checked());
599 if (cp.noJpeg != noJpeg) {
600 cp.noJpeg = noJpeg;
601 encodingChange = true;
602 }
603 qualityLevel.setParam(options.qualityLevel.getText());
604 if (cp.qualityLevel != qualityLevel) {
605 cp.qualityLevel = qualityLevel;
606 encodingChange = true;
607 }
608
609 viewOnly.setParam(options.viewOnly.checked());
610 acceptClipboard.setParam(options.acceptClipboard.checked());
611 sendClipboard.setParam(options.sendClipboard.checked());
612 sendPrimary.setParam(options.sendPrimary.checked());
613 shared = options.shared.checked();
614 setShared(shared);
615 if (fullScreen != options.fullScreen.checked()) {
616 fullScreen = options.fullScreen.checked();
617 if (viewport) recreateViewport();
618 }
619 useLocalCursor.setParam(options.useLocalCursor.checked());
620 if (cp.supportsLocalCursor != useLocalCursor) {
621 cp.supportsLocalCursor = useLocalCursor;
622 encodingChange = true;
623 if (desktop)
624 desktop->resetLocalCursor();
625 }
626 dotWhenNoCursor.setParam(options.dotWhenNoCursor.checked());
627 checkEncodings();
628}
629
Pierre Ossman49f88222009-03-20 13:02:50 +0000630void CConn::resizeFramebuffer()
631{
632 if (!desktop)
633 return;
634 if ((desktop->width() == cp.width) && (desktop->height() == cp.height))
635 return;
636
637 desktop->resize(cp.width, cp.height);
638 recreateViewport();
639}
640
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000641void CConn::recreateViewport()
642{
643 TXViewport* oldViewport = viewport;
644 viewport = new TXViewport(dpy, cp.width, cp.height);
645 desktop->setViewport(viewport);
646 CharArray windowNameStr(windowName.getData());
647 if (!windowNameStr.buf[0]) {
648 windowNameStr.replaceBuf(new char[256]);
Peter Åstrand4eacc022009-02-27 10:12:14 +0000649 snprintf(windowNameStr.buf, 256, _("TigerVNC: %.240s"), cp.name());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000650 }
651 viewport->toplevel(windowNameStr.buf, this, argc, argv);
652 viewport->setBumpScroll(fullScreen);
653 XSetWindowAttributes attr;
654 attr.override_redirect = fullScreen;
655 XChangeWindowAttributes(dpy, viewport->win(), CWOverrideRedirect, &attr);
656 XChangeWindowAttributes(dpy, menu.win(), CWOverrideRedirect, &attr);
657 XChangeWindowAttributes(dpy, options.win(), CWOverrideRedirect, &attr);
658 XChangeWindowAttributes(dpy, about.win(), CWOverrideRedirect, &attr);
659 XChangeWindowAttributes(dpy, info.win(), CWOverrideRedirect, &attr);
660 reconfigureViewport();
661 menu.setTransientFor(viewport->win());
662 viewport->map();
663 if (fullScreen) {
664 XGrabKeyboard(dpy, desktop->win(), True, GrabModeAsync, GrabModeAsync,
665 CurrentTime);
666 } else {
667 XUngrabKeyboard(dpy, CurrentTime);
668 }
669 if (oldViewport) delete oldViewport;
670}
671
672void CConn::reconfigureViewport()
673{
674 viewport->setMaxSize(cp.width, cp.height);
675 if (fullScreen) {
676 viewport->resize(DisplayWidth(dpy,DefaultScreen(dpy)),
677 DisplayHeight(dpy,DefaultScreen(dpy)));
678 } else {
679 int w = cp.width;
680 int h = cp.height;
681 if (w + wmDecorationWidth >= DisplayWidth(dpy,DefaultScreen(dpy)))
682 w = DisplayWidth(dpy,DefaultScreen(dpy)) - wmDecorationWidth;
683 if (h + wmDecorationHeight >= DisplayHeight(dpy,DefaultScreen(dpy)))
684 h = DisplayHeight(dpy,DefaultScreen(dpy)) - wmDecorationHeight;
685
686 int x = (DisplayWidth(dpy,DefaultScreen(dpy)) - w - wmDecorationWidth) / 2;
687 int y = (DisplayHeight(dpy,DefaultScreen(dpy)) - h - wmDecorationHeight)/2;
688
689 CharArray geometryStr(geometry.getData());
690 viewport->setGeometry(geometryStr.buf, x, y, w, h);
691 }
692}
693
Pierre Ossman78b23592009-03-12 12:25:11 +0000694// Note: The method below is duplicated in win/vncviewer/CConn.cxx!
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000695
696// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
697// to the connection speed:
698//
Pierre Ossman78b23592009-03-12 12:25:11 +0000699// First we wait for at least one second of bandwidth measurement.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000700//
Pierre Ossman78b23592009-03-12 12:25:11 +0000701// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
702// which should be perceptually lossless.
703//
704// If the bandwidth is below that, we choose a more lossy JPEG quality.
705//
706// If the bandwidth drops below 256 Kbps, we switch to palette mode.
707//
708// Note: The system here is fairly arbitrary and should be replaced
709// with something more intelligent at the server end.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000710//
711void CConn::autoSelectFormatAndEncoding()
712{
713 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000714 unsigned int timeWaited = sock->inStream().timeWaited();
Pierre Ossman78b23592009-03-12 12:25:11 +0000715 bool newFullColour = fullColour;
716 int newQualityLevel = qualityLevel;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000717
Pierre Ossman78b23592009-03-12 12:25:11 +0000718 // Always use Tight
719 currentEncoding = encodingTight;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000720
Pierre Ossman78b23592009-03-12 12:25:11 +0000721 // Check that we have a decent bandwidth measurement
722 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000723 return;
Pierre Ossman78b23592009-03-12 12:25:11 +0000724
725 // Select appropriate quality level
726 if (!noJpeg) {
727 if (kbitsPerSecond > 16000)
728 newQualityLevel = 8;
729 else
730 newQualityLevel = 6;
731
732 if (newQualityLevel != qualityLevel) {
733 vlog.info("Throughput %d kbit/s - changing to quality %d ",
734 kbitsPerSecond, newQualityLevel);
735 cp.qualityLevel = newQualityLevel;
736 qualityLevel.setParam(newQualityLevel);
737 encodingChange = true;
738 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000739 }
740
741 if (cp.beforeVersion(3, 8)) {
742 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
743 // cursors "asynchronously". If this happens in the middle of a
744 // pixel format change, the server will encode the cursor with
745 // the old format, but the client will try to decode it
746 // according to the new format. This will lead to a
747 // crash. Therefore, we do not allow automatic format change for
748 // old servers.
749 return;
750 }
751
752 // Select best color level
753 newFullColour = (kbitsPerSecond > 256);
754 if (newFullColour != fullColour) {
755 vlog.info("Throughput %d kbit/s - full color is now %s",
756 kbitsPerSecond,
757 newFullColour ? "enabled" : "disabled");
758 fullColour = newFullColour;
759 formatChange = true;
760 }
761}
762
763// checkEncodings() sends a setEncodings message if one is needed.
764void CConn::checkEncodings()
765{
766 if (encodingChange && writer()) {
767 vlog.info("Using %s encoding",encodingName(currentEncoding));
768 writer()->writeSetEncodings(currentEncoding, true);
769 encodingChange = false;
770 }
771}
772
773// requestNewUpdate() requests an update from the server, having set the
774// format and encoding appropriately.
775void CConn::requestNewUpdate()
776{
777 if (formatChange) {
778 if (fullColour) {
779 desktop->setPF(fullColourPF);
780 } else {
781 if (lowColourLevel == 0)
782 desktop->setPF(PixelFormat(8,3,0,1,1,1,1,2,1,0));
783 else if (lowColourLevel == 1)
784 desktop->setPF(PixelFormat(8,6,0,1,3,3,3,4,2,0));
785 else
786 desktop->setPF(PixelFormat(8,8,0,0));
787 }
788 char str[256];
789 desktop->getPF().print(str, 256);
790 vlog.info("Using pixel format %s",str);
791 cp.setPF(desktop->getPF());
792 writer()->writeSetPixelFormat(cp.pf());
793 }
794 checkEncodings();
795 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
796 !formatChange);
797 formatChange = false;
798}