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

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