View.Keyboard.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Reflection.Metadata;
  4. namespace Terminal.Gui;
  5. public partial class View // Keyboard APIs
  6. {
  7. /// <summary>
  8. /// Helper to configure all things keyboard related for a View. Called from the View constructor.
  9. /// </summary>
  10. private void SetupKeyboard ()
  11. {
  12. KeyBindings = new (this);
  13. KeyBindings.Add (Key.Space, Command.Select);
  14. KeyBindings.Add (Key.Enter, Command.Accept);
  15. HotKeyBindings = new (this);
  16. // Note, setting HotKey will bind HotKey to Command.HotKey
  17. HotKeySpecifier = (Rune)'_';
  18. TitleTextFormatter.HotKeyChanged += TitleTextFormatter_HotKeyChanged;
  19. }
  20. /// <summary>
  21. /// Helper to dispose all things keyboard related for a View. Called from the View Dispose method.
  22. /// </summary>
  23. private void DisposeKeyboard () { TitleTextFormatter.HotKeyChanged -= TitleTextFormatter_HotKeyChanged; }
  24. #region HotKey Support
  25. /// <summary>Raised when the <see cref="HotKey"/> is changed.</summary>
  26. public event EventHandler<KeyChangedEventArgs>? HotKeyChanged;
  27. private Key _hotKey = new ();
  28. private void TitleTextFormatter_HotKeyChanged (object? sender, KeyChangedEventArgs e) { HotKeyChanged?.Invoke (this, e); }
  29. /// <summary>
  30. /// Gets or sets the hot key defined for this view. Pressing the hot key on the keyboard while this view has focus will
  31. /// invoke <see cref="Command.HotKey"/>. By default, the HotKey is set to the first character of <see cref="Text"/>
  32. /// that is prefixed with <see cref="HotKeySpecifier"/>.
  33. /// <para>
  34. /// A HotKey is a keypress that causes a visible UI item to perform an action. For example, in a Dialog,
  35. /// with a Button with the text of "_Text" <c>Alt+T</c> will cause the button to gain focus and to raise its
  36. /// <see cref="Accepting"/> event.
  37. /// Or, in a
  38. /// <see cref="Menu"/> with "_File _Edit", <c>Alt+F</c> will select (show) the "_File" menu. If the "_File" menu
  39. /// has a
  40. /// sub-menu of "_New" <c>Alt+N</c> or <c>N</c> will ONLY select the "_New" sub-menu if the "_File" menu is already
  41. /// opened.
  42. /// </para>
  43. /// <para>
  44. /// View subclasses can use <see cref="View.AddCommand(Command,CommandImplementation)"/> to
  45. /// define the
  46. /// behavior of the hot key.
  47. /// </para>
  48. /// </summary>
  49. /// <remarks>
  50. /// <para>See <see href="../docs/keyboard.md"/> for an overview of Terminal.Gui keyboard APIs.</para>
  51. /// <para>
  52. /// This is a helper API for configuring a key binding for the hot key. By default, this property is set whenever
  53. /// <see cref="Text"/> changes.
  54. /// </para>
  55. /// <para>
  56. /// By default, when the Hot Key is set, key bindings are added for both the base key (e.g.
  57. /// <see cref="Key.D3"/>) and the Alt-shifted key (e.g. <see cref="Key.D3"/>.
  58. /// <see cref="Key.WithAlt"/>). This behavior can be overriden by overriding
  59. /// <see cref="AddKeyBindingsForHotKey"/>.
  60. /// </para>
  61. /// <para>
  62. /// By default, when the HotKey is set to <see cref="Key.A"/> through <see cref="Key.Z"/> key bindings will
  63. /// be added for both the un-shifted and shifted versions. This means if the HotKey is <see cref="Key.A"/>, key
  64. /// bindings for <c>Key.A</c> and <c>Key.A.WithShift</c> will be added. This behavior can be overriden by
  65. /// overriding <see cref="AddKeyBindingsForHotKey"/>.
  66. /// </para>
  67. /// <para>If the hot key is changed, the <see cref="HotKeyChanged"/> event is fired.</para>
  68. /// <para>Set to <see cref="Key.Empty"/> to disable the hot key.</para>
  69. /// </remarks>
  70. public Key HotKey
  71. {
  72. get => _hotKey;
  73. set
  74. {
  75. if (value is null)
  76. {
  77. throw new ArgumentException (
  78. @"HotKey must not be null. Use Key.Empty to clear the HotKey.",
  79. nameof (value)
  80. );
  81. }
  82. if (AddKeyBindingsForHotKey (_hotKey, value))
  83. {
  84. // This will cause TextFormatter_HotKeyChanged to be called, firing HotKeyChanged
  85. // BUGBUG: _hotkey should be set BEFORE setting TextFormatter.HotKey
  86. _hotKey = value;
  87. TitleTextFormatter.HotKey = value;
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// Adds key bindings for the specified HotKey. Useful for views that contain multiple items that each have their
  93. /// own HotKey such as <see cref="RadioGroup"/>.
  94. /// </summary>
  95. /// <remarks>
  96. /// <para>
  97. /// By default, key bindings are added for both the base key (e.g. <see cref="Key.D3"/>) and the Alt-shifted key
  98. /// (e.g. <c>Key.D3.WithAlt</c>) This behavior can be overriden by overriding <see cref="AddKeyBindingsForHotKey"/>
  99. /// .
  100. /// </para>
  101. /// <para>
  102. /// By default, when <paramref name="hotKey"/> is <see cref="Key.A"/> through <see cref="Key.Z"/> key bindings
  103. /// will be added for both the un-shifted and shifted versions. This means if the HotKey is <see cref="Key.A"/>,
  104. /// key bindings for <c>Key.A</c> and <c>Key.A.WithShift</c> will be added. This behavior can be overriden by
  105. /// overriding <see cref="AddKeyBindingsForHotKey"/>.
  106. /// </para>
  107. /// </remarks>
  108. /// <param name="prevHotKey">The HotKey <paramref name="hotKey"/> is replacing. Key bindings for this key will be removed.</param>
  109. /// <param name="hotKey">The new HotKey. If <see cref="Key.Empty"/> <paramref name="prevHotKey"/> bindings will be removed.</param>
  110. /// <param name="context">Arbitrary context that can be associated with this key binding.</param>
  111. /// <returns><see langword="true"/> if the HotKey bindings were added.</returns>
  112. /// <exception cref="ArgumentException"></exception>
  113. public virtual bool AddKeyBindingsForHotKey (Key prevHotKey, Key hotKey, object? context = null)
  114. {
  115. if (_hotKey == hotKey)
  116. {
  117. return false;
  118. }
  119. Key newKey = hotKey;
  120. Key baseKey = newKey.NoAlt.NoShift.NoCtrl;
  121. if (newKey != Key.Empty && (baseKey == Key.Space || Rune.IsControl (baseKey.AsRune)))
  122. {
  123. throw new ArgumentException (@$"HotKey must be a printable (and non-space) key ({hotKey}).");
  124. }
  125. if (newKey != baseKey)
  126. {
  127. if (newKey.IsCtrl)
  128. {
  129. throw new ArgumentException (@$"HotKey does not support CtrlMask ({hotKey}).");
  130. }
  131. // Strip off the shift mask if it's A...Z
  132. if (baseKey.IsKeyCodeAtoZ)
  133. {
  134. newKey = newKey.NoShift;
  135. }
  136. // Strip off the Alt mask
  137. newKey = newKey.NoAlt;
  138. }
  139. // Remove base version
  140. if (HotKeyBindings.TryGet (prevHotKey, out _))
  141. {
  142. HotKeyBindings.Remove (prevHotKey);
  143. }
  144. // Remove the Alt version
  145. if (HotKeyBindings.TryGet (prevHotKey.WithAlt, out _))
  146. {
  147. HotKeyBindings.Remove (prevHotKey.WithAlt);
  148. }
  149. if (_hotKey.IsKeyCodeAtoZ)
  150. {
  151. // Remove the shift version
  152. if (HotKeyBindings.TryGet (prevHotKey.WithShift, out _))
  153. {
  154. HotKeyBindings.Remove (prevHotKey.WithShift);
  155. }
  156. // Remove alt | shift version
  157. if (HotKeyBindings.TryGet (prevHotKey.WithShift.WithAlt, out _))
  158. {
  159. HotKeyBindings.Remove (prevHotKey.WithShift.WithAlt);
  160. }
  161. }
  162. // Add the new
  163. if (newKey != Key.Empty)
  164. {
  165. KeyBinding keyBinding = new ()
  166. {
  167. Commands = [Command.HotKey],
  168. Data = context
  169. };
  170. // Add the base and Alt key
  171. HotKeyBindings.Remove (newKey);
  172. HotKeyBindings.Add (newKey, keyBinding);
  173. HotKeyBindings.Remove (newKey.WithAlt);
  174. HotKeyBindings.Add (newKey.WithAlt, keyBinding);
  175. // If the Key is A..Z, add ShiftMask and AltMask | ShiftMask
  176. if (newKey.IsKeyCodeAtoZ)
  177. {
  178. HotKeyBindings.Remove (newKey.WithShift);
  179. HotKeyBindings.Add (newKey.WithShift, keyBinding);
  180. HotKeyBindings.Remove (newKey.WithShift.WithAlt);
  181. HotKeyBindings.Add (newKey.WithShift.WithAlt, keyBinding);
  182. }
  183. }
  184. return true;
  185. }
  186. /// <summary>
  187. /// Gets or sets the specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable automatic hot key
  188. /// setting support for this View instance. The default is '\xffff'.
  189. /// </summary>
  190. public virtual Rune HotKeySpecifier
  191. {
  192. get => TitleTextFormatter.HotKeySpecifier;
  193. set
  194. {
  195. TitleTextFormatter.HotKeySpecifier = TextFormatter.HotKeySpecifier = value;
  196. SetHotKeyFromTitle ();
  197. }
  198. }
  199. private void SetHotKeyFromTitle ()
  200. {
  201. if (HotKeySpecifier == new Rune ('\xFFFF'))
  202. {
  203. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  204. }
  205. if (TextFormatter.FindHotKey (_title, HotKeySpecifier, out _, out Key hk))
  206. {
  207. if (_hotKey != hk)
  208. {
  209. HotKey = hk;
  210. }
  211. }
  212. else
  213. {
  214. HotKey = Key.Empty;
  215. }
  216. }
  217. #endregion HotKey Support
  218. #region Low-level Key handling
  219. #region Key Down Event
  220. /// <summary>
  221. /// If the view is enabled, raises the related key down events on the view, and returns <see langword="true"/> if the
  222. /// event was
  223. /// handled.
  224. /// </summary>
  225. /// <remarks>
  226. /// <para>
  227. /// If the view has a sub view that is focused, <see cref="NewKeyDownEvent"/> will be called on the focused view
  228. /// first.
  229. /// </para>
  230. /// <para>
  231. /// If a more focused subview does not handle the key press, this method raises <see cref="OnKeyDown"/>/
  232. /// <see cref="KeyDown"/> to allow the
  233. /// view to pre-process the key press. If <see cref="OnKeyDown"/>/<see cref="KeyDown"/> is not handled any commands bound to the key will be invoked.
  234. /// Then, only if no key bindings are
  235. /// handled, <see cref="OnKeyDownNotHandled"/>/<see cref="KeyDownNotHandled"/> will be raised allowing the view to
  236. /// process the key press.
  237. /// </para>
  238. /// <para>
  239. /// Calling this method for a key bound to the view via an Application-scoped keybinding will have no effect.
  240. /// Instead,
  241. /// use <see cref="Application.RaiseKeyDownEvent"/>.
  242. /// </para>
  243. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  244. /// </remarks>
  245. /// <param name="key"></param>
  246. /// <returns><see langword="true"/> if the event was handled.</returns>
  247. public bool NewKeyDownEvent (Key key)
  248. {
  249. if (!Enabled)
  250. {
  251. return false;
  252. }
  253. // If there's a Focused subview, give it a chance (this recurses down the hierarchy)
  254. if (Focused?.NewKeyDownEvent (key) == true)
  255. {
  256. return true;
  257. }
  258. // Before (fire the cancellable event)
  259. if (RaiseKeyDown (key) || key.Handled)
  260. {
  261. return true;
  262. }
  263. // During (this is what can be cancelled)
  264. // TODO: NewKeyDownEvent returns bool. It should be bool? so state of InvokeCommands can be reflected up stack
  265. if (InvokeCommandsBoundToKey (key) is true || key.Handled)
  266. {
  267. return true;
  268. }
  269. bool? handled = false;
  270. if (InvokeCommandsBoundToHotKeyOnSubviews (key, ref handled))
  271. {
  272. return true;
  273. }
  274. // After
  275. if (RaiseKeyDownNotHandled (key) || key.Handled)
  276. {
  277. return true;
  278. }
  279. return key.Handled;
  280. bool RaiseKeyDown (Key k)
  281. {
  282. // Before (fire the cancellable event)
  283. if (OnKeyDown (k) || k.Handled)
  284. {
  285. return true;
  286. }
  287. // fire event
  288. KeyDown?.Invoke (this, k);
  289. return k.Handled;
  290. }
  291. bool RaiseKeyDownNotHandled (Key k)
  292. {
  293. if (OnKeyDownNotHandled (k) || k.Handled)
  294. {
  295. return true;
  296. }
  297. KeyDownNotHandled?.Invoke (this, k);
  298. return false;
  299. }
  300. }
  301. /// <summary>
  302. /// Called when the user presses a key, allowing subscribers to pre-process the key down event. Called
  303. /// before key bindings are invoked and <see cref="KeyDownNotHandled"/> is raised. Set
  304. /// <see cref="Key.Handled"/>
  305. /// to true to
  306. /// stop the key from being processed further.
  307. /// </summary>
  308. /// <param name="key">The key that produced the event.</param>
  309. /// <returns>
  310. /// <see langword="false"/> if the key down event was not handled. <see langword="true"/> if the event was handled
  311. /// and processing should stop.
  312. /// </returns>
  313. /// <remarks>
  314. /// <para>
  315. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  316. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  317. /// </para>
  318. /// <para>Fires the <see cref="KeyDown"/> event.</para>
  319. /// </remarks>
  320. protected virtual bool OnKeyDown (Key key) { return false; }
  321. /// <summary>
  322. /// Raised when the user presses a key, allowing subscribers to pre-process the key down event. Called
  323. /// before key bindings are invoked and <see cref="KeyDownNotHandled"/> is raised. Set
  324. /// <see cref="Key.Handled"/>
  325. /// to true to
  326. /// stop the key from being processed further.
  327. /// </summary>
  328. /// <remarks>
  329. /// <para>
  330. /// Not all terminals support key distinct up notifications, Applications should avoid depending on distinct
  331. /// KeyUp events.
  332. /// </para>
  333. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  334. /// </remarks>
  335. public event EventHandler<Key>? KeyDown;
  336. /// <summary>
  337. /// Called when the user has pressed key it wasn't handled by <see cref="KeyDown"/> and was not bound to a key binding.
  338. /// </summary>
  339. /// <remarks>
  340. /// <para>
  341. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  342. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  343. /// </para>
  344. /// <para>
  345. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  346. /// KeyUp events.
  347. /// </para>
  348. /// </remarks>
  349. /// <param name="key">Contains the details about the key that produced the event.</param>
  350. /// <returns>
  351. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  352. /// and no other view should see it.
  353. /// </returns>
  354. protected virtual bool OnKeyDownNotHandled (Key key) { return key.Handled; }
  355. /// <summary>
  356. /// Raised when the user has pressed key it wasn't handled by <see cref="KeyDown"/> and was not bound to a key binding.
  357. /// </summary>
  358. /// <remarks>
  359. /// <para>
  360. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  361. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  362. /// </para>
  363. /// <para>
  364. /// SubViews can use the <see cref="KeyDownNotHandled"/> of their super view override the default behavior of when
  365. /// key bindings are invoked.
  366. /// </para>
  367. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  368. /// </remarks>
  369. public event EventHandler<Key>? KeyDownNotHandled;
  370. #endregion KeyDown Event
  371. #region KeyUp Event
  372. /// <summary>
  373. /// If the view is enabled, raises the related key up events on the view, and returns <see langword="true"/> if the
  374. /// event was
  375. /// handled.
  376. /// </summary>
  377. /// <remarks>
  378. /// <para>
  379. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct
  380. /// KeyUp events.
  381. /// </para>
  382. /// <para>
  383. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view
  384. /// first.
  385. /// </para>
  386. /// <para>
  387. /// If the focused sub view does not handle the key press, this method raises <see cref="OnKeyUp"/>/
  388. /// <see cref="KeyUp"/> to allow the
  389. /// view to pre-process the key press.
  390. /// </para>
  391. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  392. /// </remarks>
  393. /// <param name="key"></param>
  394. /// <returns><see langword="true"/> if the event was handled.</returns>
  395. public bool NewKeyUpEvent (Key key)
  396. {
  397. if (!Enabled)
  398. {
  399. return false;
  400. }
  401. // Before
  402. if (RaiseKeyUp (key) || key.Handled)
  403. {
  404. return true;
  405. }
  406. // During
  407. // After
  408. return false;
  409. bool RaiseKeyUp (Key k)
  410. {
  411. // Before (fire the cancellable event)
  412. if (OnKeyUp (k) || k.Handled)
  413. {
  414. return true;
  415. }
  416. // fire event
  417. KeyUp?.Invoke (this, k);
  418. return k.Handled;
  419. }
  420. }
  421. /// <summary>Called when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.</summary>
  422. /// <param name="key">Contains the details about the key that produced the event.</param>
  423. /// <returns>
  424. /// <see langword="false"/> if the keys up event was not handled. <see langword="true"/> if no other view should see
  425. /// it.
  426. /// </returns>
  427. /// <remarks>
  428. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct KeyUp
  429. /// events.
  430. /// <para>
  431. /// Overrides must call into the base and return <see langword="true"/> if the base returns
  432. /// <see langword="true"/>.
  433. /// </para>
  434. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  435. /// </remarks>
  436. public virtual bool OnKeyUp (Key key) { return false; }
  437. /// <summary>
  438. /// Raised when a key is released. Set <see cref="Key.Handled"/> to true to stop the key up event from being processed
  439. /// by other views.
  440. /// <remarks>
  441. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on
  442. /// distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  443. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  444. /// </remarks>
  445. /// </summary>
  446. public event EventHandler<Key>? KeyUp;
  447. #endregion KeyUp Event
  448. #endregion Low-level Key handling
  449. #region Key Bindings
  450. /// <summary>Gets the bindings for this view that will be invoked only if this view has focus.</summary>
  451. public KeyBindings KeyBindings { get; internal set; } = null!;
  452. /// <summary>Gets the bindings for this view that will be invoked regardless of whehter this view has focus or not.</summary>
  453. public KeyBindings HotKeyBindings { get; internal set; } = null!;
  454. /// <summary>
  455. /// INTERNAL API: Invokes any commands bound to <paramref name="key"/> on this view, adornments, and subviews.
  456. /// </summary>
  457. /// <param name="key"></param>
  458. /// <returns>
  459. /// <see langword="null"/> if no command was invoked or there was no matching key binding; input processing should
  460. /// continue.
  461. /// <see langword="false"/> if a command was invoked and was not handled (or cancelled); input processing should
  462. /// continue.
  463. /// <see langword="true"/> if at least one command was invoked and handled (or
  464. /// cancelled); input processing should stop.
  465. /// </returns>
  466. internal bool? InvokeCommandsBoundToKey (Key key)
  467. {
  468. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  469. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  470. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  471. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  472. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  473. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  474. bool? handled = InvokeCommandsBoundToFocusedKey (key);
  475. if (handled is true)
  476. {
  477. // Stop processing if any key binding handled the key.
  478. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  479. return handled;
  480. }
  481. if (Margin is { } && InvokeCommandsBoundToKeyOnAdornment (Margin, key, ref handled))
  482. {
  483. return true;
  484. }
  485. if (Padding is { } && InvokeCommandsBoundToKeyOnAdornment (Padding, key, ref handled))
  486. {
  487. return true;
  488. }
  489. if (Border is { } && InvokeCommandsBoundToKeyOnAdornment (Border, key, ref handled))
  490. {
  491. return true;
  492. }
  493. return handled;
  494. }
  495. private static bool InvokeCommandsBoundToKeyOnAdornment (Adornment adornment, Key key, ref bool? handled)
  496. {
  497. bool? adornmentHandled = adornment.InvokeCommandsBoundToKey (key);
  498. if (adornmentHandled is true)
  499. {
  500. return true;
  501. }
  502. if (adornment?.Subviews is null)
  503. {
  504. return false;
  505. }
  506. foreach (View subview in adornment.Subviews)
  507. {
  508. bool? subViewHandled = subview.InvokeCommandsBoundToKey (key);
  509. if (subViewHandled is { })
  510. {
  511. handled = subViewHandled;
  512. if ((bool)subViewHandled)
  513. {
  514. return true;
  515. }
  516. }
  517. }
  518. return false;
  519. }
  520. internal bool InvokeCommandsBoundToHotKeyOnSubviews (Key key, ref bool? handled, bool invoke = true)
  521. {
  522. bool? weHandled = InvokeCommandsBoundToHotKey (key);
  523. if (weHandled is true)
  524. {
  525. return true;
  526. }
  527. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  528. foreach (View subview in Subviews)
  529. {
  530. if (subview == Focused)
  531. {
  532. continue;
  533. }
  534. bool recurse = subview.InvokeCommandsBoundToHotKeyOnSubviews (key, ref handled, invoke);
  535. if (recurse || (handled is { } && (bool)handled))
  536. {
  537. return true;
  538. }
  539. }
  540. return false;
  541. }
  542. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  543. // TODO: A better approach would be to have Application hold a list of bound Hotkeys, similar to
  544. // TODO: how Application holds a list of Application Scoped key bindings and then check that list.
  545. /// <summary>
  546. /// Returns true if Key is bound in this view hierarchy. For debugging
  547. /// </summary>
  548. /// <param name="key">The key to test.</param>
  549. /// <param name="boundView">Returns the view the key is bound to.</param>
  550. /// <returns></returns>
  551. public bool IsHotKeyBound (Key key, out View? boundView)
  552. {
  553. // recurse through the subviews to find the views that has the key bound
  554. boundView = null;
  555. foreach (View subview in Subviews)
  556. {
  557. if (subview.HotKeyBindings.TryGet (key, out _))
  558. {
  559. boundView = subview;
  560. return true;
  561. }
  562. if (subview.IsHotKeyBound (key, out boundView))
  563. {
  564. return true;
  565. }
  566. }
  567. return false;
  568. }
  569. /// <summary>
  570. /// Invokes the Commands bound to <paramref name="key"/>.
  571. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  572. /// </summary>
  573. /// <param name="key">The key event passed.</param>
  574. /// <returns>
  575. /// <see langword="null"/> if no command was invoked; input processing should continue.
  576. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input processing
  577. /// should continue.
  578. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input processing should
  579. /// stop.
  580. /// </returns>
  581. protected bool? InvokeCommandsBoundToFocusedKey (Key key)
  582. {
  583. if (!KeyBindings.TryGet (key, out KeyBinding binding))
  584. {
  585. return null;
  586. }
  587. #if DEBUG
  588. //if (Application.KeyBindings.TryGet (key, out KeyBinding b))
  589. //{
  590. // Debug.WriteLine (
  591. // $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.");
  592. //}
  593. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  594. // Scour the bindings up our View hierarchy
  595. // to ensure that the key is not already bound to a different set of commands.
  596. if (SuperView?.IsHotKeyBound (key, out View? previouslyBoundView) ?? false)
  597. {
  598. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  599. }
  600. #endif
  601. return InvokeCommands<KeyBinding> (binding.Commands, binding);
  602. }
  603. /// <summary>
  604. /// Invokes the Commands bound to <paramref name="key"/>.
  605. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  606. /// </summary>
  607. /// <param name="key">The key event passed.</param>
  608. /// <param name="scope">The scope.</param>
  609. /// <returns>
  610. /// <see langword="null"/> if no command was invoked; input processing should continue.
  611. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input processing
  612. /// should continue.
  613. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input processing should
  614. /// stop.
  615. /// </returns>
  616. protected bool? InvokeCommandsBoundToHotKey (Key key)
  617. {
  618. if (!HotKeyBindings.TryGet (key, out KeyBinding binding))
  619. {
  620. return null;
  621. }
  622. #if DEBUG
  623. //if (Application.KeyBindings.TryGet (key, out KeyBinding b))
  624. //{
  625. // Debug.WriteLine (
  626. // $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.");
  627. //}
  628. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  629. // Scour the bindings up our View hierarchy
  630. // to ensure that the key is not already bound to a different set of commands.
  631. if (SuperView?.IsHotKeyBound (key, out View? previouslyBoundView) ?? false)
  632. {
  633. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  634. }
  635. #endif
  636. return InvokeCommands<KeyBinding> (binding.Commands, binding);
  637. }
  638. #endregion Key Bindings
  639. }