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