View.Keyboard.cs 34 KB

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