ViewKeyboard.cs 31 KB

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