Shortcut.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. namespace Terminal.Gui;
  2. /// <summary>
  3. /// Displays a command, help text, and a key binding. When the key specified by <see cref="Key"/> is pressed, the
  4. /// command will be invoked. Useful for
  5. /// displaying a command in <see cref="Bar"/> such as a
  6. /// menu, toolbar, or status bar.
  7. /// </summary>
  8. /// <remarks>
  9. /// <para>
  10. /// The following user actions will invoke the <see cref="Command.Accept"/>, causing the
  11. /// <see cref="View.Accept"/> event to be fired:
  12. /// - Clicking on the <see cref="Shortcut"/>.
  13. /// - Pressing the key specified by <see cref="Key"/>.
  14. /// - Pressing the HotKey specified by <see cref="CommandView"/>.
  15. /// </para>
  16. /// <para>
  17. /// If <see cref="KeyBindingScope"/> is <see cref="KeyBindingScope.Application"/>, <see cref="Key"/> will invoked
  18. /// <see cref="Command.Accept"/>
  19. /// command regardless of what View has focus, enabling an application-wide keyboard shortcut.
  20. /// </para>
  21. /// <para>
  22. /// By default, a Shortcut displays the command text on the left side, the help text in the middle, and the key
  23. /// binding on the
  24. /// right side. Set <see cref="AlignmentModes"/> to <see cref="AlignmentModes.EndToStart"/> to reverse the order.
  25. /// </para>
  26. /// <para>
  27. /// The command text can be set by setting the <see cref="CommandView"/>'s Text property or by setting
  28. /// <see cref="View.Title"/>.
  29. /// </para>
  30. /// <para>
  31. /// The help text can be set by setting the <see cref="HelpText"/> property or by setting <see cref="View.Text"/>.
  32. /// </para>
  33. /// <para>
  34. /// The key text is set by setting the <see cref="Key"/> property.
  35. /// If the <see cref="Key"/> is <see cref="Key.Empty"/>, the <see cref="Key"/> text is not displayed.
  36. /// </para>
  37. /// </remarks>
  38. public class Shortcut : View, IOrientation, IDesignable
  39. {
  40. /// <summary>
  41. /// Creates a new instance of <see cref="Shortcut"/>.
  42. /// </summary>
  43. /// <remarks>
  44. /// <para>
  45. /// This is a helper API that mimics the V1 API for creating StatusItems.
  46. /// </para>
  47. /// </remarks>
  48. /// <param name="key"></param>
  49. /// <param name="commandText"></param>
  50. /// <param name="action"></param>
  51. /// <param name="helpText"></param>
  52. public Shortcut (Key key, string commandText, Action action, string helpText = null)
  53. {
  54. Id = "_shortcut";
  55. HighlightStyle = HighlightStyle.Pressed;
  56. Highlight += Shortcut_Highlight;
  57. CanFocus = true;
  58. Width = GetWidthDimAuto ();
  59. Height = Dim.Auto (DimAutoStyle.Content, 1);
  60. _orientationHelper = new (this);
  61. _orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
  62. _orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
  63. AddCommand (Command.HotKey, ctx => OnAccept (ctx));
  64. AddCommand (Command.Accept, ctx => OnAccept (ctx));
  65. AddCommand (Command.Select, ctx => OnSelect (ctx));
  66. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  67. KeyBindings.Add (KeyCode.Space, Command.Select);
  68. TitleChanged += Shortcut_TitleChanged; // This needs to be set before CommandView is set
  69. CommandView = new ()
  70. {
  71. Width = Dim.Auto (),
  72. Height = Dim.Auto (1)
  73. };
  74. HelpView.Id = "_helpView";
  75. HelpView.CanFocus = false;
  76. HelpView.Text = helpText;
  77. Add (HelpView);
  78. KeyView.Id = "_keyView";
  79. KeyView.CanFocus = false;
  80. Add (KeyView);
  81. // If the user clicks anywhere on the Shortcut, other than the CommandView, invoke the Command
  82. MouseClick += Shortcut_MouseClick;
  83. HelpView.MouseClick += Subview_MouseClick;
  84. KeyView.MouseClick += Subview_MouseClick;
  85. LayoutStarted += OnLayoutStarted;
  86. Initialized += OnInitialized;
  87. if (key is null)
  88. {
  89. key = Key.Empty;
  90. }
  91. Key = key;
  92. Title = commandText;
  93. Action = action;
  94. return;
  95. void OnInitialized (object sender, EventArgs e)
  96. {
  97. SuperViewRendersLineCanvas = true;
  98. Border.Settings &= ~BorderSettings.Title;
  99. ShowHide ();
  100. // Force Width to DimAuto to calculate natural width and then set it back
  101. Dim savedDim = Width;
  102. Width = GetWidthDimAuto ();
  103. _minimumDimAutoWidth = Frame.Width;
  104. Width = savedDim;
  105. SetCommandViewDefaultLayout ();
  106. SetHelpViewDefaultLayout ();
  107. SetKeyViewDefaultLayout ();
  108. SetColors ();
  109. }
  110. // Helper to set Width consistently
  111. Dim GetWidthDimAuto ()
  112. {
  113. // TODO: PosAlign.CalculateMinDimension is a hack. Need to figure out a better way of doing this.
  114. return Dim.Auto (
  115. DimAutoStyle.Content,
  116. Dim.Func (() => PosAlign.CalculateMinDimension (0, Subviews, Dimension.Width)),
  117. Dim.Func (() => PosAlign.CalculateMinDimension (0, Subviews, Dimension.Width)));
  118. }
  119. }
  120. /// <summary>
  121. /// Creates a new instance of <see cref="Shortcut"/>.
  122. /// </summary>
  123. public Shortcut () : this (Key.Empty, string.Empty, null) { }
  124. private readonly OrientationHelper _orientationHelper;
  125. private AlignmentModes _alignmentModes = AlignmentModes.StartToEnd | AlignmentModes.IgnoreFirstOrLast;
  126. // This is used to calculate the minimum width of the Shortcut when the width is NOT Dim.Auto
  127. private int? _minimumDimAutoWidth;
  128. private Color? _savedForeColor;
  129. /// <inheritdoc/>
  130. public bool EnableForDesign ()
  131. {
  132. Title = "_Shortcut";
  133. HelpText = "Shortcut help";
  134. Key = Key.F1;
  135. return true;
  136. }
  137. /// <summary>
  138. /// Gets or sets the <see cref="AlignmentModes"/> for this <see cref="Shortcut"/>.
  139. /// </summary>
  140. /// <remarks>
  141. /// <para>
  142. /// The default is <see cref="AlignmentModes.StartToEnd"/>. This means that the CommandView will be on the left,
  143. /// HelpView in the middle, and KeyView on the right.
  144. /// </para>
  145. /// </remarks>
  146. public AlignmentModes AlignmentModes
  147. {
  148. get => _alignmentModes;
  149. set
  150. {
  151. _alignmentModes = value;
  152. SetCommandViewDefaultLayout ();
  153. SetHelpViewDefaultLayout ();
  154. SetKeyViewDefaultLayout ();
  155. }
  156. }
  157. /// <inheritdoc/>
  158. protected override void Dispose (bool disposing)
  159. {
  160. if (disposing)
  161. {
  162. if (CommandView?.IsAdded == false)
  163. {
  164. CommandView.Dispose ();
  165. }
  166. if (HelpView?.IsAdded == false)
  167. {
  168. HelpView.Dispose ();
  169. }
  170. if (KeyView?.IsAdded == false)
  171. {
  172. KeyView.Dispose ();
  173. }
  174. }
  175. base.Dispose (disposing);
  176. }
  177. // When one of the subviews is "empty" we don't want to show it. So we
  178. // Use Add/Remove. We need to be careful to add them in the right order
  179. // so Pos.Align works correctly.
  180. internal void ShowHide ()
  181. {
  182. RemoveAll ();
  183. if (CommandView.Visible)
  184. {
  185. Add (CommandView);
  186. }
  187. if (HelpView.Visible && !string.IsNullOrEmpty (HelpView.Text))
  188. {
  189. Add (HelpView);
  190. }
  191. if (KeyView.Visible && Key != Key.Empty)
  192. {
  193. Add (KeyView);
  194. }
  195. }
  196. private Thickness GetMarginThickness ()
  197. {
  198. if (Orientation == Orientation.Vertical)
  199. {
  200. return new (1, 0, 1, 0);
  201. }
  202. return new (1, 0, 1, 0);
  203. }
  204. // When layout starts, we need to adjust the layout of the HelpView and KeyView
  205. private void OnLayoutStarted (object sender, LayoutEventArgs e)
  206. {
  207. if (Width is DimAuto widthAuto)
  208. {
  209. _minimumDimAutoWidth = Frame.Width;
  210. }
  211. else
  212. {
  213. if (string.IsNullOrEmpty (HelpView.Text))
  214. {
  215. return;
  216. }
  217. int currentWidth = Frame.Width;
  218. // If our width is smaller than the natural width then reduce width of HelpView first.
  219. // Then KeyView.
  220. // Don't ever reduce CommandView (it should spill).
  221. // When Horizontal, Key is first, then Help, then Command.
  222. // When Vertical, Command is first, then Help, then Key.
  223. // BUGBUG: This does not do what the above says.
  224. // TODO: Add Unit tests for this.
  225. if (currentWidth < _minimumDimAutoWidth)
  226. {
  227. int delta = _minimumDimAutoWidth.Value - currentWidth;
  228. int maxHelpWidth = int.Max (0, HelpView.Text.GetColumns () + Margin.Thickness.Horizontal - delta);
  229. switch (maxHelpWidth)
  230. {
  231. case 0:
  232. // Hide HelpView
  233. HelpView.Visible = false;
  234. HelpView.X = 0;
  235. break;
  236. case 1:
  237. // Scrunch it by removing margins
  238. HelpView.Margin.Thickness = new (0, 0, 0, 0);
  239. break;
  240. case 2:
  241. // Scrunch just the right margin
  242. Thickness t = GetMarginThickness ();
  243. HelpView.Margin.Thickness = new (t.Right, t.Top, t.Left - 1, t.Bottom);
  244. break;
  245. default:
  246. // Default margin
  247. HelpView.Margin.Thickness = GetMarginThickness ();
  248. break;
  249. }
  250. if (maxHelpWidth > 0)
  251. {
  252. HelpView.X = Pos.Align (Alignment.End, AlignmentModes);
  253. // Leverage Dim.Auto's max:
  254. HelpView.Width = Dim.Auto (DimAutoStyle.Text, maximumContentDim: maxHelpWidth);
  255. HelpView.Visible = true;
  256. }
  257. }
  258. else
  259. {
  260. // Reset to default
  261. //SetCommandViewDefaultLayout();
  262. SetHelpViewDefaultLayout ();
  263. //SetKeyViewDefaultLayout ();
  264. }
  265. }
  266. }
  267. private bool? OnSelect (CommandContext ctx)
  268. {
  269. if (CommandView.GetSupportedCommands ().Contains (Command.Select))
  270. {
  271. return CommandView.InvokeCommand (Command.Select, ctx.Key, ctx.KeyBinding);
  272. }
  273. return false;
  274. }
  275. private void Shortcut_Highlight (object sender, CancelEventArgs<HighlightStyle> e)
  276. {
  277. if (e.CurrentValue.HasFlag (HighlightStyle.Pressed))
  278. {
  279. if (!_savedForeColor.HasValue)
  280. {
  281. _savedForeColor = base.ColorScheme.Normal.Foreground;
  282. }
  283. var cs = new ColorScheme (base.ColorScheme)
  284. {
  285. Normal = new (ColorScheme.Normal.Foreground.GetHighlightColor (), base.ColorScheme.Normal.Background)
  286. };
  287. base.ColorScheme = cs;
  288. }
  289. if (e.CurrentValue == HighlightStyle.None && _savedForeColor.HasValue)
  290. {
  291. var cs = new ColorScheme (base.ColorScheme)
  292. {
  293. Normal = new (_savedForeColor.Value, base.ColorScheme.Normal.Background)
  294. };
  295. base.ColorScheme = cs;
  296. }
  297. SuperView?.SetNeedsDisplay ();
  298. e.Cancel = true;
  299. }
  300. private void Shortcut_MouseClick (object sender, MouseEventEventArgs e)
  301. {
  302. // When the Shortcut is clicked, we want to invoke the Command and Set focus
  303. var view = sender as View;
  304. if (!e.Handled)
  305. {
  306. // If the subview (likely CommandView) didn't handle the mouse click, invoke the command.
  307. e.Handled = InvokeCommand (Command.Accept) == true;
  308. }
  309. if (CanFocus)
  310. {
  311. SetFocus ();
  312. }
  313. }
  314. private void Subview_MouseClick (object sender, MouseEventEventArgs e)
  315. {
  316. // TODO: Remove. This does nothing.
  317. }
  318. #region IOrientation members
  319. /// <summary>
  320. /// Gets or sets the <see cref="Orientation"/> for this <see cref="Bar"/>. The default is
  321. /// <see cref="Orientation.Horizontal"/>.
  322. /// </summary>
  323. /// <remarks>
  324. /// <para>
  325. /// Horizontal orientation arranges the command, help, and key parts of each <see cref="Shortcut"/>s from right to
  326. /// left
  327. /// Vertical orientation arranges the command, help, and key parts of each <see cref="Shortcut"/>s from left to
  328. /// right.
  329. /// </para>
  330. /// </remarks>
  331. public Orientation Orientation
  332. {
  333. get => _orientationHelper.Orientation;
  334. set => _orientationHelper.Orientation = value;
  335. }
  336. /// <inheritdoc/>
  337. public event EventHandler<CancelEventArgs<Orientation>> OrientationChanging;
  338. /// <inheritdoc/>
  339. public event EventHandler<EventArgs<Orientation>> OrientationChanged;
  340. /// <summary>Called when <see cref="Orientation"/> has changed.</summary>
  341. /// <param name="newOrientation"></param>
  342. public void OnOrientationChanged (Orientation newOrientation)
  343. {
  344. // TODO: Determine what, if anything, is opinionated about the orientation.
  345. SetNeedsLayout ();
  346. }
  347. #endregion
  348. #region Command
  349. private View _commandView = new ();
  350. /// <summary>
  351. /// Gets or sets the View that displays the command text and hotkey.
  352. /// </summary>
  353. /// <remarks>
  354. /// <para>
  355. /// By default, the <see cref="View.Title"/> of the <see cref="CommandView"/> is displayed as the Shortcut's
  356. /// command text.
  357. /// </para>
  358. /// <para>
  359. /// By default, the CommandView is a <see cref="View"/> with <see cref="View.CanFocus"/> set to
  360. /// <see langword="false"/>.
  361. /// </para>
  362. /// <para>
  363. /// Setting the <see cref="CommandView"/> will add it to the <see cref="Shortcut"/> and remove any existing
  364. /// <see cref="CommandView"/>.
  365. /// </para>
  366. /// </remarks>
  367. /// <example>
  368. /// <para>
  369. /// This example illustrates how to add a <see cref="Shortcut"/> to a <see cref="StatusBar"/> that toggles the
  370. /// <see cref="Application.Force16Colors"/> property.
  371. /// </para>
  372. /// <code>
  373. /// var force16ColorsShortcut = new Shortcut
  374. /// {
  375. /// Key = Key.F6,
  376. /// KeyBindingScope = KeyBindingScope.HotKey,
  377. /// CommandView = new CheckBox { Text = "Force 16 Colors" }
  378. /// };
  379. /// var cb = force16ColorsShortcut.CommandView as CheckBox;
  380. /// cb.Checked = Application.Force16Colors;
  381. ///
  382. /// cb.Toggled += (s, e) =>
  383. /// {
  384. /// var cb = s as CheckBox;
  385. /// Application.Force16Colors = cb!.Checked == true;
  386. /// Application.Refresh();
  387. /// };
  388. /// StatusBar.Add(force16ColorsShortcut);
  389. /// </code>
  390. /// </example>
  391. public View CommandView
  392. {
  393. get => _commandView;
  394. set
  395. {
  396. if (value == null)
  397. {
  398. throw new ArgumentNullException ();
  399. }
  400. if (_commandView is { })
  401. {
  402. Remove (_commandView);
  403. _commandView?.Dispose ();
  404. }
  405. _commandView = value;
  406. _commandView.Id = "_commandView";
  407. // The default behavior is for CommandView to not get focus. I
  408. // If you want it to get focus, you need to set it.
  409. _commandView.CanFocus = false;
  410. _commandView.HotKeyChanged += (s, e) =>
  411. {
  412. if (e.NewKey != Key.Empty)
  413. {
  414. // Add it
  415. AddKeyBindingsForHotKey (e.OldKey, e.NewKey);
  416. }
  417. };
  418. _commandView.HotKeySpecifier = new ('_');
  419. Title = _commandView.Text;
  420. SetCommandViewDefaultLayout ();
  421. SetHelpViewDefaultLayout ();
  422. SetKeyViewDefaultLayout ();
  423. ShowHide ();
  424. UpdateKeyBinding (Key.Empty);
  425. }
  426. }
  427. private void SetCommandViewDefaultLayout ()
  428. {
  429. CommandView.Margin.Thickness = GetMarginThickness ();
  430. CommandView.X = Pos.Align (Alignment.End, AlignmentModes);
  431. CommandView.Y = 0; //Pos.Center ();
  432. }
  433. private void Shortcut_TitleChanged (object sender, EventArgs<string> e)
  434. {
  435. // If the Title changes, update the CommandView text.
  436. // This is a helper to make it easier to set the CommandView text.
  437. // CommandView is public and replaceable, but this is a convenience.
  438. _commandView.Text = Title;
  439. }
  440. #endregion Command
  441. #region Help
  442. /// <summary>
  443. /// The subview that displays the help text for the command. Internal for unit testing.
  444. /// </summary>
  445. internal View HelpView { get; } = new ();
  446. private void SetHelpViewDefaultLayout ()
  447. {
  448. HelpView.Margin.Thickness = GetMarginThickness ();
  449. HelpView.X = Pos.Align (Alignment.End, AlignmentModes);
  450. HelpView.Y = 0; //Pos.Center ();
  451. HelpView.Width = Dim.Auto (DimAutoStyle.Text);
  452. HelpView.Height = CommandView?.Visible == true ? Dim.Height (CommandView) : 1;
  453. HelpView.Visible = true;
  454. HelpView.VerticalTextAlignment = Alignment.Center;
  455. }
  456. /// <summary>
  457. /// Gets or sets the help text displayed in the middle of the Shortcut. Identical in function to <see cref="HelpText"/>
  458. /// .
  459. /// </summary>
  460. public override string Text
  461. {
  462. get => HelpView?.Text;
  463. set
  464. {
  465. if (HelpView is { })
  466. {
  467. HelpView.Text = value;
  468. ShowHide ();
  469. }
  470. }
  471. }
  472. /// <summary>
  473. /// Gets or sets the help text displayed in the middle of the Shortcut.
  474. /// </summary>
  475. public string HelpText
  476. {
  477. get => HelpView?.Text;
  478. set
  479. {
  480. if (HelpView is { })
  481. {
  482. HelpView.Text = value;
  483. ShowHide ();
  484. }
  485. }
  486. }
  487. #endregion Help
  488. #region Key
  489. private Key _key = Key.Empty;
  490. /// <summary>
  491. /// Gets or sets the <see cref="Key"/> that will be bound to the <see cref="Command.Accept"/> command.
  492. /// </summary>
  493. public Key Key
  494. {
  495. get => _key;
  496. set
  497. {
  498. if (value == null)
  499. {
  500. throw new ArgumentNullException ();
  501. }
  502. Key oldKey = _key;
  503. _key = value;
  504. UpdateKeyBinding (oldKey);
  505. KeyView.Text = Key == Key.Empty ? string.Empty : $"{Key}";
  506. ShowHide ();
  507. }
  508. }
  509. private KeyBindingScope _keyBindingScope = KeyBindingScope.HotKey;
  510. /// <summary>
  511. /// Gets or sets the scope for the key binding for how <see cref="Key"/> is bound to <see cref="Command"/>.
  512. /// </summary>
  513. public KeyBindingScope KeyBindingScope
  514. {
  515. get => _keyBindingScope;
  516. set
  517. {
  518. _keyBindingScope = value;
  519. UpdateKeyBinding (Key.Empty);
  520. }
  521. }
  522. /// <summary>
  523. /// Gets the subview that displays the key. Internal for unit testing.
  524. /// </summary>
  525. internal View KeyView { get; } = new ();
  526. private int _minimumKeyTextSize;
  527. /// <summary>
  528. /// Gets or sets the minimum size of the key text. Useful for aligning the key text with other <see cref="Shortcut"/>s.
  529. /// </summary>
  530. public int MinimumKeyTextSize
  531. {
  532. get => _minimumKeyTextSize;
  533. set
  534. {
  535. if (value == _minimumKeyTextSize)
  536. {
  537. //return;
  538. }
  539. _minimumKeyTextSize = value;
  540. SetKeyViewDefaultLayout ();
  541. CommandView.SetNeedsLayout ();
  542. HelpView.SetNeedsLayout ();
  543. KeyView.SetNeedsLayout ();
  544. SetSubViewNeedsDisplay ();
  545. }
  546. }
  547. private int GetMinimumKeyViewSize () { return MinimumKeyTextSize; }
  548. private void SetKeyViewDefaultLayout ()
  549. {
  550. KeyView.Margin.Thickness = GetMarginThickness ();
  551. KeyView.X = Pos.Align (Alignment.End, AlignmentModes);
  552. KeyView.Y = 0; //Pos.Center ();
  553. KeyView.Width = Dim.Auto (DimAutoStyle.Text, Dim.Func (GetMinimumKeyViewSize));
  554. KeyView.Height = CommandView?.Visible == true ? Dim.Height (CommandView) : 1;
  555. KeyView.Visible = true;
  556. // Right align the text in the keyview
  557. KeyView.TextAlignment = Alignment.End;
  558. KeyView.VerticalTextAlignment = Alignment.Center;
  559. KeyView.KeyBindings.Clear ();
  560. }
  561. private void UpdateKeyBinding (Key oldKey)
  562. {
  563. if (Key != null)
  564. {
  565. // Disable the command view key bindings
  566. CommandView.KeyBindings.Remove (Key);
  567. CommandView.KeyBindings.Remove (CommandView.HotKey);
  568. if (KeyBindingScope.FastHasFlags (KeyBindingScope.Application))
  569. {
  570. if (oldKey != Key.Empty)
  571. {
  572. Application.KeyBindings.Remove (oldKey);
  573. }
  574. Application.KeyBindings.Remove (Key);
  575. Application.KeyBindings.Add (Key, this, Command.Accept);
  576. }
  577. else
  578. {
  579. if (oldKey != Key.Empty)
  580. {
  581. KeyBindings.Remove (oldKey);
  582. }
  583. KeyBindings.Remove (Key);
  584. KeyBindings.Add (Key, KeyBindingScope | KeyBindingScope.HotKey, Command.Accept);
  585. }
  586. }
  587. }
  588. #endregion Key
  589. #region Accept Handling
  590. /// <summary>
  591. /// Called when the <see cref="Command.Accept"/> command is received. This
  592. /// occurs
  593. /// - if the user clicks anywhere on the shortcut with the mouse
  594. /// - if the user presses Key
  595. /// - if the user presses the HotKey specified by CommandView
  596. /// - if HasFocus and the user presses Space or Enter (or any other key bound to Command.Accept).
  597. /// </summary>
  598. protected bool? OnAccept (CommandContext ctx)
  599. {
  600. var cancel = false;
  601. switch (ctx.KeyBinding?.Scope)
  602. {
  603. case KeyBindingScope.Application:
  604. cancel = base.OnAccept () == true;
  605. break;
  606. case KeyBindingScope.Focused:
  607. base.OnAccept ();
  608. // cancel if we're focused
  609. cancel = true;
  610. break;
  611. case KeyBindingScope.HotKey:
  612. cancel = base.OnAccept () == true;
  613. if (CanFocus)
  614. {
  615. SetFocus ();
  616. cancel = true;
  617. }
  618. break;
  619. default:
  620. // Mouse
  621. cancel = base.OnAccept () == true;
  622. break;
  623. }
  624. CommandView.InvokeCommand (Command.Accept, ctx.Key, ctx.KeyBinding);
  625. if (Action is { })
  626. {
  627. Action.Invoke ();
  628. // Assume if there's a subscriber to Action, it's handled.
  629. cancel = true;
  630. }
  631. return cancel;
  632. }
  633. /// <summary>
  634. /// Gets or sets the action to be invoked when the shortcut key is pressed or the shortcut is clicked on with the
  635. /// mouse.
  636. /// </summary>
  637. /// <remarks>
  638. /// Note, the <see cref="View.Accept"/> event is fired first, and if cancelled, the event will not be invoked.
  639. /// </remarks>
  640. [CanBeNull]
  641. public Action Action { get; set; }
  642. #endregion Accept Handling
  643. #region Focus
  644. /// <inheritdoc/>
  645. public override ColorScheme ColorScheme
  646. {
  647. get => base.ColorScheme;
  648. set
  649. {
  650. base.ColorScheme = value;
  651. SetColors ();
  652. }
  653. }
  654. /// <summary>
  655. /// </summary>
  656. internal void SetColors ()
  657. {
  658. // Border should match superview.
  659. Border.ColorScheme = SuperView?.ColorScheme;
  660. if (HasFocus)
  661. {
  662. // When we have focus, we invert the colors
  663. base.ColorScheme = new (base.ColorScheme)
  664. {
  665. Normal = base.ColorScheme.Focus,
  666. HotNormal = base.ColorScheme.HotFocus,
  667. HotFocus = base.ColorScheme.HotNormal,
  668. Focus = base.ColorScheme.Normal
  669. };
  670. }
  671. else
  672. {
  673. base.ColorScheme = SuperView?.ColorScheme ?? base.ColorScheme;
  674. }
  675. // Set KeyView's colors to show "hot"
  676. if (IsInitialized && base.ColorScheme is { })
  677. {
  678. var cs = new ColorScheme (base.ColorScheme)
  679. {
  680. Normal = base.ColorScheme.HotNormal,
  681. HotNormal = base.ColorScheme.Normal
  682. };
  683. KeyView.ColorScheme = cs;
  684. }
  685. }
  686. private View _lastFocusedView;
  687. /// <inheritdoc/>
  688. public override bool OnEnter (View view)
  689. {
  690. SetColors ();
  691. _lastFocusedView = view;
  692. return base.OnEnter (view);
  693. }
  694. /// <inheritdoc/>
  695. public override bool OnLeave (View view)
  696. {
  697. SetColors ();
  698. _lastFocusedView = this;
  699. return base.OnLeave (view);
  700. }
  701. #endregion Focus
  702. }