Shortcut.cs 29 KB

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