Shortcut.cs 26 KB

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