Shortcut.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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 => RaiseSelectEvent ());
  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 Select command.
  321. e.Handled = CommandView.InvokeCommand (Command.Accept) == true;
  322. }
  323. if (CanFocus)
  324. {
  325. SetFocus ();
  326. }
  327. }
  328. private void Subview_MouseClick (object sender, MouseEventEventArgs e)
  329. {
  330. if (!e.Handled)
  331. {
  332. // If the subview (likely CommandView) didn't handle the mouse click, invoke the command.
  333. e.Handled = InvokeCommand (Command.Accept) == true;
  334. }
  335. }
  336. #region IOrientation members
  337. /// <summary>
  338. /// Gets or sets the <see cref="Orientation"/> for this <see cref="Bar"/>. The default is
  339. /// <see cref="Orientation.Horizontal"/>.
  340. /// </summary>
  341. /// <remarks>
  342. /// <para>
  343. /// Horizontal orientation arranges the command, help, and key parts of each <see cref="Shortcut"/>s from right to
  344. /// left
  345. /// Vertical orientation arranges the command, help, and key parts of each <see cref="Shortcut"/>s from left to
  346. /// right.
  347. /// </para>
  348. /// </remarks>
  349. public Orientation Orientation
  350. {
  351. get => _orientationHelper.Orientation;
  352. set => _orientationHelper.Orientation = value;
  353. }
  354. /// <inheritdoc/>
  355. public event EventHandler<CancelEventArgs<Orientation>> OrientationChanging;
  356. /// <inheritdoc/>
  357. public event EventHandler<EventArgs<Orientation>> OrientationChanged;
  358. /// <summary>Called when <see cref="Orientation"/> has changed.</summary>
  359. /// <param name="newOrientation"></param>
  360. public void OnOrientationChanged (Orientation newOrientation)
  361. {
  362. // TODO: Determine what, if anything, is opinionated about the orientation.
  363. SetNeedsLayout ();
  364. }
  365. #endregion
  366. #region Command
  367. private View _commandView = new ();
  368. /// <summary>
  369. /// Gets or sets the View that displays the command text and hotkey.
  370. /// </summary>
  371. /// <remarks>
  372. /// <para>
  373. /// By default, the <see cref="View.Title"/> of the <see cref="CommandView"/> is displayed as the Shortcut's
  374. /// command text.
  375. /// </para>
  376. /// <para>
  377. /// By default, the CommandView is a <see cref="View"/> with <see cref="View.CanFocus"/> set to
  378. /// <see langword="false"/>.
  379. /// </para>
  380. /// <para>
  381. /// Setting the <see cref="CommandView"/> will add it to the <see cref="Shortcut"/> and remove any existing
  382. /// <see cref="CommandView"/>.
  383. /// </para>
  384. /// </remarks>
  385. /// <example>
  386. /// <para>
  387. /// This example illustrates how to add a <see cref="Shortcut"/> to a <see cref="StatusBar"/> that toggles the
  388. /// <see cref="Application.Force16Colors"/> property.
  389. /// </para>
  390. /// <code>
  391. /// var force16ColorsShortcut = new Shortcut
  392. /// {
  393. /// Key = Key.F6,
  394. /// KeyBindingScope = KeyBindingScope.HotKey,
  395. /// CommandView = new CheckBox { Text = "Force 16 Colors" }
  396. /// };
  397. /// var cb = force16ColorsShortcut.CommandView as CheckBox;
  398. /// cb.Checked = Application.Force16Colors;
  399. ///
  400. /// cb.Toggled += (s, e) =>
  401. /// {
  402. /// var cb = s as CheckBox;
  403. /// Application.Force16Colors = cb!.Checked == true;
  404. /// Application.Refresh();
  405. /// };
  406. /// StatusBar.Add(force16ColorsShortcut);
  407. /// </code>
  408. /// </example>
  409. public View CommandView
  410. {
  411. get => _commandView;
  412. set
  413. {
  414. if (value == null)
  415. {
  416. throw new ArgumentNullException ();
  417. }
  418. if (_commandView is { })
  419. {
  420. _commandView.Accept -= CommandViewOnAccept;
  421. Remove (_commandView);
  422. _commandView?.Dispose ();
  423. }
  424. _commandView = value;
  425. _commandView.Id = "_commandView";
  426. // The default behavior is for CommandView to not get focus. I
  427. // If you want it to get focus, you need to set it.
  428. _commandView.CanFocus = false;
  429. _commandView.HotKeyChanged += (s, e) =>
  430. {
  431. if (e.NewKey != Key.Empty)
  432. {
  433. // Add it
  434. AddKeyBindingsForHotKey (e.OldKey, e.NewKey);
  435. }
  436. };
  437. _commandView.HotKeySpecifier = new ('_');
  438. Title = _commandView.Text;
  439. _commandView.Accept += CommandViewOnAccept;
  440. void CommandViewOnAccept (object sender, HandledEventArgs e)
  441. {
  442. // Always eat CommandView.Accept
  443. e.Handled = true;
  444. }
  445. _commandView.Select += CommandViewOnSelect;
  446. _commandView.MouseClick += CommandViewOnMouseClick;
  447. void CommandViewOnMouseClick (object sender, MouseEventEventArgs e)
  448. {
  449. //if (!e.Handled)
  450. {
  451. // If the subview (likely CommandView) didn't handle the mouse click, invoke the command.
  452. InvokeCommand (Command.HotKey);
  453. }
  454. }
  455. void CommandViewOnSelect (object sender, HandledEventArgs e)
  456. {
  457. // Always eat CommandView.Select
  458. e.Handled = true;
  459. // AND raise our Accept event
  460. RaiseAcceptEvent ();
  461. }
  462. SetCommandViewDefaultLayout ();
  463. SetHelpViewDefaultLayout ();
  464. SetKeyViewDefaultLayout ();
  465. ShowHide ();
  466. UpdateKeyBinding (Key.Empty);
  467. }
  468. }
  469. private void SetCommandViewDefaultLayout ()
  470. {
  471. CommandView.Margin.Thickness = GetMarginThickness ();
  472. CommandView.X = Pos.Align (Alignment.End, AlignmentModes);
  473. CommandView.Y = 0; //Pos.Center ();
  474. HelpView.HighlightStyle = HighlightStyle.None;
  475. }
  476. private void Shortcut_TitleChanged (object sender, EventArgs<string> e)
  477. {
  478. // If the Title changes, update the CommandView text.
  479. // This is a helper to make it easier to set the CommandView text.
  480. // CommandView is public and replaceable, but this is a convenience.
  481. _commandView.Text = Title;
  482. }
  483. #endregion Command
  484. #region Help
  485. /// <summary>
  486. /// The subview that displays the help text for the command. Internal for unit testing.
  487. /// </summary>
  488. internal View HelpView { get; } = new ();
  489. private void SetHelpViewDefaultLayout ()
  490. {
  491. HelpView.Margin.Thickness = GetMarginThickness ();
  492. HelpView.X = Pos.Align (Alignment.End, AlignmentModes);
  493. HelpView.Y = 0; //Pos.Center ();
  494. HelpView.Width = Dim.Auto (DimAutoStyle.Text);
  495. HelpView.Height = CommandView?.Visible == true ? Dim.Height (CommandView) : 1;
  496. HelpView.Visible = true;
  497. HelpView.VerticalTextAlignment = Alignment.Center;
  498. HelpView.HighlightStyle = HighlightStyle.None;
  499. }
  500. /// <summary>
  501. /// Gets or sets the help text displayed in the middle of the Shortcut. Identical in function to <see cref="HelpText"/>
  502. /// .
  503. /// </summary>
  504. public override string Text
  505. {
  506. get => HelpView?.Text;
  507. set
  508. {
  509. if (HelpView is { })
  510. {
  511. HelpView.Text = value;
  512. ShowHide ();
  513. }
  514. }
  515. }
  516. /// <summary>
  517. /// Gets or sets the help text displayed in the middle of the Shortcut.
  518. /// </summary>
  519. public string HelpText
  520. {
  521. get => HelpView?.Text;
  522. set
  523. {
  524. if (HelpView is { })
  525. {
  526. HelpView.Text = value;
  527. ShowHide ();
  528. }
  529. }
  530. }
  531. #endregion Help
  532. #region Key
  533. private Key _key = Key.Empty;
  534. /// <summary>
  535. /// Gets or sets the <see cref="Key"/> that will be bound to the <see cref="Command.Accept"/> command.
  536. /// </summary>
  537. public Key Key
  538. {
  539. get => _key;
  540. set
  541. {
  542. if (value == null)
  543. {
  544. throw new ArgumentNullException ();
  545. }
  546. Key oldKey = _key;
  547. _key = value;
  548. UpdateKeyBinding (oldKey);
  549. KeyView.Text = Key == Key.Empty ? string.Empty : $"{Key}";
  550. ShowHide ();
  551. }
  552. }
  553. private KeyBindingScope _keyBindingScope = KeyBindingScope.HotKey;
  554. /// <summary>
  555. /// Gets or sets the scope for the key binding for how <see cref="Key"/> is bound to <see cref="Command"/>.
  556. /// </summary>
  557. public KeyBindingScope KeyBindingScope
  558. {
  559. get => _keyBindingScope;
  560. set
  561. {
  562. if (value == _keyBindingScope)
  563. {
  564. return;
  565. }
  566. if (_keyBindingScope == KeyBindingScope.Application)
  567. {
  568. Application.KeyBindings.Remove (Key);
  569. }
  570. if (_keyBindingScope is KeyBindingScope.HotKey or KeyBindingScope.Focused)
  571. {
  572. KeyBindings.Remove (Key);
  573. }
  574. _keyBindingScope = value;
  575. UpdateKeyBinding (Key.Empty);
  576. }
  577. }
  578. /// <summary>
  579. /// Gets the subview that displays the key. Internal for unit testing.
  580. /// </summary>
  581. internal View KeyView { get; } = new ();
  582. private int _minimumKeyTextSize;
  583. /// <summary>
  584. /// Gets or sets the minimum size of the key text. Useful for aligning the key text with other <see cref="Shortcut"/>s.
  585. /// </summary>
  586. public int MinimumKeyTextSize
  587. {
  588. get => _minimumKeyTextSize;
  589. set
  590. {
  591. if (value == _minimumKeyTextSize)
  592. {
  593. //return;
  594. }
  595. _minimumKeyTextSize = value;
  596. SetKeyViewDefaultLayout ();
  597. CommandView.SetNeedsLayout ();
  598. HelpView.SetNeedsLayout ();
  599. KeyView.SetNeedsLayout ();
  600. SetSubViewNeedsDisplay ();
  601. }
  602. }
  603. private int GetMinimumKeyViewSize () { return MinimumKeyTextSize; }
  604. private void SetKeyViewDefaultLayout ()
  605. {
  606. KeyView.Margin.Thickness = GetMarginThickness ();
  607. KeyView.X = Pos.Align (Alignment.End, AlignmentModes);
  608. KeyView.Y = 0; //Pos.Center ();
  609. KeyView.Width = Dim.Auto (DimAutoStyle.Text, Dim.Func (GetMinimumKeyViewSize));
  610. KeyView.Height = CommandView?.Visible == true ? Dim.Height (CommandView) : 1;
  611. KeyView.Visible = true;
  612. // Right align the text in the keyview
  613. KeyView.TextAlignment = Alignment.End;
  614. KeyView.VerticalTextAlignment = Alignment.Center;
  615. KeyView.KeyBindings.Clear ();
  616. HelpView.HighlightStyle = HighlightStyle.None;
  617. }
  618. private void UpdateKeyBinding (Key oldKey)
  619. {
  620. if (Key != null && Key.IsValid)
  621. {
  622. // Disable the command view HotKey bindings
  623. CommandView.KeyBindings.Remove (Key);
  624. CommandView.KeyBindings.Remove (CommandView.HotKey);
  625. CommandView.KeyBindings.Remove (CommandView.HotKey.WithShift);
  626. CommandView.KeyBindings.Remove (CommandView.HotKey.WithAlt);
  627. CommandView.KeyBindings.Remove (CommandView.HotKey.WithShift.WithAlt);
  628. if (KeyBindingScope.FastHasFlags (KeyBindingScope.Application))
  629. {
  630. if (oldKey != Key.Empty)
  631. {
  632. Application.KeyBindings.Remove (oldKey);
  633. }
  634. Application.KeyBindings.Remove (Key);
  635. Application.KeyBindings.Add (Key, this, Command.Accept);
  636. }
  637. else
  638. {
  639. if (oldKey != Key.Empty)
  640. {
  641. KeyBindings.Remove (oldKey);
  642. }
  643. KeyBindings.Remove (Key);
  644. KeyBindings.Add (Key, KeyBindingScope | KeyBindingScope.HotKey, Command.Accept);
  645. }
  646. }
  647. }
  648. #endregion Key
  649. #region Accept Handling
  650. /// <summary>
  651. /// Called when the <see cref="Command.Accept"/> command is received. This
  652. /// occurs
  653. /// - if the user clicks anywhere on the shortcut with the mouse
  654. /// - if the user presses Key
  655. /// - if the user presses the HotKey specified by CommandView
  656. /// - if HasFocus and the user presses Space or Enter (or any other key bound to Command.Accept).
  657. /// </summary>
  658. protected bool? DispatchAcceptCommand (CommandContext ctx)
  659. {
  660. var cancel = false;
  661. bool? handled = CommandView.InvokeCommand (Command.Select, ctx.Key, ctx.KeyBinding);
  662. if (handled is null or false)
  663. {
  664. cancel = RaiseAcceptEvent () == true;
  665. }
  666. if (Action is { })
  667. {
  668. Action.Invoke ();
  669. // Assume if there's a subscriber to Action, it's handled.
  670. cancel = true;
  671. }
  672. if (_targetView is { })
  673. {
  674. _targetView.InvokeCommand (_command);
  675. }
  676. return cancel;
  677. }
  678. /// <summary>
  679. /// Gets or sets the action to be invoked when the shortcut key is pressed or the shortcut is clicked on with the
  680. /// mouse.
  681. /// </summary>
  682. /// <remarks>
  683. /// Note, the <see cref="View.Accept"/> event is fired first, and if cancelled, the event will not be invoked.
  684. /// </remarks>
  685. [CanBeNull]
  686. public Action Action { get; set; }
  687. #endregion Accept Handling
  688. #region Focus
  689. /// <inheritdoc/>
  690. public override ColorScheme ColorScheme
  691. {
  692. get => base.ColorScheme;
  693. set
  694. {
  695. base.ColorScheme = value;
  696. SetColors ();
  697. }
  698. }
  699. /// <summary>
  700. /// </summary>
  701. internal void SetColors (bool highlight = false)
  702. {
  703. // Border should match superview.
  704. if (Border is { })
  705. {
  706. Border.ColorScheme = SuperView?.ColorScheme;
  707. }
  708. if (HasFocus || highlight)
  709. {
  710. base.ColorScheme ??= new (Attribute.Default);
  711. // When we have focus, we invert the colors
  712. base.ColorScheme = new (base.ColorScheme)
  713. {
  714. Normal = base.ColorScheme.Focus,
  715. HotNormal = base.ColorScheme.HotFocus,
  716. HotFocus = base.ColorScheme.HotNormal,
  717. Focus = base.ColorScheme.Normal
  718. };
  719. }
  720. else
  721. {
  722. base.ColorScheme = SuperView?.ColorScheme ?? base.ColorScheme;
  723. }
  724. // Set KeyView's colors to show "hot"
  725. if (IsInitialized && base.ColorScheme is { })
  726. {
  727. var cs = new ColorScheme (base.ColorScheme)
  728. {
  729. Normal = base.ColorScheme.HotNormal,
  730. HotNormal = base.ColorScheme.Normal
  731. };
  732. KeyView.ColorScheme = cs;
  733. }
  734. }
  735. /// <inheritdoc/>
  736. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view) { SetColors (); }
  737. #endregion Focus
  738. }