Shortcut.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. using System.ComponentModel;
  2. namespace Terminal.Gui.Views;
  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.Accepting"/> 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="BindKeyToApplication"/> is <see langword="true"/>, <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="ViewBase.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, null, null, null) { }
  45. /// <summary>
  46. /// Creates a new instance of <see cref="Shortcut"/>.
  47. /// </summary>
  48. /// <remarks>
  49. /// <para>
  50. /// This is a helper API that mimics the V1 API for creating StatusItems.
  51. /// </para>
  52. /// </remarks>
  53. /// <param name="key"></param>
  54. /// <param name="commandText">The text to display for the command.</param>
  55. /// <param name="action"></param>
  56. /// <param name="helpText">The help text to display.</param>
  57. public Shortcut (Key key, string? commandText, Action? action, string? helpText = null)
  58. {
  59. HighlightStates = ViewBase.MouseState.None;
  60. CanFocus = true;
  61. if (Border is { })
  62. {
  63. Border.Settings &= ~BorderSettings.Title;
  64. }
  65. Width = GetWidthDimAuto ();
  66. Height = Dim.Auto (DimAutoStyle.Content, 1);
  67. _orientationHelper = new (this);
  68. _orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
  69. _orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
  70. AddCommands ();
  71. TitleChanged += Shortcut_TitleChanged; // This needs to be set before CommandView is set
  72. CommandView = new ()
  73. {
  74. Id = "CommandView",
  75. Width = Dim.Auto (),
  76. Height = Dim.Fill ()
  77. };
  78. Title = commandText ?? string.Empty;
  79. HelpView.Id = "_helpView";
  80. //HelpView.CanFocus = false;
  81. HelpView.Text = helpText ?? string.Empty;
  82. KeyView.Id = "_keyView";
  83. //KeyView.CanFocus = false;
  84. key ??= Key.Empty;
  85. Key = key;
  86. Action = action;
  87. ShowHide ();
  88. }
  89. // Helper to set Width consistently
  90. internal Dim GetWidthDimAuto ()
  91. {
  92. return Dim.Auto (
  93. DimAutoStyle.Content,
  94. minimumContentDim: Dim.Func (_ => _minimumNaturalWidth ?? 0),
  95. maximumContentDim: Dim.Func (_ => _minimumNaturalWidth ?? 0))!;
  96. }
  97. private AlignmentModes _alignmentModes = AlignmentModes.StartToEnd | AlignmentModes.IgnoreFirstOrLast;
  98. // This is used to calculate the minimum width of the Shortcut when Width is NOT Dim.Auto
  99. // It is calculated by setting Width to DimAuto temporarily and forcing layout.
  100. // Once Frame.Width gets below this value, LayoutStarted makes HelpView an KeyView smaller.
  101. private int? _minimumNaturalWidth;
  102. /// <summary>
  103. /// Gets or sets the <see cref="AlignmentModes"/> for this <see cref="Shortcut"/>.
  104. /// </summary>
  105. /// <remarks>
  106. /// <para>
  107. /// The default is <see cref="AlignmentModes.StartToEnd"/>. This means that the CommandView will be on the left,
  108. /// HelpView in the middle, and KeyView on the right.
  109. /// </para>
  110. /// </remarks>
  111. public AlignmentModes AlignmentModes
  112. {
  113. get => _alignmentModes;
  114. set
  115. {
  116. _alignmentModes = value;
  117. SetCommandViewDefaultLayout ();
  118. SetHelpViewDefaultLayout ();
  119. SetKeyViewDefaultLayout ();
  120. }
  121. }
  122. // When one of the subviews is "empty" we don't want to show it. So we
  123. // Use Add/Remove. We need to be careful to add them in the right order
  124. // so Pos.Align works correctly.
  125. internal void ShowHide ()
  126. {
  127. RemoveAll ();
  128. if (CommandView.Visible)
  129. {
  130. Add (CommandView);
  131. SetCommandViewDefaultLayout ();
  132. }
  133. if (HelpView.Visible && !string.IsNullOrEmpty (HelpView.Text))
  134. {
  135. Add (HelpView);
  136. SetHelpViewDefaultLayout ();
  137. }
  138. if (KeyView.Visible && (Key != Key.Empty || KeyView.Text != string.Empty))
  139. {
  140. Add (KeyView);
  141. SetKeyViewDefaultLayout ();
  142. }
  143. }
  144. // Force Width to DimAuto to calculate natural width and then set it back
  145. private void ForceCalculateNaturalWidth ()
  146. {
  147. // Get the natural size of each subview
  148. CommandView.SetRelativeLayout (Application.Screen.Size);
  149. HelpView.SetRelativeLayout (Application.Screen.Size);
  150. KeyView.SetRelativeLayout (Application.Screen.Size);
  151. _minimumNaturalWidth = PosAlign.CalculateMinDimension (0, SubViews, Dimension.Width);
  152. // Reset our relative layout
  153. SetRelativeLayout (SuperView?.GetContentSize () ?? Application.Screen.Size);
  154. }
  155. // TODO: Enable setting of the margin thickness
  156. private Thickness GetMarginThickness ()
  157. {
  158. return new (1, 0, 1, 0);
  159. }
  160. // When layout starts, we need to adjust the layout of the HelpView and KeyView
  161. /// <inheritdoc />
  162. protected override void OnSubViewLayout (LayoutEventArgs e)
  163. {
  164. base.OnSubViewLayout (e);
  165. ShowHide ();
  166. ForceCalculateNaturalWidth ();
  167. if (Width is DimAuto widthAuto || HelpView!.Margin is null)
  168. {
  169. return;
  170. }
  171. // Frame.Width is smaller than the natural width. Reduce width of HelpView.
  172. _maxHelpWidth = int.Max (0, GetContentSize ().Width - CommandView.Frame.Width - KeyView.Frame.Width);
  173. if (_maxHelpWidth < 3)
  174. {
  175. Thickness t = GetMarginThickness ();
  176. switch (_maxHelpWidth)
  177. {
  178. case 0:
  179. case 1:
  180. // Scrunch it by removing both margins
  181. HelpView.Margin!.Thickness = new (t.Right - 1, t.Top, t.Left - 1, t.Bottom);
  182. break;
  183. case 2:
  184. // Scrunch just the right margin
  185. HelpView.Margin!.Thickness = new (t.Right, t.Top, t.Left - 1, t.Bottom);
  186. break;
  187. }
  188. }
  189. else
  190. {
  191. // Reset to default
  192. HelpView.Margin!.Thickness = GetMarginThickness ();
  193. }
  194. }
  195. #region Accept/Select/HotKey Command Handling
  196. private void AddCommands ()
  197. {
  198. // Accept (Enter key) -
  199. AddCommand (Command.Accept, DispatchCommand);
  200. // Hotkey -
  201. AddCommand (Command.HotKey, DispatchCommand);
  202. // Select (Space key or click) -
  203. AddCommand (Command.Select, DispatchCommand);
  204. }
  205. /// <summary>
  206. /// Dispatches the Command in the <paramref name="commandContext"/> (Raises Selected, then Accepting, then invoke the Action, if any).
  207. /// Called when Command.Select, Accept, or HotKey has been invoked on this Shortcut.
  208. /// </summary>
  209. /// <param name="commandContext"></param>
  210. /// <returns>
  211. /// <see langword="null"/> if no event was raised; input processing should continue.
  212. /// <see langword="false"/> if the event was raised and was not handled (or cancelled); input processing should continue.
  213. /// <see langword="true"/> if the event was raised and handled (or cancelled); input processing should stop.
  214. /// </returns>
  215. internal virtual bool? DispatchCommand (ICommandContext? commandContext)
  216. {
  217. CommandContext<KeyBinding>? keyCommandContext = commandContext as CommandContext<KeyBinding>? ?? default (CommandContext<KeyBinding>);
  218. Logging.Debug ($"{Title} ({commandContext?.Source?.Title}) Command: {commandContext?.Command}");
  219. if (keyCommandContext?.Binding.Data != this)
  220. {
  221. // TODO: Optimize this to only do this if CommandView is custom (non View)
  222. // Invoke Select on the CommandView to cause it to change state if it wants to
  223. // If this causes CommandView to raise Accept, we eat it
  224. keyCommandContext = keyCommandContext!.Value with { Binding = keyCommandContext.Value.Binding with { Data = this } };
  225. Logging.Debug ($"{Title} ({commandContext?.Source?.Title}) - Invoking Select on CommandView ({CommandView.GetType ().Name}).");
  226. CommandView.InvokeCommand (Command.Select, keyCommandContext);
  227. }
  228. Logging.Debug ($"{Title} ({commandContext?.Source?.Title}) - RaiseSelecting ...");
  229. if (RaiseSelecting (commandContext) is true)
  230. {
  231. return true;
  232. }
  233. if (CanFocus && SuperView is { CanFocus: true })
  234. {
  235. // The default HotKey handler sets Focus
  236. Logging.Debug ($"{Title} ({commandContext?.Source?.Title}) - SetFocus...");
  237. SetFocus ();
  238. }
  239. var cancel = false;
  240. if (commandContext is { Source: null })
  241. {
  242. commandContext.Source = this;
  243. }
  244. Logging.Debug ($"{Title} ({commandContext?.Source?.Title}) - Calling RaiseAccepting...");
  245. cancel = RaiseAccepting (commandContext) is true;
  246. if (cancel)
  247. {
  248. return true;
  249. }
  250. if (Action is { })
  251. {
  252. Logging.Debug ($"{Title} ({commandContext?.Source?.Title}) - Invoke Action...");
  253. Action.Invoke ();
  254. // Assume if there's a subscriber to Action, it's handled.
  255. cancel = true;
  256. }
  257. return cancel;
  258. }
  259. /// <summary>
  260. /// Gets or sets the action to be invoked when the shortcut key is pressed or the shortcut is clicked on with the
  261. /// mouse.
  262. /// </summary>
  263. /// <remarks>
  264. /// Note, the <see cref="View.Accepting"/> event is fired first, and if cancelled, the event will not be invoked.
  265. /// </remarks>
  266. public Action? Action { get; set; }
  267. #endregion Accept/Select/HotKey Command Handling
  268. #region IOrientation members
  269. private readonly OrientationHelper _orientationHelper;
  270. /// <summary>
  271. /// Gets or sets the <see cref="Orientation"/> for this <see cref="Bar"/>. The default is
  272. /// <see cref="Orientation.Horizontal"/>.
  273. /// </summary>
  274. /// <remarks>
  275. /// </remarks>
  276. public Orientation Orientation
  277. {
  278. get => _orientationHelper.Orientation;
  279. set => _orientationHelper.Orientation = value;
  280. }
  281. /// <inheritdoc/>
  282. public event EventHandler<CancelEventArgs<Orientation>>? OrientationChanging;
  283. /// <inheritdoc/>
  284. public event EventHandler<EventArgs<Orientation>>? OrientationChanged;
  285. /// <summary>Called when <see cref="Orientation"/> has changed.</summary>
  286. /// <param name="newOrientation"></param>
  287. public void OnOrientationChanged (Orientation newOrientation)
  288. {
  289. // TODO: Determine what, if anything, is opinionated about the orientation.
  290. SetNeedsLayout ();
  291. }
  292. #endregion
  293. #region Command
  294. private View _commandView = new ();
  295. /// <summary>
  296. /// Gets or sets the View that displays the command text and hotkey.
  297. /// </summary>
  298. /// <exception cref="ArgumentNullException"></exception>
  299. /// <remarks>
  300. /// <para>
  301. /// By default, the <see cref="View.Title"/> of the <see cref="CommandView"/> is displayed as the Shortcut's
  302. /// command text.
  303. /// </para>
  304. /// <para>
  305. /// By default, the CommandView is a <see cref="View"/> with <see cref="View.CanFocus"/> set to
  306. /// <see langword="false"/>.
  307. /// </para>
  308. /// <para>
  309. /// Setting the <see cref="CommandView"/> will add it to the <see cref="Shortcut"/> and remove any existing
  310. /// <see cref="CommandView"/>.
  311. /// </para>
  312. /// </remarks>
  313. /// <example>
  314. /// <para>
  315. /// This example illustrates how to add a <see cref="Shortcut"/> to a <see cref="StatusBar"/> that toggles the
  316. /// <see cref="Application.Force16Colors"/> property.
  317. /// </para>
  318. /// <code>
  319. /// var force16ColorsShortcut = new Shortcut
  320. /// {
  321. /// Key = Key.F6,
  322. /// KeyBindingScope = KeyBindingScope.HotKey,
  323. /// CommandView = new CheckBox { Text = "Force 16 Colors" }
  324. /// };
  325. /// var cb = force16ColorsShortcut.CommandView as CheckBox;
  326. /// cb.Checked = Application.Force16Colors;
  327. ///
  328. /// cb.Toggled += (s, e) =>
  329. /// {
  330. /// var cb = s as CheckBox;
  331. /// Application.Force16Colors = cb!.Checked == true;
  332. /// Application.Refresh();
  333. /// };
  334. /// StatusBar.Add(force16ColorsShortcut);
  335. /// </code>
  336. /// </example>
  337. public View CommandView
  338. {
  339. get => _commandView;
  340. set
  341. {
  342. ArgumentNullException.ThrowIfNull (value);
  343. if (value == null)
  344. {
  345. throw new ArgumentNullException ();
  346. }
  347. // Clean up old
  348. _commandView.Selecting -= CommandViewOnSelecting;
  349. _commandView.Accepting -= CommandViewOnAccepted;
  350. Remove (_commandView);
  351. _commandView?.Dispose ();
  352. // Set new
  353. _commandView = value;
  354. _commandView.Id = "_commandView";
  355. // The default behavior is for CommandView to not get focus. I
  356. // If you want it to get focus, you need to set it.
  357. // _commandView.CanFocus = false;
  358. _commandView.HotKeyChanged += (s, e) =>
  359. {
  360. if (e.NewKey != Key.Empty)
  361. {
  362. // Add it
  363. AddKeyBindingsForHotKey (e.OldKey, e.NewKey);
  364. }
  365. };
  366. _commandView.HotKeySpecifier = new ('_');
  367. Title = _commandView.Text;
  368. _commandView.Selecting += CommandViewOnSelecting;
  369. _commandView.Accepting += CommandViewOnAccepted;
  370. //ShowHide ();
  371. UpdateKeyBindings (Key.Empty);
  372. return;
  373. void CommandViewOnAccepted (object? sender, CommandEventArgs e)
  374. {
  375. // Always eat CommandView.Accept
  376. e.Handled = true;
  377. }
  378. void CommandViewOnSelecting (object? sender, CommandEventArgs e)
  379. {
  380. if ((e.Context is CommandContext<KeyBinding> keyCommandContext && keyCommandContext.Binding.Data != this) ||
  381. e.Context is CommandContext<MouseBinding>)
  382. {
  383. // Forward command to ourselves
  384. InvokeCommand<KeyBinding> (Command.Select, new ([Command.Select], null, this));
  385. }
  386. e.Handled = true;
  387. }
  388. }
  389. }
  390. private void SetCommandViewDefaultLayout ()
  391. {
  392. if (CommandView.Margin is { })
  393. {
  394. CommandView.Margin!.Thickness = GetMarginThickness ();
  395. // strip off ViewportSettings.TransparentMouse
  396. CommandView.Margin!.ViewportSettings &= ~ViewportSettingsFlags.TransparentMouse;
  397. }
  398. CommandView.X = Pos.Align (Alignment.End, AlignmentModes);
  399. CommandView.VerticalTextAlignment = Alignment.Center;
  400. CommandView.TextAlignment = Alignment.Start;
  401. CommandView.TextFormatter.WordWrap = false;
  402. //CommandView.HighlightStates = HighlightStates.None;
  403. CommandView.GettingAttributeForRole += SubViewOnGettingAttributeForRole;
  404. }
  405. private void SubViewOnGettingAttributeForRole (object? sender, VisualRoleEventArgs e)
  406. {
  407. switch (e.Role)
  408. {
  409. case VisualRole.Normal:
  410. if (HasFocus)
  411. {
  412. e.Handled = true;
  413. e.Result = GetAttributeForRole (VisualRole.Focus);
  414. }
  415. break;
  416. case VisualRole.HotNormal:
  417. if (HasFocus)
  418. {
  419. e.Handled = true;
  420. e.Result = GetAttributeForRole (VisualRole.HotFocus);
  421. }
  422. break;
  423. }
  424. }
  425. private void Shortcut_TitleChanged (object? sender, EventArgs<string> e)
  426. {
  427. // If the Title changes, update the CommandView text.
  428. // This is a helper to make it easier to set the CommandView text.
  429. // CommandView is public and replaceable, but this is a convenience.
  430. _commandView.Text = Title;
  431. //_commandView.Title = Title;
  432. }
  433. #endregion Command
  434. #region Help
  435. // The maximum width of the HelpView. Calculated in OnLayoutStarted and used in HelpView.Width (Dim.Auto/Func).
  436. private int _maxHelpWidth = 0;
  437. /// <summary>
  438. /// The subview that displays the help text for the command. Internal for unit testing.
  439. /// </summary>
  440. public View HelpView { get; } = new ();
  441. private void SetHelpViewDefaultLayout ()
  442. {
  443. if (HelpView.Margin is { })
  444. {
  445. HelpView.Margin!.Thickness = GetMarginThickness ();
  446. // strip off ViewportSettings.TransparentMouse
  447. HelpView.Margin!.ViewportSettings &= ~ViewportSettingsFlags.TransparentMouse;
  448. }
  449. HelpView.X = Pos.Align (Alignment.End, AlignmentModes);
  450. _maxHelpWidth = HelpView.Text.GetColumns ();
  451. HelpView.Width = Dim.Auto (DimAutoStyle.Text, maximumContentDim: Dim.Func ((_ => _maxHelpWidth)));
  452. HelpView.Height = Dim.Fill ();
  453. HelpView.Visible = true;
  454. HelpView.VerticalTextAlignment = Alignment.Center;
  455. HelpView.TextAlignment = Alignment.Start;
  456. HelpView.TextFormatter.WordWrap = false;
  457. HelpView.HighlightStates = ViewBase.MouseState.None;
  458. HelpView.GettingAttributeForRole += SubViewOnGettingAttributeForRole;
  459. }
  460. /// <summary>
  461. /// Gets or sets the help text displayed in the middle of the Shortcut. Identical in function to <see cref="HelpText"/>
  462. /// .
  463. /// </summary>
  464. public override string Text
  465. {
  466. get => HelpView.Text;
  467. set
  468. {
  469. HelpView.Text = value;
  470. ShowHide ();
  471. }
  472. }
  473. /// <summary>
  474. /// Gets or sets the help text displayed in the middle of the Shortcut.
  475. /// </summary>
  476. public string HelpText
  477. {
  478. get => HelpView.Text;
  479. set
  480. {
  481. HelpView.Text = value;
  482. ShowHide ();
  483. }
  484. }
  485. #endregion Help
  486. #region Key
  487. private Key _key = Key.Empty;
  488. /// <summary>
  489. /// Gets or sets the <see cref="Key"/> that will be bound to the <see cref="Command.Accept"/> command.
  490. /// </summary>
  491. public Key Key
  492. {
  493. get => _key;
  494. set
  495. {
  496. ArgumentNullException.ThrowIfNull (value);
  497. Key oldKey = _key;
  498. _key = value;
  499. UpdateKeyBindings (oldKey);
  500. KeyView.Text = Key == Key.Empty ? string.Empty : $"{Key}";
  501. ShowHide ();
  502. }
  503. }
  504. private bool _bindKeyToApplication = false;
  505. /// <summary>
  506. /// Gets or sets whether <see cref="Key"/> is bound to <see cref="Command"/> via <see cref="View.HotKeyBindings"/> or <see cref="Application.KeyBindings"/>.
  507. /// </summary>
  508. public bool BindKeyToApplication
  509. {
  510. get => _bindKeyToApplication;
  511. set
  512. {
  513. if (value == _bindKeyToApplication)
  514. {
  515. return;
  516. }
  517. if (_bindKeyToApplication)
  518. {
  519. Application.KeyBindings.Remove (Key);
  520. }
  521. else
  522. {
  523. HotKeyBindings.Remove (Key);
  524. }
  525. _bindKeyToApplication = value;
  526. UpdateKeyBindings (Key.Empty);
  527. }
  528. }
  529. /// <summary>
  530. /// Gets the subview that displays the key. Is drawn with Normal and HotNormal colors reversed.
  531. /// </summary>
  532. public View KeyView { get; } = new ();
  533. private int _minimumKeyTextSize;
  534. /// <summary>
  535. /// Gets or sets the minimum size of the key text. Useful for aligning the key text with other <see cref="Shortcut"/>s.
  536. /// </summary>
  537. public int MinimumKeyTextSize
  538. {
  539. get => _minimumKeyTextSize;
  540. set
  541. {
  542. if (value == _minimumKeyTextSize)
  543. {
  544. //return;
  545. }
  546. _minimumKeyTextSize = value;
  547. SetKeyViewDefaultLayout ();
  548. }
  549. }
  550. private void SetKeyViewDefaultLayout ()
  551. {
  552. if (KeyView.Margin is { })
  553. {
  554. KeyView.Margin!.Thickness = GetMarginThickness ();
  555. // strip off ViewportSettings.TransparentMouse
  556. KeyView.Margin!.ViewportSettings &= ~ViewportSettingsFlags.TransparentMouse;
  557. }
  558. KeyView.X = Pos.Align (Alignment.End, AlignmentModes);
  559. KeyView.Width = Dim.Auto (DimAutoStyle.Text, minimumContentDim: Dim.Func (_ => MinimumKeyTextSize));
  560. KeyView.Height = Dim.Fill ();
  561. KeyView.Visible = true;
  562. // Right align the text in the keyview
  563. KeyView.TextAlignment = Alignment.End;
  564. KeyView.VerticalTextAlignment = Alignment.Center;
  565. KeyView.KeyBindings.Clear ();
  566. KeyView.HighlightStates = ViewBase.MouseState.None;
  567. KeyView.GettingAttributeForRole += (sender, args) =>
  568. {
  569. if (args.Role == VisualRole.Normal)
  570. {
  571. args.Result = SuperView?.GetAttributeForRole (HasFocus ? VisualRole.HotFocus : VisualRole.HotNormal) ?? Attribute.Default;
  572. args.Handled = true;
  573. }
  574. };
  575. KeyView.ClearingViewport += (sender, args) =>
  576. {
  577. // Do not clear; otherwise spaces will be printed with underlines
  578. args.Cancel = true;
  579. };
  580. }
  581. private void UpdateKeyBindings (Key oldKey)
  582. {
  583. if (!Key.IsValid)
  584. {
  585. return;
  586. }
  587. if (BindKeyToApplication)
  588. {
  589. if (oldKey != Key.Empty)
  590. {
  591. Application.KeyBindings.Remove (oldKey);
  592. }
  593. Application.KeyBindings.Remove (Key);
  594. Application.KeyBindings.Add (Key, this, Command.HotKey);
  595. }
  596. else
  597. {
  598. if (oldKey != Key.Empty)
  599. {
  600. HotKeyBindings.Remove (oldKey);
  601. }
  602. HotKeyBindings.Remove (Key);
  603. HotKeyBindings.Add (Key, Command.HotKey);
  604. }
  605. }
  606. #endregion Key
  607. #region Focus
  608. private bool _forceFocusColors;
  609. /// <summary>
  610. /// TODO: IS this needed?
  611. /// </summary>
  612. public bool ForceFocusColors
  613. {
  614. get => _forceFocusColors;
  615. set
  616. {
  617. _forceFocusColors = value;
  618. SetNeedsDraw ();
  619. }
  620. }
  621. /// <inheritdoc />
  622. protected override bool OnGettingAttributeForRole (in VisualRole role, ref Attribute currentAttribute)
  623. {
  624. if (!HasFocus)
  625. {
  626. return base.OnGettingAttributeForRole (role, ref currentAttribute);
  627. }
  628. if (role == VisualRole.Normal)
  629. {
  630. currentAttribute = GetAttributeForRole (VisualRole.Focus);
  631. return true;
  632. }
  633. if (role == VisualRole.HotNormal)
  634. {
  635. currentAttribute = GetAttributeForRole (VisualRole.HotFocus);
  636. return true;
  637. }
  638. return base.OnGettingAttributeForRole (role, ref currentAttribute);
  639. }
  640. #endregion Focus
  641. /// <inheritdoc/>
  642. public bool EnableForDesign ()
  643. {
  644. Title = "_Shortcut";
  645. HelpText = "Shortcut help";
  646. Key = Key.F1;
  647. return true;
  648. }
  649. /// <inheritdoc/>
  650. protected override void Dispose (bool disposing)
  651. {
  652. if (disposing)
  653. {
  654. TitleChanged -= Shortcut_TitleChanged;
  655. if (CommandView.SuperView is null)
  656. {
  657. CommandView.Dispose ();
  658. }
  659. if (HelpView.SuperView is null)
  660. {
  661. HelpView.Dispose ();
  662. }
  663. if (KeyView.SuperView is null)
  664. {
  665. KeyView.Dispose ();
  666. }
  667. }
  668. base.Dispose (disposing);
  669. }
  670. }