keyboard.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * noVNC: HTML5 VNC client
  3. * Copyright (C) 2019 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._altGrArmed = false; // Windows AltGr detection
  20. // keep these here so we can refer to them later
  21. this._eventHandlers = {
  22. 'keyup': this._handleKeyUp.bind(this),
  23. 'keydown': this._handleKeyDown.bind(this),
  24. 'blur': this._allKeysUp.bind(this),
  25. };
  26. // ===== EVENT HANDLERS =====
  27. this.onkeyevent = () => {}; // Handler for key press/release
  28. }
  29. // ===== PRIVATE METHODS =====
  30. _sendKeyEvent(keysym, code, down, numlock = null, capslock = null) {
  31. if (down) {
  32. this._keyDownList[code] = keysym;
  33. } else {
  34. // Do we really think this key is down?
  35. if (!(code in this._keyDownList)) {
  36. return;
  37. }
  38. delete this._keyDownList[code];
  39. }
  40. Log.Debug("onkeyevent " + (down ? "down" : "up") +
  41. ", keysym: " + keysym, ", code: " + code +
  42. ", numlock: " + numlock + ", capslock: " + capslock);
  43. this.onkeyevent(keysym, code, down, numlock, capslock);
  44. }
  45. _getKeyCode(e) {
  46. const code = KeyboardUtil.getKeycode(e);
  47. if (code !== 'Unidentified') {
  48. return code;
  49. }
  50. // Unstable, but we don't have anything else to go on
  51. if (e.keyCode) {
  52. // 229 is used for composition events
  53. if (e.keyCode !== 229) {
  54. return 'Platform' + e.keyCode;
  55. }
  56. }
  57. // A precursor to the final DOM3 standard. Unfortunately it
  58. // is not layout independent, so it is as bad as using keyCode
  59. if (e.keyIdentifier) {
  60. // Non-character key?
  61. if (e.keyIdentifier.substr(0, 2) !== 'U+') {
  62. return e.keyIdentifier;
  63. }
  64. const codepoint = parseInt(e.keyIdentifier.substr(2), 16);
  65. const char = String.fromCharCode(codepoint).toUpperCase();
  66. return 'Platform' + char.charCodeAt();
  67. }
  68. return 'Unidentified';
  69. }
  70. _handleKeyDown(e) {
  71. const code = this._getKeyCode(e);
  72. let keysym = KeyboardUtil.getKeysym(e);
  73. let numlock = e.getModifierState('NumLock');
  74. let capslock = e.getModifierState('CapsLock');
  75. // getModifierState for NumLock is not supported on mac and ios and always returns false.
  76. // Set to null to indicate unknown/unsupported instead.
  77. if (browser.isMac() || browser.isIOS()) {
  78. numlock = null;
  79. }
  80. // Windows doesn't have a proper AltGr, but handles it using
  81. // fake Ctrl+Alt. However the remote end might not be Windows,
  82. // so we need to merge those in to a single AltGr event. We
  83. // detect this case by seeing the two key events directly after
  84. // each other with a very short time between them (<50ms).
  85. if (this._altGrArmed) {
  86. this._altGrArmed = false;
  87. clearTimeout(this._altGrTimeout);
  88. if ((code === "AltRight") &&
  89. ((e.timeStamp - this._altGrCtrlTime) < 50)) {
  90. // FIXME: We fail to detect this if either Ctrl key is
  91. // first manually pressed as Windows then no
  92. // longer sends the fake Ctrl down event. It
  93. // does however happily send real Ctrl events
  94. // even when AltGr is already down. Some
  95. // browsers detect this for us though and set the
  96. // key to "AltGraph".
  97. keysym = KeyTable.XK_ISO_Level3_Shift;
  98. } else {
  99. this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true, numlock, capslock);
  100. }
  101. }
  102. // We cannot handle keys we cannot track, but we also need
  103. // to deal with virtual keyboards which omit key info
  104. if (code === 'Unidentified') {
  105. if (keysym) {
  106. // If it's a virtual keyboard then it should be
  107. // sufficient to just send press and release right
  108. // after each other
  109. this._sendKeyEvent(keysym, code, true, numlock, capslock);
  110. this._sendKeyEvent(keysym, code, false, numlock, capslock);
  111. }
  112. stopEvent(e);
  113. return;
  114. }
  115. // Alt behaves more like AltGraph on macOS, so shuffle the
  116. // keys around a bit to make things more sane for the remote
  117. // server. This method is used by RealVNC and TigerVNC (and
  118. // possibly others).
  119. if (browser.isMac() || browser.isIOS()) {
  120. switch (keysym) {
  121. case KeyTable.XK_Super_L:
  122. keysym = KeyTable.XK_Alt_L;
  123. break;
  124. case KeyTable.XK_Super_R:
  125. keysym = KeyTable.XK_Super_L;
  126. break;
  127. case KeyTable.XK_Alt_L:
  128. keysym = KeyTable.XK_Mode_switch;
  129. break;
  130. case KeyTable.XK_Alt_R:
  131. keysym = KeyTable.XK_ISO_Level3_Shift;
  132. break;
  133. }
  134. }
  135. // Is this key already pressed? If so, then we must use the
  136. // same keysym or we'll confuse the server
  137. if (code in this._keyDownList) {
  138. keysym = this._keyDownList[code];
  139. }
  140. // macOS doesn't send proper key releases if a key is pressed
  141. // while meta is held down
  142. if ((browser.isMac() || browser.isIOS()) &&
  143. (e.metaKey && code !== 'MetaLeft' && code !== 'MetaRight')) {
  144. this._sendKeyEvent(keysym, code, true, numlock, capslock);
  145. this._sendKeyEvent(keysym, code, false, numlock, capslock);
  146. stopEvent(e);
  147. return;
  148. }
  149. // macOS doesn't send proper key events for modifiers, only
  150. // state change events. That gets extra confusing for CapsLock
  151. // which toggles on each press, but not on release. So pretend
  152. // it was a quick press and release of the button.
  153. if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) {
  154. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true, numlock, capslock);
  155. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false, numlock, capslock);
  156. stopEvent(e);
  157. return;
  158. }
  159. // Windows doesn't send proper key releases for a bunch of
  160. // Japanese IM keys so we have to fake the release right away
  161. const jpBadKeys = [ KeyTable.XK_Zenkaku_Hankaku,
  162. KeyTable.XK_Eisu_toggle,
  163. KeyTable.XK_Katakana,
  164. KeyTable.XK_Hiragana,
  165. KeyTable.XK_Romaji ];
  166. if (browser.isWindows() && jpBadKeys.includes(keysym)) {
  167. this._sendKeyEvent(keysym, code, true, numlock, capslock);
  168. this._sendKeyEvent(keysym, code, false, numlock, capslock);
  169. stopEvent(e);
  170. return;
  171. }
  172. stopEvent(e);
  173. // Possible start of AltGr sequence? (see above)
  174. if ((code === "ControlLeft") && browser.isWindows() &&
  175. !("ControlLeft" in this._keyDownList)) {
  176. this._altGrArmed = true;
  177. this._altGrTimeout = setTimeout(this._handleAltGrTimeout.bind(this), 100);
  178. this._altGrCtrlTime = e.timeStamp;
  179. return;
  180. }
  181. this._sendKeyEvent(keysym, code, true, numlock, capslock);
  182. }
  183. _handleKeyUp(e) {
  184. stopEvent(e);
  185. const code = this._getKeyCode(e);
  186. // We can't get a release in the middle of an AltGr sequence, so
  187. // abort that detection
  188. if (this._altGrArmed) {
  189. this._altGrArmed = false;
  190. clearTimeout(this._altGrTimeout);
  191. this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
  192. }
  193. // See comment in _handleKeyDown()
  194. if ((browser.isMac() || browser.isIOS()) && (code === 'CapsLock')) {
  195. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', true);
  196. this._sendKeyEvent(KeyTable.XK_Caps_Lock, 'CapsLock', false);
  197. return;
  198. }
  199. this._sendKeyEvent(this._keyDownList[code], code, false);
  200. // Windows has a rather nasty bug where it won't send key
  201. // release events for a Shift button if the other Shift is still
  202. // pressed
  203. if (browser.isWindows() && ((code === 'ShiftLeft') ||
  204. (code === 'ShiftRight'))) {
  205. if ('ShiftRight' in this._keyDownList) {
  206. this._sendKeyEvent(this._keyDownList['ShiftRight'],
  207. 'ShiftRight', false);
  208. }
  209. if ('ShiftLeft' in this._keyDownList) {
  210. this._sendKeyEvent(this._keyDownList['ShiftLeft'],
  211. 'ShiftLeft', false);
  212. }
  213. }
  214. }
  215. _handleAltGrTimeout() {
  216. this._altGrArmed = false;
  217. clearTimeout(this._altGrTimeout);
  218. this._sendKeyEvent(KeyTable.XK_Control_L, "ControlLeft", true);
  219. }
  220. _allKeysUp() {
  221. Log.Debug(">> Keyboard.allKeysUp");
  222. for (let code in this._keyDownList) {
  223. this._sendKeyEvent(this._keyDownList[code], code, false);
  224. }
  225. Log.Debug("<< Keyboard.allKeysUp");
  226. }
  227. // ===== PUBLIC METHODS =====
  228. grab() {
  229. //Log.Debug(">> Keyboard.grab");
  230. this._target.addEventListener('keydown', this._eventHandlers.keydown);
  231. this._target.addEventListener('keyup', this._eventHandlers.keyup);
  232. // Release (key up) if window loses focus
  233. window.addEventListener('blur', this._eventHandlers.blur);
  234. //Log.Debug("<< Keyboard.grab");
  235. }
  236. ungrab() {
  237. //Log.Debug(">> Keyboard.ungrab");
  238. this._target.removeEventListener('keydown', this._eventHandlers.keydown);
  239. this._target.removeEventListener('keyup', this._eventHandlers.keyup);
  240. window.removeEventListener('blur', this._eventHandlers.blur);
  241. // Release (key up) all keys that are in a down state
  242. this._allKeysUp();
  243. //Log.Debug(">> Keyboard.ungrab");
  244. }
  245. }