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.

Viewport.cxx 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2011-2014 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. #ifdef HAVE_CONFIG_H
  20. #include <config.h>
  21. #endif
  22. #include <assert.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <rfb/CMsgWriter.h>
  26. #include <rfb/LogWriter.h>
  27. #include <rfb/Exception.h>
  28. #include <rfb/ledStates.h>
  29. // FLTK can pull in the X11 headers on some systems
  30. #ifndef XK_VoidSymbol
  31. #define XK_LATIN1
  32. #define XK_MISCELLANY
  33. #define XK_XKB_KEYS
  34. #include <rfb/keysymdef.h>
  35. #endif
  36. #ifndef XF86XK_ModeLock
  37. #include <rfb/XF86keysym.h>
  38. #endif
  39. #if ! (defined(WIN32) || defined(__APPLE__))
  40. #include <X11/XKBlib.h>
  41. #endif
  42. #ifndef NoSymbol
  43. #define NoSymbol 0
  44. #endif
  45. // Missing in at least some versions of MinGW
  46. #ifndef MAPVK_VK_TO_VSC
  47. #define MAPVK_VK_TO_VSC 0
  48. #endif
  49. #include "Viewport.h"
  50. #include "CConn.h"
  51. #include "OptionsDialog.h"
  52. #include "DesktopWindow.h"
  53. #include "i18n.h"
  54. #include "fltk_layout.h"
  55. #include "parameters.h"
  56. #include "keysym2ucs.h"
  57. #include "menukey.h"
  58. #include "vncviewer.h"
  59. #include "PlatformPixelBuffer.h"
  60. #include <FL/fl_draw.H>
  61. #include <FL/fl_ask.H>
  62. #include <FL/Fl_Menu.H>
  63. #include <FL/Fl_Menu_Button.H>
  64. #if !defined(WIN32) && !defined(__APPLE__)
  65. #include <X11/XKBlib.h>
  66. extern const struct _code_map_xkb_to_qnum {
  67. const char * from;
  68. const unsigned short to;
  69. } code_map_xkb_to_qnum[];
  70. extern const unsigned int code_map_xkb_to_qnum_len;
  71. static int code_map_keycode_to_qnum[256];
  72. #endif
  73. #ifdef __APPLE__
  74. #include "cocoa.h"
  75. extern const unsigned short code_map_osx_to_qnum[];
  76. extern const unsigned int code_map_osx_to_qnum_len;
  77. #endif
  78. #ifdef WIN32
  79. #include "win32.h"
  80. #endif
  81. using namespace rfb;
  82. using namespace rdr;
  83. static rfb::LogWriter vlog("Viewport");
  84. // Menu constants
  85. enum { ID_EXIT, ID_FULLSCREEN, ID_MINIMIZE, ID_RESIZE,
  86. ID_CTRL, ID_ALT, ID_MENUKEY, ID_CTRLALTDEL,
  87. ID_REFRESH, ID_OPTIONS, ID_INFO, ID_ABOUT, ID_DISMISS };
  88. // Used to detect fake input (0xaa is not a real key)
  89. #ifdef WIN32
  90. static const WORD SCAN_FAKE = 0xaa;
  91. #endif
  92. Viewport::Viewport(int w, int h, const rfb::PixelFormat& serverPF, CConn* cc_)
  93. : Fl_Widget(0, 0, w, h), cc(cc_), frameBuffer(NULL),
  94. lastPointerPos(0, 0), lastButtonMask(0),
  95. #ifdef WIN32
  96. altGrArmed(false),
  97. #endif
  98. menuCtrlKey(false), menuAltKey(false), cursor(NULL)
  99. {
  100. #if !defined(WIN32) && !defined(__APPLE__)
  101. XkbDescPtr xkb;
  102. Status status;
  103. xkb = XkbGetMap(fl_display, 0, XkbUseCoreKbd);
  104. if (!xkb)
  105. throw rfb::Exception("XkbGetMap");
  106. status = XkbGetNames(fl_display, XkbKeyNamesMask, xkb);
  107. if (status != Success)
  108. throw rfb::Exception("XkbGetNames");
  109. memset(code_map_keycode_to_qnum, 0, sizeof(code_map_keycode_to_qnum));
  110. for (KeyCode keycode = xkb->min_key_code;
  111. keycode < xkb->max_key_code;
  112. keycode++) {
  113. const char *keyname = xkb->names->keys[keycode].name;
  114. unsigned short rfbcode;
  115. if (keyname[0] == '\0')
  116. continue;
  117. rfbcode = 0;
  118. for (unsigned i = 0;i < code_map_xkb_to_qnum_len;i++) {
  119. if (strncmp(code_map_xkb_to_qnum[i].from,
  120. keyname, XkbKeyNameLength) == 0) {
  121. rfbcode = code_map_xkb_to_qnum[i].to;
  122. break;
  123. }
  124. }
  125. if (rfbcode != 0)
  126. code_map_keycode_to_qnum[keycode] = rfbcode;
  127. else
  128. vlog.debug("No key mapping for key %.4s", keyname);
  129. }
  130. XkbFreeKeyboard(xkb, 0, True);
  131. #endif
  132. Fl::add_clipboard_notify(handleClipboardChange, this);
  133. // We need to intercept keyboard events early
  134. Fl::add_system_handler(handleSystemEvent, this);
  135. frameBuffer = new PlatformPixelBuffer(w, h);
  136. assert(frameBuffer);
  137. cc->setFramebuffer(frameBuffer);
  138. contextMenu = new Fl_Menu_Button(0, 0, 0, 0);
  139. // Setting box type to FL_NO_BOX prevents it from trying to draw the
  140. // button component (which we don't want)
  141. contextMenu->box(FL_NO_BOX);
  142. // The (invisible) button associated with this widget can mess with
  143. // things like Fl_Scroll so we need to get rid of any parents.
  144. // Unfortunately that's not possible because of STR #2654, but
  145. // reparenting to the current window works for most cases.
  146. window()->add(contextMenu);
  147. setMenuKey();
  148. OptionsDialog::addCallback(handleOptions, this);
  149. }
  150. Viewport::~Viewport()
  151. {
  152. // Unregister all timeouts in case they get a change tro trigger
  153. // again later when this object is already gone.
  154. Fl::remove_timeout(handlePointerTimeout, this);
  155. #ifdef WIN32
  156. Fl::remove_timeout(handleAltGrTimeout, this);
  157. #endif
  158. Fl::remove_system_handler(handleSystemEvent);
  159. Fl::remove_clipboard_notify(handleClipboardChange);
  160. OptionsDialog::removeCallback(handleOptions);
  161. if (cursor) {
  162. if (!cursor->alloc_array)
  163. delete [] cursor->array;
  164. delete cursor;
  165. }
  166. // FLTK automatically deletes all child widgets, so we shouldn't touch
  167. // them ourselves here
  168. }
  169. const rfb::PixelFormat &Viewport::getPreferredPF()
  170. {
  171. return frameBuffer->getPF();
  172. }
  173. // Copy the areas of the framebuffer that have been changed (damaged)
  174. // to the displayed window.
  175. void Viewport::updateWindow()
  176. {
  177. Rect r;
  178. r = frameBuffer->getDamage();
  179. damage(FL_DAMAGE_USER1, r.tl.x + x(), r.tl.y + y(), r.width(), r.height());
  180. }
  181. static const char * dotcursor_xpm[] = {
  182. "5 5 2 1",
  183. ". c #000000",
  184. " c #FFFFFF",
  185. " ",
  186. " ... ",
  187. " ... ",
  188. " ... ",
  189. " "};
  190. void Viewport::setCursor(int width, int height, const Point& hotspot,
  191. const rdr::U8* data)
  192. {
  193. int i;
  194. if (cursor) {
  195. if (!cursor->alloc_array)
  196. delete [] cursor->array;
  197. delete cursor;
  198. }
  199. for (i = 0; i < width*height; i++)
  200. if (data[i*4 + 3] != 0) break;
  201. if ((i == width*height) && dotWhenNoCursor) {
  202. vlog.debug("cursor is empty - using dot");
  203. Fl_Pixmap pxm(dotcursor_xpm);
  204. cursor = new Fl_RGB_Image(&pxm);
  205. cursorHotspot.x = cursorHotspot.y = 2;
  206. } else {
  207. if ((width == 0) || (height == 0)) {
  208. U8 *buffer = new U8[4];
  209. memset(buffer, 0, 4);
  210. cursor = new Fl_RGB_Image(buffer, 1, 1, 4);
  211. cursorHotspot.x = cursorHotspot.y = 0;
  212. } else {
  213. U8 *buffer = new U8[width * height * 4];
  214. memcpy(buffer, data, width * height * 4);
  215. cursor = new Fl_RGB_Image(buffer, width, height, 4);
  216. cursorHotspot = hotspot;
  217. }
  218. }
  219. if (Fl::belowmouse() == this)
  220. window()->cursor(cursor, cursorHotspot.x, cursorHotspot.y);
  221. }
  222. void Viewport::setLEDState(unsigned int state)
  223. {
  224. Fl_Widget *focus;
  225. vlog.debug("Got server LED state: 0x%08x", state);
  226. focus = Fl::grab();
  227. if (!focus)
  228. focus = Fl::focus();
  229. if (!focus)
  230. return;
  231. if (focus != this)
  232. return;
  233. #if defined(WIN32)
  234. INPUT input[6];
  235. UINT count;
  236. UINT ret;
  237. memset(input, 0, sizeof(input));
  238. count = 0;
  239. if (!!(state & ledCapsLock) != !!(GetKeyState(VK_CAPITAL) & 0x1)) {
  240. input[count].type = input[count+1].type = INPUT_KEYBOARD;
  241. input[count].ki.wVk = input[count+1].ki.wVk = VK_CAPITAL;
  242. input[count].ki.wScan = input[count+1].ki.wScan = SCAN_FAKE;
  243. input[count].ki.dwFlags = 0;
  244. input[count+1].ki.dwFlags = KEYEVENTF_KEYUP;
  245. count += 2;
  246. }
  247. if (!!(state & ledNumLock) != !!(GetKeyState(VK_NUMLOCK) & 0x1)) {
  248. input[count].type = input[count+1].type = INPUT_KEYBOARD;
  249. input[count].ki.wVk = input[count+1].ki.wVk = VK_NUMLOCK;
  250. input[count].ki.wScan = input[count+1].ki.wScan = SCAN_FAKE;
  251. input[count].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
  252. input[count+1].ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_EXTENDEDKEY;
  253. count += 2;
  254. }
  255. if (!!(state & ledScrollLock) != !!(GetKeyState(VK_SCROLL) & 0x1)) {
  256. input[count].type = input[count+1].type = INPUT_KEYBOARD;
  257. input[count].ki.wVk = input[count+1].ki.wVk = VK_SCROLL;
  258. input[count].ki.wScan = input[count+1].ki.wScan = SCAN_FAKE;
  259. input[count].ki.dwFlags = 0;
  260. input[count+1].ki.dwFlags = KEYEVENTF_KEYUP;
  261. count += 2;
  262. }
  263. if (count == 0)
  264. return;
  265. ret = SendInput(count, input, sizeof(*input));
  266. if (ret < count)
  267. vlog.error(_("Failed to update keyboard LED state: %lu"), GetLastError());
  268. #elif defined(__APPLE__)
  269. int ret;
  270. ret = cocoa_set_caps_lock_state(state & ledCapsLock);
  271. if (ret != 0) {
  272. vlog.error(_("Failed to update keyboard LED state: %d"), ret);
  273. return;
  274. }
  275. ret = cocoa_set_num_lock_state(state & ledNumLock);
  276. if (ret != 0) {
  277. vlog.error(_("Failed to update keyboard LED state: %d"), ret);
  278. return;
  279. }
  280. // No support for Scroll Lock //
  281. #else
  282. unsigned int affect, values;
  283. unsigned int mask;
  284. Bool ret;
  285. affect = values = 0;
  286. affect |= LockMask;
  287. if (state & ledCapsLock)
  288. values |= LockMask;
  289. mask = getModifierMask(XK_Num_Lock);
  290. affect |= mask;
  291. if (state & ledNumLock)
  292. values |= mask;
  293. mask = getModifierMask(XK_Scroll_Lock);
  294. affect |= mask;
  295. if (state & ledScrollLock)
  296. values |= mask;
  297. ret = XkbLockModifiers(fl_display, XkbUseCoreKbd, affect, values);
  298. if (!ret)
  299. vlog.error(_("Failed to update keyboard LED state"));
  300. #endif
  301. }
  302. void Viewport::pushLEDState()
  303. {
  304. unsigned int state;
  305. // Server support?
  306. if (cc->cp.ledState() == ledUnknown)
  307. return;
  308. state = 0;
  309. #if defined(WIN32)
  310. if (GetKeyState(VK_CAPITAL) & 0x1)
  311. state |= ledCapsLock;
  312. if (GetKeyState(VK_NUMLOCK) & 0x1)
  313. state |= ledNumLock;
  314. if (GetKeyState(VK_SCROLL) & 0x1)
  315. state |= ledScrollLock;
  316. #elif defined(__APPLE__)
  317. int ret;
  318. bool on;
  319. ret = cocoa_get_caps_lock_state(&on);
  320. if (ret != 0) {
  321. vlog.error(_("Failed to get keyboard LED state: %d"), ret);
  322. return;
  323. }
  324. if (on)
  325. state |= ledCapsLock;
  326. ret = cocoa_get_num_lock_state(&on);
  327. if (ret != 0) {
  328. vlog.error(_("Failed to get keyboard LED state: %d"), ret);
  329. return;
  330. }
  331. if (on)
  332. state |= ledNumLock;
  333. // No support for Scroll Lock //
  334. state |= (cc->cp.ledState() & ledScrollLock);
  335. #else
  336. unsigned int mask;
  337. Status status;
  338. XkbStateRec xkbState;
  339. status = XkbGetState(fl_display, XkbUseCoreKbd, &xkbState);
  340. if (status != Success) {
  341. vlog.error(_("Failed to get keyboard LED state: %d"), status);
  342. return;
  343. }
  344. if (xkbState.locked_mods & LockMask)
  345. state |= ledCapsLock;
  346. mask = getModifierMask(XK_Num_Lock);
  347. if (xkbState.locked_mods & mask)
  348. state |= ledNumLock;
  349. mask = getModifierMask(XK_Scroll_Lock);
  350. if (xkbState.locked_mods & mask)
  351. state |= ledScrollLock;
  352. #endif
  353. if ((state & ledCapsLock) != (cc->cp.ledState() & ledCapsLock)) {
  354. vlog.debug("Inserting fake CapsLock to get in sync with server");
  355. handleKeyPress(0x3a, XK_Caps_Lock);
  356. handleKeyRelease(0x3a);
  357. }
  358. if ((state & ledNumLock) != (cc->cp.ledState() & ledNumLock)) {
  359. vlog.debug("Inserting fake NumLock to get in sync with server");
  360. handleKeyPress(0x45, XK_Num_Lock);
  361. handleKeyRelease(0x45);
  362. }
  363. if ((state & ledScrollLock) != (cc->cp.ledState() & ledScrollLock)) {
  364. vlog.debug("Inserting fake ScrollLock to get in sync with server");
  365. handleKeyPress(0x46, XK_Scroll_Lock);
  366. handleKeyRelease(0x46);
  367. }
  368. }
  369. void Viewport::draw(Surface* dst)
  370. {
  371. int X, Y, W, H;
  372. // Check what actually needs updating
  373. fl_clip_box(x(), y(), w(), h(), X, Y, W, H);
  374. if ((W == 0) || (H == 0))
  375. return;
  376. frameBuffer->draw(dst, X - x(), Y - y(), X, Y, W, H);
  377. }
  378. void Viewport::draw()
  379. {
  380. int X, Y, W, H;
  381. // Check what actually needs updating
  382. fl_clip_box(x(), y(), w(), h(), X, Y, W, H);
  383. if ((W == 0) || (H == 0))
  384. return;
  385. frameBuffer->draw(X - x(), Y - y(), X, Y, W, H);
  386. }
  387. void Viewport::resize(int x, int y, int w, int h)
  388. {
  389. if ((w != frameBuffer->width()) || (h != frameBuffer->height())) {
  390. vlog.debug("Resizing framebuffer from %dx%d to %dx%d",
  391. frameBuffer->width(), frameBuffer->height(), w, h);
  392. frameBuffer = new PlatformPixelBuffer(w, h);
  393. assert(frameBuffer);
  394. cc->setFramebuffer(frameBuffer);
  395. }
  396. Fl_Widget::resize(x, y, w, h);
  397. }
  398. int Viewport::handle(int event)
  399. {
  400. char *buffer;
  401. int ret;
  402. int buttonMask, wheelMask;
  403. DownMap::const_iterator iter;
  404. switch (event) {
  405. case FL_PASTE:
  406. buffer = new char[Fl::event_length() + 1];
  407. // This is documented as to ASCII, but actually does to 8859-1
  408. ret = fl_utf8toa(Fl::event_text(), Fl::event_length(), buffer,
  409. Fl::event_length() + 1);
  410. assert(ret < (Fl::event_length() + 1));
  411. vlog.debug("Sending clipboard data (%d bytes)", (int)strlen(buffer));
  412. try {
  413. cc->writer()->clientCutText(buffer, ret);
  414. } catch (rdr::Exception& e) {
  415. vlog.error("%s", e.str());
  416. exit_vncviewer(e.str());
  417. }
  418. delete [] buffer;
  419. return 1;
  420. case FL_ENTER:
  421. if (cursor)
  422. window()->cursor(cursor, cursorHotspot.x, cursorHotspot.y);
  423. // Yes, we would like some pointer events please!
  424. return 1;
  425. case FL_LEAVE:
  426. window()->cursor(FL_CURSOR_DEFAULT);
  427. // Fall through as we want a last move event to help trigger edge stuff
  428. case FL_PUSH:
  429. case FL_RELEASE:
  430. case FL_DRAG:
  431. case FL_MOVE:
  432. case FL_MOUSEWHEEL:
  433. buttonMask = 0;
  434. if (Fl::event_button1())
  435. buttonMask |= 1;
  436. if (Fl::event_button2())
  437. buttonMask |= 2;
  438. if (Fl::event_button3())
  439. buttonMask |= 4;
  440. if (event == FL_MOUSEWHEEL) {
  441. wheelMask = 0;
  442. if (Fl::event_dy() < 0)
  443. wheelMask |= 8;
  444. if (Fl::event_dy() > 0)
  445. wheelMask |= 16;
  446. if (Fl::event_dx() < 0)
  447. wheelMask |= 32;
  448. if (Fl::event_dx() > 0)
  449. wheelMask |= 64;
  450. // A quick press of the wheel "button", followed by a immediate
  451. // release below
  452. handlePointerEvent(Point(Fl::event_x() - x(), Fl::event_y() - y()),
  453. buttonMask | wheelMask);
  454. }
  455. handlePointerEvent(Point(Fl::event_x() - x(), Fl::event_y() - y()), buttonMask);
  456. return 1;
  457. case FL_FOCUS:
  458. Fl::disable_im();
  459. // Yes, we would like some focus please!
  460. return 1;
  461. case FL_UNFOCUS:
  462. // Release all keys that were pressed as that generally makes most
  463. // sense (e.g. Alt+Tab where we only see the Alt press)
  464. while (!downKeySym.empty())
  465. handleKeyRelease(downKeySym.begin()->first);
  466. Fl::enable_im();
  467. return 1;
  468. case FL_KEYDOWN:
  469. case FL_KEYUP:
  470. // Just ignore these as keys were handled in the event handler
  471. return 1;
  472. }
  473. return Fl_Widget::handle(event);
  474. }
  475. #if ! (defined(WIN32) || defined(__APPLE__))
  476. unsigned int Viewport::getModifierMask(unsigned int keysym)
  477. {
  478. XkbDescPtr xkb;
  479. unsigned int mask, keycode;
  480. XkbAction *act;
  481. mask = 0;
  482. xkb = XkbGetMap(fl_display, XkbAllComponentsMask, XkbUseCoreKbd);
  483. if (xkb == NULL)
  484. return 0;
  485. for (keycode = xkb->min_key_code; keycode <= xkb->max_key_code; keycode++) {
  486. unsigned int state_out;
  487. KeySym ks;
  488. XkbTranslateKeyCode(xkb, keycode, 0, &state_out, &ks);
  489. if (ks == NoSymbol)
  490. continue;
  491. if (ks == keysym)
  492. break;
  493. }
  494. // KeySym not mapped?
  495. if (keycode > xkb->max_key_code)
  496. goto out;
  497. act = XkbKeyAction(xkb, keycode, 0);
  498. if (act == NULL)
  499. goto out;
  500. if (act->type != XkbSA_LockMods)
  501. goto out;
  502. if (act->mods.flags & XkbSA_UseModMapMods)
  503. mask = xkb->map->modmap[keycode];
  504. else
  505. mask = act->mods.mask;
  506. out:
  507. XkbFreeKeyboard(xkb, XkbAllComponentsMask, True);
  508. return mask;
  509. }
  510. #endif
  511. void Viewport::handleClipboardChange(int source, void *data)
  512. {
  513. Viewport *self = (Viewport *)data;
  514. assert(self);
  515. if (!sendClipboard)
  516. return;
  517. #if !defined(WIN32) && !defined(__APPLE__)
  518. if (!sendPrimary && (source == 0))
  519. return;
  520. #endif
  521. Fl::paste(*self, source);
  522. }
  523. void Viewport::handlePointerEvent(const rfb::Point& pos, int buttonMask)
  524. {
  525. if (!viewOnly) {
  526. if (pointerEventInterval == 0 || buttonMask != lastButtonMask) {
  527. try {
  528. cc->writer()->pointerEvent(pos, buttonMask);
  529. } catch (rdr::Exception& e) {
  530. vlog.error("%s", e.str());
  531. exit_vncviewer(e.str());
  532. }
  533. } else {
  534. if (!Fl::has_timeout(handlePointerTimeout, this))
  535. Fl::add_timeout((double)pointerEventInterval/1000.0,
  536. handlePointerTimeout, this);
  537. }
  538. lastPointerPos = pos;
  539. lastButtonMask = buttonMask;
  540. }
  541. }
  542. void Viewport::handlePointerTimeout(void *data)
  543. {
  544. Viewport *self = (Viewport *)data;
  545. assert(self);
  546. try {
  547. self->cc->writer()->pointerEvent(self->lastPointerPos, self->lastButtonMask);
  548. } catch (rdr::Exception& e) {
  549. vlog.error("%s", e.str());
  550. exit_vncviewer(e.str());
  551. }
  552. }
  553. void Viewport::handleKeyPress(int keyCode, rdr::U32 keySym)
  554. {
  555. static bool menuRecursion = false;
  556. // Prevent recursion if the menu wants to send its own
  557. // activation key.
  558. if (menuKeySym && (keySym == menuKeySym) && !menuRecursion) {
  559. menuRecursion = true;
  560. popupContextMenu();
  561. menuRecursion = false;
  562. return;
  563. }
  564. if (viewOnly)
  565. return;
  566. if (keyCode == 0) {
  567. vlog.error(_("No key code specified on key press"));
  568. return;
  569. }
  570. #ifdef __APPLE__
  571. // Alt on OS X behaves more like AltGr on other systems, and to get
  572. // sane behaviour we should translate things in that manner for the
  573. // remote VNC server. However that means we lose the ability to use
  574. // Alt as a shortcut modifier. Do what RealVNC does and hijack the
  575. // left command key as an Alt replacement.
  576. switch (keySym) {
  577. case XK_Super_L:
  578. keySym = XK_Alt_L;
  579. break;
  580. case XK_Super_R:
  581. keySym = XK_Super_L;
  582. break;
  583. case XK_Alt_L:
  584. keySym = XK_Mode_switch;
  585. break;
  586. case XK_Alt_R:
  587. keySym = XK_ISO_Level3_Shift;
  588. break;
  589. }
  590. #endif
  591. // Because of the way keyboards work, we cannot expect to have the same
  592. // symbol on release as when pressed. This breaks the VNC protocol however,
  593. // so we need to keep track of what keysym a key _code_ generated on press
  594. // and send the same on release.
  595. downKeySym[keyCode] = keySym;
  596. #if defined(WIN32) || defined(__APPLE__)
  597. vlog.debug("Key pressed: 0x%04x => 0x%04x", keyCode, keySym);
  598. #else
  599. vlog.debug("Key pressed: 0x%04x => XK_%s (0x%04x)",
  600. keyCode, XKeysymToString(keySym), keySym);
  601. #endif
  602. try {
  603. // Fake keycode?
  604. if (keyCode > 0xff)
  605. cc->writer()->keyEvent(keySym, 0, true);
  606. else
  607. cc->writer()->keyEvent(keySym, keyCode, true);
  608. } catch (rdr::Exception& e) {
  609. vlog.error("%s", e.str());
  610. exit_vncviewer(e.str());
  611. }
  612. }
  613. void Viewport::handleKeyRelease(int keyCode)
  614. {
  615. DownMap::iterator iter;
  616. if (viewOnly)
  617. return;
  618. iter = downKeySym.find(keyCode);
  619. if (iter == downKeySym.end()) {
  620. // These occur somewhat frequently so let's not spam them unless
  621. // logging is turned up.
  622. vlog.debug("Unexpected release of key code %d", keyCode);
  623. return;
  624. }
  625. #if defined(WIN32) || defined(__APPLE__)
  626. vlog.debug("Key released: 0x%04x => 0x%04x", keyCode, iter->second);
  627. #else
  628. vlog.debug("Key released: 0x%04x => XK_%s (0x%04x)",
  629. keyCode, XKeysymToString(iter->second), iter->second);
  630. #endif
  631. try {
  632. if (keyCode > 0xff)
  633. cc->writer()->keyEvent(iter->second, 0, false);
  634. else
  635. cc->writer()->keyEvent(iter->second, keyCode, false);
  636. } catch (rdr::Exception& e) {
  637. vlog.error("%s", e.str());
  638. exit_vncviewer(e.str());
  639. }
  640. downKeySym.erase(iter);
  641. }
  642. int Viewport::handleSystemEvent(void *event, void *data)
  643. {
  644. Viewport *self = (Viewport *)data;
  645. Fl_Widget *focus;
  646. assert(self);
  647. focus = Fl::grab();
  648. if (!focus)
  649. focus = Fl::focus();
  650. if (!focus)
  651. return 0;
  652. if (focus != self)
  653. return 0;
  654. assert(event);
  655. #if defined(WIN32)
  656. MSG *msg = (MSG*)event;
  657. if ((msg->message == WM_KEYDOWN) || (msg->message == WM_SYSKEYDOWN)) {
  658. UINT vKey;
  659. bool isExtended;
  660. int keyCode;
  661. rdr::U32 keySym;
  662. vKey = msg->wParam;
  663. isExtended = (msg->lParam & (1 << 24)) != 0;
  664. keyCode = ((msg->lParam >> 16) & 0xff);
  665. // Windows doesn't have a proper AltGr, but handles it using fake
  666. // Ctrl+Alt. However the remote end might not be Windows, so we need
  667. // to merge those in to a single AltGr event. We detect this case
  668. // by seeing the two key events directly after each other with a very
  669. // short time between them (<50ms) and supress the Ctrl event.
  670. if (self->altGrArmed) {
  671. self->altGrArmed = false;
  672. Fl::remove_timeout(handleAltGrTimeout);
  673. if (isExtended && (keyCode == 0x38) && (vKey == VK_MENU) &&
  674. ((msg->time - self->altGrCtrlTime) < 50)) {
  675. // Alt seen, so this is an AltGr sequence
  676. } else {
  677. // Not Alt, so fire the queued up Ctrl event
  678. self->handleKeyPress(0x1d, XK_Control_L);
  679. }
  680. }
  681. if (keyCode == SCAN_FAKE) {
  682. vlog.debug("Ignoring fake key press (virtual key 0x%02x)", vKey);
  683. return 1;
  684. }
  685. // Windows sets the scan code to 0x00 for multimedia keys, so we
  686. // have to do a reverse lookup based on the vKey.
  687. if (keyCode == 0x00) {
  688. keyCode = MapVirtualKey(vKey, MAPVK_VK_TO_VSC);
  689. if (keyCode == 0x00) {
  690. if (isExtended)
  691. vlog.error(_("No scan code for extended virtual key 0x%02x"), (int)vKey);
  692. else
  693. vlog.error(_("No scan code for virtual key 0x%02x"), (int)vKey);
  694. return 1;
  695. }
  696. }
  697. if (keyCode & ~0x7f) {
  698. vlog.error(_("Invalid scan code 0x%02x"), (int)keyCode);
  699. return 1;
  700. }
  701. if (isExtended)
  702. keyCode |= 0x80;
  703. // Fortunately RFB and Windows use the same scan code set (mostly),
  704. // so there is no conversion needed
  705. // (as long as we encode the extended keys with the high bit)
  706. // However Pause sends a code that conflicts with NumLock, so use
  707. // the code most RFB implementations use (part of the sequence for
  708. // Ctrl+Pause, i.e. Break)
  709. if (keyCode == 0x45)
  710. keyCode = 0xc6;
  711. // And NumLock incorrectly has the extended bit set
  712. if (keyCode == 0xc5)
  713. keyCode = 0x45;
  714. // And Alt+PrintScreen (i.e. SysRq) sends a different code than
  715. // PrintScreen
  716. if (keyCode == 0xb7)
  717. keyCode = 0x54;
  718. keySym = win32_vkey_to_keysym(vKey, isExtended);
  719. if (keySym == NoSymbol) {
  720. if (isExtended)
  721. vlog.error(_("No symbol for extended virtual key 0x%02x"), (int)vKey);
  722. else
  723. vlog.error(_("No symbol for virtual key 0x%02x"), (int)vKey);
  724. }
  725. // Windows sends the same vKey for both shifts, so we need to look
  726. // at the scan code to tell them apart
  727. if ((keySym == XK_Shift_L) && (keyCode == 0x36))
  728. keySym = XK_Shift_R;
  729. // AltGr handling (see above)
  730. if (win32_has_altgr()) {
  731. if ((keyCode == 0xb8) && (keySym == XK_Alt_R))
  732. keySym = XK_ISO_Level3_Shift;
  733. // Possible start of AltGr sequence?
  734. if ((keyCode == 0x1d) && (keySym == XK_Control_L)) {
  735. self->altGrArmed = true;
  736. self->altGrCtrlTime = msg->time;
  737. Fl::add_timeout(0.1, handleAltGrTimeout, self);
  738. return 1;
  739. }
  740. }
  741. self->handleKeyPress(keyCode, keySym);
  742. return 1;
  743. } else if ((msg->message == WM_KEYUP) || (msg->message == WM_SYSKEYUP)) {
  744. UINT vKey;
  745. bool isExtended;
  746. int keyCode;
  747. vKey = msg->wParam;
  748. isExtended = (msg->lParam & (1 << 24)) != 0;
  749. keyCode = ((msg->lParam >> 16) & 0xff);
  750. // We can't get a release in the middle of an AltGr sequence, so
  751. // abort that detection
  752. if (self->altGrArmed) {
  753. self->altGrArmed = false;
  754. Fl::remove_timeout(handleAltGrTimeout);
  755. self->handleKeyPress(0x1d, XK_Control_L);
  756. }
  757. if (keyCode == SCAN_FAKE) {
  758. vlog.debug("Ignoring fake key release (virtual key 0x%02x)", vKey);
  759. return 1;
  760. }
  761. if (keyCode == 0x00)
  762. keyCode = MapVirtualKey(vKey, MAPVK_VK_TO_VSC);
  763. if (isExtended)
  764. keyCode |= 0x80;
  765. if (keyCode == 0x45)
  766. keyCode = 0xc6;
  767. if (keyCode == 0xc5)
  768. keyCode = 0x45;
  769. if (keyCode == 0xb7)
  770. keyCode = 0x54;
  771. self->handleKeyRelease(keyCode);
  772. // Windows has a rather nasty bug where it won't send key release
  773. // events for a Shift button if the other Shift is still pressed
  774. if ((keyCode == 0x2a) || (keyCode == 0x36)) {
  775. if (self->downKeySym.count(0x2a))
  776. self->handleKeyRelease(0x2a);
  777. if (self->downKeySym.count(0x36))
  778. self->handleKeyRelease(0x36);
  779. }
  780. return 1;
  781. }
  782. #elif defined(__APPLE__)
  783. if (cocoa_is_keyboard_event(event)) {
  784. int keyCode;
  785. keyCode = cocoa_event_keycode(event);
  786. if ((unsigned)keyCode >= code_map_osx_to_qnum_len)
  787. keyCode = 0;
  788. else
  789. keyCode = code_map_osx_to_qnum[keyCode];
  790. if (cocoa_is_key_press(event)) {
  791. rdr::U32 keySym;
  792. keySym = cocoa_event_keysym(event);
  793. if (keySym == NoSymbol) {
  794. vlog.error(_("No symbol for key code 0x%02x (in the current state)"),
  795. (int)keyCode);
  796. }
  797. self->handleKeyPress(keyCode, keySym);
  798. // We don't get any release events for CapsLock, so we have to
  799. // send the release right away.
  800. if (keySym == XK_Caps_Lock)
  801. self->handleKeyRelease(keyCode);
  802. } else {
  803. self->handleKeyRelease(keyCode);
  804. }
  805. return 1;
  806. }
  807. #else
  808. XEvent *xevent = (XEvent*)event;
  809. if (xevent->type == KeyPress) {
  810. int keycode;
  811. char str;
  812. KeySym keysym;
  813. keycode = code_map_keycode_to_qnum[xevent->xkey.keycode];
  814. // Generate a fake keycode just for tracking if we can't figure
  815. // out the proper one
  816. if (keycode == 0)
  817. keycode = 0x100 | xevent->xkey.keycode;
  818. XLookupString(&xevent->xkey, &str, 1, &keysym, NULL);
  819. if (keysym == NoSymbol) {
  820. vlog.error(_("No symbol for key code %d (in the current state)"),
  821. (int)xevent->xkey.keycode);
  822. }
  823. switch (keysym) {
  824. // For the first few years, there wasn't a good consensus on what the
  825. // Windows keys should be mapped to for X11. So we need to help out a
  826. // bit and map all variants to the same key...
  827. case XK_Hyper_L:
  828. keysym = XK_Super_L;
  829. break;
  830. case XK_Hyper_R:
  831. keysym = XK_Super_R;
  832. break;
  833. // There has been several variants for Shift-Tab over the years.
  834. // RFB states that we should always send a normal tab.
  835. case XK_ISO_Left_Tab:
  836. keysym = XK_Tab;
  837. break;
  838. }
  839. self->handleKeyPress(keycode, keysym);
  840. return 1;
  841. } else if (xevent->type == KeyRelease) {
  842. int keycode = code_map_keycode_to_qnum[xevent->xkey.keycode];
  843. if (keycode == 0)
  844. keycode = 0x100 | xevent->xkey.keycode;
  845. self->handleKeyRelease(keycode);
  846. return 1;
  847. }
  848. #endif
  849. return 0;
  850. }
  851. #ifdef WIN32
  852. void Viewport::handleAltGrTimeout(void *data)
  853. {
  854. Viewport *self = (Viewport *)data;
  855. assert(self);
  856. self->altGrArmed = false;
  857. self->handleKeyPress(0x1d, XK_Control_L);
  858. }
  859. #endif
  860. void Viewport::initContextMenu()
  861. {
  862. contextMenu->clear();
  863. fltk_menu_add(contextMenu, p_("ContextMenu|", "E&xit viewer"),
  864. 0, NULL, (void*)ID_EXIT, FL_MENU_DIVIDER);
  865. fltk_menu_add(contextMenu, p_("ContextMenu|", "&Full screen"),
  866. 0, NULL, (void*)ID_FULLSCREEN,
  867. FL_MENU_TOGGLE | (window()->fullscreen_active()?FL_MENU_VALUE:0));
  868. fltk_menu_add(contextMenu, p_("ContextMenu|", "Minimi&ze"),
  869. 0, NULL, (void*)ID_MINIMIZE, 0);
  870. fltk_menu_add(contextMenu, p_("ContextMenu|", "Resize &window to session"),
  871. 0, NULL, (void*)ID_RESIZE,
  872. (window()->fullscreen_active()?FL_MENU_INACTIVE:0) |
  873. FL_MENU_DIVIDER);
  874. fltk_menu_add(contextMenu, p_("ContextMenu|", "&Ctrl"),
  875. 0, NULL, (void*)ID_CTRL,
  876. FL_MENU_TOGGLE | (menuCtrlKey?FL_MENU_VALUE:0));
  877. fltk_menu_add(contextMenu, p_("ContextMenu|", "&Alt"),
  878. 0, NULL, (void*)ID_ALT,
  879. FL_MENU_TOGGLE | (menuAltKey?FL_MENU_VALUE:0));
  880. if (menuKeySym) {
  881. char sendMenuKey[64];
  882. snprintf(sendMenuKey, 64, p_("ContextMenu|", "Send %s"), (const char *)menuKey);
  883. fltk_menu_add(contextMenu, sendMenuKey, 0, NULL, (void*)ID_MENUKEY, 0);
  884. fltk_menu_add(contextMenu, "Secret shortcut menu key", menuKeyFLTK, NULL,
  885. (void*)ID_MENUKEY, FL_MENU_INVISIBLE);
  886. }
  887. fltk_menu_add(contextMenu, p_("ContextMenu|", "Send Ctrl-Alt-&Del"),
  888. 0, NULL, (void*)ID_CTRLALTDEL, FL_MENU_DIVIDER);
  889. fltk_menu_add(contextMenu, p_("ContextMenu|", "&Refresh screen"),
  890. 0, NULL, (void*)ID_REFRESH, FL_MENU_DIVIDER);
  891. fltk_menu_add(contextMenu, p_("ContextMenu|", "&Options..."),
  892. 0, NULL, (void*)ID_OPTIONS, 0);
  893. fltk_menu_add(contextMenu, p_("ContextMenu|", "Connection &info..."),
  894. 0, NULL, (void*)ID_INFO, 0);
  895. fltk_menu_add(contextMenu, p_("ContextMenu|", "About &TigerVNC viewer..."),
  896. 0, NULL, (void*)ID_ABOUT, FL_MENU_DIVIDER);
  897. fltk_menu_add(contextMenu, p_("ContextMenu|", "Dismiss &menu"),
  898. 0, NULL, (void*)ID_DISMISS, 0);
  899. }
  900. void Viewport::popupContextMenu()
  901. {
  902. const Fl_Menu_Item *m;
  903. char buffer[1024];
  904. // Make sure the menu is reset to its initial state between goes or
  905. // it will start up highlighting the previously selected entry.
  906. contextMenu->value(-1);
  907. // initialize context menu before display
  908. initContextMenu();
  909. // Unfortunately FLTK doesn't reliably restore the mouse pointer for
  910. // menus, so we have to help it out.
  911. if (Fl::belowmouse() == this)
  912. window()->cursor(FL_CURSOR_DEFAULT);
  913. m = contextMenu->popup();
  914. // Back to our proper mouse pointer.
  915. if ((Fl::belowmouse() == this) && cursor)
  916. window()->cursor(cursor, cursorHotspot.x, cursorHotspot.y);
  917. if (m == NULL)
  918. return;
  919. switch (m->argument()) {
  920. case ID_EXIT:
  921. exit_vncviewer();
  922. break;
  923. case ID_FULLSCREEN:
  924. if (window()->fullscreen_active())
  925. window()->fullscreen_off();
  926. else
  927. ((DesktopWindow*)window())->fullscreen_on();
  928. break;
  929. case ID_MINIMIZE:
  930. window()->iconize();
  931. break;
  932. case ID_RESIZE:
  933. if (window()->fullscreen_active())
  934. break;
  935. window()->size(w(), h());
  936. break;
  937. case ID_CTRL:
  938. if (m->value())
  939. handleKeyPress(0x1d, XK_Control_L);
  940. else
  941. handleKeyRelease(0x1d);
  942. menuCtrlKey = !menuCtrlKey;
  943. break;
  944. case ID_ALT:
  945. if (m->value())
  946. handleKeyPress(0x38, XK_Alt_L);
  947. else
  948. handleKeyRelease(0x38);
  949. menuAltKey = !menuAltKey;
  950. break;
  951. case ID_MENUKEY:
  952. handleKeyPress(menuKeyCode, menuKeySym);
  953. handleKeyRelease(menuKeyCode);
  954. break;
  955. case ID_CTRLALTDEL:
  956. handleKeyPress(0x1d, XK_Control_L);
  957. handleKeyPress(0x38, XK_Alt_L);
  958. handleKeyPress(0xd3, XK_Delete);
  959. handleKeyRelease(0xd3);
  960. handleKeyRelease(0x38);
  961. handleKeyRelease(0x1d);
  962. break;
  963. case ID_REFRESH:
  964. cc->refreshFramebuffer();
  965. break;
  966. case ID_OPTIONS:
  967. OptionsDialog::showDialog();
  968. break;
  969. case ID_INFO:
  970. if (fltk_escape(cc->connectionInfo(), buffer, sizeof(buffer)) < sizeof(buffer)) {
  971. fl_message_title(_("VNC connection info"));
  972. fl_message("%s", buffer);
  973. }
  974. break;
  975. case ID_ABOUT:
  976. about_vncviewer();
  977. break;
  978. case ID_DISMISS:
  979. // Don't need to do anything
  980. break;
  981. }
  982. }
  983. void Viewport::setMenuKey()
  984. {
  985. getMenuKey(&menuKeyFLTK, &menuKeyCode, &menuKeySym);
  986. }
  987. void Viewport::handleOptions(void *data)
  988. {
  989. Viewport *self = (Viewport*)data;
  990. self->setMenuKey();
  991. }