View.Keyboard.cs 34 KB

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