keybindings.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. 'use strict';
  5. const Gdk = imports.gi.Gdk;
  6. const Gio = imports.gi.Gio;
  7. const GLib = imports.gi.GLib;
  8. const GObject = imports.gi.GObject;
  9. const Gtk = imports.gi.Gtk;
  10. /*
  11. * A list of modifier keysyms we ignore
  12. */
  13. const _MODIFIERS = [
  14. Gdk.KEY_Alt_L,
  15. Gdk.KEY_Alt_R,
  16. Gdk.KEY_Caps_Lock,
  17. Gdk.KEY_Control_L,
  18. Gdk.KEY_Control_R,
  19. Gdk.KEY_Meta_L,
  20. Gdk.KEY_Meta_R,
  21. Gdk.KEY_Num_Lock,
  22. Gdk.KEY_Shift_L,
  23. Gdk.KEY_Shift_R,
  24. Gdk.KEY_Super_L,
  25. Gdk.KEY_Super_R,
  26. ];
  27. /**
  28. * Response enum for ShortcutChooserDialog
  29. */
  30. var ResponseType = {
  31. CANCEL: Gtk.ResponseType.CANCEL,
  32. SET: Gtk.ResponseType.APPLY,
  33. UNSET: 2,
  34. };
  35. /**
  36. * A simplified version of the shortcut editor from GNOME Control Center
  37. */
  38. var ShortcutChooserDialog = GObject.registerClass({
  39. GTypeName: 'GSConnectPreferencesShortcutEditor',
  40. Template: 'resource:///org/gnome/Shell/Extensions/GSConnect/ui/preferences-shortcut-editor.ui',
  41. Children: [
  42. 'cancel-button', 'set-button',
  43. 'stack', 'summary-label',
  44. 'shortcut-label', 'conflict-label',
  45. ],
  46. }, class ShortcutChooserDialog extends Gtk.Dialog {
  47. _init(params) {
  48. super._init({
  49. transient_for: Gio.Application.get_default().get_active_window(),
  50. use_header_bar: true,
  51. });
  52. this._seat = Gdk.Display.get_default().get_default_seat();
  53. // Current accelerator or %null
  54. this.accelerator = params.accelerator;
  55. // TRANSLATORS: Summary of a keyboard shortcut function
  56. // Example: Enter a new shortcut to change Messaging
  57. this.summary = _('Enter a new shortcut to change <b>%s</b>').format(
  58. params.summary
  59. );
  60. }
  61. get accelerator() {
  62. return this.shortcut_label.accelerator;
  63. }
  64. set accelerator(value) {
  65. this.shortcut_label.accelerator = value;
  66. }
  67. get summary() {
  68. return this.summary_label.label;
  69. }
  70. set summary(value) {
  71. this.summary_label.label = value;
  72. }
  73. vfunc_key_press_event(event) {
  74. let keyvalLower = Gdk.keyval_to_lower(event.keyval);
  75. let realMask = event.state & Gtk.accelerator_get_default_mod_mask();
  76. // TODO: Critical: 'WIDGET_REALIZED_FOR_EVENT (widget, event)' failed
  77. if (_MODIFIERS.includes(keyvalLower))
  78. return true;
  79. // Normalize Tab
  80. if (keyvalLower === Gdk.KEY_ISO_Left_Tab)
  81. keyvalLower = Gdk.KEY_Tab;
  82. // Put shift back if it changed the case of the key, not otherwise.
  83. if (keyvalLower !== event.keyval)
  84. realMask |= Gdk.ModifierType.SHIFT_MASK;
  85. // HACK: we don't want to use SysRq as a keybinding (but we do want
  86. // Alt+Print), so we avoid translation from Alt+Print to SysRq
  87. if (keyvalLower === Gdk.KEY_Sys_Req && (realMask & Gdk.ModifierType.MOD1_MASK) !== 0)
  88. keyvalLower = Gdk.KEY_Print;
  89. // A single Escape press cancels the editing
  90. if (realMask === 0 && keyvalLower === Gdk.KEY_Escape) {
  91. this.response(ResponseType.CANCEL);
  92. return false;
  93. }
  94. // Backspace disables the current shortcut
  95. if (realMask === 0 && keyvalLower === Gdk.KEY_BackSpace) {
  96. this.response(ResponseType.UNSET);
  97. return false;
  98. }
  99. // CapsLock isn't supported as a keybinding modifier, so keep it from
  100. // confusing us
  101. realMask &= ~Gdk.ModifierType.LOCK_MASK;
  102. if (keyvalLower !== 0 && realMask !== 0) {
  103. this._ungrab();
  104. // Set the accelerator property/label
  105. this.accelerator = Gtk.accelerator_name(keyvalLower, realMask);
  106. // TRANSLATORS: When a keyboard shortcut is unavailable
  107. // Example: [Ctrl]+[S] is already being used
  108. this.conflict_label.label = _('%s is already being used').format(
  109. Gtk.accelerator_get_label(keyvalLower, realMask)
  110. );
  111. // Show Cancel button and switch to confirm/conflict page
  112. this.cancel_button.visible = true;
  113. this.stack.visible_child_name = 'confirm';
  114. this._check();
  115. }
  116. return true;
  117. }
  118. async _check() {
  119. try {
  120. const available = await checkAccelerator(this.accelerator);
  121. this.set_button.visible = available;
  122. this.conflict_label.visible = !available;
  123. } catch (e) {
  124. logError(e);
  125. this.response(ResponseType.CANCEL);
  126. }
  127. }
  128. _grab() {
  129. const success = this._seat.grab(
  130. this.get_window(),
  131. Gdk.SeatCapabilities.KEYBOARD,
  132. true, // owner_events
  133. null, // cursor
  134. null, // event
  135. null
  136. );
  137. if (success !== Gdk.GrabStatus.SUCCESS)
  138. return this.response(ResponseType.CANCEL);
  139. if (!this._seat.get_keyboard() && !this._seat.get_pointer())
  140. return this.response(ResponseType.CANCEL);
  141. this.grab_add();
  142. }
  143. _ungrab() {
  144. this._seat.ungrab();
  145. this.grab_remove();
  146. }
  147. // Override to use our own ungrab process
  148. response(response_id) {
  149. this.hide();
  150. this._ungrab();
  151. return super.response(response_id);
  152. }
  153. // Override with a non-blocking version of Gtk.Dialog.run()
  154. run() {
  155. this.show();
  156. // Wait a bit before attempting grab
  157. GLib.timeout_add(GLib.PRIORITY_DEFAULT, 100, () => {
  158. this._grab();
  159. return GLib.SOURCE_REMOVE;
  160. });
  161. }
  162. });
  163. /**
  164. * Check the availability of an accelerator using GNOME Shell's DBus interface.
  165. *
  166. * @param {string} accelerator - An accelerator
  167. * @param {number} [modeFlags] - Mode Flags
  168. * @param {number} [grabFlags] - Grab Flags
  169. * @param {boolean} %true if available, %false on error or unavailable
  170. */
  171. async function checkAccelerator(accelerator, modeFlags = 0, grabFlags = 0) {
  172. try {
  173. let result = false;
  174. // Try to grab the accelerator
  175. const action = await new Promise((resolve, reject) => {
  176. Gio.DBus.session.call(
  177. 'org.gnome.Shell',
  178. '/org/gnome/Shell',
  179. 'org.gnome.Shell',
  180. 'GrabAccelerator',
  181. new GLib.Variant('(suu)', [accelerator, modeFlags, grabFlags]),
  182. null,
  183. Gio.DBusCallFlags.NONE,
  184. -1,
  185. null,
  186. (connection, res) => {
  187. try {
  188. res = connection.call_finish(res);
  189. resolve(res.deepUnpack()[0]);
  190. } catch (e) {
  191. reject(e);
  192. }
  193. }
  194. );
  195. });
  196. // If successful, use the result of ungrabbing as our return
  197. if (action !== 0) {
  198. result = await new Promise((resolve, reject) => {
  199. Gio.DBus.session.call(
  200. 'org.gnome.Shell',
  201. '/org/gnome/Shell',
  202. 'org.gnome.Shell',
  203. 'UngrabAccelerator',
  204. new GLib.Variant('(u)', [action]),
  205. null,
  206. Gio.DBusCallFlags.NONE,
  207. -1,
  208. null,
  209. (connection, res) => {
  210. try {
  211. res = connection.call_finish(res);
  212. resolve(res.deepUnpack()[0]);
  213. } catch (e) {
  214. reject(e);
  215. }
  216. }
  217. );
  218. });
  219. }
  220. return result;
  221. } catch (e) {
  222. logError(e);
  223. return false;
  224. }
  225. }
  226. /**
  227. * Show a dialog to get a keyboard shortcut from a user.
  228. *
  229. * @param {string} summary - A description of the keybinding's function
  230. * @param {string} accelerator - An accelerator as taken by Gtk.ShortcutLabel
  231. * @return {string} An accelerator or %null if it should be unset.
  232. */
  233. async function getAccelerator(summary, accelerator = null) {
  234. try {
  235. const dialog = new ShortcutChooserDialog({
  236. summary: summary,
  237. accelerator: accelerator,
  238. });
  239. accelerator = await new Promise((resolve, reject) => {
  240. dialog.connect('response', (dialog, response) => {
  241. switch (response) {
  242. case ResponseType.SET:
  243. accelerator = dialog.accelerator;
  244. break;
  245. case ResponseType.UNSET:
  246. accelerator = null;
  247. break;
  248. case ResponseType.CANCEL:
  249. // leave the accelerator as passed in
  250. break;
  251. }
  252. dialog.destroy();
  253. resolve(accelerator);
  254. });
  255. dialog.run();
  256. });
  257. return accelerator;
  258. } catch (e) {
  259. logError(e);
  260. return accelerator;
  261. }
  262. }