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 27KB

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