Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

CConn.cxx 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. #include <windows.h>
  19. #include <winsock2.h>
  20. #include <vncviewer/UserPasswdDialog.h>
  21. #include <vncviewer/CConn.h>
  22. #include <vncviewer/CConnThread.h>
  23. #include <vncviewer/resource.h>
  24. #include <rfb/encodings.h>
  25. #include <rfb/secTypes.h>
  26. #include <rfb/CSecurityNone.h>
  27. #include <rfb/CSecurityVncAuth.h>
  28. #include <rfb/CMsgWriter.h>
  29. #include <rfb/Configuration.h>
  30. #include <rfb/LogWriter.h>
  31. #include <rfb_win32/AboutDialog.h>
  32. using namespace rfb;
  33. using namespace rfb::win32;
  34. using namespace rdr;
  35. // - Statics & consts
  36. static LogWriter vlog("CConn");
  37. const int IDM_FULLSCREEN = ID_FULLSCREEN;
  38. const int IDM_SEND_MENU_KEY = ID_SEND_MENU_KEY;
  39. const int IDM_SEND_CAD = ID_SEND_CAD;
  40. const int IDM_SEND_CTLESC = ID_SEND_CTLESC;
  41. const int IDM_ABOUT = ID_ABOUT;
  42. const int IDM_OPTIONS = ID_OPTIONS;
  43. const int IDM_INFO = ID_INFO;
  44. const int IDM_NEWCONN = ID_NEW_CONNECTION;
  45. const int IDM_REQUEST_REFRESH = ID_REQUEST_REFRESH;
  46. const int IDM_CTRL_KEY = ID_CTRL_KEY;
  47. const int IDM_ALT_KEY = ID_ALT_KEY;
  48. const int IDM_FILE_TRANSFER = ID_FILE_TRANSFER;
  49. const int IDM_CONN_SAVE_AS = ID_CONN_SAVE_AS;
  50. const int IDM_ZOOM_IN = ID_ZOOM_IN;
  51. const int IDM_ZOOM_OUT = ID_ZOOM_OUT;
  52. const int IDM_ACTUAL_SIZE = ID_ACTUAL_SIZE;
  53. const int IDM_AUTO_SIZE = ID_AUTO_SIZE;
  54. static IntParameter debugDelay("DebugDelay","Milliseconds to display inverted "
  55. "pixel data - a debugging feature", 0);
  56. const int scaleValues[9] = {10, 25, 50, 75, 90, 100, 125, 150, 200};
  57. const int scaleCount = 9;
  58. //
  59. // -=- CConn implementation
  60. //
  61. RegKey CConn::userConfigKey;
  62. CConn::CConn()
  63. : window(0), sameMachine(false), encodingChange(false), formatChange(false),
  64. lastUsedEncoding_(encodingRaw), sock(0), sockEvent(CreateEvent(0, TRUE, FALSE, 0)),
  65. reverseConnection(false), requestUpdate(false), isClosed_(false) {
  66. }
  67. CConn::~CConn() {
  68. delete window;
  69. }
  70. bool CConn::initialise(network::Socket* s, bool reverse) {
  71. // Set the server's name for MRU purposes
  72. CharArray endpoint(s->getPeerEndpoint());
  73. setServerName(endpoint.buf);
  74. if (!options.host.buf)
  75. options.setHost(endpoint.buf);
  76. // Initialise the underlying CConnection
  77. setStreams(&s->inStream(), &s->outStream());
  78. // Enable processing of window messages while blocked on I/O
  79. s->inStream().setBlockCallback(this);
  80. // Initialise the viewer options
  81. applyOptions(options);
  82. // - Set which auth schemes we support, in order of preference
  83. addSecType(secTypeVncAuth);
  84. addSecType(secTypeNone);
  85. // Start the RFB protocol
  86. sock = s;
  87. reverseConnection = reverse;
  88. initialiseProtocol();
  89. m_fileTransfer.initialize(&s->inStream(), &s->outStream());
  90. return true;
  91. }
  92. void
  93. CConn::applyOptions(CConnOptions& opt) {
  94. // - If any encoding-related settings have changed then we must
  95. // notify the server of the new settings
  96. encodingChange |= ((options.useLocalCursor != opt.useLocalCursor) ||
  97. (options.useDesktopResize != opt.useDesktopResize) ||
  98. (options.customCompressLevel != opt.customCompressLevel) ||
  99. (options.compressLevel != opt.compressLevel) ||
  100. (options.noJpeg != opt.noJpeg) ||
  101. (options.qualityLevel != opt.qualityLevel) ||
  102. (options.preferredEncoding != opt.preferredEncoding));
  103. // - If the preferred pixel format has changed then notify the server
  104. formatChange |= (options.fullColour != opt.fullColour);
  105. if (!opt.fullColour)
  106. formatChange |= (options.lowColourLevel != opt.lowColourLevel);
  107. // - Save the new set of options
  108. options = opt;
  109. // - Set optional features in ConnParams
  110. cp.supportsLocalCursor = options.useLocalCursor;
  111. cp.supportsDesktopResize = options.useDesktopResize;
  112. cp.supportsDesktopRename = true;
  113. cp.customCompressLevel = options.customCompressLevel;
  114. cp.compressLevel = options.compressLevel;
  115. cp.noJpeg = options.noJpeg;
  116. cp.qualityLevel = options.qualityLevel;
  117. // - Configure connection sharing on/off
  118. setShared(options.shared);
  119. // - Whether to use protocol 3.3 for legacy compatibility
  120. setProtocol3_3(options.protocol3_3);
  121. // - Apply settings that affect the window, if it is visible
  122. if (window) {
  123. window->setMonitor(options.monitor.buf);
  124. window->setFullscreen(options.fullScreen);
  125. window->setEmulate3(options.emulate3);
  126. window->setPointerEventInterval(options.pointerEventInterval);
  127. window->setMenuKey(options.menuKey);
  128. window->setDisableWinKeys(options.disableWinKeys);
  129. window->setShowToolbar(options.showToolbar);
  130. window->printScale();
  131. if (options.autoScaling) {
  132. window->setAutoScaling(true);
  133. } else {
  134. window->setAutoScaling(false);
  135. window->setDesktopScale(options.scale);
  136. }
  137. if (!options.useLocalCursor)
  138. window->setCursor(0, 0, Point(), 0, 0);
  139. }
  140. }
  141. void
  142. CConn::displayChanged() {
  143. // Display format has changed - recalculate the full-colour pixel format
  144. calculateFullColourPF();
  145. }
  146. void
  147. CConn::paintCompleted() {
  148. // A repaint message has just completed - request next update if necessary
  149. requestNewUpdate();
  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 == 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. Thread* newThread = 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_FILE_TRANSFER:
  250. m_fileTransfer.show(window->getHandle());
  251. return true;
  252. case IDM_CONN_SAVE_AS:
  253. return true;
  254. };
  255. return false;
  256. }
  257. void
  258. CConn::closeWindow() {
  259. vlog.info("window closed");
  260. close();
  261. }
  262. void
  263. CConn::refreshMenu(bool enableSysItems) {
  264. HMENU menu = GetSystemMenu(window->getHandle(), FALSE);
  265. if (!enableSysItems) {
  266. // Gray out menu items that might cause a World Of Pain
  267. EnableMenuItem(menu, SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
  268. EnableMenuItem(menu, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  269. EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  270. EnableMenuItem(menu, SC_MINIMIZE, MF_BYCOMMAND | MF_ENABLED);
  271. EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_ENABLED);
  272. }
  273. // Update the modifier key menu items
  274. UINT ctrlCheckFlags = window->kbd.keyPressed(VK_CONTROL) ? MF_CHECKED : MF_UNCHECKED;
  275. UINT altCheckFlags = window->kbd.keyPressed(VK_MENU) ? MF_CHECKED : MF_UNCHECKED;
  276. CheckMenuItem(menu, IDM_CTRL_KEY, MF_BYCOMMAND | ctrlCheckFlags);
  277. CheckMenuItem(menu, IDM_ALT_KEY, MF_BYCOMMAND | altCheckFlags);
  278. // Ensure that the Send <MenuKey> menu item has the correct text
  279. if (options.menuKey) {
  280. TCharArray menuKeyStr(options.menuKeyName());
  281. TCharArray tmp(_tcslen(menuKeyStr.buf) + 6);
  282. _stprintf(tmp.buf, _T("Send %s"), menuKeyStr.buf);
  283. if (!ModifyMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf))
  284. InsertMenu(menu, IDM_SEND_CAD, MF_BYCOMMAND | MF_STRING, IDM_SEND_MENU_KEY, tmp.buf);
  285. } else {
  286. RemoveMenu(menu, IDM_SEND_MENU_KEY, MF_BYCOMMAND);
  287. }
  288. // Set the menu fullscreen option tick
  289. CheckMenuItem(menu, IDM_FULLSCREEN, (window->isFullscreen() ? MF_CHECKED : 0) | MF_BYCOMMAND);
  290. // Set the menu toolbar option tick
  291. int toolbarFlags = window->isToolbarEnabled() ? MF_CHECKED : 0;
  292. CheckMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
  293. // In the full-screen mode, "Show toolbar" should be grayed.
  294. toolbarFlags = window->isFullscreen() ? MF_GRAYED : MF_ENABLED;
  295. EnableMenuItem(menu, IDM_SHOW_TOOLBAR, MF_BYCOMMAND | toolbarFlags);
  296. }
  297. void
  298. CConn::blockCallback() {
  299. // - An InStream has blocked on I/O while processing an RFB message
  300. // We re-enable socket event notifications, so we'll know when more
  301. // data is available, then we sit and dispatch window events until
  302. // the notification arrives.
  303. if (!isClosed()) {
  304. if (WSAEventSelect(sock->getFd(), sockEvent, FD_READ | FD_CLOSE) == SOCKET_ERROR)
  305. throw rdr::SystemException("Unable to wait for sokcet data", WSAGetLastError());
  306. }
  307. while (true) {
  308. // If we have closed then we can't block waiting for data
  309. if (isClosed())
  310. throw rdr::EndOfStream();
  311. // Wait for socket data, or a message to process
  312. DWORD result = MsgWaitForMultipleObjects(1, &sockEvent.h, FALSE, INFINITE, QS_ALLINPUT);
  313. if (result == WAIT_OBJECT_0) {
  314. // - Network event notification. Return control to I/O routine.
  315. break;
  316. } else if (result == WAIT_FAILED) {
  317. // - The wait operation failed - raise an exception
  318. throw rdr::SystemException("blockCallback wait error", GetLastError());
  319. }
  320. // - There should be a message in the message queue
  321. MSG msg;
  322. while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
  323. // IMPORTANT: We mustn't call TranslateMessage() here, because instead we
  324. // call ToAscii() in CKeyboard::keyEvent(). ToAscii() stores dead key
  325. // state from one call to the next, which would be messed up by calls to
  326. // TranslateMessage() (actually it looks like TranslateMessage() calls
  327. // ToAscii() internally).
  328. DispatchMessage(&msg);
  329. }
  330. }
  331. // Before we return control to the InStream, reset the network event
  332. WSAEventSelect(sock->getFd(), sockEvent, 0);
  333. ResetEvent(sockEvent);
  334. }
  335. void CConn::keyEvent(rdr::U32 key, bool down) {
  336. if (!options.sendKeyEvents) return;
  337. try {
  338. writer()->keyEvent(key, down);
  339. } catch (rdr::Exception& e) {
  340. close(e.str());
  341. }
  342. }
  343. void CConn::pointerEvent(const Point& pos, int buttonMask) {
  344. if (!options.sendPtrEvents) return;
  345. try {
  346. writer()->pointerEvent(pos, buttonMask);
  347. } catch (rdr::Exception& e) {
  348. close(e.str());
  349. }
  350. }
  351. void CConn::clientCutText(const char* str, int len) {
  352. if (!options.clientCutText) return;
  353. if (state() != RFBSTATE_NORMAL) return;
  354. try {
  355. writer()->clientCutText(str, len);
  356. } catch (rdr::Exception& e) {
  357. close(e.str());
  358. }
  359. }
  360. CSecurity* CConn::getCSecurity(int secType)
  361. {
  362. switch (secType) {
  363. case secTypeNone:
  364. return new CSecurityNone();
  365. case secTypeVncAuth:
  366. return new CSecurityVncAuth(this);
  367. default:
  368. throw Exception("Unsupported secType?");
  369. }
  370. }
  371. void
  372. CConn::setColourMapEntries(int first, int count, U16* rgbs) {
  373. vlog.debug("setColourMapEntries: first=%d, count=%d", first, count);
  374. int i;
  375. for (i=0;i<count;i++)
  376. window->setColour(i+first, rgbs[i*3], rgbs[i*3+1], rgbs[i*3+2]);
  377. // *** change to 0, 256?
  378. window->refreshWindowPalette(first, count);
  379. }
  380. void
  381. CConn::bell() {
  382. if (options.acceptBell)
  383. MessageBeep((UINT)-1);
  384. }
  385. void
  386. CConn::setDesktopSize(int w, int h) {
  387. vlog.debug("setDesktopSize %dx%d", w, h);
  388. // Resize the window's buffer
  389. if (window)
  390. window->setSize(w, h);
  391. // Tell the underlying CConnection
  392. CConnection::setDesktopSize(w, h);
  393. }
  394. void
  395. CConn::setCursor(int w, int h, const Point& hotspot, void* data, void* mask) {
  396. if (!options.useLocalCursor) return;
  397. // Set the window to use the new cursor
  398. window->setCursor(w, h, hotspot, data, mask);
  399. }
  400. void
  401. CConn::close(const char* reason) {
  402. // If already closed then ignore this
  403. if (isClosed())
  404. return;
  405. // Hide the window, if it exists
  406. if (window)
  407. ShowWindow(window->getHandle(), SW_HIDE);
  408. // Save the reason & flag that we're closed & shutdown the socket
  409. isClosed_ = true;
  410. closeReason_.replaceBuf(strDup(reason));
  411. sock->shutdown();
  412. }
  413. void
  414. CConn::showOptionsDialog() {
  415. optionsDialog.showDialog(this);
  416. }
  417. void
  418. CConn::framebufferUpdateEnd() {
  419. if (debugDelay != 0) {
  420. vlog.debug("debug delay %d",(int)debugDelay);
  421. UpdateWindow(window->getHandle());
  422. Sleep(debugDelay);
  423. std::list<rfb::Rect>::iterator i;
  424. for (i = debugRects.begin(); i != debugRects.end(); i++) {
  425. window->invertRect(*i);
  426. }
  427. debugRects.clear();
  428. }
  429. if (options.autoSelect)
  430. autoSelectFormatAndEncoding();
  431. // Always request the next update
  432. requestUpdate = true;
  433. // Check that at least part of the window has changed
  434. if (!GetUpdateRect(window->getHandle(), 0, FALSE)) {
  435. if (!(GetWindowLong(window->getHandle(), GWL_STYLE) & WS_MINIMIZE))
  436. requestNewUpdate();
  437. }
  438. // Make sure the local cursor is shown
  439. window->showCursor();
  440. }
  441. // Note: The method below is duplicated in vncviewer_unix/CConn.cxx!
  442. // autoSelectFormatAndEncoding() chooses the format and encoding appropriate
  443. // to the connection speed:
  444. //
  445. // Above 16Mbps (timing for at least a second), switch to hextile
  446. // Otherwise, switch to ZRLE
  447. //
  448. // Above 256Kbps, use full colour mode
  449. //
  450. void
  451. CConn::autoSelectFormatAndEncoding() {
  452. int kbitsPerSecond = sock->inStream().kbitsPerSecond();
  453. unsigned int newEncoding = options.preferredEncoding;
  454. bool newFullColour = options.fullColour;
  455. unsigned int timeWaited = sock->inStream().timeWaited();
  456. // Select best encoding
  457. if (kbitsPerSecond > 16000 && timeWaited >= 10000) {
  458. newEncoding = encodingHextile;
  459. } else {
  460. newEncoding = encodingZRLE;
  461. }
  462. if (newEncoding != options.preferredEncoding) {
  463. vlog.info("Throughput %d kbit/s - changing to %s encoding",
  464. kbitsPerSecond, encodingName(newEncoding));
  465. options.preferredEncoding = newEncoding;
  466. encodingChange = true;
  467. }
  468. if (kbitsPerSecond == 0) {
  469. return;
  470. }
  471. if (cp.beforeVersion(3, 8)) {
  472. // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
  473. // cursors "asynchronously". If this happens in the middle of a
  474. // pixel format change, the server will encode the cursor with
  475. // the old format, but the client will try to decode it
  476. // according to the new format. This will lead to a
  477. // crash. Therefore, we do not allow automatic format change for
  478. // old servers.
  479. return;
  480. }
  481. // Select best color level
  482. newFullColour = (kbitsPerSecond > 256);
  483. if (newFullColour != options.fullColour) {
  484. vlog.info("Throughput %d kbit/s - full color is now %s",
  485. kbitsPerSecond,
  486. newFullColour ? "enabled" : "disabled");
  487. options.fullColour = newFullColour;
  488. formatChange = true;
  489. }
  490. }
  491. void
  492. CConn::requestNewUpdate() {
  493. if (!requestUpdate) return;
  494. if (formatChange) {
  495. // Select the required pixel format
  496. if (options.fullColour) {
  497. window->setPF(fullColourPF);
  498. } else {
  499. switch (options.lowColourLevel) {
  500. case 0:
  501. window->setPF(PixelFormat(8,3,0,1,1,1,1,2,1,0));
  502. break;
  503. case 1:
  504. window->setPF(PixelFormat(8,6,0,1,3,3,3,4,2,0));
  505. break;
  506. case 2:
  507. window->setPF(PixelFormat(8,8,0,0,0,0,0,0,0,0));
  508. break;
  509. }
  510. }
  511. // Print the current pixel format
  512. char str[256];
  513. window->getPF().print(str, 256);
  514. vlog.info("Using pixel format %s",str);
  515. // Save the connection pixel format and tell server to use it
  516. cp.setPF(window->getPF());
  517. writer()->writeSetPixelFormat(cp.pf());
  518. // Correct the local window's palette
  519. if (!window->getNativePF().trueColour)
  520. window->refreshWindowPalette(0, 1 << cp.pf().depth);
  521. }
  522. if (encodingChange) {
  523. vlog.info("Using %s encoding",encodingName(options.preferredEncoding));
  524. writer()->writeSetEncodings(options.preferredEncoding, true);
  525. }
  526. writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
  527. !formatChange);
  528. encodingChange = formatChange = requestUpdate = false;
  529. }
  530. void
  531. CConn::calculateFullColourPF() {
  532. // If the server is palette based then use palette locally
  533. // Also, don't bother doing bgr222
  534. if (!serverDefaultPF.trueColour || (serverDefaultPF.depth < 6)) {
  535. fullColourPF = serverDefaultPF;
  536. options.fullColour = true;
  537. } else {
  538. // If server is trueColour, use lowest depth PF
  539. PixelFormat native = window->getNativePF();
  540. if ((serverDefaultPF.bpp < native.bpp) ||
  541. ((serverDefaultPF.bpp == native.bpp) &&
  542. (serverDefaultPF.depth < native.depth)))
  543. fullColourPF = serverDefaultPF;
  544. else
  545. fullColourPF = window->getNativePF();
  546. }
  547. formatChange = true;
  548. }
  549. void
  550. CConn::setName(const char* name) {
  551. if (window)
  552. window->setName(name);
  553. CConnection::setName(name);
  554. }
  555. void CConn::serverInit() {
  556. CConnection::serverInit();
  557. // If using AutoSelect with old servers, start in FullColor
  558. // mode. See comment in autoSelectFormatAndEncoding.
  559. if (cp.beforeVersion(3, 8) && options.autoSelect) {
  560. options.fullColour = true;
  561. }
  562. // Show the window
  563. window = new DesktopWindow(this);
  564. window->setName(cp.name());
  565. window->setShowToolbar(options.showToolbar);
  566. window->setSize(cp.width, cp.height);
  567. applyOptions(options);
  568. // Save the server's current format
  569. serverDefaultPF = cp.pf();
  570. // Calculate the full-colour format to use
  571. calculateFullColourPF();
  572. // Request the initial update
  573. vlog.info("requesting initial update");
  574. formatChange = encodingChange = requestUpdate = true;
  575. requestNewUpdate();
  576. // Update the window menu
  577. HMENU wndmenu = GetSystemMenu(window->getHandle(), FALSE);
  578. int toolbarChecked = options.showToolbar ? MF_CHECKED : 0;
  579. AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
  580. AppendMenu(wndmenu, MF_STRING, IDM_FULLSCREEN, _T("&Full screen"));
  581. AppendMenu(wndmenu, MF_STRING | toolbarChecked, IDM_SHOW_TOOLBAR,
  582. _T("Show tool&bar"));
  583. AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
  584. AppendMenu(wndmenu, MF_STRING, IDM_CTRL_KEY, _T("Ctr&l"));
  585. AppendMenu(wndmenu, MF_STRING, IDM_ALT_KEY, _T("Al&t"));
  586. AppendMenu(wndmenu, MF_STRING, IDM_SEND_CAD, _T("Send Ctrl-Alt-&Del"));
  587. AppendMenu(wndmenu, MF_STRING, IDM_SEND_CTLESC, _T("Send Ctrl-&Esc"));
  588. AppendMenu(wndmenu, MF_STRING, IDM_REQUEST_REFRESH, _T("Refres&h Screen"));
  589. AppendMenu(wndmenu, MF_SEPARATOR, 0, 0);
  590. AppendMenu(wndmenu, MF_STRING, IDM_NEWCONN, _T("Ne&w Connection..."));
  591. AppendMenu(wndmenu, MF_STRING, IDM_OPTIONS, _T("&Options..."));
  592. AppendMenu(wndmenu, MF_STRING, IDM_INFO, _T("Connection &Info..."));
  593. AppendMenu(wndmenu, MF_STRING, IDM_ABOUT, _T("&About..."));
  594. }
  595. void
  596. CConn::serverCutText(const char* str, int len) {
  597. if (!options.serverCutText) return;
  598. window->serverCutText(str, len);
  599. }
  600. void CConn::beginRect(const Rect& r, unsigned int encoding) {
  601. sock->inStream().startTiming();
  602. }
  603. void CConn::endRect(const Rect& r, unsigned int encoding) {
  604. sock->inStream().stopTiming();
  605. lastUsedEncoding_ = encoding;
  606. if (debugDelay != 0) {
  607. window->invertRect(r);
  608. debugRects.push_back(r);
  609. }
  610. }
  611. void CConn::fillRect(const Rect& r, Pixel pix) {
  612. window->fillRect(r, pix);
  613. }
  614. void CConn::imageRect(const Rect& r, void* pixels) {
  615. window->imageRect(r, pixels);
  616. }
  617. void CConn::copyRect(const Rect& r, int srcX, int srcY) {
  618. window->copyRect(r, srcX, srcY);
  619. }
  620. void CConn::getUserPasswd(char** user, char** password) {
  621. if (!user && options.passwordFile.buf[0]) {
  622. FILE* fp = fopen(options.passwordFile.buf, "rb");
  623. if (fp) {
  624. char data[256];
  625. int datalen = fread(data, 1, 256, fp);
  626. fclose(fp);
  627. if (datalen == 8) {
  628. ObfuscatedPasswd obfPwd;
  629. obfPwd.buf = data;
  630. obfPwd.length = datalen;
  631. PlainPasswd passwd(obfPwd);
  632. obfPwd.takeBuf();
  633. *password = strDup(passwd.buf);
  634. memset(data, 0, sizeof(data));
  635. }
  636. }
  637. }
  638. if (user && options.userName.buf)
  639. *user = strDup(options.userName.buf);
  640. if (password && options.password.buf)
  641. *password = strDup(options.password.buf);
  642. if ((user && !*user) || (password && !*password)) {
  643. // Missing username or password - prompt the user
  644. UserPasswdDialog userPasswdDialog;
  645. userPasswdDialog.setCSecurity(getCurrentCSecurity());
  646. userPasswdDialog.getUserPasswd(user, password);
  647. }
  648. if (user) options.setUserName(*user);
  649. if (password) options.setPassword(*password);
  650. }
  651. bool CConn::processFTMsg(int type) {
  652. return m_fileTransfer.processFTMsg(type);
  653. }