ViewKeyboard.cs 36 KB

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