View.Keyboard.cs 29 KB

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