Shortcut.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. using System.ComponentModel;
  2. namespace Terminal.Gui;
  3. // TODO: I don't love the name Shortcut, but I can't think of a better one right now. Shortcut is a bit overloaded.
  4. // TODO: It can mean "Application-scoped key binding" or "A key binding that is displayed in a visual way".
  5. // TODO: I tried `BarItem` but that's not great either as it implies it can only be used in `Bar`s.
  6. /// <summary>
  7. /// Displays a command, help text, and a key binding. Useful for displaying a command in <see cref="Bar"/> such as a
  8. /// menu, toolbar, or status bar.
  9. /// </summary>
  10. /// <remarks>
  11. /// <para>
  12. /// When the user clicks on the <see cref="Shortcut"/> or presses the key
  13. /// specified by <see cref="Key"/> the <see cref="Command.Accept"/> command is invoked, causing the
  14. /// <see cref="Accept"/> event to be fired
  15. /// </para>
  16. /// <para>
  17. /// If <see cref="KeyBindingScope"/> is <see cref="KeyBindingScope.Application"/>, the <see cref="Command"/>
  18. /// be invoked regardless of what View has focus, enabling an application-wide keyboard shortcut.
  19. /// </para>
  20. /// <para>
  21. /// Set <see cref="View.Title"/> to change the Command text displayed in the <see cref="Shortcut"/>.
  22. /// By default, the <see cref="Command"/> text is the <see cref="View.Title"/> of <see cref="CommandView"/>.
  23. /// </para>
  24. /// <para>
  25. /// Set <see cref="View.Text"/> to change the Help text displayed in the <see cref="Shortcut"/>.
  26. /// </para>
  27. /// <para>
  28. /// The text displayed for the <see cref="Key"/> is the string representation of the <see cref="Key"/>.
  29. /// If the <see cref="Key"/> is <see cref="Key.Empty"/>, the <see cref="Key"/> text is not displayed.
  30. /// </para>
  31. /// </remarks>
  32. public class Shortcut : View
  33. {
  34. // Hosts the Command, Help, and Key Views. Needed (IIRC - wrote a long time ago) to allow mouse clicks to be handled by the Shortcut.
  35. internal readonly View _container;
  36. /// <summary>
  37. /// Creates a new instance of <see cref="Shortcut"/>.
  38. /// </summary>
  39. public Shortcut ()
  40. {
  41. CanFocus = true;
  42. Width = Dim.Auto (DimAutoStyle.Content);
  43. Height = Dim.Auto (DimAutoStyle.Content);
  44. //Height = Dim.Auto (minimumContentDim: 1, maximumContentDim: 1);
  45. AddCommand (Gui.Command.HotKey, () => true);
  46. AddCommand (Gui.Command.Accept, OnAccept);
  47. KeyBindings.Add (KeyCode.Space, Gui.Command.Accept);
  48. KeyBindings.Add (KeyCode.Enter, Gui.Command.Accept);
  49. _container = new ()
  50. {
  51. Id = "_container",
  52. // Only the Shortcut (_container) should be able to have focus, not any subviews.
  53. CanFocus = true,
  54. Width = Dim.Auto (DimAutoStyle.Content, 1),
  55. Height = Dim.Auto (DimAutoStyle.Content, 1),
  56. BorderStyle = LineStyle.Dashed
  57. };
  58. CommandView = new ();
  59. HelpView = new ()
  60. {
  61. Id = "_helpView",
  62. // Only the Shortcut should be able to have focus, not any subviews
  63. CanFocus = false,
  64. X = Pos.Align (Alignment.End, AlignmentModes.IgnoreFirstOrLast | AlignmentModes.AddSpaceBetweenItems),
  65. Y = Pos.Center (),
  66. // Helpview is the only subview that doesn't have a min width
  67. Width = Dim.Auto (DimAutoStyle.Text),
  68. Height = Dim.Auto (DimAutoStyle.Text),
  69. ColorScheme = Colors.ColorSchemes ["Error"]
  70. };
  71. _container.Add (HelpView);
  72. // HelpView.TextAlignment = Alignment.End;
  73. HelpView.MouseClick += Shortcut_MouseClick;
  74. KeyView = new ()
  75. {
  76. Id = "_keyView",
  77. // Only the Shortcut should be able to have focus, not any subviews
  78. CanFocus = false,
  79. X = Pos.Align (Alignment.End, AlignmentModes.IgnoreFirstOrLast | AlignmentModes.AddSpaceBetweenItems),
  80. Y = Pos.Center (),
  81. // Bar will set the width of all KeyViews to the width of the widest KeyView.
  82. Width = Dim.Auto (DimAutoStyle.Text),
  83. Height = Dim.Auto (DimAutoStyle.Text),
  84. };
  85. _container.Add (KeyView);
  86. KeyView.MouseClick += Shortcut_MouseClick;
  87. CommandView.Margin.Thickness = new Thickness (1, 0, 1, 0);
  88. HelpView.Margin.Thickness = new Thickness (1, 0, 1, 0);
  89. KeyView.Margin.Thickness = new Thickness (1, 0, 1, 0);
  90. MouseClick += Shortcut_MouseClick;
  91. TitleChanged += Shortcut_TitleChanged;
  92. Initialized += OnInitialized;
  93. Add (_container);
  94. return;
  95. void OnInitialized (object sender, EventArgs e)
  96. {
  97. if (ColorScheme != null)
  98. {
  99. var cs = new ColorScheme (ColorScheme)
  100. {
  101. Normal = ColorScheme.HotNormal,
  102. HotNormal = ColorScheme.Normal
  103. };
  104. KeyView.ColorScheme = cs;
  105. }
  106. }
  107. }
  108. private void Shortcut_MouseClick (object sender, MouseEventEventArgs e)
  109. {
  110. // When the Shortcut is clicked, we want to invoke the Command and Set focus
  111. View view = sender as View;
  112. if (!e.Handled && Command.HasValue)
  113. {
  114. // If the subview (likely CommandView) didn't handle the mouse click, invoke the command.
  115. bool? handled = false;
  116. handled = InvokeCommand (Command.Value);
  117. if (handled.HasValue)
  118. {
  119. e.Handled = handled.Value;
  120. }
  121. }
  122. if (CanFocus)
  123. {
  124. SetFocus ();
  125. }
  126. e.Handled = true;
  127. }
  128. /// <inheritdoc/>
  129. public override ColorScheme ColorScheme
  130. {
  131. get
  132. {
  133. if (base.ColorScheme == null)
  134. {
  135. return SuperView?.ColorScheme ?? base.ColorScheme;
  136. }
  137. return base.ColorScheme;
  138. }
  139. set
  140. {
  141. base.ColorScheme = value;
  142. if (ColorScheme != null)
  143. {
  144. var cs = new ColorScheme (ColorScheme)
  145. {
  146. Normal = ColorScheme.HotNormal,
  147. HotNormal = ColorScheme.Normal
  148. };
  149. KeyView.ColorScheme = cs;
  150. }
  151. }
  152. }
  153. #region Command
  154. private Command? _command;
  155. /// <summary>
  156. /// Gets or sets the <see cref="Command"/> that will be invoked when the user clicks on the <see cref="Shortcut"/> or
  157. /// presses <see cref="Key"/>.
  158. /// </summary>
  159. public Command? Command
  160. {
  161. get => _command;
  162. set
  163. {
  164. if (value != null)
  165. {
  166. _command = value.Value;
  167. UpdateKeyBinding ();
  168. }
  169. }
  170. }
  171. private View _commandView;
  172. /// <summary>
  173. /// Gets or sets the View that displays the command text and hotkey.
  174. /// </summary>
  175. /// <remarks>
  176. /// <para>
  177. /// By default, the <see cref="View.Title"/> of the <see cref="CommandView"/> is displayed as the Shortcut's
  178. /// command text.
  179. /// </para>
  180. /// <para>
  181. /// By default, the CommandView is a <see cref="View"/> with <see cref="View.CanFocus"/> set to
  182. /// <see langword="false"/>.
  183. /// </para>
  184. /// <para>
  185. /// Setting the <see cref="CommandView"/> will add it to the <see cref="Shortcut"/> and remove any existing
  186. /// <see cref="CommandView"/>.
  187. /// </para>
  188. /// </remarks>
  189. /// <example>
  190. /// <para>
  191. /// This example illustrates how to add a <see cref="Shortcut"/> to a <see cref="StatusBar"/> that toggles the
  192. /// <see cref="Application.Force16Colors"/> property.
  193. /// </para>
  194. /// <code>
  195. /// var force16ColorsShortcut = new Shortcut
  196. /// {
  197. /// Key = Key.F6,
  198. /// KeyBindingScope = KeyBindingScope.HotKey,
  199. /// Command = Command.Accept,
  200. /// CommandView = new CheckBox { Text = "Force 16 Colors" }
  201. /// };
  202. /// var cb = force16ColorsShortcut.CommandView as CheckBox;
  203. /// cb.Checked = Application.Force16Colors;
  204. ///
  205. /// cb.Toggled += (s, e) =>
  206. /// {
  207. /// var cb = s as CheckBox;
  208. /// Application.Force16Colors = cb!.Checked == true;
  209. /// Application.Refresh();
  210. /// };
  211. /// StatusBar.Add(force16ColorsShortcut);
  212. /// </code>
  213. /// </example>
  214. public View CommandView
  215. {
  216. get => _commandView;
  217. set
  218. {
  219. if (value == null)
  220. {
  221. throw new ArgumentNullException ();
  222. }
  223. if (_commandView is { })
  224. {
  225. _container.Remove (_commandView);
  226. _commandView?.Dispose ();
  227. }
  228. _commandView = value;
  229. _commandView.Id = "_commandView";
  230. // TODO: Determine if it makes sense to allow the CommandView to be focusable.
  231. // Right now, we don't set CanFocus to false here.
  232. _commandView.CanFocus = false;
  233. // Bar will set the width of all CommandViews to the width of the widest CommandViews.
  234. _commandView.Width = Dim.Auto (DimAutoStyle.Text);
  235. _commandView.Height = Dim.Auto (DimAutoStyle.Text);
  236. _commandView.X = X = Pos.Align (Alignment.End, AlignmentModes.IgnoreFirstOrLast | AlignmentModes.AddSpaceBetweenItems);
  237. _commandView.Y = Pos.Center ();
  238. _commandView.MouseClick += Shortcut_MouseClick;
  239. _commandView.Accept += CommandView_Accept;
  240. _commandView.Margin.Thickness = new (1, 0, 1, 0);
  241. _commandView.HotKeyChanged += (s, e) =>
  242. {
  243. if (e.NewKey != Key.Empty)
  244. {
  245. // Add it
  246. AddKeyBindingsForHotKey (e.OldKey, e.NewKey);
  247. }
  248. };
  249. _commandView.HotKeySpecifier = new ('_');
  250. _container.Remove (HelpView);
  251. _container.Remove (KeyView);
  252. _container.Add (_commandView, HelpView, KeyView);
  253. UpdateKeyBinding();
  254. }
  255. }
  256. private void _commandView_MouseEvent (object sender, MouseEventEventArgs e)
  257. {
  258. e.Handled = true;
  259. }
  260. private void Shortcut_TitleChanged (object sender, StateEventArgs<string> e)
  261. {
  262. // If the Title changes, update the CommandView text. This is a helper to make it easier to set the CommandView text.
  263. // CommandView is public and replaceable, but this is a convenience.
  264. _commandView.Text = Title;
  265. }
  266. private void CommandView_Accept (object sender, CancelEventArgs e)
  267. {
  268. // When the CommandView fires its Accept event, we want to act as though the
  269. // Shortcut was clicked.
  270. var args = new HandledEventArgs ();
  271. Accept?.Invoke (this, args);
  272. if (args.Handled)
  273. {
  274. e.Cancel = args.Handled;
  275. }
  276. }
  277. #endregion Command
  278. #region Help
  279. /// <summary>
  280. /// The subview that displays the help text for the command. Internal for unit testing.
  281. /// </summary>
  282. internal View HelpView { get; set; }
  283. /// <summary>
  284. /// Gets or sets the help text displayed in the middle of the Shortcut.
  285. /// </summary>
  286. public override string Text
  287. {
  288. get => base.Text;
  289. set
  290. {
  291. //base.Text = value;
  292. if (HelpView != null)
  293. {
  294. HelpView.Text = value;
  295. }
  296. }
  297. }
  298. #endregion Help
  299. #region Key
  300. private Key _key;
  301. /// <summary>
  302. /// Gets or sets the <see cref="Key"/> that will be bound to the <see cref="Command.Accept"/> command.
  303. /// </summary>
  304. public Key Key
  305. {
  306. get => _key;
  307. set
  308. {
  309. if (value == null)
  310. {
  311. throw new ArgumentNullException ();
  312. }
  313. _key = value;
  314. if (Command != null)
  315. {
  316. UpdateKeyBinding ();
  317. }
  318. KeyView.Text = $"{Key}";
  319. KeyView.Visible = Key != Key.Empty;
  320. }
  321. }
  322. private KeyBindingScope _keyBindingScope;
  323. /// <summary>
  324. /// Gets or sets the scope for the key binding for how <see cref="Key"/> is bound to <see cref="Command"/>.
  325. /// </summary>
  326. public KeyBindingScope KeyBindingScope
  327. {
  328. get => _keyBindingScope;
  329. set
  330. {
  331. _keyBindingScope = value;
  332. if (Command != null)
  333. {
  334. UpdateKeyBinding ();
  335. }
  336. }
  337. }
  338. /// <summary>
  339. /// Gets the subview that displays the key. Internal for unit testing.
  340. /// </summary>
  341. internal View KeyView { get; }
  342. private void UpdateKeyBinding ()
  343. {
  344. if (KeyBindingScope == KeyBindingScope.Application)
  345. {
  346. // return;
  347. }
  348. if (Command != null && Key != null && Key != Key.Empty)
  349. {
  350. // CommandView holds our command/keybinding
  351. // Add a key binding for this command to this Shortcut
  352. if (CommandView.GetSupportedCommands ().Contains (Command.Value))
  353. {
  354. CommandView.KeyBindings.Remove (Key);
  355. CommandView.KeyBindings.Add (Key, KeyBindingScope, Command.Value);
  356. }
  357. else
  358. {
  359. // throw new InvalidOperationException ($"CommandView does not support the command {Command.Value}");
  360. }
  361. }
  362. }
  363. #endregion Key
  364. /// <summary>
  365. /// The event fired when the <see cref="Command.Accept"/> command is received. This
  366. /// occurs if the user clicks on the Shortcut or presses <see cref="Key"/>.
  367. /// </summary>
  368. public new event EventHandler<HandledEventArgs> Accept;
  369. /// <summary>
  370. /// Called when the <see cref="Command.Accept"/> command is received. This
  371. /// occurs if the user clicks on the Bar with the mouse or presses the key bound to
  372. /// Command.Accept (Space by default).
  373. /// </summary>
  374. protected new bool? OnAccept ()
  375. {
  376. // TODO: This is not completely thought through.
  377. if (Key == null || Key == Key.Empty)
  378. {
  379. return false;
  380. }
  381. var handled = false;
  382. var keyCopy = new Key (Key);
  383. switch (KeyBindingScope)
  384. {
  385. case KeyBindingScope.Application:
  386. // Simulate a key down to invoke the Application scoped key binding
  387. handled = Application.OnKeyDown (keyCopy);
  388. break;
  389. case KeyBindingScope.Focused:
  390. handled = InvokeCommand (Command.Value) == true;
  391. handled = false;
  392. break;
  393. case KeyBindingScope.HotKey:
  394. if (Command.HasValue)
  395. {
  396. //handled = _commandView.InvokeCommand (Gui.Command.HotKey) == true;
  397. //handled = false;
  398. }
  399. break;
  400. }
  401. //if (handled == false)
  402. {
  403. var args = new HandledEventArgs ();
  404. Accept?.Invoke (this, args);
  405. handled = args.Handled;
  406. }
  407. return handled;
  408. }
  409. /// <inheritdoc/>
  410. public override bool OnEnter (View view)
  411. {
  412. // TODO: This is a hack. Need to refine this.
  413. var cs = new ColorScheme (ColorScheme)
  414. {
  415. Normal = ColorScheme.Focus,
  416. HotNormal = ColorScheme.HotFocus
  417. };
  418. _container.ColorScheme = cs;
  419. cs = new (ColorScheme)
  420. {
  421. Normal = ColorScheme.HotFocus,
  422. HotNormal = ColorScheme.Focus
  423. };
  424. KeyView.ColorScheme = cs;
  425. return base.OnEnter (view);
  426. }
  427. /// <inheritdoc/>
  428. public override bool OnLeave (View view)
  429. {
  430. // TODO: This is a hack. Need to refine this.
  431. var cs = new ColorScheme (ColorScheme)
  432. {
  433. Normal = ColorScheme.Normal,
  434. HotNormal = ColorScheme.HotNormal
  435. };
  436. _container.ColorScheme = cs;
  437. cs = new (ColorScheme)
  438. {
  439. Normal = ColorScheme.HotNormal,
  440. HotNormal = ColorScheme.Normal
  441. };
  442. KeyView.ColorScheme = cs;
  443. return base.OnLeave (view);
  444. }
  445. }