Shortcut.cs 26 KB

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