View.Keyboard.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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>Invoked 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 virtual 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 (TitleTextFormatter == null || 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, processes a new key down event and returns <see langword="true"/> if the event was
  216. /// handled.
  217. /// </summary>
  218. /// <remarks>
  219. /// <para>
  220. /// If the view has a sub view that is focused, <see cref="NewKeyDownEvent"/> will be called on the focused view
  221. /// first.
  222. /// </para>
  223. /// <para>
  224. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyDown"/> to allow the
  225. /// view to pre-process the key press. If <see cref="OnKeyDown"/> returns <see langword="false"/>, this method then
  226. /// calls <see cref="OnInvokingKeyBindings"/> to invoke any key bindings. Then, only if no key bindings are
  227. /// handled, <see cref="OnProcessKeyDown"/> will be called allowing the view to process the key press.
  228. /// </para>
  229. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  230. /// </remarks>
  231. /// <param name="keyEvent"></param>
  232. /// <returns><see langword="true"/> if the event was handled.</returns>
  233. public bool NewKeyDownEvent (Key keyEvent)
  234. {
  235. if (!Enabled)
  236. {
  237. return false;
  238. }
  239. // By default the KeyBindingScope is View
  240. if (Focused?.NewKeyDownEvent (keyEvent) == true)
  241. {
  242. return true;
  243. }
  244. // Before (fire the cancellable event)
  245. if (OnKeyDown (keyEvent))
  246. {
  247. return true;
  248. }
  249. // During (this is what can be cancelled)
  250. InvokingKeyBindings?.Invoke (this, keyEvent);
  251. if (keyEvent.Handled)
  252. {
  253. return true;
  254. }
  255. // TODO: NewKeyDownEvent returns bool. It should be bool? so state of InvokeCommand can be reflected up stack
  256. bool? handled = OnInvokingKeyBindings (keyEvent, KeyBindingScope.HotKey | KeyBindingScope.Focused);
  257. if (handled is { } && (bool)handled)
  258. {
  259. return true;
  260. }
  261. // TODO: The below is not right. OnXXX handlers are supposed to fire the events.
  262. // TODO: But I've moved it outside of the v-function to test something.
  263. // After (fire the cancellable event)
  264. // fire event
  265. ProcessKeyDown?.Invoke (this, keyEvent);
  266. if (!keyEvent.Handled && OnProcessKeyDown (keyEvent))
  267. {
  268. return true;
  269. }
  270. return keyEvent.Handled;
  271. }
  272. /// <summary>
  273. /// Low-level API called when the user presses a key, allowing a view to pre-process the key down event. This is
  274. /// called from <see cref="NewKeyDownEvent"/> before <see cref="OnInvokingKeyBindings"/>.
  275. /// </summary>
  276. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  277. /// <returns>
  278. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  279. /// and no other view should see it.
  280. /// </returns>
  281. /// <remarks>
  282. /// <para>
  283. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  284. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  285. /// </para>
  286. /// <para>Fires the <see cref="KeyDown"/> event.</para>
  287. /// </remarks>
  288. public virtual bool OnKeyDown (Key keyEvent)
  289. {
  290. // fire event
  291. KeyDown?.Invoke (this, keyEvent);
  292. return keyEvent.Handled;
  293. }
  294. /// <summary>
  295. /// Invoked when the user presses a key, allowing subscribers to pre-process the key down event. This is fired
  296. /// from <see cref="OnKeyDown"/> before <see cref="OnInvokingKeyBindings"/>. Set <see cref="Key.Handled"/> to true to
  297. /// stop the key from being processed by other views.
  298. /// </summary>
  299. /// <remarks>
  300. /// <para>
  301. /// Not all terminals support key distinct up notifications, Applications should avoid depending on distinct
  302. /// KeyUp events.
  303. /// </para>
  304. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  305. /// </remarks>
  306. public event EventHandler<Key>? KeyDown;
  307. /// <summary>
  308. /// Low-level API called when the user presses a key, allowing views do things during key down events. This is
  309. /// called from <see cref="NewKeyDownEvent"/> after <see cref="OnInvokingKeyBindings"/>.
  310. /// </summary>
  311. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  312. /// <returns>
  313. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  314. /// and no other view should see it.
  315. /// </returns>
  316. /// <remarks>
  317. /// <para>
  318. /// Override <see cref="OnProcessKeyDown"/> to override the behavior of how the base class processes key down
  319. /// events.
  320. /// </para>
  321. /// <para>
  322. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  323. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  324. /// </para>
  325. /// <para>Fires the <see cref="ProcessKeyDown"/> event.</para>
  326. /// <para>
  327. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  328. /// KeyUp events.
  329. /// </para>
  330. /// </remarks>
  331. public virtual bool OnProcessKeyDown (Key keyEvent)
  332. {
  333. //ProcessKeyDown?.Invoke (this, keyEvent);
  334. return keyEvent.Handled;
  335. }
  336. /// <summary>
  337. /// Invoked when the user presses a key, allowing subscribers to do things during key down events. Set
  338. /// <see cref="Key.Handled"/> to true to stop the key from being processed by other views. Invoked after
  339. /// <see cref="KeyDown"/> and before <see cref="InvokingKeyBindings"/>.
  340. /// </summary>
  341. /// <remarks>
  342. /// <para>
  343. /// SubViews can use the <see cref="ProcessKeyDown"/> of their super view override the default behavior of when
  344. /// key bindings are invoked.
  345. /// </para>
  346. /// <para>
  347. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  348. /// KeyUp events.
  349. /// </para>
  350. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  351. /// </remarks>
  352. public event EventHandler<Key>? ProcessKeyDown;
  353. #endregion KeyDown Event
  354. #region KeyUp Event
  355. /// <summary>
  356. /// If the view is enabled, processes a new key up event and returns <see langword="true"/> if the event was
  357. /// handled. Called before <see cref="NewKeyDownEvent"/>.
  358. /// </summary>
  359. /// <remarks>
  360. /// <para>
  361. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct
  362. /// KeyUp events.
  363. /// </para>
  364. /// <para>
  365. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view
  366. /// first.
  367. /// </para>
  368. /// <para>
  369. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyUp"/>, which is
  370. /// cancellable.
  371. /// </para>
  372. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  373. /// </remarks>
  374. /// <param name="keyEvent"></param>
  375. /// <returns><see langword="true"/> if the event was handled.</returns>
  376. public bool NewKeyUpEvent (Key keyEvent)
  377. {
  378. if (!Enabled)
  379. {
  380. return false;
  381. }
  382. if (Focused?.NewKeyUpEvent (keyEvent) == true)
  383. {
  384. return true;
  385. }
  386. // Before (fire the cancellable event)
  387. if (OnKeyUp (keyEvent))
  388. {
  389. return true;
  390. }
  391. // During (this is what can be cancelled)
  392. // TODO: Until there's a clear use-case, we will not define 'during' event (e.g. OnDuringKeyUp).
  393. // After (fire the cancellable event InvokingKeyBindings)
  394. // TODO: Until there's a clear use-case, we will not define an 'after' event (e.g. OnAfterKeyUp).
  395. return false;
  396. }
  397. /// <summary>Method invoked when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.</summary>
  398. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  399. /// <returns>
  400. /// <see langword="false"/> if the key stroke was not handled. <see langword="true"/> if no other view should see
  401. /// it.
  402. /// </returns>
  403. /// <remarks>
  404. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct KeyUp
  405. /// events.
  406. /// <para>
  407. /// Overrides must call into the base and return <see langword="true"/> if the base returns
  408. /// <see langword="true"/>.
  409. /// </para>
  410. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  411. /// </remarks>
  412. public virtual bool OnKeyUp (Key keyEvent)
  413. {
  414. // fire event
  415. KeyUp?.Invoke (this, keyEvent);
  416. if (keyEvent.Handled)
  417. {
  418. return true;
  419. }
  420. return false;
  421. }
  422. /// <summary>
  423. /// Invoked when a key is released. Set <see cref="Key.Handled"/> to true to stop the key up event from being processed
  424. /// by other views.
  425. /// <remarks>
  426. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on
  427. /// distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  428. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  429. /// </remarks>
  430. /// </summary>
  431. public event EventHandler<Key>? KeyUp;
  432. #endregion KeyUp Event
  433. #endregion Low-level Key handling
  434. #region Key Bindings
  435. /// <summary>Gets the key bindings for this view.</summary>
  436. public KeyBindings KeyBindings { get; internal set; } = null!;
  437. private Dictionary<Command, CommandImplementation> CommandImplementations { get; } = new ();
  438. /// <summary>
  439. /// Low-level API called when a user presses a key; invokes any key bindings set on the view. This is called
  440. /// during <see cref="NewKeyDownEvent"/> after <see cref="OnKeyDown"/> has returned.
  441. /// </summary>
  442. /// <remarks>
  443. /// <para>Fires the <see cref="InvokingKeyBindings"/> event.</para>
  444. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  445. /// </remarks>
  446. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  447. /// <param name="scope">The scope.</param>
  448. /// <returns>
  449. /// <see langword="null"/> if no event was raised; input proessing should continue.
  450. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input proessing should continue.
  451. /// <see langword="true"/> if the event was raised and handled (or cancelled); input proessing should stop.
  452. /// </returns>
  453. public virtual bool? OnInvokingKeyBindings (Key keyEvent, KeyBindingScope scope)
  454. {
  455. // fire event only if there's a hotkey binding for the key
  456. if (KeyBindings.TryGet (keyEvent, scope, out KeyBinding kb))
  457. {
  458. InvokingKeyBindings?.Invoke (this, keyEvent);
  459. if (keyEvent.Handled)
  460. {
  461. return true;
  462. }
  463. }
  464. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  465. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  466. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  467. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  468. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  469. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  470. bool? handled = InvokeKeyBindings (keyEvent, scope);
  471. if (handled is { } && (bool)handled)
  472. {
  473. // Stop processing if any key binding handled the key.
  474. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  475. return true;
  476. }
  477. if (Margin is { } && ProcessAdornmentKeyBindings (Margin, keyEvent, scope, ref handled))
  478. {
  479. return true;
  480. }
  481. if (Padding is { } && ProcessAdornmentKeyBindings (Padding, keyEvent, scope, ref handled))
  482. {
  483. return true;
  484. }
  485. if (Border is { } && ProcessAdornmentKeyBindings (Border, keyEvent, scope, ref handled))
  486. {
  487. return true;
  488. }
  489. if (ProcessSubViewKeyBindings (keyEvent, scope, ref handled))
  490. {
  491. return true;
  492. }
  493. return handled;
  494. }
  495. private bool ProcessAdornmentKeyBindings (Adornment adornment, Key keyEvent, KeyBindingScope scope, ref bool? handled)
  496. {
  497. bool? adornmentHandled = adornment.OnInvokingKeyBindings (keyEvent, scope);
  498. if (adornmentHandled is true)
  499. {
  500. return true;
  501. }
  502. if (adornment?.Subviews is null)
  503. {
  504. return false;
  505. }
  506. foreach (View subview in adornment.Subviews)
  507. {
  508. bool? subViewHandled = subview.OnInvokingKeyBindings (keyEvent, scope);
  509. if (subViewHandled is { })
  510. {
  511. handled = subViewHandled;
  512. if ((bool)subViewHandled)
  513. {
  514. return true;
  515. }
  516. }
  517. }
  518. return false;
  519. }
  520. private bool ProcessSubViewKeyBindings (Key keyEvent, KeyBindingScope scope, ref bool? handled, bool invoke = true)
  521. {
  522. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  523. foreach (View subview in Subviews)
  524. {
  525. if (subview == Focused)
  526. {
  527. continue;
  528. }
  529. if (subview.KeyBindings.TryGet (keyEvent, scope, out KeyBinding binding))
  530. {
  531. if (binding.Scope == KeyBindingScope.Focused && !subview.HasFocus)
  532. {
  533. continue;
  534. }
  535. if (!invoke)
  536. {
  537. return true;
  538. }
  539. bool? subViewHandled = subview.OnInvokingKeyBindings (keyEvent, scope);
  540. if (subViewHandled is { })
  541. {
  542. handled = subViewHandled;
  543. if ((bool)subViewHandled)
  544. {
  545. return true;
  546. }
  547. }
  548. }
  549. bool recurse = subview.ProcessSubViewKeyBindings (keyEvent, scope, ref handled, invoke);
  550. if (recurse || (handled is { } && (bool)handled))
  551. {
  552. return true;
  553. }
  554. }
  555. return false;
  556. }
  557. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  558. // TODO: A better approach would be to have Application hold a list of bound Hotkeys, similar to
  559. // TODO: how Application holds a list of Application Scoped key bindings and then check that list.
  560. /// <summary>
  561. /// Returns true if Key is bound in this view hierarchy. For debugging
  562. /// </summary>
  563. /// <param name="key">The key to test.</param>
  564. /// <param name="boundView">Returns the view the key is bound to.</param>
  565. /// <returns></returns>
  566. public bool IsHotKeyKeyBound (Key key, out View? boundView)
  567. {
  568. // recurse through the subviews to find the views that has the key bound
  569. boundView = null;
  570. foreach (View subview in Subviews)
  571. {
  572. if (subview.KeyBindings.TryGet (key, KeyBindingScope.HotKey, out _))
  573. {
  574. boundView = subview;
  575. return true;
  576. }
  577. if (subview.IsHotKeyKeyBound (key, out boundView))
  578. {
  579. return true;
  580. }
  581. }
  582. return false;
  583. }
  584. /// <summary>
  585. /// Raised when a key is pressed that may be mapped to a key binding. Set <see cref="Key.Handled"/> to true to
  586. /// stop the key from being processed by other views.
  587. /// </summary>
  588. public event EventHandler<Key>? InvokingKeyBindings;
  589. /// <summary>
  590. /// Invokes any binding that is registered on this <see cref="View"/> and matches the <paramref name="key"/>
  591. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  592. /// </summary>
  593. /// <param name="key">The key event passed.</param>
  594. /// <param name="scope">The scope.</param>
  595. /// <returns>
  596. /// <see langword="null"/> if no command was invoked; input proessing should continue.
  597. /// <see langword="false"/> if at least one command was invoked and was not handled (or cancelled); input proessing should continue.
  598. /// <see langword="true"/> if at least one command was invoked and handled (or cancelled); input proessing should stop.
  599. /// </returns>
  600. protected bool? InvokeKeyBindings (Key key, KeyBindingScope scope)
  601. {
  602. bool? toReturn = null;
  603. if (!KeyBindings.TryGet (key, scope, out KeyBinding binding))
  604. {
  605. return null;
  606. }
  607. #if DEBUG
  608. // TODO: Determine if App scope bindings should be fired first or last (currently last).
  609. if (Application.KeyBindings.TryGet (key, KeyBindingScope.Focused | KeyBindingScope.HotKey, out KeyBinding b))
  610. {
  611. //var boundView = views [0];
  612. //var commandBinding = boundView.KeyBindings.Get (key);
  613. Debug.WriteLine (
  614. $"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command."); //{commandBinding.Commands [0]}: {boundView}.");
  615. }
  616. // TODO: This is a "prototype" debug check. It may be too annoying vs. useful.
  617. // Scour the bindings up our View hierarchy
  618. // to ensure that the key is not already bound to a different set of commands.
  619. if (SuperView?.IsHotKeyKeyBound (key, out View? previouslyBoundView) ?? false)
  620. {
  621. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  622. }
  623. #endif
  624. return InvokeCommands (binding.Commands, key, binding);
  625. foreach (Command command in binding.Commands)
  626. {
  627. if (!CommandImplementations.ContainsKey (command))
  628. {
  629. throw new NotSupportedException (
  630. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by this View ({GetType ().Name})"
  631. );
  632. }
  633. // each command has its own return value
  634. bool? thisReturn = InvokeCommand (command, key, binding);
  635. // if we haven't got anything yet, the current command result should be used
  636. toReturn ??= thisReturn;
  637. // if ever see a true then that's what we will return
  638. if (thisReturn ?? false)
  639. {
  640. toReturn = true;
  641. }
  642. }
  643. return toReturn;
  644. }
  645. #endregion Key Bindings
  646. }