View.Keyboard.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. if (adornment?.Subviews is null)
  505. {
  506. return false;
  507. }
  508. foreach (View subview in adornment.Subviews)
  509. {
  510. bool? subViewHandled = subview.OnInvokingKeyBindings (keyEvent, scope);
  511. if (subViewHandled is { })
  512. {
  513. handled = subViewHandled;
  514. if ((bool)subViewHandled)
  515. {
  516. return true;
  517. }
  518. }
  519. }
  520. return false;
  521. }
  522. private bool ProcessSubViewKeyBindings (Key keyEvent, KeyBindingScope scope, ref bool? handled, bool invoke = true)
  523. {
  524. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  525. foreach (View subview in Subviews)
  526. {
  527. if (subview == Focused)
  528. {
  529. continue;
  530. }
  531. if (subview.KeyBindings.TryGet (keyEvent, scope, out KeyBinding binding))
  532. {
  533. if (binding.Scope == KeyBindingScope.Focused && !subview.HasFocus)
  534. {
  535. continue;
  536. }
  537. if (!invoke)
  538. {
  539. return true;
  540. }
  541. bool? subViewHandled = subview.OnInvokingKeyBindings (keyEvent, scope);
  542. if (subViewHandled is { })
  543. {
  544. handled = subViewHandled;
  545. if ((bool)subViewHandled)
  546. {
  547. return true;
  548. }
  549. }
  550. }
  551. bool recurse = subview.ProcessSubViewKeyBindings (keyEvent, scope, ref handled, invoke);
  552. if (recurse || (handled is { } && (bool)handled))
  553. {
  554. return true;
  555. }
  556. }
  557. return false;
  558. }
  559. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  560. // TODO: A better approach would be to have Application hold a list of bound Hotkeys, similar to
  561. // TODO: how Application holds a list of Application Scoped key bindings and then check that list.
  562. /// <summary>
  563. /// Returns true if Key is bound in this view hierarchy. For debugging
  564. /// </summary>
  565. /// <param name="key">The key to test.</param>
  566. /// <param name="boundView">Returns the view the key is bound to.</param>
  567. /// <returns></returns>
  568. public bool IsHotKeyKeyBound (Key key, out View? boundView)
  569. {
  570. // recurse through the subviews to find the views that has the key bound
  571. boundView = null;
  572. foreach (View subview in Subviews)
  573. {
  574. if (subview.KeyBindings.TryGet (key, KeyBindingScope.HotKey, out _))
  575. {
  576. boundView = subview;
  577. return true;
  578. }
  579. if (subview.IsHotKeyKeyBound (key, out boundView))
  580. {
  581. return true;
  582. }
  583. }
  584. return false;
  585. }
  586. /// <summary>
  587. /// Invoked when a key is pressed that may be mapped to a key binding. Set <see cref="Key.Handled"/> to true to
  588. /// stop the key from being processed by other views.
  589. /// </summary>
  590. public event EventHandler<Key>? InvokingKeyBindings;
  591. /// <summary>
  592. /// Invokes any binding that is registered on this <see cref="View"/> and matches the <paramref name="key"/>
  593. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  594. /// </summary>
  595. /// <param name="key">The key event passed.</param>
  596. /// <param name="scope">The scope.</param>
  597. /// <returns>
  598. /// <see langword="null"/> if no command was bound the <paramref name="key"/>. <see langword="true"/> if
  599. /// commands were invoked and at least one handled the command. <see langword="false"/> if commands were invoked and at
  600. /// none handled the command.
  601. /// </returns>
  602. protected bool? InvokeKeyBindings (Key key, KeyBindingScope scope)
  603. {
  604. bool? toReturn = null;
  605. if (!KeyBindings.TryGet (key, scope, out KeyBinding binding))
  606. {
  607. return null;
  608. }
  609. #if DEBUG
  610. // TODO: Determine if App scope bindings should be fired first or last (currently last).
  611. if (Application.KeyBindings.TryGet (key, KeyBindingScope.Focused | KeyBindingScope.HotKey, out KeyBinding b))
  612. {
  613. //var boundView = views [0];
  614. //var commandBinding = boundView.KeyBindings.Get (key);
  615. Debug.WriteLine (
  616. $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command."); //{commandBinding.Commands [0]}: {boundView}.");
  617. }
  618. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  619. // Scour the bindings up our View hierarchy
  620. // to ensure that the key is not already bound to a different set of commands.
  621. if (SuperView?.IsHotKeyKeyBound (key, out View? previouslyBoundView) ?? false)
  622. {
  623. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  624. }
  625. #endif
  626. foreach (Command command in binding.Commands)
  627. {
  628. if (!CommandImplementations.ContainsKey (command))
  629. {
  630. throw new NotSupportedException (
  631. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by this View ({GetType ().Name})"
  632. );
  633. }
  634. // each command has its own return value
  635. bool? thisReturn = InvokeCommand (command, key, binding);
  636. // if we haven't got anything yet, the current command result should be used
  637. toReturn ??= thisReturn;
  638. // if ever see a true then that's what we will return
  639. if (thisReturn ?? false)
  640. {
  641. toReturn = true;
  642. }
  643. }
  644. return toReturn;
  645. }
  646. /// <summary>
  647. /// Invokes the specified commands.
  648. /// </summary>
  649. /// <param name="commands"></param>
  650. /// <param name="key">The key that caused the commands to be invoked, if any.</param>
  651. /// <param name="keyBinding"></param>
  652. /// <returns>
  653. /// <see langword="null"/> if no command was found.
  654. /// <see langword="true"/> if the command was invoked the command was handled.
  655. /// <see langword="false"/> if the command was invoked and the command was not handled.
  656. /// </returns>
  657. public bool? InvokeCommands (Command [] commands, Key? key = null, KeyBinding? keyBinding = null)
  658. {
  659. bool? toReturn = null;
  660. foreach (Command command in commands)
  661. {
  662. if (!CommandImplementations.ContainsKey (command))
  663. {
  664. throw new NotSupportedException (@$"{command} is not supported by ({GetType ().Name}).");
  665. }
  666. // each command has its own return value
  667. bool? thisReturn = InvokeCommand (command, key, keyBinding);
  668. // if we haven't got anything yet, the current command result should be used
  669. toReturn ??= thisReturn;
  670. // if ever see a true then that's what we will return
  671. if (thisReturn ?? false)
  672. {
  673. toReturn = true;
  674. }
  675. }
  676. return toReturn;
  677. }
  678. /// <summary>Invokes the specified command.</summary>
  679. /// <param name="command">The command to invoke.</param>
  680. /// <param name="key">The key that caused the command to be invoked, if any.</param>
  681. /// <param name="keyBinding"></param>
  682. /// <returns>
  683. /// <see langword="null"/> if no command was found. <see langword="true"/> if the command was invoked, and it
  684. /// handled the command. <see langword="false"/> if the command was invoked, and it did not handle the command.
  685. /// </returns>
  686. public bool? InvokeCommand (Command command, Key? key = null, KeyBinding? keyBinding = null)
  687. {
  688. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?>? implementation))
  689. {
  690. var context = new CommandContext (command, key, keyBinding); // Create the context here
  691. return implementation (context);
  692. }
  693. return null;
  694. }
  695. /// <summary>
  696. /// <para>
  697. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  698. /// AddCommand for each command they support.
  699. /// </para>
  700. /// <para>
  701. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  702. /// replace the old one.
  703. /// </para>
  704. /// </summary>
  705. /// <remarks>
  706. /// <para>
  707. /// This version of AddCommand is for commands that require <see cref="CommandContext"/>. Use
  708. /// <see cref="AddCommand(Command,Func{System.Nullable{bool}})"/>
  709. /// in cases where the command does not require a <see cref="CommandContext"/>.
  710. /// </para>
  711. /// </remarks>
  712. /// <param name="command">The command.</param>
  713. /// <param name="f">The function.</param>
  714. protected void AddCommand (Command command, Func<CommandContext, bool?> f) { CommandImplementations [command] = f; }
  715. /// <summary>
  716. /// <para>
  717. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  718. /// AddCommand for each command they support.
  719. /// </para>
  720. /// <para>
  721. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  722. /// replace the old one.
  723. /// </para>
  724. /// </summary>
  725. /// <remarks>
  726. /// <para>
  727. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  728. /// If the command requires context, use
  729. /// <see cref="AddCommand(Command,Func{CommandContext,System.Nullable{bool}})"/>
  730. /// </para>
  731. /// </remarks>
  732. /// <param name="command">The command.</param>
  733. /// <param name="f">The function.</param>
  734. protected void AddCommand (Command command, Func<bool?> f) { CommandImplementations [command] = ctx => f (); }
  735. /// <summary>Returns all commands that are supported by this <see cref="View"/>.</summary>
  736. /// <returns></returns>
  737. public IEnumerable<Command> GetSupportedCommands () { return CommandImplementations.Keys; }
  738. // TODO: Add GetKeysBoundToCommand() - given a Command, return all Keys that would invoke it
  739. #endregion Key Bindings
  740. }