ViewKeyboard.cs 31 KB

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