View.Keyboard.cs 27 KB

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