View.Keyboard.cs 34 KB

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