Shortcut.cs 29 KB

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