View.Keyboard.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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 (InvokeCommands (key) is true || key.Handled)
  267. {
  268. return true;
  269. }
  270. bool? handled = false;
  271. if (InvokeCommandsBoundToHotKey (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>Fires the <see cref="KeyDown"/> event.</para>
  316. /// </remarks>
  317. protected virtual bool OnKeyDown (Key key) { return false; }
  318. /// <summary>
  319. /// Raised when the user presses a key, allowing subscribers to pre-process the key down event. Called
  320. /// before key bindings are invoked and <see cref="KeyDownNotHandled"/> is raised. Set
  321. /// <see cref="Key.Handled"/>
  322. /// to true to
  323. /// stop the key from being processed further.
  324. /// </summary>
  325. /// <remarks>
  326. /// <para>
  327. /// Not all terminals support key distinct up notifications, Applications should avoid depending on distinct
  328. /// KeyUp events.
  329. /// </para>
  330. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  331. /// </remarks>
  332. public event EventHandler<Key>? KeyDown;
  333. /// <summary>
  334. /// Called when the user has pressed key it wasn't handled by <see cref="KeyDown"/> and was not bound to a key binding.
  335. /// </summary>
  336. /// <remarks>
  337. /// <para>
  338. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  339. /// KeyUp events.
  340. /// </para>
  341. /// </remarks>
  342. /// <param name="key">Contains the details about the key that produced the event.</param>
  343. /// <returns>
  344. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  345. /// and no other view should see it.
  346. /// </returns>
  347. protected virtual bool OnKeyDownNotHandled (Key key) { return key.Handled; }
  348. /// <summary>
  349. /// Raised when the user has pressed key it wasn't handled by <see cref="KeyDown"/> and was not bound to a key binding.
  350. /// </summary>
  351. /// <remarks>
  352. /// <para>
  353. /// SubViews can use the <see cref="KeyDownNotHandled"/> of their super view override the default behavior of when
  354. /// key bindings are invoked.
  355. /// </para>
  356. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  357. /// </remarks>
  358. public event EventHandler<Key>? KeyDownNotHandled;
  359. #endregion KeyDown Event
  360. #region KeyUp Event
  361. /// <summary>
  362. /// If the view is enabled, raises the related key up events on the view, and returns <see langword="true"/> if the
  363. /// event was
  364. /// handled.
  365. /// </summary>
  366. /// <remarks>
  367. /// <para>
  368. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct
  369. /// KeyUp events.
  370. /// </para>
  371. /// <para>
  372. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view
  373. /// first.
  374. /// </para>
  375. /// <para>
  376. /// If the focused sub view does not handle the key press, this method raises <see cref="OnKeyUp"/>/
  377. /// <see cref="KeyUp"/> to allow the
  378. /// view to pre-process the key press.
  379. /// </para>
  380. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  381. /// </remarks>
  382. /// <param name="key"></param>
  383. /// <returns><see langword="true"/> if the event was handled.</returns>
  384. public bool NewKeyUpEvent (Key key)
  385. {
  386. if (!Enabled)
  387. {
  388. return false;
  389. }
  390. // Before
  391. if (RaiseKeyUp (key) || key.Handled)
  392. {
  393. return true;
  394. }
  395. // During
  396. // After
  397. return false;
  398. bool RaiseKeyUp (Key k)
  399. {
  400. // Before (fire the cancellable event)
  401. if (OnKeyUp (k) || k.Handled)
  402. {
  403. return true;
  404. }
  405. // fire event
  406. KeyUp?.Invoke (this, k);
  407. return k.Handled;
  408. }
  409. }
  410. /// <summary>Called when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.</summary>
  411. /// <param name="key">Contains the details about the key that produced the event.</param>
  412. /// <returns>
  413. /// <see langword="false"/> if the keys up event was not handled. <see langword="true"/> if no other view should see
  414. /// it.
  415. /// </returns>
  416. /// <remarks>
  417. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct KeyUp
  418. /// events.
  419. /// <para>
  420. /// Overrides must call into the base and return <see langword="true"/> if the base returns
  421. /// <see langword="true"/>.
  422. /// </para>
  423. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  424. /// </remarks>
  425. public virtual bool OnKeyUp (Key key) { return false; }
  426. /// <summary>
  427. /// Raised when a key is released. Set <see cref="Key.Handled"/> to true to stop the key up event from being processed
  428. /// by other views.
  429. /// <remarks>
  430. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on
  431. /// distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  432. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  433. /// </remarks>
  434. /// </summary>
  435. public event EventHandler<Key>? KeyUp;
  436. #endregion KeyUp Event
  437. #endregion Low-level Key handling
  438. #region Key Bindings
  439. /// <summary>Gets the bindings for this view that will be invoked only if this view has focus.</summary>
  440. public KeyBindings KeyBindings { get; internal set; } = null!;
  441. /// <summary>Gets the bindings for this view that will be invoked regardless of whether this view has focus or not.</summary>
  442. public KeyBindings HotKeyBindings { get; internal set; } = null!;
  443. /// <summary>
  444. /// INTERNAL API: Invokes any commands bound to <paramref name="key"/> on this view, adornments, and subviews.
  445. /// </summary>
  446. /// <param name="key"></param>
  447. /// <returns>
  448. /// <see langword="null"/> if no command was invoked or there was no matching key binding; input processing should
  449. /// continue.
  450. /// <see langword="false"/> if a command was invoked and was not handled (or cancelled); input processing should
  451. /// continue.
  452. /// <see langword="true"/> if at least one command was invoked and handled (or
  453. /// cancelled); input processing should stop.
  454. /// </returns>
  455. internal bool? InvokeCommands (Key key)
  456. {
  457. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  458. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  459. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  460. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  461. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  462. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  463. bool? handled = DoInvokeCommands (key);
  464. if (handled is true)
  465. {
  466. // Stop processing if any key binding handled the key.
  467. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  468. return handled;
  469. }
  470. if (Margin is { } && InvokeCommandsBoundToKeyOnAdornment (Margin, key, ref handled))
  471. {
  472. return true;
  473. }
  474. if (Padding is { } && InvokeCommandsBoundToKeyOnAdornment (Padding, key, ref handled))
  475. {
  476. return true;
  477. }
  478. if (Border is { } && InvokeCommandsBoundToKeyOnAdornment (Border, key, ref handled))
  479. {
  480. return true;
  481. }
  482. return handled;
  483. }
  484. private static bool InvokeCommandsBoundToKeyOnAdornment (Adornment adornment, Key key, ref bool? handled)
  485. {
  486. bool? adornmentHandled = adornment.InvokeCommands (key);
  487. if (adornmentHandled is true)
  488. {
  489. return true;
  490. }
  491. if (adornment?.Subviews is null)
  492. {
  493. return false;
  494. }
  495. foreach (View subview in adornment.Subviews)
  496. {
  497. bool? subViewHandled = subview.InvokeCommands (key);
  498. if (subViewHandled is { })
  499. {
  500. handled = subViewHandled;
  501. if ((bool)subViewHandled)
  502. {
  503. return true;
  504. }
  505. }
  506. }
  507. return false;
  508. }
  509. // BUGBUG: This will miss any hotkeys in subviews of Adornments.
  510. /// <summary>
  511. /// Invokes any commands bound to <paramref name="key"/> on this view and subviews.
  512. /// </summary>
  513. /// <param name="key"></param>
  514. /// <param name="handled"></param>
  515. /// <returns></returns>
  516. internal bool InvokeCommandsBoundToHotKey (Key key, ref bool? handled)
  517. {
  518. bool? weHandled = InvokeCommandsBoundToHotKey (key);
  519. if (weHandled is true)
  520. {
  521. return true;
  522. }
  523. // Now, process any HotKey bindings in the subviews
  524. foreach (View subview in Subviews)
  525. {
  526. if (subview == Focused)
  527. {
  528. continue;
  529. }
  530. bool recurse = subview.InvokeCommandsBoundToHotKey (key, ref handled);
  531. if (recurse || (handled is { } && (bool)handled))
  532. {
  533. return true;
  534. }
  535. }
  536. return false;
  537. }
  538. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  539. // TODO: A better approach would be to have Application hold a list of bound Hotkeys, similar to
  540. // TODO: how Application holds a list of Application Scoped key bindings and then check that list.
  541. /// <summary>
  542. /// Returns true if Key is bound in this view hierarchy. For debugging
  543. /// </summary>
  544. /// <param name="key">The key to test.</param>
  545. /// <param name="boundView">Returns the view the key is bound to.</param>
  546. /// <returns></returns>
  547. public bool IsHotKeyBound (Key key, out View? boundView)
  548. {
  549. // recurse through the subviews to find the views that has the key bound
  550. boundView = null;
  551. foreach (View subview in Subviews)
  552. {
  553. if (subview.HotKeyBindings.TryGet (key, out _))
  554. {
  555. boundView = subview;
  556. return true;
  557. }
  558. if (subview.IsHotKeyBound (key, out boundView))
  559. {
  560. return true;
  561. }
  562. }
  563. return false;
  564. }
  565. /// <summary>
  566. /// Invokes the Commands bound to <paramref name="key"/>.
  567. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  568. /// </summary>
  569. /// <param name="key">The key event passed.</param>
  570. /// <returns>
  571. /// <see langword="null"/> if no command was invoked; input processing should continue.
  572. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input processing
  573. /// should continue.
  574. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input processing should
  575. /// stop.
  576. /// </returns>
  577. protected bool? DoInvokeCommands (Key key)
  578. {
  579. if (!KeyBindings.TryGet (key, out KeyBinding binding))
  580. {
  581. return null;
  582. }
  583. #if DEBUG
  584. //if (Application.KeyBindings.TryGet (key, out KeyBinding b))
  585. //{
  586. // Debug.WriteLine (
  587. // $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.");
  588. //}
  589. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  590. // Scour the bindings up our View hierarchy
  591. // to ensure that the key is not already bound to a different set of commands.
  592. if (SuperView?.IsHotKeyBound (key, out View? previouslyBoundView) ?? false)
  593. {
  594. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  595. }
  596. #endif
  597. return InvokeCommands<KeyBinding> (binding.Commands, binding);
  598. }
  599. /// <summary>
  600. /// Invokes the Commands bound to <paramref name="hotKey"/>.
  601. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  602. /// </summary>
  603. /// <param name="hotKey">The hot key event passed.</param>
  604. /// <returns>
  605. /// <see langword="null"/> if no command was invoked; input processing should continue.
  606. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input processing
  607. /// should continue.
  608. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input processing should
  609. /// stop.
  610. /// </returns>
  611. protected bool? InvokeCommandsBoundToHotKey (Key hotKey)
  612. {
  613. if (!HotKeyBindings.TryGet (hotKey, out KeyBinding binding))
  614. {
  615. return null;
  616. }
  617. //#if DEBUG
  618. // //if (Application.KeyBindings.TryGet (key, out KeyBinding b))
  619. // //{
  620. // // Debug.WriteLine (
  621. // // $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.");
  622. // //}
  623. // // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  624. // // Scour the bindings up our View hierarchy
  625. // // to ensure that the key is not already bound to a different set of commands.
  626. // if (SuperView?.IsHotKeyBound (hotKey, out View? previouslyBoundView) ?? false)
  627. // {
  628. // Debug.WriteLine ($"WARNING: InvokeKeyBindings ({hotKey}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  629. // }
  630. //#endif
  631. return InvokeCommands<KeyBinding> (binding.Commands, binding);
  632. }
  633. #endregion Key Bindings
  634. }