Shortcut.cs 29 KB

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