View.Keyboard.cs 33 KB

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