ViewKeyboard.cs 30 KB

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