ViewKeyboard.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 || value.KeyCode == KeyCode.Unknown) {
  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 == KeyCode.Unknown ? KeyCode.Null : 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, true, out _, out var hk)) {
  179. if (_hotKey.KeyCode != hk && hk != KeyCode.Unknown) {
  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. var handled = OnInvokingKeyBindings (keyEvent);
  299. if (handled != null && (bool)handled) {
  300. return true;
  301. }
  302. // TODO: The below is not right. OnXXX handlers are supposed to fire the events.
  303. // TODO: But I've moved it outside of the v-function to test something.
  304. // After (fire the cancellable event)
  305. // fire event
  306. ProcessKeyDown?.Invoke (this, keyEvent);
  307. if (!keyEvent.Handled && OnProcessKeyDown (keyEvent)) {
  308. return true;
  309. }
  310. return keyEvent.Handled;
  311. }
  312. /// <summary>
  313. /// Low-level API called when the user presses a key, allowing a view to pre-process the key down event.
  314. /// This is called from <see cref="NewKeyDownEvent"/> before <see cref="OnInvokingKeyBindings"/>.
  315. /// </summary>
  316. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  317. /// <returns><see langword="false"/> if the key press was not handled. <see langword="true"/> if
  318. /// the keypress was handled and no other view should see it.</returns>
  319. /// <remarks>
  320. /// <para>
  321. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  322. /// </para>
  323. /// <para>
  324. /// Fires the <see cref="KeyDown"/> event.
  325. /// </para>
  326. /// </remarks>
  327. public virtual bool OnKeyDown (Key keyEvent)
  328. {
  329. // fire event
  330. KeyDown?.Invoke (this, keyEvent);
  331. return keyEvent.Handled;
  332. }
  333. /// <summary>
  334. /// Invoked when the user presses a key, allowing subscribers to pre-process the key down event.
  335. /// This is fired from <see cref="OnKeyDown"/> before <see cref="OnInvokingKeyBindings"/>.
  336. /// Set <see cref="Key.Handled"/> to true to stop the key from
  337. /// being processed by other views.
  338. /// </summary>
  339. /// <remarks>
  340. /// <para>
  341. /// Not all terminals support key distinct up notifications, Applications should avoid
  342. /// depending on distinct KeyUp events.
  343. /// </para>
  344. /// <para>
  345. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  346. /// </para>
  347. /// </remarks>
  348. public event EventHandler<Key> KeyDown;
  349. /// <summary>
  350. /// Low-level API called when the user presses a key, allowing views do things during key down events.
  351. /// This is called from <see cref="NewKeyDownEvent"/> after <see cref="OnInvokingKeyBindings"/>.
  352. /// </summary>
  353. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  354. /// <returns><see langword="false"/> if the key press was not handled. <see langword="true"/> if
  355. /// the keypress was handled and no other view should see it.</returns>
  356. /// <remarks>
  357. /// <para>
  358. /// Override <see cref="OnProcessKeyDown"/> to override the behavior of how the base class processes key down events.
  359. /// </para>
  360. /// <para>
  361. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  362. /// </para>
  363. /// <para>
  364. /// Fires the <see cref="ProcessKeyDown"/> event.
  365. /// </para>
  366. /// <para>
  367. /// Not all terminals support distinct key up notifications; applications should avoid
  368. /// depending on distinct KeyUp events.
  369. /// </para>
  370. /// </remarks>
  371. public virtual bool OnProcessKeyDown (Key keyEvent)
  372. {
  373. //ProcessKeyDown?.Invoke (this, keyEvent);
  374. return keyEvent.Handled;
  375. }
  376. /// <summary>
  377. /// Invoked when the users presses a key, allowing subscribers to do things during key down events.
  378. /// Set <see cref="Key.Handled"/> to true to stop the key from
  379. /// being processed by other views. Invoked after <see cref="KeyDown"/> and before <see cref="InvokingKeyBindings"/>.
  380. /// </summary>
  381. /// <remarks>
  382. /// <para>
  383. /// SubViews can use the <see cref="ProcessKeyDown"/> of their super view override the default behavior of
  384. /// when key bindings are invoked.
  385. /// </para>
  386. /// <para>
  387. /// Not all terminals support distinct key up notifications; applications should avoid
  388. /// depending on distinct KeyUp events.
  389. /// </para>
  390. /// <para>
  391. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  392. /// </para>
  393. /// </remarks>
  394. public event EventHandler<Key> ProcessKeyDown;
  395. #endregion KeyDown Event
  396. #region KeyUp Event
  397. /// <summary>
  398. /// If the view is enabled, processes a new key up event and returns <see langword="true"/> if the event was handled.
  399. /// Called before <see cref="NewKeyDownEvent"/>.
  400. /// </summary>
  401. /// <remarks>
  402. /// <para>
  403. /// Not all terminals support key distinct down/up notifications, Applications should avoid
  404. /// depending on distinct KeyUp events.
  405. /// </para>
  406. /// <para>
  407. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view first.
  408. /// </para>
  409. /// <para>
  410. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyUp"/>, which is cancellable.
  411. /// </para>
  412. /// <para>
  413. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  414. /// </para>
  415. /// </remarks>
  416. /// <param name="keyEvent"></param>
  417. /// <returns><see langword="true"/> if the event was handled.</returns>
  418. public bool NewKeyUpEvent (Key keyEvent)
  419. {
  420. if (!Enabled) {
  421. return false;
  422. }
  423. if (Focused?.NewKeyUpEvent (keyEvent) == true) {
  424. return true;
  425. }
  426. // Before (fire the cancellable event)
  427. if (OnKeyUp (keyEvent)) {
  428. return true;
  429. }
  430. // During (this is what can be cancelled)
  431. // TODO: Until there's a clear use-case, we will not define 'during' event (e.g. OnDuringKeyUp).
  432. // After (fire the cancellable event InvokingKeyBindings)
  433. // TODO: Until there's a clear use-case, we will not define an 'after' event (e.g. OnAfterKeyUp).
  434. return false;
  435. }
  436. /// <summary>
  437. /// Method invoked when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.
  438. /// </summary>
  439. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  440. /// <returns><see langword="false"/> if the key stroke was not handled. <see langword="true"/> if no
  441. /// other view should see it.</returns>
  442. /// <remarks>
  443. /// Not all terminals support key distinct down/up notifications, Applications should avoid
  444. /// depending on distinct KeyUp events.
  445. /// <para>
  446. /// Overrides must call into the base and return <see langword="true"/> if the base returns <see langword="true"/>.
  447. /// </para>
  448. /// <para>
  449. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  450. /// </para>
  451. /// </remarks>
  452. public virtual bool OnKeyUp (Key keyEvent)
  453. {
  454. // fire event
  455. KeyUp?.Invoke (this, keyEvent);
  456. if (keyEvent.Handled) {
  457. return true;
  458. }
  459. return false;
  460. }
  461. /// <summary>
  462. /// 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.
  463. /// <remarks>
  464. /// Not all terminals support key distinct down/up notifications, Applications should avoid
  465. /// depending on distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  466. /// <para>
  467. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  468. /// </para>
  469. /// </remarks>
  470. /// </summary>
  471. public event EventHandler<Key> KeyUp;
  472. #endregion KeyUp Event
  473. #endregion Low-level Key handling
  474. #region Key Bindings
  475. /// <summary>
  476. /// Gets the key bindings for this view.
  477. /// </summary>
  478. public KeyBindings KeyBindings { get; } = new ();
  479. private Dictionary<Command, Func<bool?>> CommandImplementations { get; } = new ();
  480. /// <summary>
  481. /// Low-level API called when a user presses a key; invokes any key bindings set on the view.
  482. /// This is called during <see cref="NewKeyDownEvent"/> after <see cref="OnKeyDown"/> has returned.
  483. /// </summary>
  484. /// <remarks>
  485. /// <para>
  486. /// Fires the <see cref="InvokingKeyBindings"/> event.
  487. /// </para>
  488. /// <para>
  489. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  490. /// </para>
  491. /// </remarks>
  492. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  493. /// <returns><see langword="false"/> if the key press was not handled. <see langword="true"/> if
  494. /// the keypress was handled and no other view should see it.</returns>
  495. public virtual bool? OnInvokingKeyBindings (Key keyEvent)
  496. {
  497. // fire event
  498. // BUGBUG: KeyEventArgs doesn't include scope, so the event never sees it.
  499. InvokingKeyBindings?.Invoke (this, keyEvent);
  500. if (keyEvent.Handled) {
  501. return true;
  502. }
  503. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  504. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  505. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  506. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  507. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  508. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  509. var handled = InvokeKeyBindings (keyEvent);
  510. if (handled != null && (bool)handled) {
  511. // Stop processing if any key binding handled the key.
  512. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  513. return true;
  514. }
  515. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  516. foreach (var view in Subviews.Where (v => v.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.HotKey, out var _))) {
  517. // TODO: I think this TryGet is not needed due to the one in the lambda above. Use `Get` instead?
  518. if (view.KeyBindings.TryGet (keyEvent.KeyCode, KeyBindingScope.HotKey, out var binding)) {
  519. keyEvent.Scope = KeyBindingScope.HotKey;
  520. handled = view.OnInvokingKeyBindings (keyEvent);
  521. if (handled != null && (bool)handled) {
  522. return true;
  523. }
  524. }
  525. }
  526. return handled;
  527. }
  528. /// <summary>
  529. /// Invoked when a key is pressed that may be mapped to a key binding. Set <see cref="Key.Handled"/>
  530. /// to true to stop the key from being processed by other views.
  531. /// </summary>
  532. public event EventHandler<Key> InvokingKeyBindings;
  533. /// <summary>
  534. /// Invokes any binding that is registered on this <see cref="View"/>
  535. /// and matches the <paramref name="keyEvent"/>
  536. /// <para>
  537. /// See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see>
  538. /// </para>
  539. /// </summary>
  540. /// <param name="keyEvent">The key event passed.</param>
  541. /// <returns>
  542. /// <see langword="null"/> if no command was bound the <paramref name="keyEvent"/>.
  543. /// <see langword="true"/> if commands were invoked and at least one handled the command.
  544. /// <see langword="false"/> if commands were invoked and at none handled the command.
  545. /// </returns>
  546. protected bool? InvokeKeyBindings (Key keyEvent)
  547. {
  548. bool? toReturn = null;
  549. var key = keyEvent.KeyCode;
  550. if (!KeyBindings.TryGet (key, out var binding)) {
  551. return null;
  552. }
  553. foreach (var command in binding.Commands) {
  554. if (!CommandImplementations.ContainsKey (command)) {
  555. 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})");
  556. }
  557. // each command has its own return value
  558. var thisReturn = InvokeCommand (command);
  559. // if we haven't got anything yet, the current command result should be used
  560. toReturn ??= thisReturn;
  561. // if ever see a true then that's what we will return
  562. if (thisReturn ?? false) {
  563. toReturn = true;
  564. }
  565. }
  566. return toReturn;
  567. }
  568. /// <summary>
  569. /// Invokes the specified command.
  570. /// </summary>
  571. /// <param name="command"></param>
  572. /// <returns>
  573. /// <see langword="null"/> if no command was found.
  574. /// <see langword="true"/> if the command was invoked and it handled the command.
  575. /// <see langword="false"/> if the command was invoked and it did not handle the command.
  576. /// </returns>
  577. public bool? InvokeCommand (Command command)
  578. {
  579. if (!CommandImplementations.ContainsKey (command)) {
  580. return null;
  581. }
  582. return CommandImplementations [command] ();
  583. }
  584. /// <summary>
  585. /// <para>
  586. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call <see cref="AddCommand"/>
  587. /// for each command they support.
  588. /// </para>
  589. /// <para>
  590. /// If <see cref="AddCommand"/> has already been called for <paramref name="command"/> <paramref name="f"/> will replace the old one.</para>
  591. /// </summary>
  592. /// <param name="command">The command.</param>
  593. /// <param name="f">The function.</param>
  594. protected void AddCommand (Command command, Func<bool?> f)
  595. {
  596. // if there is already an implementation of this command
  597. // replace that implementation
  598. // else record how to perform the action (this should be the normal case)
  599. if (CommandImplementations != null) {
  600. CommandImplementations [command] = f;
  601. }
  602. }
  603. /// <summary>
  604. /// Returns all commands that are supported by this <see cref="View"/>.
  605. /// </summary>
  606. /// <returns></returns>
  607. public IEnumerable<Command> GetSupportedCommands ()
  608. {
  609. return CommandImplementations.Keys;
  610. }
  611. // TODO: Add GetKeysBoundToCommand() - given a Command, return all Keys that would invoke it
  612. #endregion Key Bindings
  613. }