ViewKeyboard.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. using System.ComponentModel;
  2. using System.Diagnostics;
  3. namespace Terminal.Gui;
  4. public partial class View
  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. HotKeySpecifier = (Rune)'_';
  13. TitleTextFormatter.HotKeyChanged += TitleTextFormatter_HotKeyChanged;
  14. // By default, the HotKey command sets the focus
  15. AddCommand (Command.HotKey, OnHotKey);
  16. // By default, the Accept command raises the Accept event
  17. AddCommand (Command.Accept, OnAccept);
  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 ()
  23. {
  24. TitleTextFormatter.HotKeyChanged -= TitleTextFormatter_HotKeyChanged;
  25. KeyBindings.Clear ();
  26. }
  27. #region HotKey Support
  28. /// <summary>
  29. /// Called when the HotKey command (<see cref="Command.HotKey"/>) is invoked. Causes this view to be focused.
  30. /// </summary>
  31. /// <returns>If <see langword="true"/> the command was canceled.</returns>
  32. private bool? OnHotKey ()
  33. {
  34. if (CanFocus)
  35. {
  36. SetFocus ();
  37. return true;
  38. }
  39. return false;
  40. }
  41. /// <summary>Invoked when the <see cref="HotKey"/> is changed.</summary>
  42. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  43. private Key _hotKey = new ();
  44. private void TitleTextFormatter_HotKeyChanged (object sender, KeyChangedEventArgs e) { HotKeyChanged?.Invoke (this, e); }
  45. /// <summary>
  46. /// Gets or sets the hot key defined for this view. Pressing the hot key on the keyboard while this view has focus will
  47. /// invoke the <see cref="Command.HotKey"/> and <see cref="Command.Accept"/> commands. <see cref="Command.HotKey"/>
  48. /// causes the view to be focused and <see cref="Command.Accept"/> does nothing. By default, the HotKey is
  49. /// automatically set to the first character of <see cref="Text"/> that is prefixed with with
  50. /// <see cref="HotKeySpecifier"/>.
  51. /// <para>
  52. /// A HotKey is a keypress that selects a visible UI item. For selecting items across <see cref="View"/>`s (e.g.a
  53. /// <see cref="Button"/> in a <see cref="Dialog"/>) the keypress must include the <see cref="Key.WithAlt"/>
  54. /// modifier. For selecting items within a View that are not Views themselves, the keypress can be key without the
  55. /// Alt modifier. For example, in a Dialog, a Button with the text of "_Text" can be selected with Alt-T. Or, in a
  56. /// <see cref="Menu"/> with "_File _Edit", Alt-F will select (show) the "_File" menu. If the "_File" menu has a
  57. /// sub-menu of "_New" `Alt-N` or `N` will ONLY select the "_New" sub-menu if the "_File" menu is already opened.
  58. /// </para>
  59. /// </summary>
  60. /// <remarks>
  61. /// <para>See <see href="../docs/keyboard.md"/> for an overview of Terminal.Gui keyboard APIs.</para>
  62. /// <para>
  63. /// This is a helper API for configuring a key binding for the hot key. By default, this property is set whenever
  64. /// <see cref="Text"/> changes.
  65. /// </para>
  66. /// <para>
  67. /// By default, when the Hot Key is set, key bindings are added for both the base key (e.g.
  68. /// <see cref="Key.D3"/>) and the Alt-shifted key (e.g. <see cref="Key.D3"/>.
  69. /// <see cref="Key.WithAlt"/>). This behavior can be overriden by overriding
  70. /// <see cref="AddKeyBindingsForHotKey"/>.
  71. /// </para>
  72. /// <para>
  73. /// By default, when the HotKey is set to <see cref="Key.A"/> through <see cref="Key.Z"/> key bindings will
  74. /// be added for both the un-shifted and shifted versions. This means if the HotKey is <see cref="Key.A"/>, key
  75. /// bindings for <c>Key.A</c> and <c>Key.A.WithShift</c> will be added. This behavior can be overriden by
  76. /// overriding <see cref="AddKeyBindingsForHotKey"/>.
  77. /// </para>
  78. /// <para>If the hot key is changed, the <see cref="HotKeyChanged"/> event is fired.</para>
  79. /// <para>Set to <see cref="Key.Empty"/> to disable the hot key.</para>
  80. /// </remarks>
  81. public virtual Key HotKey
  82. {
  83. get => _hotKey;
  84. set
  85. {
  86. if (value is null)
  87. {
  88. throw new ArgumentException (
  89. @"HotKey must not be null. Use Key.Empty to clear the HotKey.",
  90. nameof (value)
  91. );
  92. }
  93. if (AddKeyBindingsForHotKey (_hotKey, value))
  94. {
  95. // This will cause TextFormatter_HotKeyChanged to be called, firing HotKeyChanged
  96. // BUGBUG: _hotkey should be set BEFORE setting TextFormatter.HotKey
  97. _hotKey = value;
  98. TitleTextFormatter.HotKey = value;
  99. }
  100. }
  101. }
  102. /// <summary>
  103. /// Adds key bindings for the specified HotKey. Useful for views that contain multiple items that each have their
  104. /// own HotKey such as <see cref="RadioGroup"/>.
  105. /// </summary>
  106. /// <remarks>
  107. /// <para>
  108. /// By default, key bindings are added for both the base key (e.g. <see cref="Key.D3"/>) and the Alt-shifted key
  109. /// (e.g. <c>Key.D3.WithAlt</c>) This behavior can be overriden by overriding <see cref="AddKeyBindingsForHotKey"/>.
  110. /// </para>
  111. /// <para>
  112. /// By default, when <paramref name="hotKey"/> is <see cref="Key.A"/> through <see cref="Key.Z"/> key bindings
  113. /// will be added for both the un-shifted and shifted versions. This means if the HotKey is <see cref="Key.A"/>,
  114. /// key bindings for <c>Key.A</c> and <c>Key.A.WithShift</c> will be added. This behavior can be overriden by
  115. /// overriding <see cref="AddKeyBindingsForHotKey"/>.
  116. /// </para>
  117. /// </remarks>
  118. /// <param name="prevHotKey">The HotKey <paramref name="hotKey"/> is replacing. Key bindings for this key will be removed.</param>
  119. /// <param name="hotKey">The new HotKey. If <see cref="Key.Empty"/> <paramref name="prevHotKey"/> bindings will be removed.</param>
  120. /// <param name="context">Arbitrary context that can be associated with this key binding.</param>
  121. /// <returns><see langword="true"/> if the HotKey bindings were added.</returns>
  122. /// <exception cref="ArgumentException"></exception>
  123. public virtual bool AddKeyBindingsForHotKey (Key prevHotKey, Key hotKey, [CanBeNull] object context = null)
  124. {
  125. if (_hotKey == hotKey)
  126. {
  127. return false;
  128. }
  129. Key newKey = hotKey;
  130. Key baseKey = newKey.NoAlt.NoShift.NoCtrl;
  131. if (newKey != Key.Empty && (baseKey == Key.Space || Rune.IsControl (baseKey.AsRune)))
  132. {
  133. throw new ArgumentException (@$"HotKey must be a printable (and non-space) key ({hotKey}).");
  134. }
  135. if (newKey != baseKey)
  136. {
  137. if (newKey.IsCtrl)
  138. {
  139. throw new ArgumentException (@$"HotKey does not support CtrlMask ({hotKey}).");
  140. }
  141. // Strip off the shift mask if it's A...Z
  142. if (baseKey.IsKeyCodeAtoZ)
  143. {
  144. newKey = newKey.NoShift;
  145. }
  146. // Strip off the Alt mask
  147. newKey = newKey.NoAlt;
  148. }
  149. // Remove base version
  150. if (KeyBindings.TryGet (prevHotKey, out _))
  151. {
  152. KeyBindings.Remove (prevHotKey);
  153. }
  154. // Remove the Alt version
  155. if (KeyBindings.TryGet (prevHotKey.WithAlt, out _))
  156. {
  157. KeyBindings.Remove (prevHotKey.WithAlt);
  158. }
  159. if (_hotKey.IsKeyCodeAtoZ)
  160. {
  161. // Remove the shift version
  162. if (KeyBindings.TryGet (prevHotKey.WithShift, out _))
  163. {
  164. KeyBindings.Remove (prevHotKey.WithShift);
  165. }
  166. // Remove alt | shift version
  167. if (KeyBindings.TryGet (prevHotKey.WithShift.WithAlt, out _))
  168. {
  169. KeyBindings.Remove (prevHotKey.WithShift.WithAlt);
  170. }
  171. }
  172. // Add the new
  173. if (newKey != Key.Empty)
  174. {
  175. KeyBinding keyBinding = new ([Command.HotKey], KeyBindingScope.HotKey, context);
  176. // Add the base and Alt key
  177. KeyBindings.Add (newKey, keyBinding);
  178. KeyBindings.Add (newKey.WithAlt, keyBinding);
  179. // If the Key is A..Z, add ShiftMask and AltMask | ShiftMask
  180. if (newKey.IsKeyCodeAtoZ)
  181. {
  182. KeyBindings.Add (newKey.WithShift, keyBinding);
  183. KeyBindings.Add (newKey.WithShift.WithAlt, keyBinding);
  184. }
  185. }
  186. return true;
  187. }
  188. /// <summary>
  189. /// Gets or sets the specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable automatic hot key
  190. /// setting support for this View instance. The default is '\xffff'.
  191. /// </summary>
  192. public virtual Rune HotKeySpecifier
  193. {
  194. get
  195. {
  196. return TitleTextFormatter.HotKeySpecifier;
  197. }
  198. set
  199. {
  200. TitleTextFormatter.HotKeySpecifier = TextFormatter.HotKeySpecifier = value;
  201. SetHotKeyFromTitle ();
  202. }
  203. }
  204. private void SetHotKeyFromTitle ()
  205. {
  206. if (TitleTextFormatter == null || HotKeySpecifier == new Rune ('\xFFFF'))
  207. {
  208. return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
  209. }
  210. if (TextFormatter.FindHotKey (_title, HotKeySpecifier, out _, out Key hk))
  211. {
  212. if (_hotKey != hk)
  213. {
  214. HotKey = hk;
  215. }
  216. }
  217. else
  218. {
  219. HotKey = Key.Empty;
  220. }
  221. }
  222. #endregion HotKey Support
  223. #region Tab/Focus Handling
  224. // This is null, and allocated on demand.
  225. private List<View> _tabIndexes;
  226. /// <summary>Gets a list of the subviews that are <see cref="TabStop"/>s.</summary>
  227. /// <value>The tabIndexes.</value>
  228. public IList<View> TabIndexes => _tabIndexes?.AsReadOnly () ?? _empty;
  229. private int _tabIndex = -1;
  230. private int _oldTabIndex;
  231. /// <summary>
  232. /// Indicates the index of the current <see cref="View"/> from the <see cref="TabIndexes"/> list. See also:
  233. /// <seealso cref="TabStop"/>.
  234. /// </summary>
  235. public int TabIndex
  236. {
  237. get => _tabIndex;
  238. set
  239. {
  240. if (!CanFocus)
  241. {
  242. _tabIndex = -1;
  243. return;
  244. }
  245. if (SuperView?._tabIndexes is null || SuperView?._tabIndexes.Count == 1)
  246. {
  247. _tabIndex = 0;
  248. return;
  249. }
  250. if (_tabIndex == value && TabIndexes.IndexOf (this) == value)
  251. {
  252. return;
  253. }
  254. _tabIndex = value > SuperView._tabIndexes.Count - 1 ? SuperView._tabIndexes.Count - 1 :
  255. value < 0 ? 0 : value;
  256. _tabIndex = GetTabIndex (_tabIndex);
  257. if (SuperView._tabIndexes.IndexOf (this) != _tabIndex)
  258. {
  259. SuperView._tabIndexes.Remove (this);
  260. SuperView._tabIndexes.Insert (_tabIndex, this);
  261. SetTabIndex ();
  262. }
  263. }
  264. }
  265. private int GetTabIndex (int idx)
  266. {
  267. var i = 0;
  268. foreach (View v in SuperView._tabIndexes)
  269. {
  270. if (v._tabIndex == -1 || v == this)
  271. {
  272. continue;
  273. }
  274. i++;
  275. }
  276. return Math.Min (i, idx);
  277. }
  278. private void SetTabIndex ()
  279. {
  280. var i = 0;
  281. foreach (View v in SuperView._tabIndexes)
  282. {
  283. if (v._tabIndex == -1)
  284. {
  285. continue;
  286. }
  287. v._tabIndex = i;
  288. i++;
  289. }
  290. }
  291. private bool _tabStop = true;
  292. /// <summary>
  293. /// Gets or sets whether the view is a stop-point for keyboard navigation of focus. Will be <see langword="true"/>
  294. /// only if the <see cref="CanFocus"/> is also <see langword="true"/>. Set to <see langword="false"/> to prevent the
  295. /// view from being a stop-point for keyboard navigation.
  296. /// </summary>
  297. /// <remarks>
  298. /// The default keyboard navigation keys are <c>Key.Tab</c> and <c>Key>Tab.WithShift</c>. These can be changed by
  299. /// modifying the key bindings (see <see cref="KeyBindings.Add(Key, Command[])"/>) of the SuperView.
  300. /// </remarks>
  301. public bool TabStop
  302. {
  303. get => _tabStop;
  304. set
  305. {
  306. if (_tabStop == value)
  307. {
  308. return;
  309. }
  310. _tabStop = CanFocus && value;
  311. }
  312. }
  313. #endregion Tab/Focus Handling
  314. #region Low-level Key handling
  315. #region Key Down Event
  316. /// <summary>
  317. /// If the view is enabled, processes a new key down event and returns <see langword="true"/> if the event was
  318. /// handled.
  319. /// </summary>
  320. /// <remarks>
  321. /// <para>
  322. /// If the view has a sub view that is focused, <see cref="NewKeyDownEvent"/> will be called on the focused view
  323. /// first.
  324. /// </para>
  325. /// <para>
  326. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyDown"/> to allow the
  327. /// view to pre-process the key press. If <see cref="OnKeyDown"/> returns <see langword="false"/>, this method then
  328. /// calls <see cref="OnInvokingKeyBindings"/> to invoke any key bindings. Then, only if no key bindings are
  329. /// handled, <see cref="OnProcessKeyDown"/> will be called allowing the view to process the key press.
  330. /// </para>
  331. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  332. /// </remarks>
  333. /// <param name="keyEvent"></param>
  334. /// <returns><see langword="true"/> if the event was handled.</returns>
  335. public bool NewKeyDownEvent (Key keyEvent)
  336. {
  337. if (!Enabled)
  338. {
  339. return false;
  340. }
  341. // By default the KeyBindingScope is View
  342. if (Focused?.NewKeyDownEvent (keyEvent) == true)
  343. {
  344. return true;
  345. }
  346. // Before (fire the cancellable event)
  347. if (OnKeyDown (keyEvent))
  348. {
  349. return true;
  350. }
  351. // During (this is what can be cancelled)
  352. InvokingKeyBindings?.Invoke (this, keyEvent);
  353. if (keyEvent.Handled)
  354. {
  355. return true;
  356. }
  357. // TODO: NewKeyDownEvent returns bool. It should be bool? so state of InvokeCommand can be reflected up stack
  358. bool? handled = OnInvokingKeyBindings (keyEvent, KeyBindingScope.HotKey | KeyBindingScope.Focused);
  359. if (handled is { } && (bool)handled)
  360. {
  361. return true;
  362. }
  363. // TODO: The below is not right. OnXXX handlers are supposed to fire the events.
  364. // TODO: But I've moved it outside of the v-function to test something.
  365. // After (fire the cancellable event)
  366. // fire event
  367. ProcessKeyDown?.Invoke (this, keyEvent);
  368. if (!keyEvent.Handled && OnProcessKeyDown (keyEvent))
  369. {
  370. return true;
  371. }
  372. return keyEvent.Handled;
  373. }
  374. /// <summary>
  375. /// Low-level API called when the user presses a key, allowing a view to pre-process the key down event. This is
  376. /// called from <see cref="NewKeyDownEvent"/> before <see cref="OnInvokingKeyBindings"/>.
  377. /// </summary>
  378. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  379. /// <returns>
  380. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  381. /// and no other view should see it.
  382. /// </returns>
  383. /// <remarks>
  384. /// <para>
  385. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  386. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  387. /// </para>
  388. /// <para>Fires the <see cref="KeyDown"/> event.</para>
  389. /// </remarks>
  390. public virtual bool OnKeyDown (Key keyEvent)
  391. {
  392. // fire event
  393. KeyDown?.Invoke (this, keyEvent);
  394. return keyEvent.Handled;
  395. }
  396. /// <summary>
  397. /// Invoked when the user presses a key, allowing subscribers to pre-process the key down event. This is fired
  398. /// from <see cref="OnKeyDown"/> before <see cref="OnInvokingKeyBindings"/>. Set <see cref="Key.Handled"/> to true to
  399. /// stop the key from being processed by other views.
  400. /// </summary>
  401. /// <remarks>
  402. /// <para>
  403. /// Not all terminals support key distinct up notifications, Applications should avoid depending on distinct
  404. /// KeyUp events.
  405. /// </para>
  406. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  407. /// </remarks>
  408. public event EventHandler<Key> KeyDown;
  409. /// <summary>
  410. /// Low-level API called when the user presses a key, allowing views do things during key down events. This is
  411. /// called from <see cref="NewKeyDownEvent"/> after <see cref="OnInvokingKeyBindings"/>.
  412. /// </summary>
  413. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  414. /// <returns>
  415. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  416. /// and no other view should see it.
  417. /// </returns>
  418. /// <remarks>
  419. /// <para>
  420. /// Override <see cref="OnProcessKeyDown"/> to override the behavior of how the base class processes key down
  421. /// events.
  422. /// </para>
  423. /// <para>
  424. /// For processing <see cref="HotKey"/>s and commands, use <see cref="Command"/> and
  425. /// <see cref="KeyBindings.Add(Key, Command[])"/>instead.
  426. /// </para>
  427. /// <para>Fires the <see cref="ProcessKeyDown"/> event.</para>
  428. /// <para>
  429. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  430. /// KeyUp events.
  431. /// </para>
  432. /// </remarks>
  433. public virtual bool OnProcessKeyDown (Key keyEvent)
  434. {
  435. //ProcessKeyDown?.Invoke (this, keyEvent);
  436. return keyEvent.Handled;
  437. }
  438. /// <summary>
  439. /// Invoked when the user presses a key, allowing subscribers to do things during key down events. Set
  440. /// <see cref="Key.Handled"/> to true to stop the key from being processed by other views. Invoked after
  441. /// <see cref="KeyDown"/> and before <see cref="InvokingKeyBindings"/>.
  442. /// </summary>
  443. /// <remarks>
  444. /// <para>
  445. /// SubViews can use the <see cref="ProcessKeyDown"/> of their super view override the default behavior of when
  446. /// key bindings are invoked.
  447. /// </para>
  448. /// <para>
  449. /// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
  450. /// KeyUp events.
  451. /// </para>
  452. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  453. /// </remarks>
  454. public event EventHandler<Key> ProcessKeyDown;
  455. #endregion KeyDown Event
  456. #region KeyUp Event
  457. /// <summary>
  458. /// If the view is enabled, processes a new key up event and returns <see langword="true"/> if the event was
  459. /// handled. Called before <see cref="NewKeyDownEvent"/>.
  460. /// </summary>
  461. /// <remarks>
  462. /// <para>
  463. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct
  464. /// KeyUp events.
  465. /// </para>
  466. /// <para>
  467. /// If the view has a sub view that is focused, <see cref="NewKeyUpEvent"/> will be called on the focused view
  468. /// first.
  469. /// </para>
  470. /// <para>
  471. /// If the focused sub view does not handle the key press, this method calls <see cref="OnKeyUp"/>, which is
  472. /// cancellable.
  473. /// </para>
  474. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  475. /// </remarks>
  476. /// <param name="keyEvent"></param>
  477. /// <returns><see langword="true"/> if the event was handled.</returns>
  478. public bool NewKeyUpEvent (Key keyEvent)
  479. {
  480. if (!Enabled)
  481. {
  482. return false;
  483. }
  484. if (Focused?.NewKeyUpEvent (keyEvent) == true)
  485. {
  486. return true;
  487. }
  488. // Before (fire the cancellable event)
  489. if (OnKeyUp (keyEvent))
  490. {
  491. return true;
  492. }
  493. // During (this is what can be cancelled)
  494. // TODO: Until there's a clear use-case, we will not define 'during' event (e.g. OnDuringKeyUp).
  495. // After (fire the cancellable event InvokingKeyBindings)
  496. // TODO: Until there's a clear use-case, we will not define an 'after' event (e.g. OnAfterKeyUp).
  497. return false;
  498. }
  499. /// <summary>Method invoked when a key is released. This method is called from <see cref="NewKeyUpEvent"/>.</summary>
  500. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  501. /// <returns>
  502. /// <see langword="false"/> if the key stroke was not handled. <see langword="true"/> if no other view should see
  503. /// it.
  504. /// </returns>
  505. /// <remarks>
  506. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct KeyUp
  507. /// events.
  508. /// <para>
  509. /// Overrides must call into the base and return <see langword="true"/> if the base returns
  510. /// <see langword="true"/>.
  511. /// </para>
  512. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  513. /// </remarks>
  514. public virtual bool OnKeyUp (Key keyEvent)
  515. {
  516. // fire event
  517. KeyUp?.Invoke (this, keyEvent);
  518. if (keyEvent.Handled)
  519. {
  520. return true;
  521. }
  522. return false;
  523. }
  524. /// <summary>
  525. /// Invoked when a key is released. Set <see cref="Key.Handled"/> to true to stop the key up event from being processed
  526. /// by other views.
  527. /// <remarks>
  528. /// Not all terminals support key distinct down/up notifications, Applications should avoid depending on
  529. /// distinct KeyDown and KeyUp events and instead should use <see cref="KeyDown"/>.
  530. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  531. /// </remarks>
  532. /// </summary>
  533. public event EventHandler<Key> KeyUp;
  534. #endregion KeyUp Event
  535. #endregion Low-level Key handling
  536. #region Key Bindings
  537. /// <summary>Gets the key bindings for this view.</summary>
  538. public KeyBindings KeyBindings { get; internal set; }
  539. private Dictionary<Command, Func<CommandContext, bool?>> CommandImplementations { get; } = new ();
  540. /// <summary>
  541. /// Low-level API called when a user presses a key; invokes any key bindings set on the view. This is called
  542. /// during <see cref="NewKeyDownEvent"/> after <see cref="OnKeyDown"/> has returned.
  543. /// </summary>
  544. /// <remarks>
  545. /// <para>Fires the <see cref="InvokingKeyBindings"/> event.</para>
  546. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  547. /// </remarks>
  548. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  549. /// <param name="scope">The scope.</param>
  550. /// <returns>
  551. /// <see langword="false"/> if the key press was not handled. <see langword="true"/> if the keypress was handled
  552. /// and no other view should see it.
  553. /// </returns>
  554. public virtual bool? OnInvokingKeyBindings (Key keyEvent, KeyBindingScope scope)
  555. {
  556. // fire event only if there's an hotkey binding for the key
  557. if (KeyBindings.TryGet (keyEvent, scope, out KeyBinding kb))
  558. {
  559. InvokingKeyBindings?.Invoke (this, keyEvent);
  560. if (keyEvent.Handled)
  561. {
  562. return true;
  563. }
  564. }
  565. // * If no key binding was found, `InvokeKeyBindings` returns `null`.
  566. // Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  567. // * If key bindings were found, but none handled the key (all `Command`s returned `false`),
  568. // `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
  569. // * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
  570. // `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
  571. bool? handled = InvokeKeyBindings (keyEvent, scope);
  572. if (handled is { } && (bool)handled)
  573. {
  574. // Stop processing if any key binding handled the key.
  575. // DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
  576. return true;
  577. }
  578. if (Margin is { } && ProcessAdornmentKeyBindings (Margin, keyEvent, scope, ref handled))
  579. {
  580. return true;
  581. }
  582. if (Padding is { } && ProcessAdornmentKeyBindings (Padding, keyEvent, scope, ref handled))
  583. {
  584. return true;
  585. }
  586. if (Border is { } && ProcessAdornmentKeyBindings (Border, keyEvent, scope, ref handled))
  587. {
  588. return true;
  589. }
  590. if (ProcessSubViewKeyBindings (keyEvent, scope, ref handled))
  591. {
  592. return true;
  593. }
  594. return handled;
  595. }
  596. private bool ProcessAdornmentKeyBindings (Adornment adornment, Key keyEvent, KeyBindingScope scope, ref bool? handled)
  597. {
  598. foreach (View subview in adornment?.Subviews)
  599. {
  600. handled = subview.OnInvokingKeyBindings (keyEvent, scope);
  601. if (handled is { } && (bool)handled)
  602. {
  603. return true;
  604. }
  605. }
  606. return false;
  607. }
  608. private bool ProcessSubViewKeyBindings (Key keyEvent, KeyBindingScope scope, ref bool? handled, bool invoke = true)
  609. {
  610. // Now, process any key bindings in the subviews that are tagged to KeyBindingScope.HotKey.
  611. foreach (View subview in Subviews)
  612. {
  613. if (subview.KeyBindings.TryGet (keyEvent, scope, out KeyBinding binding))
  614. {
  615. if (binding.Scope == KeyBindingScope.Focused && !subview.HasFocus)
  616. {
  617. continue;
  618. }
  619. if (!invoke)
  620. {
  621. return true;
  622. }
  623. handled = subview.OnInvokingKeyBindings (keyEvent, scope);
  624. if (handled is { } && (bool)handled)
  625. {
  626. return true;
  627. }
  628. }
  629. bool recurse = subview.ProcessSubViewKeyBindings (keyEvent, scope, ref handled, invoke);
  630. if (recurse || (handled is { } && (bool)handled))
  631. {
  632. return true;
  633. }
  634. }
  635. return false;
  636. }
  637. // TODO: This is a "prototype" debug check. It may be too annyoing vs. useful.
  638. // TODO: A better approach would be have Application hold a list of bound Hotkeys, similar to
  639. // TODO: how Application holds a list of Application Scoped key bindings and then check that list.
  640. /// <summary>
  641. /// Returns true if Key is bound in this view heirarchy. For debugging
  642. /// </summary>
  643. /// <param name="key">The key to test.</param>
  644. /// <param name="boundView">Returns the view the key is bound to.</param>
  645. /// <returns></returns>
  646. public bool IsHotKeyKeyBound (Key key, out View boundView)
  647. {
  648. // recurse through the subviews to find the views that has the key bound
  649. boundView = null;
  650. foreach (View subview in Subviews)
  651. {
  652. if (subview.KeyBindings.TryGet (key, KeyBindingScope.HotKey, out _))
  653. {
  654. boundView = subview;
  655. return true;
  656. }
  657. if (subview.IsHotKeyKeyBound (key, out boundView))
  658. {
  659. return true;
  660. }
  661. }
  662. return false;
  663. }
  664. /// <summary>
  665. /// Invoked when a key is pressed that may be mapped to a key binding. Set <see cref="Key.Handled"/> to true to
  666. /// stop the key from being processed by other views.
  667. /// </summary>
  668. public event EventHandler<Key> InvokingKeyBindings;
  669. /// <summary>
  670. /// Invokes any binding that is registered on this <see cref="View"/> and matches the <paramref name="key"/>
  671. /// <para>See <see href="../docs/keyboard.md">for an overview of Terminal.Gui keyboard APIs.</see></para>
  672. /// </summary>
  673. /// <param name="key">The key event passed.</param>
  674. /// <param name="scope">The scope.</param>
  675. /// <returns>
  676. /// <see langword="null"/> if no command was bound the <paramref name="key"/>. <see langword="true"/> if
  677. /// commands were invoked and at least one handled the command. <see langword="false"/> if commands were invoked and at
  678. /// none handled the command.
  679. /// </returns>
  680. protected bool? InvokeKeyBindings (Key key, KeyBindingScope scope)
  681. {
  682. bool? toReturn = null;
  683. if (!KeyBindings.TryGet (key, scope, out KeyBinding binding))
  684. {
  685. return null;
  686. }
  687. #if DEBUG
  688. // TODO: Determine if App scope bindings should be fired first or last (currently last).
  689. if (Application.TryGetKeyBindings (key, out List<View> views))
  690. {
  691. var boundView = views [0];
  692. var commandBinding = boundView.KeyBindings.Get (key);
  693. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - An Application scope binding exists for this key. The registered view will not invoke Command.{commandBinding.Commands [0]}: {boundView}.");
  694. }
  695. // TODO: This is a "prototype" debug check. It may be too annyoing vs. useful.
  696. // Scour the bindings up our View heirarchy
  697. // to ensure that the key is not already bound to a different set of commands.
  698. if (SuperView?.IsHotKeyKeyBound (key, out View previouslyBoundView) ?? false)
  699. {
  700. Debug.WriteLine ($"WARNING: InvokeKeyBindings ({key}) - A subview or peer has bound this Key and will not see it: {previouslyBoundView}.");
  701. }
  702. #endif
  703. foreach (Command command in binding.Commands)
  704. {
  705. if (!CommandImplementations.ContainsKey (command))
  706. {
  707. throw new NotSupportedException (
  708. @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by this View ({GetType ().Name})"
  709. );
  710. }
  711. // each command has its own return value
  712. bool? thisReturn = InvokeCommand (command, key, binding);
  713. // if we haven't got anything yet, the current command result should be used
  714. toReturn ??= thisReturn;
  715. // if ever see a true then that's what we will return
  716. if (thisReturn ?? false)
  717. {
  718. toReturn = true;
  719. }
  720. }
  721. return toReturn;
  722. }
  723. /// <summary>
  724. /// Invokes the specified commands.
  725. /// </summary>
  726. /// <param name="commands"></param>
  727. /// <param name="key">The key that caused the commands to be invoked, if any.</param>
  728. /// <param name="keyBinding"></param>
  729. /// <returns>
  730. /// <see langword="null"/> if no command was found.
  731. /// <see langword="true"/> if the command was invoked the command was handled.
  732. /// <see langword="false"/> if the command was invoked and the command was not handled.
  733. /// </returns>
  734. public bool? InvokeCommands (Command [] commands, [CanBeNull] Key key = null, [CanBeNull] KeyBinding? keyBinding = null)
  735. {
  736. bool? toReturn = null;
  737. foreach (Command command in commands)
  738. {
  739. if (!CommandImplementations.ContainsKey (command))
  740. {
  741. throw new NotSupportedException (@$"{command} is not supported by ({GetType ().Name}).");
  742. }
  743. // each command has its own return value
  744. bool? thisReturn = InvokeCommand (command, key, keyBinding);
  745. // if we haven't got anything yet, the current command result should be used
  746. toReturn ??= thisReturn;
  747. // if ever see a true then that's what we will return
  748. if (thisReturn ?? false)
  749. {
  750. toReturn = true;
  751. }
  752. }
  753. return toReturn;
  754. }
  755. /// <summary>Invokes the specified command.</summary>
  756. /// <param name="command">The command to invoke.</param>
  757. /// <param name="key">The key that caused the command to be invoked, if any.</param>
  758. /// <param name="keyBinding"></param>
  759. /// <returns>
  760. /// <see langword="null"/> if no command was found. <see langword="true"/> if the command was invoked, and it
  761. /// handled the command. <see langword="false"/> if the command was invoked, and it did not handle the command.
  762. /// </returns>
  763. public bool? InvokeCommand (Command command, [CanBeNull] Key key = null, [CanBeNull] KeyBinding? keyBinding = null)
  764. {
  765. if (CommandImplementations.TryGetValue (command, out Func<CommandContext, bool?> implementation))
  766. {
  767. var context = new CommandContext (command, key, keyBinding); // Create the context here
  768. return implementation (context);
  769. }
  770. return null;
  771. }
  772. /// <summary>
  773. /// <para>
  774. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  775. /// AddCommand for each command they support.
  776. /// </para>
  777. /// <para>
  778. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  779. /// replace the old one.
  780. /// </para>
  781. /// </summary>
  782. /// <remarks>
  783. /// <para>
  784. /// This version of AddCommand is for commands that require <see cref="CommandContext"/>. Use <see cref="AddCommand(Command,Func{System.Nullable{bool}})"/>
  785. /// in cases where the command does not require a <see cref="CommandContext"/>.
  786. /// </para>
  787. /// </remarks>
  788. /// <param name="command">The command.</param>
  789. /// <param name="f">The function.</param>
  790. protected void AddCommand (Command command, Func<CommandContext, bool?> f)
  791. {
  792. CommandImplementations [command] = f;
  793. }
  794. /// <summary>
  795. /// <para>
  796. /// Sets the function that will be invoked for a <see cref="Command"/>. Views should call
  797. /// AddCommand for each command they support.
  798. /// </para>
  799. /// <para>
  800. /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
  801. /// replace the old one.
  802. /// </para>
  803. /// </summary>
  804. /// <remarks>
  805. /// <para>
  806. /// This version of AddCommand is for commands that do not require a <see cref="CommandContext"/>.
  807. /// If the command requires context, use <see cref="AddCommand(Command,Func{CommandContext,System.Nullable{bool}})"/>
  808. /// </para>
  809. /// </remarks>
  810. /// <param name="command">The command.</param>
  811. /// <param name="f">The function.</param>
  812. protected void AddCommand (Command command, Func<bool?> f)
  813. {
  814. CommandImplementations [command] = ctx => f ();
  815. }
  816. /// <summary>Returns all commands that are supported by this <see cref="View"/>.</summary>
  817. /// <returns></returns>
  818. public IEnumerable<Command> GetSupportedCommands () { return CommandImplementations.Keys; }
  819. // TODO: Add GetKeysBoundToCommand() - given a Command, return all Keys that would invoke it
  820. #endregion Key Bindings
  821. }