You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CConn.cxx 26KB

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