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