keyboard.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. /**
  4. *
  5. *
  6. * @module keyboard
  7. * @namespace keyboard
  8. * @class ShortcutManager
  9. */
  10. define([
  11. 'jquery',
  12. 'base/js/utils',
  13. 'underscore',
  14. ], function($, utils, _) {
  15. "use strict";
  16. /**
  17. * Setup global keycodes and inverse keycodes.
  18. *
  19. * See http://unixpapa.com/js/key.html for a complete description. The short of
  20. * it is that there are different keycode sets. Firefox uses the "Mozilla keycodes"
  21. * and Webkit/IE use the "IE keycodes". These keycode sets are mostly the same
  22. * but have minor differences.
  23. **/
  24. // These apply to Firefox, (Webkit and IE)
  25. // This does work **only** on US keyboard.
  26. var _keycodes = {
  27. 'a': 65, 'b': 66, 'c': 67, 'd': 68, 'e': 69, 'f': 70, 'g': 71, 'h': 72, 'i': 73,
  28. 'j': 74, 'k': 75, 'l': 76, 'm': 77, 'n': 78, 'o': 79, 'p': 80, 'q': 81, 'r': 82,
  29. 's': 83, 't': 84, 'u': 85, 'v': 86, 'w': 87, 'x': 88, 'y': 89, 'z': 90,
  30. '1 !': 49, '2 @': 50, '3 #': 51, '4 $': 52, '5 %': 53, '6 ^': 54,
  31. '7 &': 55, '8 *': 56, '9 (': 57, '0 )': 48,
  32. '[ {': 219, '] }': 221, '` ~': 192, ', <': 188, '. >': 190, '/ ?': 191,
  33. '\\ |': 220, '\' "': 222,
  34. 'numpad0': 96, 'numpad1': 97, 'numpad2': 98, 'numpad3': 99, 'numpad4': 100,
  35. 'numpad5': 101, 'numpad6': 102, 'numpad7': 103, 'numpad8': 104, 'numpad9': 105,
  36. 'multiply': 106, 'add': 107, 'subtract': 109, 'decimal': 110, 'divide': 111,
  37. 'f1': 112, 'f2': 113, 'f3': 114, 'f4': 115, 'f5': 116, 'f6': 117, 'f7': 118,
  38. 'f8': 119, 'f9': 120, 'f10': 121, 'f11': 122, 'f12': 123, 'f13': 124, 'f14': 125, 'f15': 126,
  39. 'backspace': 8, 'tab': 9, 'enter': 13, 'shift': 16, 'ctrl': 17, 'alt': 18,
  40. 'meta': 91, 'capslock': 20, 'esc': 27, 'space': 32, 'pageup': 33, 'pagedown': 34,
  41. 'end': 35, 'home': 36, 'left': 37, 'up': 38, 'right': 39, 'down': 40,
  42. 'insert': 45, 'delete': 46, 'numlock': 144,
  43. };
  44. // These apply to Firefox and Opera
  45. var _mozilla_keycodes = {
  46. '; :': 59, '= +': 61, '- _': 173, 'meta': 224, 'minus':173
  47. };
  48. // This apply to Webkit and IE
  49. var _ie_keycodes = {
  50. '; :': 186, '= +': 187, '- _': 189, 'minus':189
  51. };
  52. var browser = utils.browser[0];
  53. var platform = utils.platform;
  54. if (browser === 'Firefox' || browser === 'Opera' || browser === 'Netscape') {
  55. $.extend(_keycodes, _mozilla_keycodes);
  56. } else if (browser === 'Safari' || browser === 'Chrome' || browser === 'MSIE') {
  57. $.extend(_keycodes, _ie_keycodes);
  58. }
  59. var keycodes = {};
  60. var inv_keycodes = {};
  61. for (var name in _keycodes) {
  62. var names = name.split(' ');
  63. if (names.length === 1) {
  64. var n = names[0];
  65. keycodes[n] = _keycodes[n];
  66. inv_keycodes[_keycodes[n]] = n;
  67. } else {
  68. var primary = names[0];
  69. var secondary = names[1];
  70. keycodes[primary] = _keycodes[name];
  71. keycodes[secondary] = _keycodes[name];
  72. inv_keycodes[_keycodes[name]] = primary;
  73. }
  74. }
  75. var normalize_key = function (key) {
  76. return inv_keycodes[keycodes[key]];
  77. };
  78. var normalize_shortcut = function (shortcut) {
  79. /**
  80. * @function _normalize_shortcut
  81. * @private
  82. * return a dict containing the normalized shortcut and the number of time it should be pressed:
  83. *
  84. * Put a shortcut into normalized form:
  85. * 1. Make lowercase
  86. * 2. Replace cmd by meta
  87. * 3. Sort '-' separated modifiers into the order alt-ctrl-meta-shift
  88. * 4. Normalize keys
  89. **/
  90. if (platform === 'MacOS') {
  91. shortcut = shortcut.toLowerCase().replace('cmdtrl-', 'cmd-');
  92. } else {
  93. shortcut = shortcut.toLowerCase().replace('cmdtrl-', 'ctrl-');
  94. }
  95. shortcut = shortcut.toLowerCase().replace('cmd', 'meta');
  96. shortcut = shortcut.replace(/-$/, 'minus'); // catch shortcuts using '-' key
  97. shortcut = shortcut.replace(/,$/, 'comma'); // catch shortcuts using '-' key
  98. if(shortcut.indexOf(',') !== -1){
  99. var sht = shortcut.split(',');
  100. sht = _.map(sht, normalize_shortcut);
  101. return shortcut;
  102. }
  103. shortcut = shortcut.replace(/comma/g, ','); // catch shortcuts using '-' key
  104. var values = shortcut.split("-");
  105. if (values.length === 1) {
  106. return normalize_key(values[0]);
  107. } else {
  108. var modifiers = values.slice(0,-1);
  109. var key = normalize_key(values[values.length-1]);
  110. modifiers.sort();
  111. return modifiers.join('-') + '-' + key;
  112. }
  113. };
  114. var shortcut_to_event = function (shortcut, type) {
  115. /**
  116. * Convert a shortcut (shift-r) to a jQuery Event object
  117. **/
  118. type = type || 'keydown';
  119. shortcut = normalize_shortcut(shortcut);
  120. shortcut = shortcut.replace(/-$/, 'minus'); // catch shortcuts using '-' key
  121. var values = shortcut.split("-");
  122. var modifiers = values.slice(0,-1);
  123. var key = values[values.length-1];
  124. var opts = {which: keycodes[key]};
  125. if (modifiers.indexOf('alt') !== -1) {opts.altKey = true;}
  126. if (modifiers.indexOf('ctrl') !== -1) {opts.ctrlKey = true;}
  127. if (modifiers.indexOf('meta') !== -1) {opts.metaKey = true;}
  128. if (modifiers.indexOf('shift') !== -1) {opts.shiftKey = true;}
  129. return $.Event(type, opts);
  130. };
  131. var only_modifier_event = function(event){
  132. /**
  133. * Return `true` if the event only contains modifiers keys.
  134. * false otherwise
  135. **/
  136. var key = inv_keycodes[event.which];
  137. return ((event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) &&
  138. (key === 'alt'|| key === 'ctrl'|| key === 'meta'|| key === 'shift'));
  139. };
  140. var event_to_shortcut = function (event) {
  141. /**
  142. * Convert a jQuery Event object to a normalized shortcut string (shift-r)
  143. **/
  144. var shortcut = '';
  145. var key = inv_keycodes[event.which];
  146. if (event.altKey && key !== 'alt') {shortcut += 'alt-';}
  147. if (event.ctrlKey && key !== 'ctrl') {shortcut += 'ctrl-';}
  148. if (event.metaKey && key !== 'meta') {shortcut += 'meta-';}
  149. if (event.shiftKey && key !== 'shift') {shortcut += 'shift-';}
  150. shortcut += key;
  151. return shortcut;
  152. };
  153. // Shortcut manager class
  154. var ShortcutManager = function (delay, events, actions, env, config, mode) {
  155. /**
  156. * A class to deal with keyboard event and shortcut
  157. *
  158. * @class ShortcutManager
  159. * @constructor
  160. *
  161. * :config: configobjet on which to call `update(....)` to persist the config.
  162. * :mode: mode of this shortcut manager where to persist config.
  163. */
  164. mode = mode || 'command';
  165. this._shortcuts = {};
  166. this._defaults_bindings = [];
  167. this.delay = delay || 800; // delay in milliseconds
  168. this.events = events;
  169. this.actions = actions;
  170. this.actions.extend_env(env);
  171. this._queue = [];
  172. this._cleartimeout = null;
  173. this._config = config;
  174. this._mode = mode;
  175. Object.seal(this);
  176. };
  177. ShortcutManager.prototype.clearsoon = function(){
  178. /**
  179. * Clear the pending shortcut soon, and cancel previous clearing
  180. * that might be registered.
  181. **/
  182. var that = this;
  183. clearTimeout(this._cleartimeout);
  184. this._cleartimeout = setTimeout(function(){that.clearqueue();}, this.delay);
  185. };
  186. ShortcutManager.prototype.clearqueue = function(){
  187. /**
  188. * clear the pending shortcut sequence now.
  189. **/
  190. this._queue = [];
  191. clearTimeout(this._cleartimeout);
  192. };
  193. var flatten_shorttree = function(tree){
  194. /**
  195. * Flatten a tree of shortcut sequences.
  196. * use full to iterate over all the key/values of available shortcuts.
  197. **/
  198. var dct = {};
  199. _.forEach(tree, function(value, key) {
  200. if(typeof(value) === 'string'){
  201. dct[key] = value;
  202. } else {
  203. var ftree=flatten_shorttree(value);
  204. _.forEach(ftree, function(v2, subkey) {
  205. dct[key+','+subkey] = ftree[subkey];
  206. });
  207. }
  208. });
  209. return dct;
  210. };
  211. ShortcutManager.prototype.get_action_shortcuts = function(name){
  212. var ftree = flatten_shorttree(this._shortcuts);
  213. var res = [];
  214. _.forEach(ftree, function(value, key) {
  215. if(value === name){
  216. res.push(key);
  217. }
  218. });
  219. return res;
  220. };
  221. ShortcutManager.prototype.get_action_shortcut = function(name){
  222. var matches = this.get_action_shortcuts(name);
  223. if (matches.length > 0) {
  224. return matches[0];
  225. }
  226. return undefined;
  227. };
  228. ShortcutManager.prototype.help = function () {
  229. var that = this;
  230. var help = [];
  231. var ftree = flatten_shorttree(this._shortcuts);
  232. _.forEach(ftree, function(value, key) {
  233. var action = that.actions.get(value);
  234. var help_string = action.help||'== no help ==';
  235. var help_index = action.help_index;
  236. if (help_string) {
  237. var shortstring = (action.shortstring||key);
  238. help.push({
  239. shortcut: shortstring,
  240. help: help_string,
  241. help_index: help_index}
  242. );
  243. }
  244. });
  245. help.sort(function (a, b) {
  246. if (a.help_index === b.help_index) {
  247. if (a.shortcut === b.shortcut) {
  248. return 0;
  249. }
  250. if (a.shortcut > b.shortcut) {
  251. return 1;
  252. }
  253. return -1;
  254. }
  255. if (a.help_index === undefined || a.help_index > b.help_index){
  256. return 1;
  257. }
  258. return -1;
  259. });
  260. return help;
  261. };
  262. ShortcutManager.prototype.clear_shortcuts = function () {
  263. this._shortcuts = {};
  264. };
  265. ShortcutManager.prototype.get_shortcut = function (shortcut){
  266. /**
  267. * return a node of the shortcut tree which an action name (string) if leaf,
  268. * and an object with `object.subtree===true`
  269. **/
  270. if(typeof(shortcut) === 'string'){
  271. shortcut = shortcut.split(',');
  272. }
  273. return this._get_leaf(shortcut, this._shortcuts);
  274. };
  275. ShortcutManager.prototype._get_leaf = function(shortcut_array, tree){
  276. /**
  277. * @private
  278. * find a leaf/node in a subtree of the keyboard shortcut
  279. *
  280. **/
  281. if(shortcut_array.length === 1){
  282. return tree[shortcut_array[0]];
  283. } else if( typeof(tree[shortcut_array[0]]) !== 'string'){
  284. return this._get_leaf(shortcut_array.slice(1), tree[shortcut_array[0]]);
  285. }
  286. return null;
  287. };
  288. ShortcutManager.prototype.set_shortcut = function( shortcut, action_name){
  289. if( typeof(action_name) !== 'string'){throw new Error('action is not a string', action_name);}
  290. if( typeof(shortcut) === 'string'){
  291. shortcut = shortcut.split(',');
  292. }
  293. return this._set_leaf(shortcut, action_name, this._shortcuts);
  294. };
  295. ShortcutManager.prototype._is_leaf = function(shortcut_array, tree){
  296. if(shortcut_array.length === 1){
  297. return(typeof(tree[shortcut_array[0]]) === 'string');
  298. } else {
  299. var subtree = tree[shortcut_array[0]];
  300. return this._is_leaf(shortcut_array.slice(1), subtree );
  301. }
  302. };
  303. ShortcutManager.prototype._remove_leaf = function(shortcut_array, tree, allow_node){
  304. if(shortcut_array.length === 1){
  305. var current_node = tree[shortcut_array[0]];
  306. if(typeof(current_node) === 'string'){
  307. delete tree[shortcut_array[0]];
  308. } else {
  309. throw new Error('try to delete non-leaf');
  310. }
  311. } else {
  312. this._remove_leaf(shortcut_array.slice(1), tree[shortcut_array[0]], allow_node);
  313. if(_.keys(tree[shortcut_array[0]]).length === 0){
  314. delete tree[shortcut_array[0]];
  315. }
  316. }
  317. };
  318. ShortcutManager.prototype.is_available_shortcut = function(shortcut){
  319. var shortcut_array = shortcut.split(',');
  320. return this._is_available_shortcut(shortcut_array, this._shortcuts);
  321. };
  322. ShortcutManager.prototype._is_available_shortcut = function(shortcut_array, tree){
  323. var current_node = tree[shortcut_array[0]];
  324. if(!shortcut_array[0]){
  325. return false;
  326. }
  327. if(current_node === undefined){
  328. return true;
  329. } else {
  330. if (typeof(current_node) === 'string'){
  331. return false;
  332. } else { // assume is a sub-shortcut tree
  333. return this._is_available_shortcut(shortcut_array.slice(1), current_node);
  334. }
  335. }
  336. };
  337. ShortcutManager.prototype._set_leaf = function(shortcut_array, action_name, tree){
  338. var current_node = tree[shortcut_array[0]];
  339. if(shortcut_array.length === 1){
  340. if(current_node !== undefined && typeof(current_node) !== 'string'){
  341. console.warn('[warning], you are overriting a long shortcut with a shorter one');
  342. }
  343. tree[shortcut_array[0]] = action_name;
  344. return true;
  345. } else {
  346. if(typeof(current_node) === 'string'){
  347. console.warn('you are trying to set a shortcut that will be shadowed'+
  348. 'by a more specific one. Aborting for :', action_name, 'the follwing '+
  349. 'will take precedence', current_node);
  350. return false;
  351. } else {
  352. tree[shortcut_array[0]] = tree[shortcut_array[0]]||{};
  353. }
  354. this._set_leaf(shortcut_array.slice(1), action_name, tree[shortcut_array[0]]);
  355. return true;
  356. }
  357. };
  358. ShortcutManager.prototype._persist_shortcut = function(shortcut, data) {
  359. /**
  360. * add a shortcut to this manager and persist it to the config file.
  361. **/
  362. shortcut = shortcut.toLowerCase();
  363. this.add_shortcut(shortcut, data);
  364. var patch = {keys:{}};
  365. patch.keys[this._mode] = {bind:{}};
  366. patch.keys[this._mode].bind[shortcut] = data;
  367. this._config.update(patch);
  368. };
  369. ShortcutManager.prototype._persist_remove_shortcut = function(shortcut){
  370. /**
  371. * Remove a shortcut from this manager and persist its removal.
  372. */
  373. shortcut = shortcut.toLowerCase();
  374. this.remove_shortcut(shortcut);
  375. var patch = {keys: {}};
  376. patch.keys[this._mode] = {bind:{}};
  377. patch.keys[this._mode].bind[shortcut] = null;
  378. this._config.update(patch);
  379. // if the shortcut we unbind is a default one, we add it to the list of
  380. // things to unbind at startup
  381. if( this._defaults_bindings.indexOf(shortcut) !== -1 ){
  382. var cnf = (this._config.data.keys || {})[this._mode];
  383. var unbind_array = cnf.unbind || [];
  384. // unless it's already there (like if we have remapped a default
  385. // shortcut to another command): unbind it)
  386. if(unbind_array.indexOf(shortcut) === -1){
  387. var _parray = unbind_array.concat(shortcut);
  388. var unbind_patch = {keys:{}};
  389. unbind_patch.keys[this._mode] = {unbind:_parray};
  390. console.warn('up:', unbind_patch);
  391. this._config.update(unbind_patch);
  392. }
  393. }
  394. };
  395. ShortcutManager.prototype.add_shortcut = function (shortcut, data, suppress_help_update) {
  396. /**
  397. * Add an action to be handled by shortcut manager.
  398. *
  399. * - `shortcut` should be a `Shortcut Sequence` of the for `Ctrl-Alt-C,Meta-X`...
  400. * - `data` could be an `action name`, an `action` or a `function`.
  401. * if a `function` is passed it will be converted to an anonymous `action`.
  402. *
  403. **/
  404. var action_name = this.actions.get_name(data);
  405. if (! action_name){
  406. if (typeof data === 'string') {
  407. // If we have an action name, allow it to be bound anyway.
  408. console.log("Unknown action '" + data + "' for shortcut " + shortcut
  409. + "; it may be defined by an extension which is not yet loaded.");
  410. action_name = data;
  411. } else {
  412. throw new Error('does not know how to deal with : ' + data);
  413. }
  414. }
  415. var _shortcut = normalize_shortcut(shortcut);
  416. this.set_shortcut(_shortcut, action_name);
  417. if (!suppress_help_update) {
  418. // update the keyboard shortcuts notebook help
  419. this.events.trigger('rebuild.QuickHelp');
  420. }
  421. };
  422. ShortcutManager.prototype.add_shortcuts = function (data) {
  423. /**
  424. * Convenient methods to call `add_shortcut(key, value)` on several items
  425. *
  426. * data : Dict of the form {key:value, ...}
  427. **/
  428. var that = this;
  429. _.forEach(data, function(value, key) {
  430. that.add_shortcut(key, value, true);
  431. });
  432. // update the keyboard shortcuts notebook help
  433. this.events.trigger('rebuild.QuickHelp');
  434. };
  435. ShortcutManager.prototype._add_default_shortcuts = function (data) {
  436. /**
  437. * same as add_shortcuts, but register them as "default" that if persistently unbound, with
  438. * persist_remove_shortcut, need to be on the "unbind" list.
  439. **/
  440. this._defaults_bindings = this._defaults_bindings.concat(Object.keys(data));
  441. this.add_shortcuts(data);
  442. };
  443. ShortcutManager.prototype.remove_shortcut = function (shortcut, suppress_help_update) {
  444. /**
  445. * Remove the binding of shortcut `sortcut` with its action.
  446. * throw an error if trying to remove a non-exiting shortcut
  447. **/
  448. if(!shortcut){
  449. console.warn('trying to remove empty shortcut');
  450. return;
  451. }
  452. shortcut = normalize_shortcut(shortcut);
  453. if( typeof(shortcut) === 'string'){
  454. shortcut = shortcut.split(',');
  455. }
  456. /*
  457. * The shortcut error should be explicit here, because it will be
  458. * seen by users.
  459. */
  460. try {
  461. this._remove_leaf(shortcut, this._shortcuts);
  462. if (!suppress_help_update) {
  463. // update the keyboard shortcuts notebook help
  464. this.events.trigger('rebuild.QuickHelp');
  465. }
  466. } catch (ex) {
  467. throw new Error('trying to remove a non-existent shortcut', shortcut, typeof shortcut);
  468. }
  469. };
  470. ShortcutManager.prototype.call_handler = function (event) {
  471. /**
  472. * Call the corresponding shortcut handler for a keyboard event
  473. * @method call_handler
  474. * @return {Boolean} `true|false`, `false` if no handler was found, otherwise the value return by the handler.
  475. * @param event {event}
  476. *
  477. * given an event, call the corresponding shortcut.
  478. * return false is event wan handled, true otherwise
  479. * in any case returning false stop event propagation
  480. **/
  481. this.clearsoon();
  482. if(only_modifier_event(event)){
  483. return true;
  484. }
  485. var shortcut = event_to_shortcut(event);
  486. this._queue.push(shortcut);
  487. var action_name = this.get_shortcut(this._queue);
  488. if (typeof(action_name) === 'undefined'|| action_name === null){
  489. this.clearqueue();
  490. return true;
  491. }
  492. if (this.actions.exists(action_name)) {
  493. event.preventDefault();
  494. this.clearqueue();
  495. return this.actions.call(action_name, event);
  496. }
  497. return false;
  498. };
  499. ShortcutManager.prototype.handles = function (event) {
  500. var shortcut = event_to_shortcut(event);
  501. var action_name = this.get_shortcut(this._queue.concat(shortcut));
  502. return (typeof(action_name) !== 'undefined');
  503. };
  504. return {
  505. keycodes : keycodes,
  506. inv_keycodes : inv_keycodes,
  507. ShortcutManager : ShortcutManager,
  508. normalize_key : normalize_key,
  509. normalize_shortcut : normalize_shortcut,
  510. shortcut_to_event : shortcut_to_event,
  511. event_to_shortcut : event_to_shortcut,
  512. };
  513. });