Shortcut.cs 16 KB

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