keyboard.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /*
  2. * noVNC: HTML5 VNC client
  3. * Copyright (C) 2018 The noVNC Authors
  4. * Licensed under MPL 2.0 or any later version (see LICENSE.txt)
  5. */
  6. import * as Log from '../util/logging.js';
  7. import { stopEvent } from '../util/events.js';
  8. import * as KeyboardUtil from "./util.js";
  9. import KeyTable from "./keysym.js";
  10. import * as browser from "../util/browser.js";
  11. //
  12. // Keyboard event handler
  13. //
  14. export default class Keyboard {
  15. constructor(target) {
  16. this._target = target || null;
  17. this._keyDownList = {}; // List of depressed keys
  18. // (even if they are happy)
  19. this._pendingKey = null; // Key waiting for keypress
  20. this._altGrArmed = false; // Windows AltGr detection
  21. // keep these here so we can refer to them later
  22. this._eventHandlers = {
  23. 'keyup': this._handleKeyUp.bind(this),
  24. 'keydown': this._handleKeyDown.bind(this),
  25. 'keypress': this._handleKeyPress.bind(this),
  26. 'blur': this._allKeysUp.bind(this),
  27. 'checkalt': this._checkAlt.bind(this),
  28. };
  29. // ===== EVENT HANDLERS =====
  30. this.onkeyevent = () => {}; // Handler for key press/release
  31. }
  32. // ===== PRIVATE METHODS =====
  33. _sendKeyEvent(keysym, code, down) {
  34. if (down) {
  35. this._keyDownList[code] = keysym;
  36. } else {
  37. // Do we really think this key is down?
  38. if (!(code in this._keyDownList)) {
  39. return;
  40. }
  41. delete this._keyDownList[code];
  42. }
  43. Log.Debug("onkeyevent " + (down ? "down" : "up") +
  44. ", keysym: " + keysym, ", code: " + code);
  45. this.onkeyevent(keysym, code, down);
  46. }
  47. _getKeyCode(e) {
  48. const code = KeyboardUtil.getKeycode(e);
  49. if (code !== 'Unidentified') {
  50. return code;
  51. }
  52. // Unstable, but we don't have anything else to go on
  53. // (don't use it for 'keypress' events thought since
  54. // WebKit sets it to the same as charCode)
  55. if (e.keyCode && (e.type !== 'keypress')) {
  56. // 229 is used for composition events
  57. if (e.keyCode !== 229) {
  58. return 'Platform' + e.keyCode;
  59. }
  60. }
  61. // A precursor to the final DOM3 standard. Unfortunately it
  62. // is not layout independent, so it is as bad as using keyCode
  63. if (e.keyIdentifier) {
  64. // Non-character key?
  65. if (e.keyIdentifier.substr(0, 2) !== 'U+') {
  66. return e.keyIdentifier;
  67. }
  68. const codepoint = parseInt(e.keyIdentifier.substr(2), 16);
  69. const char = String.fromCharCode(codepoint).toUpperCase();
  70. return 'Platform' + char.charCodeAt();
  71. }
  72. return 'Unidentified';
  73. }
  74. _handleKeyDown(e) {
  75. const code = this._getKeyCode(e);
  76. let keysym = KeyboardUtil.getKeysym(e);
  77. // Windows doesn't have a proper AltGr, but handles it using
  78. // fake Ctrl+Alt. However the remote end might not be Windows,
  79. // so we need to merge those in to a single AltGr event. We
  80. // detect this case by seeing the two key events directly after
  81. // each other with a very short time between them (<50ms).
  82. if (this._altGrArmed) {
  83. this._altGrArmed = false;
  84. clearTimeout(this._altGrTimeout);
  85. if ((code === "AltRight") &&
  86. ((e.timeStamp - this._altGrCtrlTime) < 50)) {
  87. // FIXME: We fail to detect this if either Ctrl key is
  88. // first manually pressed as Windows then no
  89. // longer sends the fake Ctrl down event. It
  90. // does however happily send real Ctrl events
  91. // even when AltGr is already down. Some
  92. // browsers detect this for us though and set the
  93. // key to "AltGraph".
  94. keysym = KeyTable.XK_ISO_Level3_Shift;
  95. } else {
  96. this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
  97. }
  98. }
  99. // We cannot handle keys we cannot track, but we also need
  100. // to deal with virtual keyboards which omit key info
  101. // (iOS omits tracking info on keyup events, which forces us to
  102. // special treat that platform here)
  103. if ((code === 'Unidentified') || browser.isIOS()) {
  104. if (keysym) {
  105. // If it's a virtual keyboard then it should be
  106. // sufficient to just send press and release right
  107. // after each other
  108. this._sendKeyEvent(keysym, code, true);
  109. this._sendKeyEvent(keysym, code, false);
  110. }
  111. stopEvent(e);
  112. return;
  113. }
  114. // Alt behaves more like AltGraph on macOS, so shuffle the
  115. // keys around a bit to make things more sane for the remote
  116. // server. This method is used by RealVNC and TigerVNC (and
  117. // possibly others).
  118. if (browser.isMac()) {
  119. switch (keysym) {
  120. case KeyTable.XK_Super_L:
  121. keysym = KeyTable.XK_Alt_L;
  122. break;
  123. case KeyTable.XK_Super_R:
  124. keysym = KeyTable.XK_Super_L;
  125. break;
  126. case KeyTable.XK_Alt_L:
  127. keysym = KeyTable.XK_Mode_switch;
  128. break;
  129. case KeyTable.XK_Alt_R:
  130. keysym = KeyTable.XK_ISO_Level3_Shift;
  131. break;
  132. }
  133. }
  134. // Is this key already pressed? If so, then we must use the
  135. // same keysym or we'll confuse the server
  136. if (code in this._keyDownList) {
  137. keysym = this._keyDownList[code];
  138. }
  139. // macOS doesn't send proper key events for modifiers, only
  140. // state change events. That gets extra confusing for CapsLock
  141. // which toggles on each press, but not on release. So pretend
  142. // it was a quick press and release of the button.
  143. if (browser.isMac() && (code === 'CapsLock')) {
  144. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true);
  145. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false);
  146. stopEvent(e);
  147. return;
  148. }
  149. // If this is a legacy browser then we'll need to wait for
  150. // a keypress event as well
  151. // (IE and Edge has a broken KeyboardEvent.key, so we can't
  152. // just check for the presence of that field)
  153. if (!keysym && (!e.key || browser.isIE() || browser.isEdge())) {
  154. this._pendingKey = code;
  155. // However we might not get a keypress event if the key
  156. // is non-printable, which needs some special fallback
  157. // handling
  158. setTimeout(this._handleKeyPressTimeout.bind(this), 10, e);
  159. return;
  160. }
  161. this._pendingKey = null;
  162. stopEvent(e);
  163. // Possible start of AltGr sequence? (see above)
  164. if ((code === "ControlLeft") && browser.isWindows() &&
  165. !("ControlLeft" in this._keyDownList)) {
  166. this._altGrArmed = true;
  167. this._altGrTimeout = setTimeout(this._handleAltGrTimeout.bind(this), 100);
  168. this._altGrCtrlTime = e.timeStamp;
  169. return;
  170. }
  171. this._sendKeyEvent(keysym, code, true);
  172. }
  173. // Legacy event for browsers without code/key
  174. _handleKeyPress(e) {
  175. stopEvent(e);
  176. // Are we expecting a keypress?
  177. if (this._pendingKey === null) {
  178. return;
  179. }
  180. let code = this._getKeyCode(e);
  181. const keysym = KeyboardUtil.getKeysym(e);
  182. // The key we were waiting for?
  183. if ((code !== 'Unidentified') && (code != this._pendingKey)) {
  184. return;
  185. }
  186. code = this._pendingKey;
  187. this._pendingKey = null;
  188. if (!keysym) {
  189. Log.Info('keypress with no keysym:', e);
  190. return;
  191. }
  192. this._sendKeyEvent(keysym, code, true);
  193. }
  194. _handleKeyPressTimeout(e) {
  195. // Did someone manage to sort out the key already?
  196. if (this._pendingKey === null) {
  197. return;
  198. }
  199. let keysym;
  200. const code = this._pendingKey;
  201. this._pendingKey = null;
  202. // We have no way of knowing the proper keysym with the
  203. // information given, but the following are true for most
  204. // layouts
  205. if ((e.keyCode >= 0x30) && (e.keyCode <= 0x39)) {
  206. // Digit
  207. keysym = e.keyCode;
  208. } else if ((e.keyCode >= 0x41) && (e.keyCode <= 0x5a)) {
  209. // Character (A-Z)
  210. let char = String.fromCharCode(e.keyCode);
  211. // A feeble attempt at the correct case
  212. if (e.shiftKey) {
  213. char = char.toUpperCase();
  214. } else {
  215. char = char.toLowerCase();
  216. }
  217. keysym = char.charCodeAt();
  218. } else {
  219. // Unknown, give up
  220. keysym = 0;
  221. }
  222. this._sendKeyEvent(keysym, code, true);
  223. }
  224. _handleKeyUp(e) {
  225. stopEvent(e);
  226. const code = this._getKeyCode(e);
  227. // We can't get a release in the middle of an AltGr sequence, so
  228. // abort that detection
  229. if (this._altGrArmed) {
  230. this._altGrArmed = false;
  231. clearTimeout(this._altGrTimeout);
  232. this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
  233. }
  234. // See comment in _handleKeyDown()
  235. if (browser.isMac() && (code === 'CapsLock')) {
  236. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true);
  237. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false);
  238. return;
  239. }
  240. this._sendKeyEvent(this._keyDownList[code], code, false);
  241. }
  242. _handleAltGrTimeout() {
  243. this._altGrArmed = false;
  244. clearTimeout(this._altGrTimeout);
  245. this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
  246. }
  247. _allKeysUp() {
  248. Log.Debug(">> Keyboard.allKeysUp");
  249. for (let code in this._keyDownList) {
  250. this._sendKeyEvent(this._keyDownList[code], code, false);
  251. }
  252. Log.Debug("<< Keyboard.allKeysUp");
  253. }
  254. // Firefox Alt workaround, see below
  255. _checkAlt(e) {
  256. if (e.altKey) {
  257. return;
  258. }
  259. const target = this._target;
  260. const downList = this._keyDownList;
  261. ['AltLeft', 'AltRight'].forEach((code) => {
  262. if (!(code in downList)) {
  263. return;
  264. }
  265. const event = new KeyboardEvent('keyup',
  266. { key: downList[code],
  267. code: code });
  268. target.dispatchEvent(event);
  269. });
  270. }
  271. // ===== PUBLIC METHODS =====
  272. grab() {
  273. //Log.Debug(">> Keyboard.grab");
  274. this._target.addEventListener('keydown', this._eventHandlers.keydown);
  275. this._target.addEventListener('keyup', this._eventHandlers.keyup);
  276. this._target.addEventListener('keypress', this._eventHandlers.keypress);
  277. // Release (key up) if window loses focus
  278. window.addEventListener('blur', this._eventHandlers.blur);
  279. // Firefox has broken handling of Alt, so we need to poll as
  280. // best we can for releases (still doesn't prevent the menu
  281. // from popping up though as we can't call preventDefault())
  282. if (browser.isWindows() && browser.isFirefox()) {
  283. const handler = this._eventHandlers.checkalt;
  284. ['mousedown', 'mouseup', 'mousemove', 'wheel',
  285. 'touchstart', 'touchend', 'touchmove',
  286. 'keydown', 'keyup'].forEach(type =>
  287. document.addEventListener(type, handler,
  288. { capture: true,
  289. passive: true }));
  290. }
  291. //Log.Debug("<< Keyboard.grab");
  292. }
  293. ungrab() {
  294. //Log.Debug(">> Keyboard.ungrab");
  295. if (browser.isWindows() && browser.isFirefox()) {
  296. const handler = this._eventHandlers.checkalt;
  297. ['mousedown', 'mouseup', 'mousemove', 'wheel',
  298. 'touchstart', 'touchend', 'touchmove',
  299. 'keydown', 'keyup'].forEach(type => document.removeEventListener(type, handler));
  300. }
  301. this._target.removeEventListener('keydown', this._eventHandlers.keydown);
  302. this._target.removeEventListener('keyup', this._eventHandlers.keyup);
  303. this._target.removeEventListener('keypress', this._eventHandlers.keypress);
  304. window.removeEventListener('blur', this._eventHandlers.blur);
  305. // Release (key up) all keys that are in a down state
  306. this._allKeysUp();
  307. //Log.Debug(">> Keyboard.ungrab");
  308. }
  309. }