Shortcut.cs 27 KB

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