View.Keyboard.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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. Key = newKey,
  169. Data = context,
  170. };
  171. // Add the base and Alt key
  172. HotKeyBindings.Remove (newKey);
  173. HotKeyBindings.Add (newKey, keyBinding);
  174. HotKeyBindings.Remove (newKey.WithAlt);
  175. HotKeyBindings.Add (newKey.WithAlt, keyBinding);
  176. // If the Key is A..Z, add ShiftMask and AltMask | ShiftMask
  177. if (newKey.IsKeyCodeAtoZ)
  178. {
  179. HotKeyBindings.Remove (newKey.WithShift);
  180. HotKeyBindings.Add (newKey.WithShift, keyBinding);
  181. HotKeyBindings.Remove (newKey.WithShift.WithAlt);
  182. HotKeyBindings.Add (newKey.WithShift.WithAlt, keyBinding);
  183. }
  184. }
  185. return true;
  186. }
  187. /// <summary>
  188. /// Gets or sets the specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable automatic hot key
  189. /// setting support for this View instance. The default is '\xffff'.
  190. /// </summary>
  191. public virtual Rune HotKeySpecifier
  192. {
  193. get => TitleTextFormatter.HotKeySpecifier;
  194. set
  195. {
  196. TitleTextFormatter.HotKeySpecifier = TextFormatter.HotKeySpecifier = value;
  197. SetHotKeyFromTitle ();
  198. }
  199. }
  200. private void SetHotKeyFromTitle ()
  201. {
  202. if (HotKeySpecifier == new Rune ('\xFFFF'))
  203. {
  204. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  205. }
  206. if (TextFormatter.FindHotKey (_title, HotKeySpecifier, out _, out Key hk))
  207. {
  208. if (_hotKey != hk)
  209. {
  210. HotKey = hk;
  211. }
  212. }
  213. else
  214. {
  215. HotKey = Key.Empty;
  216. }
  217. }
  218. #endregion HotKey Support
  219. #region Low-level Key handling
  220. #region Key Down Event
  221. /// <summary>
  222. /// If the view is enabled, raises the related key down events on the view, and returns <see langword="true"/> if the
  223. /// event was
  224. /// handled.
  225. /// </summary>
  226. /// <remarks>
  227. /// <para>
  228. /// If the view has a sub view that is focused, <see cref="NewKeyDownEvent"/> will be called on the focused view
  229. /// first.
  230. /// </para>
  231. /// <para>
  232. /// If a more focused subview does not handle the key press, this method raises <see cref="OnKeyDown"/>/
  233. /// <see cref="KeyDown"/> to allow the
  234. /// 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.
  235. /// Then, only if no key bindings are
  236. /// handled, <see cref="OnKeyDownNotHandled"/>/<see cref="KeyDownNotHandled"/> will be raised allowing the view to
  237. /// process the key press.
  238. /// </para>
  239. /// <para>
  240. /// Calling this method for a key bound to the view via an Application-scoped keybinding will have no effect.
  241. /// Instead,
  242. /// use <see cref="Application.RaiseKeyDownEvent"/>.
  243. /// </para>
  244. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  245. /// </remarks>
  246. /// <param name="key"></param>
  247. /// <returns><see langword="true"/> if the event was handled.</returns>
  248. public bool NewKeyDownEvent (Key key)
  249. {
  250. if (!Enabled)
  251. {
  252. return false;
  253. }
  254. // If there's a Focused subview, give it a chance (this recurses down the hierarchy)
  255. if (Focused?.NewKeyDownEvent (key) == true)
  256. {
  257. return true;
  258. }
  259. // Before (fire the cancellable event)
  260. if (RaiseKeyDown (key) || key.Handled)
  261. {
  262. return true;
  263. }
  264. // During (this is what can be cancelled)
  265. // TODO: NewKeyDownEvent returns bool. It should be bool? so state of InvokeCommands can be reflected up stack
  266. if (InvokeCommandsBoundToKey (key) is true || key.Handled)
  267. {
  268. return true;
  269. }
  270. bool? handled = false;
  271. if (InvokeCommandsBoundToHotKeyOnSubviews (key, ref handled))
  272. {
  273. return true;
  274. }
  275. // After
  276. if (RaiseKeyDownNotHandled (key) || key.Handled)
  277. {
  278. return true;
  279. }
  280. return key.Handled;
  281. bool RaiseKeyDown (Key k)
  282. {
  283. // Before (fire the cancellable event)
  284. if (OnKeyDown (k) || k.Handled)
  285. {
  286. return true;
  287. }
  288. // fire event
  289. KeyDown?.Invoke (this, k);
  290. return k.Handled;
  291. }
  292. bool RaiseKeyDownNotHandled (Key k)
  293. {
  294. if (OnKeyDownNotHandled (k) || k.Handled)
  295. {
  296. return true;
  297. }
  298. KeyDownNotHandled?.Invoke (this, k);
  299. return false;
  300. }
  301. }
  302. /// <summary>
  303. /// Called when the user presses a key, allowing subscribers to pre-process the key down event. Called
  304. /// before key bindings are invoked and <see cref="KeyDownNotHandled"/> is raised. Set
  305. /// <see cref="Key.Handled"/>
  306. /// to true to
  307. /// stop the key from being processed further.
  308. /// </summary>
  309. /// <param name="key">The key that produced the event.</param>
  310. /// <returns>
  311. /// <see langword="false"/> if the key down event was not handled. <see langword="true"/> if the event was handled
  312. /// and processing should stop.
  313. /// </returns>
  314. /// <remarks>
  315. /// <para>
  316. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  317. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  318. /// </para>
  319. /// <para>Fires the <see cref="KeyDown"/> event.</para>
  320. /// </remarks>
  321. protected virtual bool OnKeyDown (Key key) { return false; }
  322. /// <summary>
  323. /// Raised when the user presses a key, allowing subscribers to pre-process the key down event. Called
  324. /// before key bindings are invoked and <see cref="KeyDownNotHandled"/> is raised. Set
  325. /// <see cref="Key.Handled"/>
  326. /// to true to
  327. /// stop the key from being processed further.
  328. /// </summary>
  329. /// <remarks>
  330. /// <para>
  331. /// Not all terminals support key distinct up notifications, Applications should avoid depending on distinct
  332. /// KeyUp events.
  333. /// </para>
  334. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  335. /// </remarks>
  336. public event EventHandler<Key>? KeyDown;
  337. /// <summary>
  338. /// Called when the user has pressed key it wasn't handled by <see cref="KeyDown"/> and was not bound to a key binding.
  339. /// </summary>
  340. /// <remarks>
  341. /// <para>
  342. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  343. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  344. /// </para>
  345. /// <para>
  346. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  347. /// KeyUp events.
  348. /// </para>
  349. /// </remarks>
  350. /// <param name="key">Contains the details about the key that produced the event.</param>
  351. /// <returns>
  352. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  353. /// and no other view should see it.
  354. /// </returns>
  355. protected virtual bool OnKeyDownNotHandled (Key key) { return key.Handled; }
  356. /// <summary>
  357. /// Raised when the user has pressed key it wasn't handled by <see cref="KeyDown"/> and was not bound to a key binding.
  358. /// </summary>
  359. /// <remarks>
  360. /// <para>
  361. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  362. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  363. /// </para>
  364. /// <para>
  365. /// SubViews can use the <see cref="KeyDownNotHandled"/> of their super view override the default behavior of when
  366. /// key bindings are invoked.
  367. /// </para>
  368. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  369. /// </remarks>
  370. public event EventHandler<Key>? KeyDownNotHandled;
  371. #endregion KeyDown Event
  372. #region KeyUp Event
  373. /// <summary>
  374. /// If the view is enabled, raises the related key up events on the view, and returns <see langword="true"/> if the
  375. /// event was
  376. /// handled.
  377. /// </summary>
  378. /// <remarks>
  379. /// <para>
  380. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct
  381. /// KeyUp events.
  382. /// </para>
  383. /// <para>
  384. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view
  385. /// first.
  386. /// </para>
  387. /// <para>
  388. /// If the focused sub view does not handle the key press, this method raises <see cref="OnKeyUp"/>/
  389. /// <see cref="KeyUp"/> to allow the
  390. /// view to pre-process the key press.
  391. /// </para>
  392. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  393. /// </remarks>
  394. /// <param name="key"></param>
  395. /// <returns><see langword="true"/> if the event was handled.</returns>
  396. public bool NewKeyUpEvent (Key key)
  397. {
  398. if (!Enabled)
  399. {
  400. return false;
  401. }
  402. // Before
  403. if (RaiseKeyUp (key) || key.Handled)
  404. {
  405. return true;
  406. }
  407. // During
  408. // After
  409. return false;
  410. bool RaiseKeyUp (Key k)
  411. {
  412. // Before (fire the cancellable event)
  413. if (OnKeyUp (k) || k.Handled)
  414. {
  415. return true;
  416. }
  417. // fire event
  418. KeyUp?.Invoke (this, k);
  419. return k.Handled;
  420. }
  421. }
  422. /// <summary>Called when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.</summary>
  423. /// <param name="key">Contains the details about the key that produced the event.</param>
  424. /// <returns>
  425. /// <see langword="false"/> if the keys up event was not handled. <see langword="true"/> if no other view should see
  426. /// it.
  427. /// </returns>
  428. /// <remarks>
  429. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct KeyUp
  430. /// events.
  431. /// <para>
  432. /// Overrides must call into the base and return <see langword="true"/> if the base returns
  433. /// <see langword="true"/>.
  434. /// </para>
  435. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  436. /// </remarks>
  437. public virtual bool OnKeyUp (Key key) { return false; }
  438. /// <summary>
  439. /// Raised when a key is released. Set <see cref="Key.Handled"/> to true to stop the key up event from being processed
  440. /// by other views.
  441. /// <remarks>
  442. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on
  443. /// distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  444. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  445. /// </remarks>
  446. /// </summary>
  447. public event EventHandler<Key>? KeyUp;
  448. #endregion KeyUp Event
  449. #endregion Low-level Key handling
  450. #region Key Bindings
  451. /// <summary>Gets the bindings for this view that will be invoked only if this view has focus.</summary>
  452. public KeyBindings KeyBindings { get; internal set; } = null!;
  453. /// <summary>Gets the bindings for this view that will be invoked regardless of whehter this view has focus or not.</summary>
  454. public KeyBindings HotKeyBindings { get; internal set; } = null!;
  455. /// <summary>
  456. /// INTERNAL API: Invokes any commands bound to <paramref name="key"/> on this view, adornments, and subviews.
  457. /// </summary>
  458. /// <param name="key"></param>
  459. /// <returns>
  460. /// <see langword="null"/> if no command was invoked or there was no matching key binding; input processing should
  461. /// continue.
  462. /// <see langword="false"/> if a command was invoked and was not handled (or cancelled); input processing should
  463. /// continue.
  464. /// <see langword="true"/> if at least one command was invoked and handled (or
  465. /// cancelled); input processing should stop.
  466. /// </returns>
  467. internal bool? InvokeCommandsBoundToKey (Key key)
  468. {
  469. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  470. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  471. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  472. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  473. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  474. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  475. bool? handled = InvokeCommandsBoundToFocusedKey (key);
  476. if (handled is true)
  477. {
  478. // Stop processing if any key binding handled the key.
  479. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  480. return handled;
  481. }
  482. if (Margin is { } && InvokeCommandsBoundToKeyOnAdornment (Margin, key, ref handled))
  483. {
  484. return true;
  485. }
  486. if (Padding is { } && InvokeCommandsBoundToKeyOnAdornment (Padding, key, ref handled))
  487. {
  488. return true;
  489. }
  490. if (Border is { } && InvokeCommandsBoundToKeyOnAdornment (Border, key, ref handled))
  491. {
  492. return true;
  493. }
  494. return handled;
  495. }
  496. private static bool InvokeCommandsBoundToKeyOnAdornment (Adornment adornment, Key key, ref bool? handled)
  497. {
  498. bool? adornmentHandled = adornment.InvokeCommandsBoundToKey (key);
  499. if (adornmentHandled is true)
  500. {
  501. return true;
  502. }
  503. if (adornment?.Subviews is null)
  504. {
  505. return false;
  506. }
  507. foreach (View subview in adornment.Subviews)
  508. {
  509. bool? subViewHandled = subview.InvokeCommandsBoundToKey (key);
  510. if (subViewHandled is { })
  511. {
  512. handled = subViewHandled;
  513. if ((bool)subViewHandled)
  514. {
  515. return true;
  516. }
  517. }
  518. }
  519. return false;
  520. }
  521. internal bool InvokeCommandsBoundToHotKeyOnSubviews (Key key, ref bool? handled, bool invoke = true)
  522. {
  523. bool? weHandled = InvokeCommandsBoundToHotKey (key);
  524. if (weHandled is true)
  525. {
  526. return true;
  527. }
  528. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  529. foreach (View subview in Subviews)
  530. {
  531. if (subview == Focused)
  532. {
  533. continue;
  534. }
  535. bool recurse = subview.InvokeCommandsBoundToHotKeyOnSubviews (key, ref handled, invoke);
  536. if (recurse || (handled is { } && (bool)handled))
  537. {
  538. return true;
  539. }
  540. }
  541. return false;
  542. }
  543. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  544. // TODO: A better approach would be to have Application hold a list of bound Hotkeys, similar to
  545. // TODO: how Application holds a list of Application Scoped key bindings and then check that list.
  546. /// <summary>
  547. /// Returns true if Key is bound in this view hierarchy. For debugging
  548. /// </summary>
  549. /// <param name="key">The key to test.</param>
  550. /// <param name="boundView">Returns the view the key is bound to.</param>
  551. /// <returns></returns>
  552. public bool IsHotKeyBound (Key key, out View? boundView)
  553. {
  554. // recurse through the subviews to find the views that has the key bound
  555. boundView = null;
  556. foreach (View subview in Subviews)
  557. {
  558. if (subview.HotKeyBindings.TryGet (key, out _))
  559. {
  560. boundView = subview;
  561. return true;
  562. }
  563. if (subview.IsHotKeyBound (key, out boundView))
  564. {
  565. return true;
  566. }
  567. }
  568. return false;
  569. }
  570. /// <summary>
  571. /// Invokes the Commands bound to <paramref name="key"/>.
  572. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  573. /// </summary>
  574. /// <param name="key">The key event passed.</param>
  575. /// <returns>
  576. /// <see langword="null"/> if no command was invoked; input processing should continue.
  577. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input processing
  578. /// should continue.
  579. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input processing should
  580. /// stop.
  581. /// </returns>
  582. protected bool? InvokeCommandsBoundToFocusedKey (Key key)
  583. {
  584. if (!KeyBindings.TryGet (key, out KeyBinding binding))
  585. {
  586. return null;
  587. }
  588. #if DEBUG
  589. //if (Application.KeyBindings.TryGet (key, out KeyBinding b))
  590. //{
  591. // Debug.WriteLine (
  592. // $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.");
  593. //}
  594. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  595. // Scour the bindings up our View hierarchy
  596. // to ensure that the key is not already bound to a different set of commands.
  597. if (SuperView?.IsHotKeyBound (key, out View? previouslyBoundView) ?? false)
  598. {
  599. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  600. }
  601. #endif
  602. return InvokeCommands<KeyBinding> (binding.Commands, binding);
  603. }
  604. /// <summary>
  605. /// Invokes the Commands bound to <paramref name="key"/>.
  606. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  607. /// </summary>
  608. /// <param name="key">The key event passed.</param>
  609. /// <param name="scope">The scope.</param>
  610. /// <returns>
  611. /// <see langword="null"/> if no command was invoked; input processing should continue.
  612. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input processing
  613. /// should continue.
  614. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input processing should
  615. /// stop.
  616. /// </returns>
  617. protected bool? InvokeCommandsBoundToHotKey (Key key)
  618. {
  619. if (!HotKeyBindings.TryGet (key, out KeyBinding binding))
  620. {
  621. return null;
  622. }
  623. #if DEBUG
  624. //if (Application.KeyBindings.TryGet (key, out KeyBinding b))
  625. //{
  626. // Debug.WriteLine (
  627. // $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.");
  628. //}
  629. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  630. // Scour the bindings up our View hierarchy
  631. // to ensure that the key is not already bound to a different set of commands.
  632. if (SuperView?.IsHotKeyBound (key, out View? previouslyBoundView) ?? false)
  633. {
  634. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  635. }
  636. #endif
  637. return InvokeCommands<KeyBinding> (binding.Commands, binding);
  638. }
  639. #endregion Key Bindings
  640. }