blob: 556d05867a95a8fee16c40031ee128c25c826d4d [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>
Adam Tkac5a0caed2010-04-23 13:58:10 +000027#include <rfb/Security.h>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000028#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>
Adam Tkac12c0fc32010-03-04 15:33:11 +000036#include <cassert>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000037
38#include "TXViewport.h"
39#include "DesktopWindow.h"
40#include "ServerDialog.h"
41#include "PasswdDialog.h"
42#include "parameters.h"
43
44using namespace rfb;
45
46static rfb::LogWriter vlog("CConn");
47
48IntParameter debugDelay("DebugDelay","Milliseconds to display inverted "
49 "pixel data - a debugging feature", 0);
50
51StringParameter menuKey("MenuKey", "The key which brings up the popup menu",
52 "F8");
53StringParameter windowName("name", "The X window name", "");
54
55CConn::CConn(Display* dpy_, int argc_, char** argv_, network::Socket* sock_,
56 char* vncServerName, bool reverse)
57 : dpy(dpy_), argc(argc_),
58 argv(argv_), serverHost(0), serverPort(0), sock(sock_), viewport(0),
59 desktop(0), desktopEventHandler(0),
Pierre Ossman7dfa22e2009-03-12 13:03:22 +000060 currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000061 fullColour(::fullColour),
62 autoSelect(::autoSelect), shared(::shared), formatChange(false),
63 encodingChange(false), sameMachine(false), fullScreen(::fullScreen),
64 ctrlDown(false), altDown(false),
65 menuKeysym(0), menu(dpy, this), options(dpy, this), about(dpy), info(dpy),
Adam Tkac12c0fc32010-03-04 15:33:11 +000066 reverseConnection(reverse), firstUpdate(true), pendingUpdate(false)
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000067{
68 CharArray menuKeyStr(menuKey.getData());
69 menuKeysym = XStringToKeysym(menuKeyStr.buf);
70
71 setShared(shared);
72 addSecType(secTypeNone);
73 addSecType(secTypeVncAuth);
Adam Tkacf324dc42010-04-23 14:10:17 +000074 security->upg = this; /* Security instance is created in CConnection costructor. */
75
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000076 CharArray encStr(preferredEncoding.getData());
77 int encNum = encodingNum(encStr.buf);
78 if (encNum != -1) {
79 currentEncoding = encNum;
80 }
81 cp.supportsDesktopResize = true;
Pierre Ossman49f88222009-03-20 13:02:50 +000082 cp.supportsExtendedDesktopSize = true;
Peter Åstrandc39e0782009-01-15 12:21:42 +000083 cp.supportsDesktopRename = true;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000084 cp.supportsLocalCursor = useLocalCursor;
85 cp.customCompressLevel = customCompressLevel;
86 cp.compressLevel = compressLevel;
87 cp.noJpeg = noJpeg;
88 cp.qualityLevel = qualityLevel;
89 initMenu();
90
91 if (sock) {
92 char* name = sock->getPeerEndpoint();
93 vlog.info("Accepted connection from %s", name);
94 if (name) free(name);
95 } else {
96 if (vncServerName) {
97 getHostAndPort(vncServerName, &serverHost, &serverPort);
98 } else {
99 ServerDialog dlg(dpy, &options, &about);
100 if (!dlg.show() || dlg.entry.getText()[0] == 0) {
101 exit(1);
102 }
103 getHostAndPort(dlg.entry.getText(), &serverHost, &serverPort);
104 }
105
106 sock = new network::TcpSocket(serverHost, serverPort);
107 vlog.info("connected to host %s port %d", serverHost, serverPort);
108 }
109
110 sameMachine = sock->sameMachine();
111 sock->inStream().setBlockCallback(this);
112 setServerName(sock->getPeerEndpoint());
113 setStreams(&sock->inStream(), &sock->outStream());
114 initialiseProtocol();
115}
116
117CConn::~CConn() {
118 free(serverHost);
119 delete desktop;
120 delete viewport;
121 delete sock;
122}
123
124// deleteWindow() is called when the user closes the desktop or menu windows.
125
126void CConn::deleteWindow(TXWindow* w) {
127 if (w == &menu) {
128 menu.unmap();
129 } else if (w == viewport) {
130 exit(1);
131 }
132}
133
134// handleEvent() filters all events on the desktop and menu. Most are passed
135// straight through. The exception is the F8 key. When pressed on the
136// desktop, it is used to bring up the menu. An F8 press or release on the
137// menu is passed through as if it were on the desktop.
138
139void CConn::handleEvent(TXWindow* w, XEvent* ev)
140{
141 KeySym ks;
142 char str[256];
143
144 switch (ev->type) {
145 case KeyPress:
146 case KeyRelease:
147 XLookupString(&ev->xkey, str, 256, &ks, NULL);
148 if (ks == menuKeysym && (ev->xkey.state & (ShiftMask|ControlMask)) == 0) {
149 if (w == desktop && ev->type == KeyPress) {
150 showMenu(ev->xkey.x_root, ev->xkey.y_root);
151 break;
152 } else if (w == &menu) {
153 if (ev->type == KeyPress) menu.unmap();
154 desktopEventHandler->handleEvent(w, ev);
155 break;
156 }
157 }
158 // drop through
159
160 default:
161 if (w == desktop) desktopEventHandler->handleEvent(w, ev);
162 else if (w == &menu) menuEventHandler->handleEvent(w, ev);
163 }
164}
165
166// blockCallback() is called when reading from the socket would block. We
167// process X events until the socket is ready for reading again.
168
169void CConn::blockCallback() {
170 fd_set rfds;
171 do {
172 struct timeval tv;
173 struct timeval* tvp = 0;
174
175 // Process any incoming X events
176 TXWindow::handleXEvents(dpy);
177
178 // Process expired timers and get the time until the next one
179 int timeoutMs = Timer::checkTimeouts();
180 if (timeoutMs) {
181 tv.tv_sec = timeoutMs / 1000;
182 tv.tv_usec = (timeoutMs % 1000) * 1000;
183 tvp = &tv;
184 }
185
186 // If there are X requests pending then poll, don't wait!
187 if (XPending(dpy)) {
188 tv.tv_usec = tv.tv_sec = 0;
189 tvp = &tv;
190 }
191
192 // Wait for X events, VNC traffic, or the next timer expiry
193 FD_ZERO(&rfds);
194 FD_SET(ConnectionNumber(dpy), &rfds);
195 FD_SET(sock->getFd(), &rfds);
196 int n = select(FD_SETSIZE, &rfds, 0, 0, tvp);
197 if (n < 0) throw rdr::SystemException("select",errno);
198 } while (!(FD_ISSET(sock->getFd(), &rfds)));
199}
200
201
202// getPasswd() is called by the CSecurity object when it needs us to read a
203// password from the user.
204
205void CConn::getUserPasswd(char** user, char** password)
206{
207 CharArray passwordFileStr(passwordFile.getData());
208 if (!user && passwordFileStr.buf[0]) {
209 FILE* fp = fopen(passwordFileStr.buf, "r");
210 if (!fp) throw rfb::Exception("Opening password file failed");
211 ObfuscatedPasswd obfPwd(256);
212 obfPwd.length = fread(obfPwd.buf, 1, obfPwd.length, fp);
213 fclose(fp);
214 PlainPasswd passwd(obfPwd);
215 *password = passwd.takeBuf();
216 return;
217 }
218
Adam Tkacf324dc42010-04-23 14:10:17 +0000219 const char* secType = secTypeName(csecurity->getType());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000220 const char* titlePrefix = _("VNC authentication");
221 unsigned int titleLen = strlen(titlePrefix) + strlen(secType) + 4;
222 CharArray title(titleLen);
223 snprintf(title.buf, titleLen, "%s [%s]", titlePrefix, secType);
224 PasswdDialog dlg(dpy, title.buf, !user);
225 if (!dlg.show()) throw rfb::Exception("Authentication cancelled");
226 if (user)
Adam Tkacd36b6262009-09-04 10:57:20 +0000227 *user = strDup(dlg.userEntry.getText());
228 *password = strDup(dlg.passwdEntry.getText());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000229}
230
231
232// CConnection callback methods
233
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000234// serverInit() is called when the serverInit message has been received. At
235// this point we create the desktop window and display it. We also tell the
236// server the pixel format and encodings to use and request the first update.
237void CConn::serverInit() {
238 CConnection::serverInit();
239
240 // If using AutoSelect with old servers, start in FullColor
241 // mode. See comment in autoSelectFormatAndEncoding.
242 if (cp.beforeVersion(3, 8) && autoSelect) {
243 fullColour = true;
244 }
245
246 serverPF = cp.pf();
247 desktop = new DesktopWindow(dpy, cp.width, cp.height, serverPF, this);
248 desktopEventHandler = desktop->setEventHandler(this);
249 desktop->addEventMask(KeyPressMask | KeyReleaseMask);
250 fullColourPF = desktop->getPF();
251 if (!serverPF.trueColour)
252 fullColour = true;
253 recreateViewport();
254 formatChange = encodingChange = true;
255 requestNewUpdate();
256}
257
258// setDesktopSize() is called when the desktop size changes (including when
259// it is set initially).
260void CConn::setDesktopSize(int w, int h) {
261 CConnection::setDesktopSize(w,h);
Pierre Ossman49f88222009-03-20 13:02:50 +0000262 resizeFramebuffer();
263}
264
265// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
Pierre Ossmancbd1b2c2009-03-20 16:05:04 +0000266void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
267 const rfb::ScreenSet& layout) {
268 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
Pierre Ossman49f88222009-03-20 13:02:50 +0000269
Pierre Ossmaneb3cecb2009-03-23 16:49:47 +0000270 if ((reason == reasonClient) && (result != resultSuccess)) {
271 vlog.error("SetDesktopSize failed: %d", result);
Pierre Ossman49f88222009-03-20 13:02:50 +0000272 return;
Pierre Ossmaneb3cecb2009-03-23 16:49:47 +0000273 }
Pierre Ossman49f88222009-03-20 13:02:50 +0000274
275 resizeFramebuffer();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000276}
277
Peter Åstrandc39e0782009-01-15 12:21:42 +0000278// setName() is called when the desktop name changes
279void CConn::setName(const char* name) {
280 CConnection::setName(name);
Peter Åstrand051a83a2009-01-15 13:36:03 +0000281
282 CharArray windowNameStr(windowName.getData());
283 if (!windowNameStr.buf[0]) {
284 windowNameStr.replaceBuf(new char[256]);
Peter Åstrand4eacc022009-02-27 10:12:14 +0000285 snprintf(windowNameStr.buf, 256, _("TigerVNC: %.240s"), cp.name());
Peter Åstrand051a83a2009-01-15 13:36:03 +0000286 }
287
Peter Åstrandc39e0782009-01-15 12:21:42 +0000288 if (viewport) {
Peter Åstrand051a83a2009-01-15 13:36:03 +0000289 viewport->setName(windowNameStr.buf);
Peter Åstrandc39e0782009-01-15 12:21:42 +0000290 }
291}
292
Pierre Ossman42d20e72009-04-01 14:42:34 +0000293// framebufferUpdateStart() is called at the beginning of an update.
294// Here we try to send out a new framebuffer update request so that the
295// next update can be sent out in parallel with us decoding the current
296// one. We cannot do this if we're in the middle of a format change
297// though.
298void CConn::framebufferUpdateStart() {
Adam Tkac12c0fc32010-03-04 15:33:11 +0000299 if (!formatChange) {
300 pendingUpdate = true;
Pierre Ossman42d20e72009-04-01 14:42:34 +0000301 requestNewUpdate();
Adam Tkac12c0fc32010-03-04 15:33:11 +0000302 } else
303 pendingUpdate = false;
Pierre Ossman42d20e72009-04-01 14:42:34 +0000304}
305
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000306// framebufferUpdateEnd() is called at the end of an update.
307// For each rectangle, the FdInStream will have timed the speed
308// of the connection, allowing us to select format and encoding
309// appropriately, and then request another incremental update.
310void CConn::framebufferUpdateEnd() {
311 if (debugDelay != 0) {
312 XSync(dpy, False);
313 struct timeval tv;
314 tv.tv_sec = debugDelay / 1000;
315 tv.tv_usec = (debugDelay % 1000) * 1000;
316 select(0, 0, 0, 0, &tv);
317 std::list<rfb::Rect>::iterator i;
318 for (i = debugRects.begin(); i != debugRects.end(); i++) {
319 desktop->invertRect(*i);
320 }
321 debugRects.clear();
322 }
323 desktop->framebufferUpdateEnd();
Pierre Ossmaneb3cecb2009-03-23 16:49:47 +0000324
325 if (firstUpdate) {
326 int width, height;
327
328 if (cp.supportsSetDesktopSize &&
329 sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
330 ScreenSet layout;
331
332 layout = cp.screenLayout;
333
334 if (layout.num_screens() == 0)
335 layout.add_screen(rfb::Screen());
336 else if (layout.num_screens() != 1) {
337 ScreenSet::iterator iter;
338
339 while (true) {
340 iter = layout.begin();
341 ++iter;
342
343 if (iter == layout.end())
344 break;
345
346 layout.remove_screen(iter->id);
347 }
348 }
349
350 layout.begin()->dimensions.tl.x = 0;
351 layout.begin()->dimensions.tl.y = 0;
352 layout.begin()->dimensions.br.x = width;
353 layout.begin()->dimensions.br.y = height;
354
355 writer()->writeSetDesktopSize(width, height, layout);
356 }
357
358 firstUpdate = false;
359 }
360
Pierre Ossman42d20e72009-04-01 14:42:34 +0000361 // A format change prevented us from sending this before the update,
362 // so make sure to send it now.
Adam Tkac12c0fc32010-03-04 15:33:11 +0000363 if (formatChange && !pendingUpdate)
Pierre Ossman42d20e72009-04-01 14:42:34 +0000364 requestNewUpdate();
365
366 // Compute new settings based on updated bandwidth values
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000367 if (autoSelect)
368 autoSelectFormatAndEncoding();
Pierre Ossman42d20e72009-04-01 14:42:34 +0000369
370 // Make sure that the X11 handling and the timers gets some CPU time
371 // in case of back to back framebuffer updates.
372 TXWindow::handleXEvents(dpy);
373 Timer::checkTimeouts();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000374}
375
376// The rest of the callbacks are fairly self-explanatory...
377
378void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
379{
380 desktop->setColourMapEntries(firstColour, nColours, rgbs);
381}
382
383void CConn::bell() { XBell(dpy, 0); }
384
Adam Tkac141c1722009-06-16 10:43:59 +0000385void CConn::serverCutText(const char* str, rdr::U32 len) {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000386 desktop->serverCutText(str,len);
387}
388
389// We start timing on beginRect and stop timing on endRect, to
390// avoid skewing the bandwidth estimation as a result of the server
391// being slow or the network having high latency
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000392void CConn::beginRect(const Rect& r, int encoding)
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000393{
394 sock->inStream().startTiming();
395 if (encoding != encodingCopyRect) {
396 lastServerEncoding = encoding;
397 }
398}
399
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000400void CConn::endRect(const Rect& r, int encoding)
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000401{
402 sock->inStream().stopTiming();
403 if (debugDelay != 0) {
404 desktop->invertRect(r);
405 debugRects.push_back(r);
406 }
407}
408
409void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p) {
410 desktop->fillRect(r,p);
411}
412void CConn::imageRect(const rfb::Rect& r, void* p) {
413 desktop->imageRect(r,p);
414}
415void CConn::copyRect(const rfb::Rect& r, int sx, int sy) {
416 desktop->copyRect(r,sx,sy);
417}
418void CConn::setCursor(int width, int height, const Point& hotspot,
419 void* data, void* mask) {
420 desktop->setCursor(width, height, hotspot, data, mask);
421}
422
423
424// Menu stuff - menuSelect() is called when the user selects a menu option.
425
426enum { ID_OPTIONS, ID_INFO, ID_FULLSCREEN, ID_REFRESH, ID_F8, ID_CTRLALTDEL,
427 ID_ABOUT, ID_DISMISS, ID_EXIT, ID_NEWCONN, ID_CTRL, ID_ALT };
428
429void CConn::initMenu() {
430 menuEventHandler = menu.setEventHandler(this);
431 menu.addEventMask(KeyPressMask | KeyReleaseMask);
432 menu.addEntry(_("Exit viewer"), ID_EXIT);
433 menu.addEntry(0, 0);
434 menu.addEntry(_("Full screen"), ID_FULLSCREEN);
435 menu.check(ID_FULLSCREEN, fullScreen);
436 menu.addEntry(0, 0);
437 menu.addEntry(_("Ctrl"), ID_CTRL);
438 menu.addEntry(_("Alt"), ID_ALT);
439 CharArray menuKeyStr(menuKey.getData());
440 CharArray sendMenuKey(64);
441 snprintf(sendMenuKey.buf, 64, _("Send %s"), menuKeyStr.buf);
442 menu.addEntry(sendMenuKey.buf, ID_F8);
443 menu.addEntry(_("Send Ctrl-Alt-Del"), ID_CTRLALTDEL);
444 menu.addEntry(0, 0);
445 menu.addEntry(_("Refresh screen"), ID_REFRESH);
446 menu.addEntry(0, 0);
447 menu.addEntry(_("New connection..."), ID_NEWCONN);
448 menu.addEntry(_("Options..."), ID_OPTIONS);
449 menu.addEntry(_("Connection info..."), ID_INFO);
Peter Åstrandf55ca172009-08-27 12:22:10 +0000450 menu.addEntry(_("About TigerVNC viewer..."), ID_ABOUT);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000451 menu.addEntry(0, 0);
452 menu.addEntry(_("Dismiss menu"), ID_DISMISS);
453 menu.toplevel(_("VNC Menu"), this);
454 menu.setBorderWidth(1);
455}
456
457void CConn::showMenu(int x, int y) {
458 menu.check(ID_FULLSCREEN, fullScreen);
459 if (x + menu.width() > viewport->width())
460 x = viewport->width() - menu.width();
461 if (y + menu.height() > viewport->height())
462 y = viewport->height() - menu.height();
463 menu.move(x, y);
464 menu.raise();
465 menu.map();
466}
467
468void CConn::menuSelect(long id, TXMenu* m) {
469 switch (id) {
470 case ID_NEWCONN:
471 {
472 menu.unmap();
473 if (fullScreen) {
474 fullScreen = false;
475 if (viewport) recreateViewport();
476 }
477 int pid = fork();
478 if (pid < 0) { perror("fork"); exit(1); }
479 if (pid == 0) {
480 delete sock;
481 close(ConnectionNumber(dpy));
482 struct timeval tv;
483 tv.tv_sec = 0;
484 tv.tv_usec = 200*1000;
485 select(0, 0, 0, 0, &tv);
Adam Tkacfee32e32008-10-10 15:48:22 +0000486 execlp(programName, programName, NULL);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000487 perror("execlp"); exit(1);
488 }
489 break;
490 }
491 case ID_OPTIONS:
492 menu.unmap();
493 options.show();
494 break;
495 case ID_INFO:
496 {
497 menu.unmap();
498 char pfStr[100];
499 char spfStr[100];
500 cp.pf().print(pfStr, 100);
501 serverPF.print(spfStr, 100);
Adam Tkacf324dc42010-04-23 14:10:17 +0000502 int secType = csecurity->getType();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000503 char infoText[1024];
504 snprintf(infoText, sizeof(infoText),
505 _("Desktop name: %.80s\n"
506 "Host: %.80s port: %d\n"
507 "Size: %d x %d\n"
508 "Pixel format: %s\n"
509 "(server default %s)\n"
510 "Requested encoding: %s\n"
511 "Last used encoding: %s\n"
512 "Line speed estimate: %d kbit/s\n"
513 "Protocol version: %d.%d\n"
514 "Security method: %s\n"),
515 cp.name(), serverHost, serverPort, cp.width, cp.height,
516 pfStr, spfStr, encodingName(currentEncoding),
517 encodingName(lastServerEncoding),
518 sock->inStream().kbitsPerSecond(),
519 cp.majorVersion, cp.minorVersion,
520 secTypeName(secType));
521 info.setText(infoText);
522 info.show();
523 break;
524 }
525 case ID_FULLSCREEN:
526 menu.unmap();
527 fullScreen = !fullScreen;
528 if (viewport) recreateViewport();
529 break;
530 case ID_REFRESH:
531 menu.unmap();
Adam Tkac12c0fc32010-03-04 15:33:11 +0000532 if (!formatChange) {
533 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
534 false);
535 pendingUpdate = true;
536 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000537 break;
538 case ID_F8:
539 menu.unmap();
540 if (!viewOnly) {
541 writer()->keyEvent(menuKeysym, true);
542 writer()->keyEvent(menuKeysym, false);
543 }
544 break;
545 case ID_CTRLALTDEL:
546 menu.unmap();
547 if (!viewOnly) {
548 writer()->keyEvent(XK_Control_L, true);
549 writer()->keyEvent(XK_Alt_L, true);
550 writer()->keyEvent(XK_Delete, true);
551 writer()->keyEvent(XK_Delete, false);
552 writer()->keyEvent(XK_Alt_L, false);
553 writer()->keyEvent(XK_Control_L, false);
554 }
555 break;
556 case ID_CTRL:
557 menu.unmap();
558 if (!viewOnly) {
559 ctrlDown = !ctrlDown;
560 writer()->keyEvent(XK_Control_L, ctrlDown);
561 menu.check(ID_CTRL, ctrlDown);
562 }
563 break;
564 case ID_ALT:
565 menu.unmap();
566 if (!viewOnly) {
567 altDown = !altDown;
568 writer()->keyEvent(XK_Alt_L, altDown);
569 menu.check(ID_ALT, altDown);
570 }
571 break;
572 case ID_ABOUT:
573 menu.unmap();
574 about.show();
575 break;
576 case ID_DISMISS:
577 menu.unmap();
578 break;
579 case ID_EXIT:
580 exit(1);
581 break;
582 }
583}
584
585
586// OptionsDialogCallback. setOptions() sets the options dialog's checkboxes
587// etc to reflect our flags. getOptions() sets our flags according to the
588// options dialog's checkboxes.
589
590void CConn::setOptions() {
591 char digit[2] = "0";
592 options.autoSelect.checked(autoSelect);
593 options.fullColour.checked(fullColour);
594 options.veryLowColour.checked(!fullColour && lowColourLevel == 0);
595 options.lowColour.checked(!fullColour && lowColourLevel == 1);
596 options.mediumColour.checked(!fullColour && lowColourLevel == 2);
597 options.tight.checked(currentEncoding == encodingTight);
598 options.zrle.checked(currentEncoding == encodingZRLE);
599 options.hextile.checked(currentEncoding == encodingHextile);
600 options.raw.checked(currentEncoding == encodingRaw);
601
602 options.customCompressLevel.checked(customCompressLevel);
603 digit[0] = '0' + compressLevel;
604 options.compressLevel.setText(digit);
605 options.noJpeg.checked(!noJpeg);
606 digit[0] = '0' + qualityLevel;
607 options.qualityLevel.setText(digit);
608
609 options.viewOnly.checked(viewOnly);
610 options.acceptClipboard.checked(acceptClipboard);
611 options.sendClipboard.checked(sendClipboard);
612 options.sendPrimary.checked(sendPrimary);
613 if (state() == RFBSTATE_NORMAL)
614 options.shared.disabled(true);
615 else
616 options.shared.checked(shared);
617 options.fullScreen.checked(fullScreen);
618 options.useLocalCursor.checked(useLocalCursor);
619 options.dotWhenNoCursor.checked(dotWhenNoCursor);
620}
621
622void CConn::getOptions() {
623 autoSelect = options.autoSelect.checked();
624 if (fullColour != options.fullColour.checked())
625 formatChange = true;
626 fullColour = options.fullColour.checked();
627 if (!fullColour) {
628 int newLowColourLevel = (options.veryLowColour.checked() ? 0 :
629 options.lowColour.checked() ? 1 : 2);
630 if (newLowColourLevel != lowColourLevel) {
631 lowColourLevel.setParam(newLowColourLevel);
632 formatChange = true;
633 }
634 }
Peter Åstrand98fe98c2010-02-10 07:43:02 +0000635 int newEncoding = (options.tight.checked() ? encodingTight :
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000636 options.zrle.checked() ? encodingZRLE :
637 options.hextile.checked() ? encodingHextile :
638 encodingRaw);
639 if (newEncoding != currentEncoding) {
640 currentEncoding = newEncoding;
641 encodingChange = true;
642 }
643
644 customCompressLevel.setParam(options.customCompressLevel.checked());
645 if (cp.customCompressLevel != customCompressLevel) {
646 cp.customCompressLevel = customCompressLevel;
647 encodingChange = true;
648 }
649 compressLevel.setParam(options.compressLevel.getText());
650 if (cp.compressLevel != compressLevel) {
651 cp.compressLevel = compressLevel;
652 encodingChange = true;
653 }
654 noJpeg.setParam(!options.noJpeg.checked());
655 if (cp.noJpeg != noJpeg) {
656 cp.noJpeg = noJpeg;
657 encodingChange = true;
658 }
659 qualityLevel.setParam(options.qualityLevel.getText());
660 if (cp.qualityLevel != qualityLevel) {
661 cp.qualityLevel = qualityLevel;
662 encodingChange = true;
663 }
664
665 viewOnly.setParam(options.viewOnly.checked());
666 acceptClipboard.setParam(options.acceptClipboard.checked());
667 sendClipboard.setParam(options.sendClipboard.checked());
668 sendPrimary.setParam(options.sendPrimary.checked());
669 shared = options.shared.checked();
670 setShared(shared);
671 if (fullScreen != options.fullScreen.checked()) {
672 fullScreen = options.fullScreen.checked();
673 if (viewport) recreateViewport();
674 }
675 useLocalCursor.setParam(options.useLocalCursor.checked());
676 if (cp.supportsLocalCursor != useLocalCursor) {
677 cp.supportsLocalCursor = useLocalCursor;
678 encodingChange = true;
679 if (desktop)
680 desktop->resetLocalCursor();
681 }
682 dotWhenNoCursor.setParam(options.dotWhenNoCursor.checked());
Adam Tkaccc247c92010-01-11 13:46:48 +0000683 if (desktop)
684 desktop->setNoCursor();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000685 checkEncodings();
686}
687
Pierre Ossman49f88222009-03-20 13:02:50 +0000688void CConn::resizeFramebuffer()
689{
690 if (!desktop)
691 return;
692 if ((desktop->width() == cp.width) && (desktop->height() == cp.height))
693 return;
694
695 desktop->resize(cp.width, cp.height);
696 recreateViewport();
697}
698
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000699void CConn::recreateViewport()
700{
701 TXViewport* oldViewport = viewport;
702 viewport = new TXViewport(dpy, cp.width, cp.height);
703 desktop->setViewport(viewport);
704 CharArray windowNameStr(windowName.getData());
705 if (!windowNameStr.buf[0]) {
706 windowNameStr.replaceBuf(new char[256]);
Peter Åstrand4eacc022009-02-27 10:12:14 +0000707 snprintf(windowNameStr.buf, 256, _("TigerVNC: %.240s"), cp.name());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000708 }
709 viewport->toplevel(windowNameStr.buf, this, argc, argv);
710 viewport->setBumpScroll(fullScreen);
711 XSetWindowAttributes attr;
712 attr.override_redirect = fullScreen;
713 XChangeWindowAttributes(dpy, viewport->win(), CWOverrideRedirect, &attr);
714 XChangeWindowAttributes(dpy, menu.win(), CWOverrideRedirect, &attr);
715 XChangeWindowAttributes(dpy, options.win(), CWOverrideRedirect, &attr);
716 XChangeWindowAttributes(dpy, about.win(), CWOverrideRedirect, &attr);
717 XChangeWindowAttributes(dpy, info.win(), CWOverrideRedirect, &attr);
718 reconfigureViewport();
719 menu.setTransientFor(viewport->win());
720 viewport->map();
721 if (fullScreen) {
722 XGrabKeyboard(dpy, desktop->win(), True, GrabModeAsync, GrabModeAsync,
723 CurrentTime);
724 } else {
725 XUngrabKeyboard(dpy, CurrentTime);
726 }
727 if (oldViewport) delete oldViewport;
728}
729
730void CConn::reconfigureViewport()
731{
732 viewport->setMaxSize(cp.width, cp.height);
733 if (fullScreen) {
734 viewport->resize(DisplayWidth(dpy,DefaultScreen(dpy)),
735 DisplayHeight(dpy,DefaultScreen(dpy)));
736 } else {
737 int w = cp.width;
738 int h = cp.height;
739 if (w + wmDecorationWidth >= DisplayWidth(dpy,DefaultScreen(dpy)))
740 w = DisplayWidth(dpy,DefaultScreen(dpy)) - wmDecorationWidth;
741 if (h + wmDecorationHeight >= DisplayHeight(dpy,DefaultScreen(dpy)))
742 h = DisplayHeight(dpy,DefaultScreen(dpy)) - wmDecorationHeight;
743
744 int x = (DisplayWidth(dpy,DefaultScreen(dpy)) - w - wmDecorationWidth) / 2;
745 int y = (DisplayHeight(dpy,DefaultScreen(dpy)) - h - wmDecorationHeight)/2;
746
747 CharArray geometryStr(geometry.getData());
748 viewport->setGeometry(geometryStr.buf, x, y, w, h);
749 }
750}
751
Pierre Ossman78b23592009-03-12 12:25:11 +0000752// Note: The method below is duplicated in win/vncviewer/CConn.cxx!
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000753
754// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
755// to the connection speed:
756//
Pierre Ossman78b23592009-03-12 12:25:11 +0000757// First we wait for at least one second of bandwidth measurement.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000758//
Pierre Ossman78b23592009-03-12 12:25:11 +0000759// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
760// which should be perceptually lossless.
761//
762// If the bandwidth is below that, we choose a more lossy JPEG quality.
763//
764// If the bandwidth drops below 256 Kbps, we switch to palette mode.
765//
766// Note: The system here is fairly arbitrary and should be replaced
767// with something more intelligent at the server end.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000768//
769void CConn::autoSelectFormatAndEncoding()
770{
771 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000772 unsigned int timeWaited = sock->inStream().timeWaited();
Pierre Ossman78b23592009-03-12 12:25:11 +0000773 bool newFullColour = fullColour;
774 int newQualityLevel = qualityLevel;
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000775
Pierre Ossman78b23592009-03-12 12:25:11 +0000776 // Always use Tight
Pierre Ossman315b9992010-03-03 16:24:36 +0000777 if (currentEncoding != encodingTight) {
778 currentEncoding = encodingTight;
779 encodingChange = true;
780 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000781
Pierre Ossman78b23592009-03-12 12:25:11 +0000782 // Check that we have a decent bandwidth measurement
783 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000784 return;
Pierre Ossman78b23592009-03-12 12:25:11 +0000785
786 // Select appropriate quality level
787 if (!noJpeg) {
788 if (kbitsPerSecond > 16000)
789 newQualityLevel = 8;
790 else
791 newQualityLevel = 6;
792
793 if (newQualityLevel != qualityLevel) {
794 vlog.info("Throughput %d kbit/s - changing to quality %d ",
795 kbitsPerSecond, newQualityLevel);
796 cp.qualityLevel = newQualityLevel;
797 qualityLevel.setParam(newQualityLevel);
798 encodingChange = true;
799 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000800 }
801
802 if (cp.beforeVersion(3, 8)) {
803 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
804 // cursors "asynchronously". If this happens in the middle of a
805 // pixel format change, the server will encode the cursor with
806 // the old format, but the client will try to decode it
807 // according to the new format. This will lead to a
808 // crash. Therefore, we do not allow automatic format change for
809 // old servers.
810 return;
811 }
812
813 // Select best color level
814 newFullColour = (kbitsPerSecond > 256);
815 if (newFullColour != fullColour) {
816 vlog.info("Throughput %d kbit/s - full color is now %s",
817 kbitsPerSecond,
818 newFullColour ? "enabled" : "disabled");
819 fullColour = newFullColour;
820 formatChange = true;
821 }
822}
823
824// checkEncodings() sends a setEncodings message if one is needed.
825void CConn::checkEncodings()
826{
827 if (encodingChange && writer()) {
828 vlog.info("Using %s encoding",encodingName(currentEncoding));
829 writer()->writeSetEncodings(currentEncoding, true);
830 encodingChange = false;
831 }
832}
833
834// requestNewUpdate() requests an update from the server, having set the
835// format and encoding appropriately.
836void CConn::requestNewUpdate()
837{
838 if (formatChange) {
Adam Tkac12c0fc32010-03-04 15:33:11 +0000839
840 /* Catch incorrect requestNewUpdate calls */
841 assert(pendingUpdate == false);
842
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000843 if (fullColour) {
844 desktop->setPF(fullColourPF);
845 } else {
846 if (lowColourLevel == 0)
847 desktop->setPF(PixelFormat(8,3,0,1,1,1,1,2,1,0));
848 else if (lowColourLevel == 1)
849 desktop->setPF(PixelFormat(8,6,0,1,3,3,3,4,2,0));
850 else
851 desktop->setPF(PixelFormat(8,8,0,0));
852 }
853 char str[256];
854 desktop->getPF().print(str, 256);
855 vlog.info("Using pixel format %s",str);
856 cp.setPF(desktop->getPF());
857 writer()->writeSetPixelFormat(cp.pf());
858 }
859 checkEncodings();
860 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
861 !formatChange);
862 formatChange = false;
863}