Shortcut.cs 22 KB

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