blob: 28c8abbcaf8fb5ddcb96bb173139419eb2d34fff [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 Ossmand81e8f42011-05-19 14:47:15 +0000342 char buffer[1024];
343 int ret;
344
345 ret = fl_utf8froma(buffer, sizeof(buffer), str, len);
346 if (ret >= sizeof(buffer)) {
347 vlog.error(_("Clipboard buffer overflow!"));
348 return;
349 }
350
351 vlog.debug("Got clipboard data: '%s'", buffer);
352
353 Fl::copy(buffer, ret, 1);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000354}
355
356// We start timing on beginRect and stop timing on endRect, to
357// avoid skewing the bandwidth estimation as a result of the server
358// being slow or the network having high latency
359void CConn::beginRect(const Rect& r, int encoding)
360{
361 sock->inStream().startTiming();
362 if (encoding != encodingCopyRect) {
363 lastServerEncoding = encoding;
364 }
365}
366
367void CConn::endRect(const Rect& r, int encoding)
368{
369 sock->inStream().stopTiming();
370}
371
372void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
373{
374 desktop->fillRect(r,p);
375}
376void CConn::imageRect(const rfb::Rect& r, void* p)
377{
378 desktop->imageRect(r,p);
379}
380void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
381{
382 desktop->copyRect(r,sx,sy);
383}
384void CConn::setCursor(int width, int height, const Point& hotspot,
385 void* data, void* mask)
386{
387// desktop->setCursor(width, height, hotspot, data, mask);
388}
389
390////////////////////// Internal methods //////////////////////
391
392void CConn::resizeFramebuffer()
393{
394/*
395 if (!desktop)
396 return;
397 if ((desktop->width() == cp.width) && (desktop->height() == cp.height))
398 return;
399
400 desktop->resize(cp.width, cp.height);
401*/
402}
403
404// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
405// to the connection speed:
406//
407// First we wait for at least one second of bandwidth measurement.
408//
409// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
410// which should be perceptually lossless.
411//
412// If the bandwidth is below that, we choose a more lossy JPEG quality.
413//
414// If the bandwidth drops below 256 Kbps, we switch to palette mode.
415//
416// Note: The system here is fairly arbitrary and should be replaced
417// with something more intelligent at the server end.
418//
419void CConn::autoSelectFormatAndEncoding()
420{
421 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
422 unsigned int timeWaited = sock->inStream().timeWaited();
423 bool newFullColour = fullColour;
424 int newQualityLevel = qualityLevel;
425
426 // Always use Tight
427 if (currentEncoding != encodingTight) {
428 currentEncoding = encodingTight;
429 encodingChange = true;
430 }
431
432 // Check that we have a decent bandwidth measurement
433 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
434 return;
435
436 // Select appropriate quality level
437 if (!noJpeg) {
438 if (kbitsPerSecond > 16000)
439 newQualityLevel = 8;
440 else
441 newQualityLevel = 6;
442
443 if (newQualityLevel != qualityLevel) {
444 vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
445 kbitsPerSecond, newQualityLevel);
446 cp.qualityLevel = newQualityLevel;
447 qualityLevel.setParam(newQualityLevel);
448 encodingChange = true;
449 }
450 }
451
452 if (cp.beforeVersion(3, 8)) {
453 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
454 // cursors "asynchronously". If this happens in the middle of a
455 // pixel format change, the server will encode the cursor with
456 // the old format, but the client will try to decode it
457 // according to the new format. This will lead to a
458 // crash. Therefore, we do not allow automatic format change for
459 // old servers.
460 return;
461 }
462
463 // Select best color level
464 newFullColour = (kbitsPerSecond > 256);
465 if (newFullColour != fullColour) {
466 vlog.info(_("Throughput %d kbit/s - full color is now %s"),
467 kbitsPerSecond,
468 newFullColour ? _("enabled") : _("disabled"));
469 fullColour.setParam(newFullColour);
470 formatChange = true;
471 }
472}
473
474// checkEncodings() sends a setEncodings message if one is needed.
475void CConn::checkEncodings()
476{
477 if (encodingChange && writer()) {
478 vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
479 writer()->writeSetEncodings(currentEncoding, true);
480 encodingChange = false;
481 }
482}
483
484// requestNewUpdate() requests an update from the server, having set the
485// format and encoding appropriately.
486void CConn::requestNewUpdate()
487{
488 if (formatChange) {
489 PixelFormat pf;
490
491 /* Catch incorrect requestNewUpdate calls */
492 assert(pendingUpdate == false);
493
494 if (fullColour) {
495 pf = fullColourPF;
496 } else {
497 if (lowColourLevel == 0)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000498 pf = mediumColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000499 else if (lowColourLevel == 1)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000500 pf = lowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000501 else
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000502 pf = verylowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000503 }
504 char str[256];
505 pf.print(str, 256);
506 vlog.info(_("Using pixel format %s"),str);
507 desktop->setServerPF(pf);
508 cp.setPF(pf);
509 writer()->writeSetPixelFormat(pf);
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000510
511 forceNonincremental = true;
512
513 formatChange = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000514 }
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000515
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000516 checkEncodings();
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000517
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000518 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000519 !forceNonincremental);
520
521 forceNonincremental = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000522}
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000523
524void CConn::handleOptions(void *data)
525{
526 CConn *self = (CConn*)data;
527
528 // Checking all the details of the current set of encodings is just
529 // a pain. Assume something has changed, as resending the encoding
530 // list is cheap. Avoid overriding what the auto logic has selected
531 // though.
532 if (!autoSelect) {
533 int encNum = encodingNum(preferredEncoding);
534
535 if (encNum != -1)
536 self->currentEncoding = encNum;
537
538 self->cp.qualityLevel = qualityLevel;
539 }
540
541 self->cp.supportsLocalCursor = useLocalCursor;
542
543 self->cp.customCompressLevel = customCompressLevel;
544 self->cp.compressLevel = compressLevel;
545
546 self->cp.noJpeg = noJpeg;
547
548 self->encodingChange = true;
549
550 // Format changes refreshes the entire screen though and are therefore
551 // very costly. It's probably worth the effort to see if it is necessary
552 // here.
553 PixelFormat pf;
554
555 if (fullColour) {
556 pf = self->fullColourPF;
557 } else {
558 if (lowColourLevel == 0)
559 pf = mediumColourPF;
560 else if (lowColourLevel == 1)
561 pf = lowColourPF;
562 else
563 pf = verylowColourPF;
564 }
565
566 if (!pf.equal(self->cp.pf()))
567 self->formatChange = true;
568}