Shortcut.cs 26 KB

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