ViewKeyboard.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Terminal.Gui;
  6. public partial class View {
  7. void AddCommands ()
  8. {
  9. // By default, the Default command is bound to the HotKey enabling focus
  10. AddCommand (Command.Default, () => {
  11. if (CanFocus) {
  12. SetFocus ();
  13. return true;
  14. }
  15. return false;
  16. });
  17. // By default the Accept command does nothing
  18. AddCommand (Command.Accept, () => false);
  19. }
  20. #region HotKey Support
  21. /// <summary>
  22. /// Invoked when the <see cref="HotKey"/> is changed.
  23. /// </summary>
  24. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  25. Key _hotKey = new Key ();
  26. void TextFormatter_HotKeyChanged (object sender, KeyChangedEventArgs e)
  27. {
  28. HotKeyChanged?.Invoke (this, e);
  29. }
  30. /// <summary>
  31. /// Gets or sets the hot key defined for this view. Pressing the hot key on the keyboard while this view has
  32. /// focus will invoke the <see cref="Command.Default"/> and <see cref="Command.Accept"/> commands. <see cref="Command.Default"/>
  33. /// causes the view to be focused and <see cref="Command.Accept"/> does nothing.
  34. /// By default, the HotKey is automatically set to the first
  35. /// character of <see cref="Text"/> that is prefixed with with <see cref="HotKeySpecifier"/>.
  36. /// <para>
  37. /// A HotKey is a keypress that selects a visible UI item. For selecting items across <see cref="View"/>`s
  38. /// (e.g.a <see cref="Button"/> in a <see cref="Dialog"/>) the keypress must include the <see cref="Key.WithAlt"/> modifier.
  39. /// For selecting items within a View that are not Views themselves, the keypress can be key without the Alt modifier.
  40. /// For example, in a Dialog, a Button with the text of "_Text" can be selected with Alt-T.
  41. /// Or, in a <see cref="Menu"/> with "_File _Edit", Alt-F will select (show) the "_File" menu.
  42. /// If the "_File" menu has a sub-menu of "_New" `Alt-N` or `N` will ONLY select the "_New" sub-menu if the "_File" menu is already opened.
  43. /// </para>
  44. /// </summary>
  45. /// <remarks>
  46. /// <para>
  47. /// See <see href="../docs/keyboard.md"/> for an overview of Terminal.Gui keyboard APIs.
  48. /// </para>
  49. /// <para>
  50. /// This is a helper API for configuring a key binding for the hot key. By default, this property is set whenever <see cref="Text"/> changes.
  51. /// </para>
  52. /// <para>
  53. /// By default, when the Hot Key is set, key bindings are added for both the base key (e.g. <see cref="KeyCode.D3"/>) and
  54. /// the Alt-shifted key (e.g. <see cref="KeyCode.D3"/> | <see cref="KeyCode.AltMask"/>).
  55. /// This behavior can be overriden by overriding <see cref="AddKeyBindingsForHotKey"/>.
  56. /// </para>
  57. /// <para>
  58. /// By default, when the HotKey is set to <see cref="Key.A"/> through <see cref="KeyCode.Z"/> key bindings will be added for both the un-shifted and shifted
  59. /// versions. This means if the HotKey is <see cref="Key.A"/>, key bindings for <c>Key.A</c> and <c>Key.A.WithShift</c>
  60. /// will be added. This behavior can be overriden by overriding <see cref="AddKeyBindingsForHotKey"/>.
  61. /// </para>
  62. /// <para>
  63. /// If the hot key is changed, the <see cref="HotKeyChanged"/> event is fired.
  64. /// </para>
  65. /// <para>
  66. /// Set to <see cref="KeyCode.Null"/> to disable the hot key.
  67. /// </para>
  68. /// </remarks>
  69. public virtual Key HotKey {
  70. get => _hotKey;
  71. set {
  72. if (value is null) {
  73. throw new ArgumentException (@"HotKey must not be null. Use Key.Empty to clear the HotKey.", nameof (value));
  74. }
  75. if (AddKeyBindingsForHotKey (_hotKey, value)) {
  76. // This will cause TextFormatter_HotKeyChanged to be called, firing HotKeyChanged
  77. _hotKey = TextFormatter.HotKey = value;
  78. }
  79. }
  80. }
  81. /// <summary>
  82. /// Adds key bindings for the specified HotKey. Useful for views that contain multiple items that each have their own HotKey
  83. /// such as <see cref="RadioGroup"/>.
  84. /// </summary>
  85. /// <remarks>
  86. /// <para>
  87. /// By default key bindings are added for both the base key (e.g. <see cref="Key.D3"/>) and
  88. /// the Alt-shifted key (e.g. <c>Key.D3.WithAlt</c>
  89. /// This behavior can be overriden by overriding <see cref="AddKeyBindingsForHotKey"/>.
  90. /// </para>
  91. /// <para>
  92. /// By default, when <paramref name="hotKey"/> is <see cref="Key.A"/> through <see cref="Key.Z"/> key bindings will be added for both the un-shifted and shifted
  93. /// versions. This means if the HotKey is <see cref="Key.A"/>, key bindings for <c>Key.A</c> and <c>Key.A.WithShift</c>
  94. /// will be added. This behavior can be overriden by overriding <see cref="AddKeyBindingsForHotKey"/>.
  95. /// </para>
  96. /// <para>
  97. /// For each of the bound keys <see cref="Command.Default"/> causes the view to be focused and <see cref="Command.Accept"/> does nothing.
  98. /// </para>
  99. /// </remarks>
  100. /// <param name="prevHotKey">The HotKey <paramref name="hotKey"/> is replacing. Key bindings for this key will be removed.</param>
  101. /// <param name="hotKey">The new HotKey. If <see cref="Key.Empty"/> <paramref name="prevHotKey"/> bindings will be removed.</param>
  102. /// <returns><see langword="true"/> if the HotKey bindings were added.</returns>
  103. /// <exception cref="ArgumentException"></exception>
  104. public virtual bool AddKeyBindingsForHotKey (Key prevHotKey, Key hotKey)
  105. {
  106. if ((KeyCode)_hotKey == hotKey) {
  107. return false;
  108. }
  109. var newKey = hotKey;
  110. var baseKey = newKey.NoAlt.NoShift.NoCtrl;
  111. if (newKey != Key.Empty && (baseKey == Key.Space || Rune.IsControl (baseKey.AsRune))) {
  112. throw new ArgumentException (@$"HotKey must be a printable (and non-space) key ({hotKey}).");
  113. }
  114. if (newKey != baseKey) {
  115. if (newKey.IsCtrl) {
  116. throw new ArgumentException (@$"HotKey does not support CtrlMask ({hotKey}).");
  117. }
  118. // Strip off the shift mask if it's A...Z
  119. if (baseKey.IsKeyCodeAtoZ) {
  120. newKey = newKey.NoShift;
  121. }
  122. // Strip off the Alt mask
  123. newKey = newKey.NoAlt;
  124. }
  125. // Remove base version
  126. if (KeyBindings.TryGet (prevHotKey, out _)) {
  127. KeyBindings.Remove (prevHotKey);
  128. }
  129. // Remove the Alt version
  130. if (KeyBindings.TryGet (prevHotKey.WithAlt, out _)) {
  131. KeyBindings.Remove (prevHotKey.WithAlt);
  132. }
  133. if (_hotKey.KeyCode is >= KeyCode.A and <= KeyCode.Z) {
  134. // Remove the shift version
  135. if (KeyBindings.TryGet (prevHotKey.WithShift, out _)) {
  136. KeyBindings.Remove (prevHotKey.WithShift);
  137. }
  138. // Remove alt | shift version
  139. if (KeyBindings.TryGet (prevHotKey.WithShift.WithAlt, out _)) {
  140. KeyBindings.Remove (prevHotKey.WithShift.WithAlt);
  141. }
  142. }
  143. // Add the new
  144. if (newKey != KeyCode.Null) {
  145. // Add the base and Alt key
  146. KeyBindings.Add (newKey, KeyBindingScope.HotKey, Command.Default, Command.Accept);
  147. KeyBindings.Add (newKey.WithAlt, KeyBindingScope.HotKey, Command.Default, Command.Accept);
  148. // If the Key is A..Z, add ShiftMask and AltMask | ShiftMask
  149. if (newKey.IsKeyCodeAtoZ) {
  150. KeyBindings.Add (newKey.WithShift, KeyBindingScope.HotKey, Command.Default, Command.Accept);
  151. KeyBindings.Add (newKey.WithShift.WithAlt, KeyBindingScope.HotKey, Command.Default, Command.Accept);
  152. }
  153. }
  154. return true;
  155. }
  156. /// <summary>
  157. /// Gets or sets the specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable automatic hot key setting
  158. /// support for this View instance. The default is '\xffff'.
  159. /// </summary>
  160. public virtual Rune HotKeySpecifier {
  161. get {
  162. if (TextFormatter != null) {
  163. return TextFormatter.HotKeySpecifier;
  164. } else {
  165. return new Rune ('\xFFFF');
  166. }
  167. }
  168. set {
  169. TextFormatter.HotKeySpecifier = value;
  170. SetHotKey ();
  171. }
  172. }
  173. void SetHotKey ()
  174. {
  175. if (TextFormatter == null || HotKeySpecifier == new Rune ('\xFFFF')) {
  176. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  177. }
  178. if (TextFormatter.FindHotKey (_text, HotKeySpecifier, out _, out var hk)) {
  179. if (_hotKey.KeyCode != hk) {
  180. HotKey = hk;
  181. }
  182. } else {
  183. HotKey = KeyCode.Null;
  184. }
  185. }
  186. #endregion HotKey Support
  187. #region Tab/Focus Handling
  188. // This is null, and allocated on demand.
  189. List<View> _tabIndexes;
  190. /// <summary>
  191. /// Gets a list of the subviews that are <see cref="TabStop"/>s.
  192. /// </summary>
  193. /// <value>The tabIndexes.</value>
  194. public IList<View> TabIndexes => _tabIndexes?.AsReadOnly () ?? _empty;
  195. int _tabIndex = -1;
  196. int _oldTabIndex;
  197. /// <summary>
  198. /// Indicates the index of the current <see cref="View"/> from the <see cref="TabIndexes"/> list. See also: <seealso cref="TabStop"/>.
  199. /// </summary>
  200. public int TabIndex {
  201. get { return _tabIndex; }
  202. set {
  203. if (!CanFocus) {
  204. _tabIndex = -1;
  205. return;
  206. } else if (SuperView?._tabIndexes == null || SuperView?._tabIndexes.Count == 1) {
  207. _tabIndex = 0;
  208. return;
  209. } else if (_tabIndex == value) {
  210. return;
  211. }
  212. _tabIndex = value > SuperView._tabIndexes.Count - 1 ? SuperView._tabIndexes.Count - 1 : value < 0 ? 0 : value;
  213. _tabIndex = GetTabIndex (_tabIndex);
  214. if (SuperView._tabIndexes.IndexOf (this) != _tabIndex) {
  215. SuperView._tabIndexes.Remove (this);
  216. SuperView._tabIndexes.Insert (_tabIndex, this);
  217. SetTabIndex ();
  218. }
  219. }
  220. }
  221. int GetTabIndex (int idx)
  222. {
  223. var i = 0;
  224. foreach (var v in SuperView._tabIndexes) {
  225. if (v._tabIndex == -1 || v == this) {
  226. continue;
  227. }
  228. i++;
  229. }
  230. return Math.Min (i, idx);
  231. }
  232. void SetTabIndex ()
  233. {
  234. var i = 0;
  235. foreach (var v in SuperView._tabIndexes) {
  236. if (v._tabIndex == -1) {
  237. continue;
  238. }
  239. v._tabIndex = i;
  240. i++;
  241. }
  242. }
  243. bool _tabStop = true;
  244. /// <summary>
  245. /// Gets or sets whether the view is a stop-point for keyboard navigation of focus. Will be
  246. /// <see langword="true"/> only if the <see cref="CanFocus"/> is also <see langword="true"/>.
  247. /// Set to <see langword="false"/> to prevent the view from being a stop-point for keyboard navigation.
  248. /// </summary>
  249. /// <remarks>
  250. /// The default keyboard navigation keys are <c>Key.Tab</c> and <c>Key>Tab.WithShift</c>.
  251. /// These can be changed by modifying the key bindings (see <see cref="KeyBindings.Add(Key, Command[])"/>) of the SuperView.
  252. /// </remarks>
  253. public bool TabStop {
  254. get => _tabStop;
  255. set {
  256. if (_tabStop == value) {
  257. return;
  258. }
  259. _tabStop = CanFocus && value;
  260. }
  261. }
  262. #endregion Tab/Focus Handling
  263. #region Low-level Key handling
  264. #region Key Down Event
  265. /// <summary>
  266. /// If the view is enabled, processes a new key down event and returns <see langword="true"/> if the event was handled.
  267. /// </summary>
  268. /// <remarks>
  269. /// <para>
  270. /// If the view has a sub view that is focused, <see cref="NewKeyDownEvent"/> will be called on the focused view first.
  271. /// </para>
  272. /// <para>
  273. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyDown"/> to allow the view
  274. /// to pre-process the key press. If <see cref="OnKeyDown"/> returns <see langword="false"/>, this method then calls
  275. /// <see cref="OnInvokingKeyBindings"/> to invoke any key bindings. Then, only if no key bindings are handled,
  276. /// <see cref="OnProcessKeyDown"/> will be called allowing the view to process the key press.
  277. /// </para>
  278. /// <para>
  279. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  280. /// </para>
  281. /// </remarks>
  282. /// <param name="keyEvent"></param>
  283. /// <returns><see langword="true"/> if the event was handled.</returns>
  284. public bool NewKeyDownEvent (Key keyEvent)
  285. {
  286. if (!Enabled) {
  287. return false;
  288. }
  289. // By default the KeyBindingScope is View
  290. if (Focused?.NewKeyDownEvent (keyEvent) == true) {
  291. return true;
  292. }
  293. // Before (fire the cancellable event)
  294. if (OnKeyDown (keyEvent)) {
  295. return true;
  296. }
  297. // During (this is what can be cancelled)
  298. InvokingKeyBindings?.Invoke (this, keyEvent);
  299. if (keyEvent.Handled) {
  300. return true;
  301. }
  302. var handled = OnInvokingKeyBindings (keyEvent);
  303. if (handled != null && (bool)handled) {
  304. return true;
  305. }
  306. // TODO: The below is not right. OnXXX handlers are supposed to fire the events.
  307. // TODO: But I've moved it outside of the v-function to test something.
  308. // After (fire the cancellable event)
  309. // fire event
  310. ProcessKeyDown?.Invoke (this, keyEvent);
  311. if (!keyEvent.Handled && OnProcessKeyDown (keyEvent)) {
  312. return true;
  313. }
  314. return keyEvent.Handled;
  315. }
  316. /// <summary>
  317. /// Low-level API called when the user presses a key, allowing a view to pre-process the key down event.
  318. /// This is called from <see cref="NewKeyDownEvent"/> before <see cref="OnInvokingKeyBindings"/>.
  319. /// </summary>
  320. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  321. /// <returns><see langword="false"/> if the key press was not handled. <see langword="true"/> if
  322. /// the keypress was handled and no other view should see it.</returns>
  323. /// <remarks>
  324. /// <para>
  325. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  326. /// </para>
  327. /// <para>
  328. /// Fires the <see cref="KeyDown"/> event.
  329. /// </para>
  330. /// </remarks>
  331. public virtual bool OnKeyDown (Key keyEvent)
  332. {
  333. // fire event
  334. KeyDown?.Invoke (this, keyEvent);
  335. return keyEvent.Handled;
  336. }
  337. /// <summary>
  338. /// Invoked when the user presses a key, allowing subscribers to pre-process the key down event.
  339. /// This is fired from <see cref="OnKeyDown"/> before <see cref="OnInvokingKeyBindings"/>.
  340. /// Set <see cref="Key.Handled"/> to true to stop the key from
  341. /// being processed by other views.
  342. /// </summary>
  343. /// <remarks>
  344. /// <para>
  345. /// Not all terminals support key distinct up notifications, Applications should avoid
  346. /// depending on distinct KeyUp events.
  347. /// </para>
  348. /// <para>
  349. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  350. /// </para>
  351. /// </remarks>
  352. public event EventHandler<Key> KeyDown;
  353. /// <summary>
  354. /// Low-level API called when the user presses a key, allowing views do things during key down events.
  355. /// This is called from <see cref="NewKeyDownEvent"/> after <see cref="OnInvokingKeyBindings"/>.
  356. /// </summary>
  357. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  358. /// <returns><see langword="false"/> if the key press was not handled. <see langword="true"/> if
  359. /// the keypress was handled and no other view should see it.</returns>
  360. /// <remarks>
  361. /// <para>
  362. /// Override <see cref="OnProcessKeyDown"/> to override the behavior of how the base class processes key down events.
  363. /// </para>
  364. /// <para>
  365. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  366. /// </para>
  367. /// <para>
  368. /// Fires the <see cref="ProcessKeyDown"/> event.
  369. /// </para>
  370. /// <para>
  371. /// Not all terminals support distinct key up notifications; applications should avoid
  372. /// depending on distinct KeyUp events.
  373. /// </para>
  374. /// </remarks>
  375. public virtual bool OnProcessKeyDown (Key keyEvent)
  376. {
  377. //ProcessKeyDown?.Invoke (this, keyEvent);
  378. return keyEvent.Handled;
  379. }
  380. /// <summary>
  381. /// Invoked when the users presses a key, allowing subscribers to do things during key down events.
  382. /// Set <see cref="Key.Handled"/> to true to stop the key from
  383. /// being processed by other views. Invoked after <see cref="KeyDown"/> and before <see cref="InvokingKeyBindings"/>.
  384. /// </summary>
  385. /// <remarks>
  386. /// <para>
  387. /// SubViews can use the <see cref="ProcessKeyDown"/> of their super view override the default behavior of
  388. /// when key bindings are invoked.
  389. /// </para>
  390. /// <para>
  391. /// Not all terminals support distinct key up notifications; applications should avoid
  392. /// depending on distinct KeyUp events.
  393. /// </para>
  394. /// <para>
  395. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  396. /// </para>
  397. /// </remarks>
  398. public event EventHandler<Key> ProcessKeyDown;
  399. #endregion KeyDown Event
  400. #region KeyUp Event
  401. /// <summary>
  402. /// If the view is enabled, processes a new key up event and returns <see langword="true"/> if the event was handled.
  403. /// Called before <see cref="NewKeyDownEvent"/>.
  404. /// </summary>
  405. /// <remarks>
  406. /// <para>
  407. /// Not all terminals support key distinct down/up notifications, Applications should avoid
  408. /// depending on distinct KeyUp events.
  409. /// </para>
  410. /// <para>
  411. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view first.
  412. /// </para>
  413. /// <para>
  414. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyUp"/>, which is cancellable.
  415. /// </para>
  416. /// <para>
  417. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  418. /// </para>
  419. /// </remarks>
  420. /// <param name="keyEvent"></param>
  421. /// <returns><see langword="true"/> if the event was handled.</returns>
  422. public bool NewKeyUpEvent (Key keyEvent)
  423. {
  424. if (!Enabled) {
  425. return false;
  426. }
  427. if (Focused?.NewKeyUpEvent (keyEvent) == true) {
  428. return true;
  429. }
  430. // Before (fire the cancellable event)
  431. if (OnKeyUp (keyEvent)) {
  432. return true;
  433. }
  434. // During (this is what can be cancelled)
  435. // TODO: Until there's a clear use-case, we will not define 'during' event (e.g. OnDuringKeyUp).
  436. // After (fire the cancellable event InvokingKeyBindings)
  437. // TODO: Until there's a clear use-case, we will not define an 'after' event (e.g. OnAfterKeyUp).
  438. return false;
  439. }
  440. /// <summary>
  441. /// Method invoked when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.
  442. /// </summary>
  443. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  444. /// <returns><see langword="false"/> if the key stroke was not handled. <see langword="true"/> if no
  445. /// other view should see it.</returns>
  446. /// <remarks>
  447. /// Not all terminals support key distinct down/up notifications, Applications should avoid
  448. /// depending on distinct KeyUp events.
  449. /// <para>
  450. /// Overrides must call into the base and return <see langword="true"/> if the base returns <see langword="true"/>.
  451. /// </para>
  452. /// <para>
  453. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  454. /// </para>
  455. /// </remarks>
  456. public virtual bool OnKeyUp (Key keyEvent)
  457. {
  458. // fire event
  459. KeyUp?.Invoke (this, keyEvent);
  460. if (keyEvent.Handled) {
  461. return true;
  462. }
  463. return false;
  464. }
  465. /// <summary>
  466. /// Invoked when a key is released. Set <see cref="Key.Handled"/> to true to stop the key up event from being processed by other views.
  467. /// <remarks>
  468. /// Not all terminals support key distinct down/up notifications, Applications should avoid
  469. /// depending on distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  470. /// <para>
  471. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  472. /// </para>
  473. /// </remarks>
  474. /// </summary>
  475. public event EventHandler<Key> KeyUp;
  476. #endregion KeyUp Event
  477. #endregion Low-level Key handling
  478. #region Key Bindings
  479. /// <summary>
  480. /// Gets the key bindings for this view.
  481. /// </summary>
  482. public KeyBindings KeyBindings { get; } = new ();
  483. private Dictionary<Command, Func<bool?>> CommandImplementations { get; } = new ();
  484. /// <summary>
  485. /// Low-level API called when a user presses a key; invokes any key bindings set on the view.
  486. /// This is called during <see cref="NewKeyDownEvent"/> after <see cref="OnKeyDown"/> has returned.
  487. /// </summary>
  488. /// <remarks>
  489. /// <para>
  490. /// Fires the <see cref="InvokingKeyBindings"/> event.
  491. /// </para>
  492. /// <para>
  493. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  494. /// </para>
  495. /// </remarks>
  496. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  497. /// <returns><see langword="false"/> if the key press was not handled. <see langword="true"/> if
  498. /// the keypress was handled and no other view should see it.</returns>
  499. public virtual bool? OnInvokingKeyBindings (Key keyEvent)
  500. {
  501. // fire event
  502. // BUGBUG: KeyEventArgs doesn't include scope, so the event never sees it.
  503. if (keyEvent.Scope == KeyBindingScope.Application || keyEvent.Scope == KeyBindingScope.HotKey) {
  504. InvokingKeyBindings?.Invoke (this, keyEvent);
  505. if (keyEvent.Handled) {
  506. return true;
  507. }
  508. }
  509. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  510. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  511. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  512. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  513. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  514. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  515. var handled = InvokeKeyBindings (keyEvent);
  516. if (handled != null && (bool)handled) {
  517. // Stop processing if any key binding handled the key.
  518. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  519. return true;
  520. }
  521. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  522. foreach (var view in Subviews.Where (v => v.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.HotKey, out var _))) {
  523. // TODO: I think this TryGet is not needed due to the one in the lambda above. Use `Get` instead?
  524. if (view.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.HotKey, out var binding)) {
  525. keyEvent.Scope = KeyBindingScope.HotKey;
  526. handled = view.OnInvokingKeyBindings (keyEvent);
  527. if (handled != null && (bool)handled) {
  528. return true;
  529. }
  530. }
  531. }
  532. return handled;
  533. }
  534. /// <summary>
  535. /// Invoked when a key is pressed that may be mapped to a key binding. Set <see cref="Key.Handled"/>
  536. /// to true to stop the key from being processed by other views.
  537. /// </summary>
  538. public event EventHandler<Key> InvokingKeyBindings;
  539. /// <summary>
  540. /// Invokes any binding that is registered on this <see cref="View"/>
  541. /// and matches the <paramref name="keyEvent"/>
  542. /// <para>
  543. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  544. /// </para>
  545. /// </summary>
  546. /// <param name="keyEvent">The key event passed.</param>
  547. /// <returns>
  548. /// <see langword="null"/> if no command was bound the <paramref name="keyEvent"/>.
  549. /// <see langword="true"/> if commands were invoked and at least one handled the command.
  550. /// <see langword="false"/> if commands were invoked and at none handled the command.
  551. /// </returns>
  552. protected bool? InvokeKeyBindings (Key keyEvent)
  553. {
  554. bool? toReturn = null;
  555. var key = keyEvent.KeyCode;
  556. if (!KeyBindings.TryGet (key, out var binding)) {
  557. return null;
  558. }
  559. foreach (var command in binding.Commands) {
  560. if (!CommandImplementations.ContainsKey (command)) {
  561. throw new NotSupportedException (@$"A KeyBinding was set up for the command {command} ({keyEvent.KeyCode}) but that command is not supported by this View ({GetType ().Name})");
  562. }
  563. // each command has its own return value
  564. var thisReturn = InvokeCommand (command);
  565. // if we haven't got anything yet, the current command result should be used
  566. toReturn ??= thisReturn;
  567. // if ever see a true then that's what we will return
  568. if (thisReturn ?? false) {
  569. toReturn = true;
  570. }
  571. }
  572. return toReturn;
  573. }
  574. /// <summary>
  575. /// Invokes the specified command.
  576. /// </summary>
  577. /// <param name="command"></param>
  578. /// <returns>
  579. /// <see langword="null"/> if no command was found.
  580. /// <see langword="true"/> if the command was invoked and it handled the command.
  581. /// <see langword="false"/> if the command was invoked and it did not handle the command.
  582. /// </returns>
  583. public bool? InvokeCommand (Command command)
  584. {
  585. if (!CommandImplementations.ContainsKey (command)) {
  586. return null;
  587. }
  588. return CommandImplementations [command] ();
  589. }
  590. /// <summary>
  591. /// <para>
  592. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call <see cref="AddCommand"/>
  593. /// for each command they support.
  594. /// </para>
  595. /// <para>
  596. /// If <see cref="AddCommand"/> has already been called for <paramref name="command"/> <paramref name="f"/> will replace the old one.</para>
  597. /// </summary>
  598. /// <param name="command">The command.</param>
  599. /// <param name="f">The function.</param>
  600. protected void AddCommand (Command command, Func<bool?> f)
  601. {
  602. // if there is already an implementation of this command
  603. // replace that implementation
  604. // else record how to perform the action (this should be the normal case)
  605. if (CommandImplementations != null) {
  606. CommandImplementations [command] = f;
  607. }
  608. }
  609. /// <summary>
  610. /// Returns all commands that are supported by this <see cref="View"/>.
  611. /// </summary>
  612. /// <returns></returns>
  613. public IEnumerable<Command> GetSupportedCommands ()
  614. {
  615. return CommandImplementations.Keys;
  616. }
  617. // TODO: Add GetKeysBoundToCommand() - given a Command, return all Keys that would invoke it
  618. #endregion Key Bindings
  619. }