Shortcut.cs 27 KB

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