blob: 5ae26f0b9375773831bb716571df0432c86a68a6 [file] [log] [blame]
Pierre Ossman5156d5e2011-03-09 09:42:34 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 * Copyright 2009-2011 Pierre Ossman <ossman@cendio.se> for Cendio AB
3 *
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#include <assert.h>
21#include <unistd.h>
22
23#include <rfb/CMsgWriter.h>
24#include <rfb/encodings.h>
25#include <rfb/Hostname.h>
26#include <rfb/LogWriter.h>
27#include <rfb/util.h>
28#include <rfb/screenTypes.h>
29#include <rfb/Timer.h>
30#include <network/TcpSocket.h>
31
32#include <FL/Fl.H>
33#include <FL/fl_ask.H>
34
35#include "CConn.h"
Pierre Ossmanf4f30942011-05-17 09:39:07 +000036#include "OptionsDialog.h"
Pierre Ossman5156d5e2011-03-09 09:42:34 +000037#include "i18n.h"
38#include "parameters.h"
39
40using namespace rdr;
41using namespace rfb;
42using namespace std;
43
44extern void exit_vncviewer();
45
46static rfb::LogWriter vlog("CConn");
47
Pierre Ossmanf4f30942011-05-17 09:39:07 +000048static const PixelFormat mediumColourPF(8,3,0,1,1,1,1,2,1,0);
49static const PixelFormat lowColourPF(8,6,0,1,3,3,3,4,2,0);
50static const PixelFormat verylowColourPF(8,8,0,0);
51
Pierre Ossman5156d5e2011-03-09 09:42:34 +000052CConn::CConn(const char* vncServerName)
53 : serverHost(0), serverPort(0), sock(NULL), desktop(NULL),
54 currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
55 formatChange(false), encodingChange(false),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +000056 firstUpdate(true), pendingUpdate(false),
57 forceNonincremental(false)
Pierre Ossman5156d5e2011-03-09 09:42:34 +000058{
59 setShared(::shared);
60
61 int encNum = encodingNum(preferredEncoding);
62 if (encNum != -1)
63 currentEncoding = encNum;
64
Pierre Ossmanda389562011-06-09 08:24:37 +000065 cp.supportsLocalCursor = true;
66
Pierre Ossman5156d5e2011-03-09 09:42:34 +000067 cp.supportsDesktopResize = true;
68 cp.supportsExtendedDesktopSize = true;
69 cp.supportsDesktopRename = true;
Pierre Ossman5156d5e2011-03-09 09:42:34 +000070
71 cp.customCompressLevel = customCompressLevel;
72 cp.compressLevel = compressLevel;
73
74 cp.noJpeg = noJpeg;
75 cp.qualityLevel = qualityLevel;
76
77 try {
78 getHostAndPort(vncServerName, &serverHost, &serverPort);
79
80 sock = new network::TcpSocket(serverHost, serverPort);
81 vlog.info(_("connected to host %s port %d"), serverHost, serverPort);
82 } catch (rdr::Exception& e) {
83 vlog.error(e.str());
84 fl_alert(e.str());
85 exit_vncviewer();
86 return;
87 }
88
89 Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
90
91 // See callback below
92 sock->inStream().setBlockCallback(this);
93
94 setServerName(serverHost);
95 setStreams(&sock->inStream(), &sock->outStream());
96
97 initialiseProtocol();
Pierre Ossmanf4f30942011-05-17 09:39:07 +000098
99 OptionsDialog::addCallback(handleOptions, this);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000100}
101
102CConn::~CConn()
103{
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000104 OptionsDialog::removeCallback(handleOptions);
105
Pierre Ossman6a9e2e62011-05-19 14:47:43 +0000106 if (desktop)
107 delete desktop;
108
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000109 free(serverHost);
110 if (sock)
111 Fl::remove_fd(sock->getFd());
112 delete sock;
113}
114
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000115void CConn::refreshFramebuffer()
116{
117 // FIXME: We cannot safely trigger an update request directly but must
118 // wait for the next update to arrive.
119 if (!formatChange)
120 forceNonincremental = true;
121}
122
Pierre Ossman2eb1d112011-05-16 12:18:08 +0000123const char *CConn::connectionInfo()
124{
125 static char infoText[1024] = "";
126
127 char pfStr[100];
128 char spfStr[100];
129
130 cp.pf().print(pfStr, 100);
131 serverPF.print(spfStr, 100);
132
133 int secType = csecurity->getType();
134
135 snprintf(infoText, sizeof(infoText),
136 _("Desktop name: %.80s\n"
137 "Host: %.80s port: %d\n"
138 "Size: %d x %d\n"
139 "Pixel format: %s\n"
140 "(server default %s)\n"
141 "Requested encoding: %s\n"
142 "Last used encoding: %s\n"
143 "Line speed estimate: %d kbit/s\n"
144 "Protocol version: %d.%d\n"
145 "Security method: %s\n"),
146 cp.name(), serverHost, serverPort, cp.width, cp.height,
147 pfStr, spfStr, encodingName(currentEncoding),
148 encodingName(lastServerEncoding),
149 sock->inStream().kbitsPerSecond(),
150 cp.majorVersion, cp.minorVersion,
151 secTypeName(secType));
152
153 return infoText;
154}
155
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000156// The RFB core is not properly asynchronous, so it calls this callback
157// whenever it needs to block to wait for more data. Since FLTK is
158// monitoring the socket, we just make sure FLTK gets to run.
159
160void CConn::blockCallback()
161{
162 int next_timer;
163
164 next_timer = Timer::checkTimeouts();
165 if (next_timer == 0)
166 next_timer = INT_MAX;
167
168 Fl::wait((double)next_timer / 1000.0);
169}
170
171void CConn::socketEvent(int fd, void *data)
172{
173 CConn *cc;
174 static bool recursing = false;
175
176 assert(data);
177 cc = (CConn*)data;
178
179 // I don't think processMsg() is recursion safe, so add this check
180 if (recursing)
181 return;
182
183 recursing = true;
184
185 try {
186 // processMsg() only processes one message, so we need to loop
187 // until the buffers are empty or things will stall.
188 do {
189 cc->processMsg();
190 } while (cc->sock->inStream().checkNoWait(1));
191 } catch (rdr::EndOfStream& e) {
192 vlog.info(e.str());
193 exit_vncviewer();
194 } catch (rdr::Exception& e) {
195 vlog.error(e.str());
196 fl_alert(e.str());
197 exit_vncviewer();
198 }
199
200 recursing = false;
201}
202
203////////////////////// CConnection callback methods //////////////////////
204
205// serverInit() is called when the serverInit message has been received. At
206// this point we create the desktop window and display it. We also tell the
207// server the pixel format and encodings to use and request the first update.
208void CConn::serverInit()
209{
210 CConnection::serverInit();
211
212 // If using AutoSelect with old servers, start in FullColor
213 // mode. See comment in autoSelectFormatAndEncoding.
214 if (cp.beforeVersion(3, 8) && autoSelect)
215 fullColour.setParam(true);
216
217 serverPF = cp.pf();
218
219 desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
220 fullColourPF = desktop->getPreferredPF();
221
222 formatChange = encodingChange = true;
223 requestNewUpdate();
224}
225
226// setDesktopSize() is called when the desktop size changes (including when
227// it is set initially).
228void CConn::setDesktopSize(int w, int h)
229{
230 CConnection::setDesktopSize(w,h);
231 resizeFramebuffer();
232}
233
234// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
235void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
236 const rfb::ScreenSet& layout)
237{
238 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
239
240 if ((reason == reasonClient) && (result != resultSuccess)) {
241 vlog.error(_("SetDesktopSize failed: %d"), result);
242 return;
243 }
244
245 resizeFramebuffer();
246}
247
248// setName() is called when the desktop name changes
249void CConn::setName(const char* name)
250{
251 CConnection::setName(name);
252 if (desktop)
253 desktop->setName(name);
254}
255
256// framebufferUpdateStart() is called at the beginning of an update.
257// Here we try to send out a new framebuffer update request so that the
258// next update can be sent out in parallel with us decoding the current
259// one. We cannot do this if we're in the middle of a format change
260// though.
261void CConn::framebufferUpdateStart()
262{
263 if (!formatChange) {
264 pendingUpdate = true;
265 requestNewUpdate();
266 } else
267 pendingUpdate = false;
268}
269
270// framebufferUpdateEnd() is called at the end of an update.
271// For each rectangle, the FdInStream will have timed the speed
272// of the connection, allowing us to select format and encoding
273// appropriately, and then request another incremental update.
274void CConn::framebufferUpdateEnd()
275{
276 desktop->updateWindow();
277
278 if (firstUpdate) {
279 int width, height;
280
281 if (cp.supportsSetDesktopSize &&
282 sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
283 ScreenSet layout;
284
285 layout = cp.screenLayout;
286
287 if (layout.num_screens() == 0)
288 layout.add_screen(rfb::Screen());
289 else if (layout.num_screens() != 1) {
290 ScreenSet::iterator iter;
291
292 while (true) {
293 iter = layout.begin();
294 ++iter;
295
296 if (iter == layout.end())
297 break;
298
299 layout.remove_screen(iter->id);
300 }
301 }
302
303 layout.begin()->dimensions.tl.x = 0;
304 layout.begin()->dimensions.tl.y = 0;
305 layout.begin()->dimensions.br.x = width;
306 layout.begin()->dimensions.br.y = height;
307
308 writer()->writeSetDesktopSize(width, height, layout);
309 }
310
311 firstUpdate = false;
312 }
313
314 // A format change prevented us from sending this before the update,
315 // so make sure to send it now.
316 if (formatChange && !pendingUpdate)
317 requestNewUpdate();
318
319 // Compute new settings based on updated bandwidth values
320 if (autoSelect)
321 autoSelectFormatAndEncoding();
322
323 // Make sure that the FLTK handling and the timers gets some CPU time
324 // in case of back to back framebuffer updates.
325 Fl::check();
326 Timer::checkTimeouts();
327}
328
329// The rest of the callbacks are fairly self-explanatory...
330
331void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
332{
333 desktop->setColourMapEntries(firstColour, nColours, rgbs);
334}
335
336void CConn::bell()
337{
338 fl_beep();
339}
340
341void CConn::serverCutText(const char* str, rdr::U32 len)
342{
Pierre Ossman689c4582011-05-26 15:39:41 +0000343 char *buffer;
344 int size, ret;
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000345
Pierre Ossman689c4582011-05-26 15:39:41 +0000346 size = fl_utf8froma(NULL, 0, str, len);
347 if (size <= 0)
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000348 return;
Pierre Ossman689c4582011-05-26 15:39:41 +0000349
350 size++;
351
352 buffer = new char[size];
353
354 ret = fl_utf8froma(buffer, size, str, len);
355 assert(ret < size);
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000356
357 vlog.debug("Got clipboard data: '%s'", buffer);
358
359 Fl::copy(buffer, ret, 1);
Pierre Ossman689c4582011-05-26 15:39:41 +0000360
361 delete [] buffer;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000362}
363
364// We start timing on beginRect and stop timing on endRect, to
365// avoid skewing the bandwidth estimation as a result of the server
366// being slow or the network having high latency
367void CConn::beginRect(const Rect& r, int encoding)
368{
369 sock->inStream().startTiming();
370 if (encoding != encodingCopyRect) {
371 lastServerEncoding = encoding;
372 }
373}
374
375void CConn::endRect(const Rect& r, int encoding)
376{
377 sock->inStream().stopTiming();
378}
379
380void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
381{
382 desktop->fillRect(r,p);
383}
384void CConn::imageRect(const rfb::Rect& r, void* p)
385{
386 desktop->imageRect(r,p);
387}
388void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
389{
390 desktop->copyRect(r,sx,sy);
391}
392void CConn::setCursor(int width, int height, const Point& hotspot,
393 void* data, void* mask)
394{
Pierre Ossman835b4ef2011-06-08 17:02:36 +0000395 desktop->setCursor(width, height, hotspot, data, mask);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000396}
397
398////////////////////// Internal methods //////////////////////
399
400void CConn::resizeFramebuffer()
401{
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000402 if (!desktop)
403 return;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000404
Pierre Ossman6455d852011-06-01 09:33:00 +0000405 desktop->resizeFramebuffer(cp.width, cp.height);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000406}
407
408// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
409// to the connection speed:
410//
411// First we wait for at least one second of bandwidth measurement.
412//
413// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
414// which should be perceptually lossless.
415//
416// If the bandwidth is below that, we choose a more lossy JPEG quality.
417//
418// If the bandwidth drops below 256 Kbps, we switch to palette mode.
419//
420// Note: The system here is fairly arbitrary and should be replaced
421// with something more intelligent at the server end.
422//
423void CConn::autoSelectFormatAndEncoding()
424{
425 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
426 unsigned int timeWaited = sock->inStream().timeWaited();
427 bool newFullColour = fullColour;
428 int newQualityLevel = qualityLevel;
429
430 // Always use Tight
431 if (currentEncoding != encodingTight) {
432 currentEncoding = encodingTight;
433 encodingChange = true;
434 }
435
436 // Check that we have a decent bandwidth measurement
437 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
438 return;
439
440 // Select appropriate quality level
441 if (!noJpeg) {
442 if (kbitsPerSecond > 16000)
443 newQualityLevel = 8;
444 else
445 newQualityLevel = 6;
446
447 if (newQualityLevel != qualityLevel) {
448 vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
449 kbitsPerSecond, newQualityLevel);
450 cp.qualityLevel = newQualityLevel;
451 qualityLevel.setParam(newQualityLevel);
452 encodingChange = true;
453 }
454 }
455
456 if (cp.beforeVersion(3, 8)) {
457 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
458 // cursors "asynchronously". If this happens in the middle of a
459 // pixel format change, the server will encode the cursor with
460 // the old format, but the client will try to decode it
461 // according to the new format. This will lead to a
462 // crash. Therefore, we do not allow automatic format change for
463 // old servers.
464 return;
465 }
466
467 // Select best color level
468 newFullColour = (kbitsPerSecond > 256);
469 if (newFullColour != fullColour) {
470 vlog.info(_("Throughput %d kbit/s - full color is now %s"),
471 kbitsPerSecond,
472 newFullColour ? _("enabled") : _("disabled"));
473 fullColour.setParam(newFullColour);
474 formatChange = true;
475 }
476}
477
478// checkEncodings() sends a setEncodings message if one is needed.
479void CConn::checkEncodings()
480{
481 if (encodingChange && writer()) {
482 vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
483 writer()->writeSetEncodings(currentEncoding, true);
484 encodingChange = false;
485 }
486}
487
488// requestNewUpdate() requests an update from the server, having set the
489// format and encoding appropriately.
490void CConn::requestNewUpdate()
491{
492 if (formatChange) {
493 PixelFormat pf;
494
495 /* Catch incorrect requestNewUpdate calls */
496 assert(pendingUpdate == false);
497
498 if (fullColour) {
499 pf = fullColourPF;
500 } else {
501 if (lowColourLevel == 0)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000502 pf = mediumColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000503 else if (lowColourLevel == 1)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000504 pf = lowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000505 else
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000506 pf = verylowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000507 }
508 char str[256];
509 pf.print(str, 256);
510 vlog.info(_("Using pixel format %s"),str);
511 desktop->setServerPF(pf);
512 cp.setPF(pf);
513 writer()->writeSetPixelFormat(pf);
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000514
515 forceNonincremental = true;
516
517 formatChange = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000518 }
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000519
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000520 checkEncodings();
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000521
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000522 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000523 !forceNonincremental);
524
525 forceNonincremental = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000526}
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000527
528void CConn::handleOptions(void *data)
529{
530 CConn *self = (CConn*)data;
531
532 // Checking all the details of the current set of encodings is just
533 // a pain. Assume something has changed, as resending the encoding
534 // list is cheap. Avoid overriding what the auto logic has selected
535 // though.
536 if (!autoSelect) {
537 int encNum = encodingNum(preferredEncoding);
538
539 if (encNum != -1)
540 self->currentEncoding = encNum;
541
542 self->cp.qualityLevel = qualityLevel;
543 }
544
Pierre Ossmanda389562011-06-09 08:24:37 +0000545 self->cp.supportsLocalCursor = true;
546
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000547 self->cp.customCompressLevel = customCompressLevel;
548 self->cp.compressLevel = compressLevel;
549
550 self->cp.noJpeg = noJpeg;
551
552 self->encodingChange = true;
553
554 // Format changes refreshes the entire screen though and are therefore
555 // very costly. It's probably worth the effort to see if it is necessary
556 // here.
557 PixelFormat pf;
558
559 if (fullColour) {
560 pf = self->fullColourPF;
561 } else {
562 if (lowColourLevel == 0)
563 pf = mediumColourPF;
564 else if (lowColourLevel == 1)
565 pf = lowColourPF;
566 else
567 pf = verylowColourPF;
568 }
569
570 if (!pf.equal(self->cp.pf()))
571 self->formatChange = true;
572}