PopupAutocomplete.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. namespace Terminal.Gui;
  2. /// <summary>
  3. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  4. /// options.
  5. /// </summary>
  6. public abstract class PopupAutocomplete : AutocompleteBase
  7. {
  8. private bool closed;
  9. private ColorScheme colorScheme;
  10. private View hostControl;
  11. private View top, popup;
  12. private int toRenderLength;
  13. /// <summary>Creates a new instance of the <see cref="PopupAutocomplete"/> class.</summary>
  14. public PopupAutocomplete () { PopupInsideContainer = true; }
  15. /// <summary>
  16. /// The colors to use to render the overlay. Accessing this property before the Application has been initialized
  17. /// will cause an error
  18. /// </summary>
  19. public override ColorScheme ColorScheme
  20. {
  21. get
  22. {
  23. if (colorScheme == null)
  24. {
  25. colorScheme = Colors.ColorSchemes ["Menu"];
  26. }
  27. return colorScheme;
  28. }
  29. set => colorScheme = value;
  30. }
  31. /// <summary>The host control to handle.</summary>
  32. public override View HostControl
  33. {
  34. get => hostControl;
  35. set
  36. {
  37. hostControl = value;
  38. top = hostControl.SuperView;
  39. if (top != null)
  40. {
  41. top.DrawContent += Top_DrawContent;
  42. top.DrawContentComplete += Top_DrawContentComplete;
  43. top.Removed += Top_Removed;
  44. }
  45. }
  46. }
  47. /// <summary>
  48. /// When more suggestions are available than can be rendered the user can scroll down the dropdown list. This
  49. /// indicates how far down they have gone
  50. /// </summary>
  51. public virtual int ScrollOffset { get; set; }
  52. private Point? LastPopupPos { get; set; }
  53. /// <inheritdoc/>
  54. public override void EnsureSelectedIdxIsValid ()
  55. {
  56. base.EnsureSelectedIdxIsValid ();
  57. // if user moved selection up off top of current scroll window
  58. if (SelectedIdx < ScrollOffset)
  59. {
  60. ScrollOffset = SelectedIdx;
  61. }
  62. // if user moved selection down past bottom of current scroll window
  63. while (toRenderLength > 0 && SelectedIdx >= ScrollOffset + toRenderLength)
  64. {
  65. ScrollOffset++;
  66. }
  67. }
  68. /// <summary>
  69. /// Handle mouse events before <see cref="HostControl"/> e.g. to make mouse events like report/click apply to the
  70. /// autocomplete control instead of changing the cursor position in the underlying text view.
  71. /// </summary>
  72. /// <param name="me">The mouse event.</param>
  73. /// <param name="fromHost">If was called from the popup or from the host.</param>
  74. /// <returns><c>true</c>if the mouse can be handled <c>false</c>otherwise.</returns>
  75. public override bool MouseEvent (MouseEvent me, bool fromHost = false)
  76. {
  77. if (fromHost)
  78. {
  79. if (!Visible)
  80. {
  81. return false;
  82. }
  83. // TODO: Revisit this
  84. //GenerateSuggestions ();
  85. if (Visible && Suggestions.Count == 0)
  86. {
  87. Visible = false;
  88. HostControl?.SetNeedsDisplay ();
  89. return true;
  90. }
  91. if (!Visible && Suggestions.Count > 0)
  92. {
  93. Visible = true;
  94. HostControl?.SetNeedsDisplay ();
  95. Application.UngrabMouse ();
  96. return false;
  97. }
  98. // not in the popup
  99. if (Visible && HostControl != null)
  100. {
  101. Visible = false;
  102. closed = false;
  103. }
  104. HostControl?.SetNeedsDisplay ();
  105. return false;
  106. }
  107. if (popup == null || Suggestions.Count == 0)
  108. {
  109. ManipulatePopup ();
  110. return false;
  111. }
  112. if (me.Flags == MouseFlags.ReportMousePosition)
  113. {
  114. RenderSelectedIdxByMouse (me);
  115. return true;
  116. }
  117. if (me.Flags == MouseFlags.Button1Clicked)
  118. {
  119. SelectedIdx = me.Y - ScrollOffset;
  120. return Select ();
  121. }
  122. if (me.Flags == MouseFlags.WheeledDown)
  123. {
  124. MoveDown ();
  125. return true;
  126. }
  127. if (me.Flags == MouseFlags.WheeledUp)
  128. {
  129. MoveUp ();
  130. return true;
  131. }
  132. return false;
  133. }
  134. /// <summary>
  135. /// Handle key events before <see cref="HostControl"/> e.g. to make key events like up/down apply to the
  136. /// autocomplete control instead of changing the cursor position in the underlying text view.
  137. /// </summary>
  138. /// <param name="a">The key event.</param>
  139. /// <returns><c>true</c>if the key can be handled <c>false</c>otherwise.</returns>
  140. public override bool ProcessKey (Key a)
  141. {
  142. if (SuggestionGenerator.IsWordChar ((Rune)a))
  143. {
  144. Visible = true;
  145. ManipulatePopup ();
  146. closed = false;
  147. return false;
  148. }
  149. if (a.KeyCode == Reopen)
  150. {
  151. Context.Canceled = false;
  152. return ReopenSuggestions ();
  153. }
  154. if (closed || Suggestions.Count == 0)
  155. {
  156. Visible = false;
  157. if (!closed)
  158. {
  159. Close ();
  160. }
  161. return false;
  162. }
  163. if (a.KeyCode == KeyCode.CursorDown)
  164. {
  165. MoveDown ();
  166. return true;
  167. }
  168. if (a.KeyCode == KeyCode.CursorUp)
  169. {
  170. MoveUp ();
  171. return true;
  172. }
  173. // TODO : Revisit this
  174. /*if (a.ConsoleDriverKey == Key.CursorLeft || a.ConsoleDriverKey == Key.CursorRight) {
  175. GenerateSuggestions (a.ConsoleDriverKey == Key.CursorLeft ? -1 : 1);
  176. if (Suggestions.Count == 0) {
  177. Visible = false;
  178. if (!closed) {
  179. Close ();
  180. }
  181. }
  182. return false;
  183. }*/
  184. if (a.KeyCode == SelectionKey)
  185. {
  186. return Select ();
  187. }
  188. if (a.KeyCode == CloseKey)
  189. {
  190. Close ();
  191. Context.Canceled = true;
  192. return true;
  193. }
  194. return false;
  195. }
  196. /// <summary>Renders the autocomplete dialog inside or outside the given <see cref="HostControl"/> at the given point.</summary>
  197. /// <param name="renderAt"></param>
  198. public override void RenderOverlay (Point renderAt)
  199. {
  200. if (!Context.Canceled && Suggestions.Count > 0 && !Visible && HostControl?.HasFocus == true)
  201. {
  202. ProcessKey (new Key ((KeyCode)Suggestions [0].Title [0]));
  203. }
  204. else if (!Visible || HostControl?.HasFocus == false || Suggestions.Count == 0)
  205. {
  206. LastPopupPos = null;
  207. Visible = false;
  208. if (Suggestions.Count == 0)
  209. {
  210. Context.Canceled = false;
  211. }
  212. return;
  213. }
  214. LastPopupPos = renderAt;
  215. int height, width;
  216. if (PopupInsideContainer)
  217. {
  218. // don't overspill vertically
  219. height = Math.Min (HostControl.Bounds.Height - renderAt.Y, MaxHeight);
  220. // There is no space below, lets see if can popup on top
  221. if (height < Suggestions.Count && HostControl.Bounds.Height - renderAt.Y >= height)
  222. {
  223. // Verifies that the upper limit available is greater than the lower limit
  224. if (renderAt.Y > HostControl.Bounds.Height - renderAt.Y)
  225. {
  226. renderAt.Y = Math.Max (renderAt.Y - Math.Min (Suggestions.Count + 1, MaxHeight + 1), 0);
  227. height = Math.Min (Math.Min (Suggestions.Count, MaxHeight), LastPopupPos.Value.Y - 1);
  228. }
  229. }
  230. }
  231. else
  232. {
  233. // don't overspill vertically
  234. height = Math.Min (Math.Min (top.Bounds.Height - HostControl.Frame.Bottom, MaxHeight), Suggestions.Count);
  235. // There is no space below, lets see if can popup on top
  236. if (height < Suggestions.Count && HostControl.Frame.Y - top.Frame.Y >= height)
  237. {
  238. // Verifies that the upper limit available is greater than the lower limit
  239. if (HostControl.Frame.Y > top.Bounds.Height - HostControl.Frame.Y)
  240. {
  241. renderAt.Y = Math.Max (HostControl.Frame.Y - Math.Min (Suggestions.Count, MaxHeight), 0);
  242. height = Math.Min (Math.Min (Suggestions.Count, MaxHeight), HostControl.Frame.Y);
  243. }
  244. }
  245. else
  246. {
  247. renderAt.Y = HostControl.Frame.Bottom;
  248. }
  249. }
  250. if (ScrollOffset > Suggestions.Count - height)
  251. {
  252. ScrollOffset = 0;
  253. }
  254. Suggestion [] toRender = Suggestions.Skip (ScrollOffset).Take (height).ToArray ();
  255. toRenderLength = toRender.Length;
  256. if (toRender.Length == 0)
  257. {
  258. return;
  259. }
  260. width = Math.Min (MaxWidth, toRender.Max (s => s.Title.Length));
  261. if (PopupInsideContainer)
  262. {
  263. // don't overspill horizontally, let's see if can be displayed on the left
  264. if (width > HostControl.Bounds.Width - renderAt.X)
  265. {
  266. // Verifies that the left limit available is greater than the right limit
  267. if (renderAt.X > HostControl.Bounds.Width - renderAt.X)
  268. {
  269. renderAt.X -= Math.Min (width, LastPopupPos.Value.X);
  270. width = Math.Min (width, LastPopupPos.Value.X);
  271. }
  272. else
  273. {
  274. width = Math.Min (width, HostControl.Bounds.Width - renderAt.X);
  275. }
  276. }
  277. }
  278. else
  279. {
  280. // don't overspill horizontally, let's see if can be displayed on the left
  281. if (width > top.Bounds.Width - (renderAt.X + HostControl.Frame.X))
  282. {
  283. // Verifies that the left limit available is greater than the right limit
  284. if (renderAt.X + HostControl.Frame.X > top.Bounds.Width - (renderAt.X + HostControl.Frame.X))
  285. {
  286. renderAt.X -= Math.Min (width, LastPopupPos.Value.X);
  287. width = Math.Min (width, LastPopupPos.Value.X);
  288. }
  289. else
  290. {
  291. width = Math.Min (width, top.Bounds.Width - renderAt.X);
  292. }
  293. }
  294. }
  295. if (PopupInsideContainer)
  296. {
  297. popup.Frame = new Rect (
  298. new Point (HostControl.Frame.X + renderAt.X, HostControl.Frame.Y + renderAt.Y),
  299. new Size (width, height)
  300. );
  301. }
  302. else
  303. {
  304. popup.Frame = new Rect (
  305. new Point (HostControl.Frame.X + renderAt.X, renderAt.Y),
  306. new Size (width, height)
  307. );
  308. }
  309. popup.Move (0, 0);
  310. for (var i = 0; i < toRender.Length; i++)
  311. {
  312. if (i == SelectedIdx - ScrollOffset)
  313. {
  314. Application.Driver.SetAttribute (ColorScheme.Focus);
  315. }
  316. else
  317. {
  318. Application.Driver.SetAttribute (ColorScheme.Normal);
  319. }
  320. popup.Move (0, i);
  321. string text = TextFormatter.ClipOrPad (toRender [i].Title, width);
  322. Application.Driver.AddStr (text);
  323. }
  324. }
  325. /// <summary>
  326. /// Closes the Autocomplete context menu if it is showing and <see cref="IAutocomplete.ClearSuggestions"/>
  327. /// </summary>
  328. protected void Close ()
  329. {
  330. ClearSuggestions ();
  331. Visible = false;
  332. closed = true;
  333. HostControl?.SetNeedsDisplay ();
  334. ManipulatePopup ();
  335. }
  336. /// <summary>Deletes the text backwards before insert the selected text in the <see cref="HostControl"/>.</summary>
  337. protected abstract void DeleteTextBackwards ();
  338. /// <summary>
  339. /// Called when the user confirms a selection at the current cursor location in the <see cref="HostControl"/>. The
  340. /// <paramref name="accepted"/> string is the full autocomplete word to be inserted. Typically a host will have to
  341. /// remove some characters such that the <paramref name="accepted"/> string completes the word instead of simply being
  342. /// appended.
  343. /// </summary>
  344. /// <param name="accepted"></param>
  345. /// <returns>True if the insertion was possible otherwise false</returns>
  346. protected virtual bool InsertSelection (Suggestion accepted)
  347. {
  348. SetCursorPosition (Context.CursorPosition + accepted.Remove);
  349. // delete the text
  350. for (var i = 0; i < accepted.Remove; i++)
  351. {
  352. DeleteTextBackwards ();
  353. }
  354. InsertText (accepted.Replacement);
  355. return true;
  356. }
  357. /// <summary>Insert the selected text in the <see cref="HostControl"/>.</summary>
  358. /// <param name="accepted"></param>
  359. protected abstract void InsertText (string accepted);
  360. /// <summary>Moves the selection in the Autocomplete context menu down one</summary>
  361. protected void MoveDown ()
  362. {
  363. SelectedIdx++;
  364. if (SelectedIdx > Suggestions.Count - 1)
  365. {
  366. SelectedIdx = 0;
  367. }
  368. EnsureSelectedIdxIsValid ();
  369. HostControl?.SetNeedsDisplay ();
  370. }
  371. /// <summary>Moves the selection in the Autocomplete context menu up one</summary>
  372. protected void MoveUp ()
  373. {
  374. SelectedIdx--;
  375. if (SelectedIdx < 0)
  376. {
  377. SelectedIdx = Suggestions.Count - 1;
  378. }
  379. EnsureSelectedIdxIsValid ();
  380. HostControl?.SetNeedsDisplay ();
  381. }
  382. /// <summary>Render the current selection in the Autocomplete context menu by the mouse reporting.</summary>
  383. /// <param name="me"></param>
  384. protected void RenderSelectedIdxByMouse (MouseEvent me)
  385. {
  386. if (SelectedIdx != me.Y - ScrollOffset)
  387. {
  388. SelectedIdx = me.Y - ScrollOffset;
  389. if (LastPopupPos != null)
  390. {
  391. RenderOverlay ((Point)LastPopupPos);
  392. }
  393. }
  394. }
  395. /// <summary>Reopen the popup after it has been closed.</summary>
  396. /// <returns></returns>
  397. protected bool ReopenSuggestions ()
  398. {
  399. // TODO: Revisit
  400. //GenerateSuggestions ();
  401. if (Suggestions.Count > 0)
  402. {
  403. Visible = true;
  404. closed = false;
  405. HostControl?.SetNeedsDisplay ();
  406. return true;
  407. }
  408. return false;
  409. }
  410. /// <summary>
  411. /// Completes the autocomplete selection process. Called when user hits the
  412. /// <see cref="IAutocomplete.SelectionKey"/>.
  413. /// </summary>
  414. /// <returns></returns>
  415. protected bool Select ()
  416. {
  417. if (SelectedIdx >= 0 && SelectedIdx < Suggestions.Count)
  418. {
  419. Suggestion accepted = Suggestions [SelectedIdx];
  420. return InsertSelection (accepted);
  421. }
  422. return false;
  423. }
  424. /// <summary>Set the cursor position in the <see cref="HostControl"/>.</summary>
  425. /// <param name="column"></param>
  426. protected abstract void SetCursorPosition (int column);
  427. private void ManipulatePopup ()
  428. {
  429. if (Visible && popup == null)
  430. {
  431. popup = new Popup (this) { Frame = Rect.Empty };
  432. top?.Add (popup);
  433. }
  434. if (!Visible && popup != null)
  435. {
  436. top?.Remove (popup);
  437. popup.Dispose ();
  438. popup = null;
  439. }
  440. }
  441. private void Top_DrawContent (object sender, DrawEventArgs e)
  442. {
  443. if (!closed)
  444. {
  445. ReopenSuggestions ();
  446. }
  447. ManipulatePopup ();
  448. if (Visible)
  449. {
  450. top.BringSubviewToFront (popup);
  451. }
  452. }
  453. private void Top_DrawContentComplete (object sender, DrawEventArgs e) { ManipulatePopup (); }
  454. private void Top_Removed (object sender, SuperViewChangedEventArgs e)
  455. {
  456. Visible = false;
  457. ManipulatePopup ();
  458. }
  459. private class Popup : View
  460. {
  461. private readonly PopupAutocomplete autocomplete;
  462. public Popup (PopupAutocomplete autocomplete)
  463. {
  464. this.autocomplete = autocomplete;
  465. CanFocus = true;
  466. WantMousePositionReports = true;
  467. }
  468. public override bool MouseEvent (MouseEvent mouseEvent) { return autocomplete.MouseEvent (mouseEvent); }
  469. public override void OnDrawContent (Rect contentArea)
  470. {
  471. if (autocomplete.LastPopupPos == null)
  472. {
  473. return;
  474. }
  475. autocomplete.RenderOverlay ((Point)autocomplete.LastPopupPos);
  476. }
  477. }
  478. }