View.Keyboard.cs 34 KB

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