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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. *
  3. * This is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This software is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this software; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  16. * USA.
  17. */
  18. #ifdef HAVE_CONFIG_H
  19. #include <config.h>
  20. #endif
  21. #include <winsock2.h>
  22. #include <vncviewer/UserPasswdDialog.h>
  23. #include <vncviewer/CConn.h>
  24. #include <vncviewer/CConnThread.h>
  25. #include <vncviewer/resource.h>
  26. #include <rfb/encodings.h>
  27. #include <rfb/Security.h>
  28. #include <rfb/CMsgWriter.h>
  29. #include <rfb/Configuration.h>
  30. #ifdef HAVE_GNUTLS
  31. #include <rfb/CSecurityTLS.h>
  32. #endif
  33. #include <rfb/LogWriter.h>
  34. #include <rfb_win32/AboutDialog.h>
  35. using namespace rfb;
  36. using namespace rfb::win32;
  37. using namespace rdr;
  38. // - Statics & consts
  39. static LogWriter vlog("CConn");
  40. const int IDM_FULLSCREEN = ID_FULLSCREEN;
  41. const int IDM_SEND_MENU_KEY = ID_SEND_MENU_KEY;
  42. const int IDM_SEND_CAD = ID_SEND_CAD;
  43. const int IDM_SEND_CTLESC = ID_SEND_CTLESC;
  44. const int IDM_ABOUT = ID_ABOUT;
  45. const int IDM_OPTIONS = ID_OPTIONS;
  46. const int IDM_INFO = ID_INFO;
  47. const int IDM_NEWCONN = ID_NEW_CONNECTION;
  48. const int IDM_REQUEST_REFRESH = ID_REQUEST_REFRESH;
  49. const int IDM_CTRL_KEY = ID_CTRL_KEY;
  50. const int IDM_ALT_KEY = ID_ALT_KEY;
  51. const int IDM_CONN_SAVE_AS = ID_CONN_SAVE_AS;
  52. const int IDM_ZOOM_IN = ID_ZOOM_IN;
  53. const int IDM_ZOOM_OUT = ID_ZOOM_OUT;
  54. const int IDM_ACTUAL_SIZE = ID_ACTUAL_SIZE;
  55. const int IDM_AUTO_SIZE = ID_AUTO_SIZE;
  56. static IntParameter debugDelay("DebugDelay","Milliseconds to display inverted "
  57. "pixel data - a debugging feature", 0);
  58. const int scaleValues[9] = {10, 25, 50, 75, 90, 100, 125, 150, 200};
  59. const int scaleCount = 9;
  60. //
  61. // -=- CConn implementation
  62. //
  63. RegKey CConn::userConfigKey;
  64. CConn::CConn()
  65. : window(0), sameMachine(false), encodingChange(false), formatChange(false),
  66. lastUsedEncoding_(encodingRaw), sock(0), sockEvent(CreateEvent(0, TRUE, FALSE, 0)),
  67. reverseConnection(false), requestUpdate(false), firstUpdate(true),
  68. pendingUpdate(false), isClosed_(false) {
  69. }
  70. CConn::~CConn() {
  71. delete window;
  72. }
  73. bool CConn::initialise(network::Socket* s, bool reverse) {
  74. // Set the server's name for MRU purposes
  75. CharArray endpoint(s->getPeerEndpoint());
  76. if (!options.host.buf)
  77. options.setHost(endpoint.buf);
  78. setServerName(options.host.buf);
  79. // Initialise the underlying CConnection
  80. setStreams(&s->inStream(), &s->outStream());
  81. // Enable processing of window messages while blocked on I/O
  82. s->inStream().setBlockCallback(this);
  83. // Initialise the viewer options
  84. applyOptions(options);
  85. CSecurity::upg = this;
  86. #ifdef HAVE_GNUTLS
  87. CSecurityTLS::msg = this;
  88. #endif
  89. // Start the RFB protocol
  90. sock = s;
  91. reverseConnection = reverse;
  92. initialiseProtocol();
  93. return true;
  94. }
  95. void
  96. CConn::applyOptions(CConnOptions& opt) {
  97. // - If any encoding-related settings have changed then we must
  98. // notify the server of the new settings
  99. encodingChange |= ((options.useLocalCursor != opt.useLocalCursor) ||
  100. (options.useDesktopResize != opt.useDesktopResize) ||
  101. (options.customCompressLevel != opt.customCompressLevel) ||
  102. (options.compressLevel != opt.compressLevel) ||
  103. (options.noJpeg != opt.noJpeg) ||
  104. (options.qualityLevel != opt.qualityLevel) ||
  105. (options.preferredEncoding != opt.preferredEncoding));
  106. // - If the preferred pixel format has changed then notify the server
  107. formatChange |= (options.fullColour != opt.fullColour);
  108. if (!opt.fullColour)
  109. formatChange |= (options.lowColourLevel != opt.lowColourLevel);
  110. // - Save the new set of options
  111. options = opt;
  112. // - Set optional features in ConnParams
  113. cp.supportsLocalCursor = options.useLocalCursor;
  114. cp.supportsDesktopResize = options.useDesktopResize;
  115. cp.supportsExtendedDesktopSize = options.useDesktopResize;
  116. cp.supportsDesktopRename = true;
  117. cp.customCompressLevel = options.customCompressLevel;
  118. cp.compressLevel = options.compressLevel;
  119. cp.noJpeg = options.noJpeg;
  120. cp.qualityLevel = options.qualityLevel;
  121. // - Configure connection sharing on/off
  122. setShared(options.shared);
  123. // - Whether to use protocol 3.3 for legacy compatibility
  124. setProtocol3_3(options.protocol3_3);
  125. // - Apply settings that affect the window, if it is visible
  126. if (window) {
  127. window->setMonitor(options.monitor.buf);
  128. window->setFullscreen(options.fullScreen);
  129. window->setEmulate3(options.emulate3);
  130. window->setPointerEventInterval(options.pointerEventInterval);
  131. window->setMenuKey(options.menuKey);
  132. window->setDisableWinKeys(options.disableWinKeys);
  133. window->setShowToolbar(options.showToolbar);
  134. window->printScale();
  135. if (options.autoScaling) {
  136. window->setAutoScaling(true);
  137. } else {
  138. window->setAutoScaling(false);
  139. window->setDesktopScale(options.scale);
  140. }
  141. if (!options.useLocalCursor)
  142. window->setCursor(0, 0, Point(), 0, 0);
  143. }
  144. security->SetSecTypes(options.secTypes);
  145. }
  146. void
  147. CConn::displayChanged() {
  148. // Display format has changed - recalculate the full-colour pixel format
  149. calculateFullColourPF();
  150. }
  151. bool
  152. CConn::sysCommand(WPARAM wParam, LPARAM lParam) {
  153. // - If it's one of our (F8 Menu) messages
  154. switch (wParam) {
  155. case IDM_FULLSCREEN:
  156. options.fullScreen = !window->isFullscreen();
  157. window->setFullscreen(options.fullScreen);
  158. return true;
  159. case IDM_ZOOM_IN:
  160. case IDM_ZOOM_OUT:
  161. {
  162. if (options.autoScaling) {
  163. options.scale = window->getDesktopScale();
  164. options.autoScaling = false;
  165. window->setAutoScaling(false);
  166. }
  167. if (wParam == (unsigned)IDM_ZOOM_IN) {
  168. for (int i = 0; i < scaleCount; i++)
  169. if (options.scale < scaleValues[i]) {
  170. options.scale = scaleValues[i];
  171. break;
  172. }
  173. } else {
  174. for (int i = scaleCount-1; i >= 0; i--)
  175. if (options.scale > scaleValues[i]) {
  176. options.scale = scaleValues[i];
  177. break;
  178. }
  179. }
  180. if (options.scale != window->getDesktopScale())
  181. window->setDesktopScale(options.scale);
  182. }
  183. return true;
  184. case IDM_ACTUAL_SIZE:
  185. if (options.autoScaling) {
  186. options.autoScaling = false;
  187. window->setAutoScaling(false);
  188. }
  189. options.scale = 100;
  190. window->setDesktopScale(100);
  191. return true;
  192. case IDM_AUTO_SIZE:
  193. options.autoScaling = !options.autoScaling;
  194. window->setAutoScaling(options.autoScaling);
  195. if (!options.autoScaling) options.scale = window->getDesktopScale();
  196. return true;
  197. case IDM_SHOW_TOOLBAR:
  198. options.showToolbar = !window->isToolbarEnabled();
  199. window->setShowToolbar(options.showToolbar);
  200. return true;
  201. case IDM_CTRL_KEY:
  202. window->kbd.keyEvent(this, VK_CONTROL, 0, !window->kbd.keyPressed(VK_CONTROL));
  203. return true;
  204. case IDM_ALT_KEY:
  205. window->kbd.keyEvent(this, VK_MENU, 0, !window->kbd.keyPressed(VK_MENU));
  206. return true;
  207. case IDM_SEND_MENU_KEY:
  208. window->kbd.keyEvent(this, options.menuKey, 0, true);
  209. window->kbd.keyEvent(this, options.menuKey, 0, false);
  210. return true;
  211. case IDM_SEND_CAD:
  212. window->kbd.keyEvent(this, VK_CONTROL, 0, true);
  213. window->kbd.keyEvent(this, VK_MENU, 0, true);
  214. window->kbd.keyEvent(this, VK_DELETE, 0x1000000, true);
  215. window->kbd.keyEvent(this, VK_DELETE, 0x1000000, false);
  216. window->kbd.keyEvent(this, VK_MENU, 0, false);
  217. window->kbd.keyEvent(this, VK_CONTROL, 0, false);
  218. return true;
  219. case IDM_SEND_CTLESC:
  220. window->kbd.keyEvent(this, VK_CONTROL, 0, true);
  221. window->kbd.keyEvent(this, VK_ESCAPE, 0, true);
  222. window->kbd.keyEvent(this, VK_ESCAPE, 0, false);
  223. window->kbd.keyEvent(this, VK_CONTROL, 0, false);
  224. return true;
  225. case IDM_REQUEST_REFRESH:
  226. try {
  227. writer()->writeFramebufferUpdateRequest(Rect(0,0,cp.width,cp.height), false);
  228. requestUpdate = false;
  229. } catch (rdr::Exception& e) {
  230. close(e.str());
  231. }
  232. return true;
  233. case IDM_NEWCONN:
  234. {
  235. new CConnThread;
  236. }
  237. return true;
  238. case IDM_OPTIONS:
  239. // Update the monitor device name in the CConnOptions instance
  240. options.monitor.replaceBuf(window->getMonitor());
  241. showOptionsDialog();
  242. return true;
  243. case IDM_INFO:
  244. infoDialog.showDialog(this);
  245. return true;
  246. case IDM_ABOUT:
  247. AboutDialog::instance.showDialog();
  248. return true;
  249. case IDM_CONN_SAVE_AS:
  250. return true;
  251. };
  252. return false;
  253. }
  254. void
  255. CConn::closeWindow() {
  256. vlog.info("window closed");
  257. close();
  258. }
  259. void
  260. CConn::refreshMenu(bool enableSysItems) {
  261. HMENU menu = GetSystemMenu(window->getHandle(), FALSE);
  262. if (!enableSysItems) {
  263. // Gray out menu items that might cause a World Of Pain
  264. EnableMenuItem(menu, SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
  265. EnableMenuItem(menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  266. EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  267. EnableMenuItem(menu, SC_MINIMIZE, MF_BYCOMMAND | MF_ENABLED);
  268. EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_ENABLED);
  269. }
  270. // Update the modifier key menu items
  271. UINT ctrlCheckFlags = window->kbd.keyPressed(VK_CONTROL) ? MF_CHECKED : MF_UNCHECKED;
  272. UINT altCheckFlags = window->kbd.keyPressed(VK_MENU) ? MF_CHECKED : MF_UNCHECKED;
  273. CheckMenuItem(menu, IDM_CTRL_KEY, MF_BYCOMMAND | ctrlCheckFlags);
  274. CheckMenuItem(menu, IDM_ALT_KEY, MF_BYCOMMAND | altCheckFlags);
  275. // Ensure that the Send <MenuKey> menu item has the correct text
  276. if (options.menuKey) {
  277. TCharArray menuKeyStr(options.menuKeyName());
  278. TCharArray tmp(_tcslen(menuKeyStr.buf) + 6);
  279. _stprintf(tmp.buf, _T("Send %s"), menuKeyStr.buf);
  280. if (!ModifyMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf))
  281. InsertMenu(menu, IDM_SEND_CAD, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf);
  282. } else {
  283. RemoveMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND);
  284. }
  285. // Set the menu fullscreen option tick
  286. CheckMenuItem(menu, IDM_FULLSCREEN, (window->isFullscreen() ? MF_CHECKED : 0) | MF_BYCOMMAND);
  287. // Set the menu toolbar option tick
  288. int toolbarFlags = window->isToolbarEnabled() ? MF_CHECKED : 0;
  289. CheckMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
  290. // In the full-screen mode, "Show toolbar" should be grayed.
  291. toolbarFlags = window->isFullscreen() ? MF_GRAYED : MF_ENABLED;
  292. EnableMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
  293. }
  294. void
  295. CConn::blockCallback() {
  296. // - An InStream has blocked on I/O while processing an RFB message
  297. // We re-enable socket event notifications, so we'll know when more
  298. // data is available, then we sit and dispatch window events until
  299. // the notification arrives.
  300. if (!isClosed()) {
  301. if (WSAEventSelect(sock->getFd(), sockEvent, FD_READ | FD_CLOSE) == SOCKET_ERROR)
  302. throw rdr::SystemException("Unable to wait for sokcet data", WSAGetLastError());
  303. }
  304. while (true) {
  305. // If we have closed then we can't block waiting for data
  306. if (isClosed())
  307. throw rdr::EndOfStream();
  308. // Wait for socket data, or a message to process
  309. DWORD result = MsgWaitForMultipleObjects(1, &sockEvent.h, FALSE, INFINITE, QS_ALLINPUT);
  310. if (result == WAIT_FAILED) {
  311. // - The wait operation failed - raise an exception
  312. throw rdr::SystemException("blockCallback wait error", GetLastError());
  313. }
  314. // - There should be a message in the message queue
  315. MSG msg;
  316. while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
  317. // IMPORTANT: We mustn't call TranslateMessage() here, because instead we
  318. // call ToAscii() in CKeyboard::keyEvent(). ToAscii() stores dead key
  319. // state from one call to the next, which would be messed up by calls to
  320. // TranslateMessage() (actually it looks like TranslateMessage() calls
  321. // ToAscii() internally).
  322. DispatchMessage(&msg);
  323. }
  324. if (result == WAIT_OBJECT_0)
  325. // - Network event notification. Return control to I/O routine.
  326. break;
  327. }
  328. // Before we return control to the InStream, reset the network event
  329. WSAEventSelect(sock->getFd(), sockEvent, 0);
  330. ResetEvent(sockEvent);
  331. }
  332. void CConn::keyEvent(rdr::U32 key, bool down) {
  333. if (!options.sendKeyEvents) return;
  334. try {
  335. writer()->keyEvent(key, down);
  336. } catch (rdr::Exception& e) {
  337. close(e.str());
  338. }
  339. }
  340. void CConn::pointerEvent(const Point& pos, int buttonMask) {
  341. if (!options.sendPtrEvents) return;
  342. try {
  343. writer()->pointerEvent(pos, buttonMask);
  344. } catch (rdr::Exception& e) {
  345. close(e.str());
  346. }
  347. }
  348. void CConn::clientCutText(const char* str, int len) {
  349. if (!options.clientCutText) return;
  350. if (state() != RFBSTATE_NORMAL) return;
  351. try {
  352. writer()->clientCutText(str, len);
  353. } catch (rdr::Exception& e) {
  354. close(e.str());
  355. }
  356. }
  357. void
  358. CConn::setColourMapEntries(int first, int count, U16* rgbs) {
  359. vlog.debug("setColourMapEntries: first=%d, count=%d", first, count);
  360. int i;
  361. for (i=0;i<count;i++)
  362. window->setColour(i+first, rgbs[i*3], rgbs[i*3+1], rgbs[i*3+2]);
  363. // *** change to 0, 256?
  364. window->refreshWindowPalette(first, count);
  365. }
  366. void
  367. CConn::bell() {
  368. if (options.acceptBell)
  369. MessageBeep((UINT)-1);
  370. }
  371. void
  372. CConn::setDesktopSize(int w, int h) {
  373. vlog.debug("setDesktopSize %dx%d", w, h);
  374. // Resize the window's buffer
  375. if (window)
  376. window->setSize(w, h);
  377. // Tell the underlying CConnection
  378. CConnection::setDesktopSize(w, h);
  379. }
  380. void
  381. CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
  382. const rfb::ScreenSet& layout) {
  383. if ((reason == (signed)reasonClient) && (result != (signed)resultSuccess)) {
  384. vlog.error("SetDesktopSize failed: %d", result);
  385. return;
  386. }
  387. // Resize the window's buffer
  388. if (window)
  389. window->setSize(w, h);
  390. // Tell the underlying CConnection
  391. CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
  392. }
  393. void
  394. CConn::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
  395. if (!options.useLocalCursor) return;
  396. // Set the window to use the new cursor
  397. window->setCursor(w, h, hotspot, data, mask);
  398. }
  399. void
  400. CConn::close(const char* reason) {
  401. // If already closed then ignore this
  402. if (isClosed())
  403. return;
  404. // Hide the window, if it exists
  405. if (window)
  406. ShowWindow(window->getHandle(), SW_HIDE);
  407. // Save the reason & flag that we're closed & shutdown the socket
  408. isClosed_ = true;
  409. closeReason_.replaceBuf(strDup(reason));
  410. sock->shutdown();
  411. }
  412. bool CConn::showMsgBox(int flags, const char* title, const char* text)
  413. {
  414. UINT winflags = 0;
  415. int ret;
  416. /* Translate flags */
  417. if ((flags & M_OK) != 0)
  418. winflags |= MB_OK;
  419. if ((flags & M_OKCANCEL) != 0)
  420. winflags |= MB_OKCANCEL;
  421. if ((flags & M_YESNO) != 0)
  422. winflags |= MB_YESNO;
  423. if ((flags & M_ICONERROR) != 0)
  424. winflags |= MB_ICONERROR;
  425. if ((flags & M_ICONQUESTION) != 0)
  426. winflags |= MB_ICONQUESTION;
  427. if ((flags & M_ICONWARNING) != 0)
  428. winflags |= MB_ICONWARNING;
  429. if ((flags & M_ICONINFORMATION) != 0)
  430. winflags |= MB_ICONINFORMATION;
  431. if ((flags & M_DEFBUTTON1) != 0)
  432. winflags |= MB_DEFBUTTON1;
  433. if ((flags & M_DEFBUTTON2) != 0)
  434. winflags |= MB_DEFBUTTON2;
  435. ret = MessageBox(NULL, text, title, flags);
  436. return (ret == IDOK || ret == IDYES) ? true : false;
  437. }
  438. void
  439. CConn::showOptionsDialog() {
  440. optionsDialog.showDialog(this);
  441. }
  442. void
  443. CConn::framebufferUpdateStart() {
  444. if (!formatChange) {
  445. requestUpdate = pendingUpdate = true;
  446. requestNewUpdate();
  447. } else
  448. pendingUpdate = false;
  449. }
  450. void
  451. CConn::framebufferUpdateEnd() {
  452. if (debugDelay != 0) {
  453. vlog.debug("debug delay %d",(int)debugDelay);
  454. UpdateWindow(window->getHandle());
  455. Sleep(debugDelay);
  456. std::list<rfb::Rect>::iterator i;
  457. for (i = debugRects.begin(); i != debugRects.end(); i++) {
  458. window->invertRect(*i);
  459. }
  460. debugRects.clear();
  461. }
  462. window->framebufferUpdateEnd();
  463. if (firstUpdate) {
  464. int width, height;
  465. if (cp.supportsSetDesktopSize &&
  466. sscanf(options.desktopSize.buf, "%dx%d", &width, &height) == 2) {
  467. ScreenSet layout;
  468. layout = cp.screenLayout;
  469. if (layout.num_screens() == 0)
  470. layout.add_screen(rfb::Screen());
  471. else if (layout.num_screens() != 1) {
  472. ScreenSet::iterator iter;
  473. while (true) {
  474. iter = layout.begin();
  475. ++iter;
  476. if (iter == layout.end())
  477. break;
  478. layout.remove_screen(iter->id);
  479. }
  480. }
  481. layout.begin()->dimensions.tl.x = 0;
  482. layout.begin()->dimensions.tl.y = 0;
  483. layout.begin()->dimensions.br.x = width;
  484. layout.begin()->dimensions.br.y = height;
  485. writer()->writeSetDesktopSize(width, height, layout);
  486. }
  487. firstUpdate = false;
  488. }
  489. // Always request the next update
  490. requestUpdate = true;
  491. // A format change prevented us from sending this before the update,
  492. // so make sure to send it now.
  493. if (formatChange && !pendingUpdate)
  494. requestNewUpdate();
  495. if (options.autoSelect)
  496. autoSelectFormatAndEncoding();
  497. // Check that at least part of the window has changed
  498. if (!GetUpdateRect(window->getHandle(), 0, FALSE)) {
  499. if (!(GetWindowLong(window->getHandle(), GWL_STYLE) & WS_MINIMIZE))
  500. requestNewUpdate();
  501. }
  502. // Make sure the local cursor is shown
  503. window->showCursor();
  504. }
  505. // Note: The method below is duplicated in win/vncviewer/CConn.cxx!
  506. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  507. // to the connection speed:
  508. //
  509. // First we wait for at least one second of bandwidth measurement.
  510. //
  511. // Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
  512. // which should be perceptually lossless.
  513. //
  514. // If the bandwidth is below that, we choose a more lossy JPEG quality.
  515. //
  516. // If the bandwidth drops below 256 Kbps, we switch to palette mode.
  517. //
  518. // Note: The system here is fairly arbitrary and should be replaced
  519. // with something more intelligent at the server end.
  520. //
  521. void CConn::autoSelectFormatAndEncoding()
  522. {
  523. int kbitsPerSecond = sock->inStream().kbitsPerSecond();
  524. unsigned int timeWaited = sock->inStream().timeWaited();
  525. bool newFullColour = options.fullColour;
  526. int newQualityLevel = options.qualityLevel;
  527. // Always use Tight
  528. options.preferredEncoding = encodingTight;
  529. // Check that we have a decent bandwidth measurement
  530. if ((kbitsPerSecond == 0) || (timeWaited < 10000))
  531. return;
  532. // Select appropriate quality level
  533. if (!options.noJpeg) {
  534. if (kbitsPerSecond > 16000)
  535. newQualityLevel = 8;
  536. else
  537. newQualityLevel = 6;
  538. if (newQualityLevel != options.qualityLevel) {
  539. vlog.info("Throughput %d kbit/s - changing to quality %d ",
  540. kbitsPerSecond, newQualityLevel);
  541. cp.qualityLevel = newQualityLevel;
  542. options.qualityLevel = newQualityLevel;
  543. encodingChange = true;
  544. }
  545. }
  546. if (cp.beforeVersion(3, 8)) {
  547. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  548. // cursors "asynchronously". If this happens in the middle of a
  549. // pixel format change, the server will encode the cursor with
  550. // the old format, but the client will try to decode it
  551. // according to the new format. This will lead to a
  552. // crash. Therefore, we do not allow automatic format change for
  553. // old servers.
  554. return;
  555. }
  556. // Select best color level
  557. newFullColour = (kbitsPerSecond > 256);
  558. if (newFullColour != options.fullColour) {
  559. vlog.info("Throughput %d kbit/s - full color is now %s",
  560. kbitsPerSecond,
  561. newFullColour ? "enabled" : "disabled");
  562. options.fullColour = newFullColour;
  563. formatChange = true;
  564. }
  565. }
  566. void
  567. CConn::requestNewUpdate() {
  568. if (!requestUpdate) return;
  569. if (formatChange) {
  570. /* Catch incorrect requestNewUpdate calls */
  571. assert(pendingUpdate == false);
  572. // Select the required pixel format
  573. if (options.fullColour) {
  574. window->setPF(fullColourPF);
  575. } else {
  576. switch (options.lowColourLevel) {
  577. case 0:
  578. window->setPF(PixelFormat(8,3,0,1,1,1,1,2,1,0));
  579. break;
  580. case 1:
  581. window->setPF(PixelFormat(8,6,0,1,3,3,3,4,2,0));
  582. break;
  583. case 2:
  584. window->setPF(PixelFormat(8,8,0,0,0,0,0,0,0,0));
  585. break;
  586. }
  587. }
  588. // Print the current pixel format
  589. char str[256];
  590. window->getPF().print(str, 256);
  591. vlog.info("Using pixel format %s",str);
  592. // Save the connection pixel format and tell server to use it
  593. cp.setPF(window->getPF());
  594. writer()->writeSetPixelFormat(cp.pf());
  595. // Correct the local window's palette
  596. if (!window->getNativePF().trueColour)
  597. window->refreshWindowPalette(0, 1 << cp.pf().depth);
  598. }
  599. if (encodingChange) {
  600. vlog.info("Using %s encoding",encodingName(options.preferredEncoding));
  601. writer()->writeSetEncodings(options.preferredEncoding, true);
  602. }
  603. writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
  604. !formatChange);
  605. encodingChange = formatChange = requestUpdate = false;
  606. }
  607. void
  608. CConn::calculateFullColourPF() {
  609. // If the server is palette based then use palette locally
  610. // Also, don't bother doing bgr222
  611. if (!serverDefaultPF.trueColour || (serverDefaultPF.depth < 6)) {
  612. fullColourPF = serverDefaultPF;
  613. options.fullColour = true;
  614. } else {
  615. // If server is trueColour, use lowest depth PF
  616. PixelFormat native = window->getNativePF();
  617. if ((serverDefaultPF.bpp < native.bpp) ||
  618. ((serverDefaultPF.bpp == native.bpp) &&
  619. (serverDefaultPF.depth < native.depth)))
  620. fullColourPF = serverDefaultPF;
  621. else
  622. fullColourPF = window->getNativePF();
  623. }
  624. formatChange = true;
  625. }
  626. void
  627. CConn::setName(const char* name) {
  628. if (window)
  629. window->setName(name);
  630. CConnection::setName(name);
  631. }
  632. void CConn::serverInit() {
  633. CConnection::serverInit();
  634. // If using AutoSelect with old servers, start in FullColor
  635. // mode. See comment in autoSelectFormatAndEncoding.
  636. if (cp.beforeVersion(3, 8) && options.autoSelect) {
  637. options.fullColour = true;
  638. }
  639. // Show the window
  640. window = new DesktopWindow(this);
  641. // Update the window menu
  642. HMENU wndmenu = GetSystemMenu(window->getHandle(), FALSE);
  643. int toolbarChecked = options.showToolbar ? MF_CHECKED : 0;
  644. AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
  645. AppendMenu(wndmenu, MF_STRING, IDM_FULLSCREEN, _T("&Full screen"));
  646. AppendMenu(wndmenu, MF_STRING | toolbarChecked, IDM_SHOW_TOOLBAR,
  647. _T("Show tool&bar"));
  648. AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
  649. AppendMenu(wndmenu, MF_STRING, IDM_CTRL_KEY, _T("Ctr&l"));
  650. AppendMenu(wndmenu, MF_STRING, IDM_ALT_KEY, _T("Al&t"));
  651. AppendMenu(wndmenu, MF_STRING, IDM_SEND_CAD, _T("Send Ctrl-Alt-&Del"));
  652. AppendMenu(wndmenu, MF_STRING, IDM_SEND_CTLESC, _T("Send Ctrl-&Esc"));
  653. AppendMenu(wndmenu, MF_STRING, IDM_REQUEST_REFRESH, _T("Refres&h Screen"));
  654. AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
  655. AppendMenu(wndmenu, MF_STRING, IDM_NEWCONN, _T("Ne&w Connection..."));
  656. AppendMenu(wndmenu, MF_STRING, IDM_OPTIONS, _T("&Options..."));
  657. AppendMenu(wndmenu, MF_STRING, IDM_INFO, _T("Connection &Info..."));
  658. AppendMenu(wndmenu, MF_STRING, IDM_ABOUT, _T("&About..."));
  659. // Set window attributes
  660. window->setName(cp.name());
  661. window->setShowToolbar(options.showToolbar);
  662. window->setSize(cp.width, cp.height);
  663. applyOptions(options);
  664. // Save the server's current format
  665. serverDefaultPF = cp.pf();
  666. // Calculate the full-colour format to use
  667. calculateFullColourPF();
  668. // Request the initial update
  669. vlog.info("requesting initial update");
  670. formatChange = encodingChange = requestUpdate = true;
  671. requestNewUpdate();
  672. }
  673. void
  674. CConn::serverCutText(const char* str, rdr::U32 len) {
  675. if (!options.serverCutText) return;
  676. window->serverCutText(str, len);
  677. }
  678. void CConn::beginRect(const Rect& r, int encoding) {
  679. sock->inStream().startTiming();
  680. }
  681. void CConn::endRect(const Rect& r, int encoding) {
  682. sock->inStream().stopTiming();
  683. lastUsedEncoding_ = encoding;
  684. if (debugDelay != 0) {
  685. window->invertRect(r);
  686. debugRects.push_back(r);
  687. }
  688. }
  689. void CConn::fillRect(const Rect& r, Pixel pix) {
  690. window->fillRect(r, pix);
  691. }
  692. void CConn::imageRect(const Rect& r, void* pixels) {
  693. window->imageRect(r, pixels);
  694. }
  695. void CConn::copyRect(const Rect& r, int srcX, int srcY) {
  696. window->copyRect(r, srcX, srcY);
  697. }
  698. void CConn::getUserPasswd(char** user, char** password) {
  699. if (!user && options.passwordFile.buf[0]) {
  700. FILE* fp = fopen(options.passwordFile.buf, "rb");
  701. if (fp) {
  702. char data[256];
  703. int datalen = fread(data, 1, 256, fp);
  704. fclose(fp);
  705. if (datalen == 8) {
  706. ObfuscatedPasswd obfPwd;
  707. obfPwd.buf = data;
  708. obfPwd.length = datalen;
  709. PlainPasswd passwd(obfPwd);
  710. obfPwd.takeBuf();
  711. *password = strDup(passwd.buf);
  712. memset(data, 0, sizeof(data));
  713. }
  714. }
  715. }
  716. if (user && options.userName.buf)
  717. *user = strDup(options.userName.buf);
  718. if (password && options.password.buf)
  719. *password = strDup(options.password.buf);
  720. if ((user && !*user) || (password && !*password)) {
  721. // Missing username or password - prompt the user
  722. UserPasswdDialog userPasswdDialog;
  723. userPasswdDialog.setCSecurity(csecurity);
  724. userPasswdDialog.getUserPasswd(user, password);
  725. }
  726. if (user) options.setUserName(*user);
  727. if (password) options.setPassword(*password);
  728. }