2
0

View.Keyboard.cs 33 KB

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