Shortcut.cs 27 KB

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