Autocomplete.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using System.Text;
  6. using Rune = System.Rune;
  7. namespace Terminal.Gui {
  8. /// <summary>
  9. /// Renders an overlay on another view at a given point that allows selecting
  10. /// from a range of 'autocomplete' options.
  11. /// </summary>
  12. public abstract class Autocomplete : IAutocomplete {
  13. private class Popup : View {
  14. Autocomplete autocomplete;
  15. public Popup (Autocomplete autocomplete)
  16. {
  17. this.autocomplete = autocomplete;
  18. CanFocus = true;
  19. WantMousePositionReports = true;
  20. }
  21. public override Rect Frame {
  22. get => base.Frame;
  23. set {
  24. base.Frame = value;
  25. X = value.X;
  26. Y = value.Y;
  27. Width = value.Width;
  28. Height = value.Height;
  29. }
  30. }
  31. public override void Redraw (Rect bounds)
  32. {
  33. if (autocomplete.LastPopupPos == null) {
  34. return;
  35. }
  36. autocomplete.RenderOverlay ((Point)autocomplete.LastPopupPos);
  37. }
  38. public override bool MouseEvent (MouseEvent mouseEvent)
  39. {
  40. return autocomplete.MouseEvent (mouseEvent);
  41. }
  42. }
  43. private View top, popup;
  44. private bool closed;
  45. int toRenderLength;
  46. private Point? LastPopupPos { get; set; }
  47. private ColorScheme colorScheme;
  48. private View hostControl;
  49. /// <summary>
  50. /// The host control to handle.
  51. /// </summary>
  52. public virtual View HostControl {
  53. get => hostControl;
  54. set {
  55. hostControl = value;
  56. top = hostControl.SuperView;
  57. if (top != null) {
  58. top.DrawContent += Top_DrawContent;
  59. top.DrawContentComplete += Top_DrawContentComplete;
  60. top.Removed += Top_Removed;
  61. }
  62. }
  63. }
  64. private void Top_Removed (View obj)
  65. {
  66. Visible = false;
  67. ManipulatePopup ();
  68. }
  69. private void Top_DrawContentComplete (Rect obj)
  70. {
  71. ManipulatePopup ();
  72. }
  73. private void Top_DrawContent (Rect obj)
  74. {
  75. if (!closed) {
  76. ReopenSuggestions ();
  77. }
  78. ManipulatePopup ();
  79. if (Visible) {
  80. top.BringSubviewToFront (popup);
  81. }
  82. }
  83. private void ManipulatePopup ()
  84. {
  85. if (Visible && popup == null) {
  86. popup = new Popup (this) {
  87. Frame = Rect.Empty
  88. };
  89. top?.Add (popup);
  90. }
  91. if (!Visible && popup != null) {
  92. top.Remove (popup);
  93. popup.Dispose ();
  94. popup = null;
  95. }
  96. }
  97. /// <summary>
  98. /// Gets or sets If the popup is displayed inside or outside the host limits.
  99. /// </summary>
  100. public bool PopupInsideContainer { get; set; } = true;
  101. /// <summary>
  102. /// The maximum width of the autocomplete dropdown
  103. /// </summary>
  104. public virtual int MaxWidth { get; set; } = 10;
  105. /// <summary>
  106. /// The maximum number of visible rows in the autocomplete dropdown to render
  107. /// </summary>
  108. public virtual int MaxHeight { get; set; } = 6;
  109. /// <summary>
  110. /// True if the autocomplete should be considered open and visible
  111. /// </summary>
  112. public virtual bool Visible { get; set; }
  113. /// <summary>
  114. /// The strings that form the current list of suggestions to render
  115. /// based on what the user has typed so far.
  116. /// </summary>
  117. public virtual ReadOnlyCollection<string> Suggestions { get; set; } = new ReadOnlyCollection<string> (new string [0]);
  118. /// <summary>
  119. /// The full set of all strings that can be suggested.
  120. /// </summary>
  121. /// <returns></returns>
  122. public virtual List<string> AllSuggestions { get; set; } = new List<string> ();
  123. /// <summary>
  124. /// The currently selected index into <see cref="Suggestions"/> that the user has highlighted
  125. /// </summary>
  126. public virtual int SelectedIdx { get; set; }
  127. /// <summary>
  128. /// When more suggestions are available than can be rendered the user
  129. /// can scroll down the dropdown list. This indicates how far down they
  130. /// have gone
  131. /// </summary>
  132. public virtual int ScrollOffset { get; set; }
  133. /// <summary>
  134. /// The colors to use to render the overlay. Accessing this property before
  135. /// the Application has been initialized will cause an error
  136. /// </summary>
  137. public virtual ColorScheme ColorScheme {
  138. get {
  139. if (colorScheme == null) {
  140. colorScheme = Colors.Menu;
  141. }
  142. return colorScheme;
  143. }
  144. set {
  145. colorScheme = value;
  146. }
  147. }
  148. /// <summary>
  149. /// The key that the user must press to accept the currently selected autocomplete suggestion
  150. /// </summary>
  151. public virtual Key SelectionKey { get; set; } = Key.Enter;
  152. /// <summary>
  153. /// The key that the user can press to close the currently popped autocomplete menu
  154. /// </summary>
  155. public virtual Key CloseKey { get; set; } = Key.Esc;
  156. /// <summary>
  157. /// The key that the user can press to reopen the currently popped autocomplete menu
  158. /// </summary>
  159. public virtual Key Reopen { get; set; } = Key.Space | Key.CtrlMask | Key.AltMask;
  160. /// <summary>
  161. /// Renders the autocomplete dialog inside or outside the given <see cref="HostControl"/> at the
  162. /// given point.
  163. /// </summary>
  164. /// <param name="renderAt"></param>
  165. public virtual void RenderOverlay (Point renderAt)
  166. {
  167. if (!Visible || HostControl?.HasFocus == false || Suggestions.Count == 0) {
  168. LastPopupPos = null;
  169. Visible = false;
  170. return;
  171. }
  172. LastPopupPos = renderAt;
  173. int height, width;
  174. if (PopupInsideContainer) {
  175. // don't overspill vertically
  176. height = Math.Min (HostControl.Bounds.Height - renderAt.Y, MaxHeight);
  177. // There is no space below, lets see if can popup on top
  178. if (height < Suggestions.Count && HostControl.Bounds.Height - renderAt.Y >= height) {
  179. // Verifies that the upper limit available is greater than the lower limit
  180. if (renderAt.Y > HostControl.Bounds.Height - renderAt.Y) {
  181. renderAt.Y = Math.Max (renderAt.Y - Math.Min (Suggestions.Count + 1, MaxHeight + 1), 0);
  182. height = Math.Min (Math.Min (Suggestions.Count, MaxHeight), LastPopupPos.Value.Y - 1);
  183. }
  184. }
  185. } else {
  186. // don't overspill vertically
  187. height = Math.Min (Math.Min (top.Bounds.Height - HostControl.Frame.Bottom, MaxHeight), Suggestions.Count);
  188. // There is no space below, lets see if can popup on top
  189. if (height < Suggestions.Count && HostControl.Frame.Y - top.Frame.Y >= height) {
  190. // Verifies that the upper limit available is greater than the lower limit
  191. if (HostControl.Frame.Y > top.Bounds.Height - HostControl.Frame.Y) {
  192. renderAt.Y = Math.Max (HostControl.Frame.Y - Math.Min (Suggestions.Count, MaxHeight), 0);
  193. height = Math.Min (Math.Min (Suggestions.Count, MaxHeight), HostControl.Frame.Y);
  194. }
  195. } else {
  196. renderAt.Y = HostControl.Frame.Bottom;
  197. }
  198. }
  199. if (ScrollOffset > Suggestions.Count - height) {
  200. ScrollOffset = 0;
  201. }
  202. var toRender = Suggestions.Skip (ScrollOffset).Take (height).ToArray ();
  203. toRenderLength = toRender.Length;
  204. if (toRender.Length == 0) {
  205. return;
  206. }
  207. width = Math.Min (MaxWidth, toRender.Max (s => s.Length));
  208. if (PopupInsideContainer) {
  209. // don't overspill horizontally, let's see if can be displayed on the left
  210. if (width > HostControl.Bounds.Width - renderAt.X) {
  211. // Verifies that the left limit available is greater than the right limit
  212. if (renderAt.X > HostControl.Bounds.Width - renderAt.X) {
  213. renderAt.X -= Math.Min (width, LastPopupPos.Value.X);
  214. width = Math.Min (width, LastPopupPos.Value.X);
  215. } else {
  216. width = Math.Min (width, HostControl.Bounds.Width - renderAt.X);
  217. }
  218. }
  219. } else {
  220. // don't overspill horizontally, let's see if can be displayed on the left
  221. if (width > top.Bounds.Width - (renderAt.X + HostControl.Frame.X)) {
  222. // Verifies that the left limit available is greater than the right limit
  223. if (renderAt.X + HostControl.Frame.X > top.Bounds.Width - (renderAt.X + HostControl.Frame.X)) {
  224. renderAt.X -= Math.Min (width, LastPopupPos.Value.X);
  225. width = Math.Min (width, LastPopupPos.Value.X);
  226. } else {
  227. width = Math.Min (width, top.Bounds.Width - renderAt.X);
  228. }
  229. }
  230. }
  231. if (PopupInsideContainer) {
  232. popup.Frame = new Rect (
  233. new Point (HostControl.Frame.X + renderAt.X, HostControl.Frame.Y + renderAt.Y),
  234. new Size (width, height));
  235. } else {
  236. popup.Frame = new Rect (
  237. new Point (HostControl.Frame.X + renderAt.X, renderAt.Y),
  238. new Size (width, height));
  239. }
  240. popup.Move (0, 0);
  241. for (int i = 0; i < toRender.Length; i++) {
  242. if (i == SelectedIdx - ScrollOffset) {
  243. Application.Driver.SetAttribute (ColorScheme.Focus);
  244. } else {
  245. Application.Driver.SetAttribute (ColorScheme.Normal);
  246. }
  247. popup.Move (0, i);
  248. var text = TextFormatter.ClipOrPad (toRender [i], width);
  249. Application.Driver.AddStr (text);
  250. }
  251. }
  252. /// <summary>
  253. /// Updates <see cref="SelectedIdx"/> to be a valid index within <see cref="Suggestions"/>
  254. /// </summary>
  255. public virtual void EnsureSelectedIdxIsValid ()
  256. {
  257. SelectedIdx = Math.Max (0, Math.Min (Suggestions.Count - 1, SelectedIdx));
  258. // if user moved selection up off top of current scroll window
  259. if (SelectedIdx < ScrollOffset) {
  260. ScrollOffset = SelectedIdx;
  261. }
  262. // if user moved selection down past bottom of current scroll window
  263. while (toRenderLength > 0 && SelectedIdx >= ScrollOffset + toRenderLength) {
  264. ScrollOffset++;
  265. }
  266. }
  267. /// <summary>
  268. /// Handle key events before <see cref="HostControl"/> e.g. to make key events like
  269. /// up/down apply to the autocomplete control instead of changing the cursor position in
  270. /// the underlying text view.
  271. /// </summary>
  272. /// <param name="kb">The key event.</param>
  273. /// <returns><c>true</c>if the key can be handled <c>false</c>otherwise.</returns>
  274. public virtual bool ProcessKey (KeyEvent kb)
  275. {
  276. if (IsWordChar ((char)kb.Key)) {
  277. Visible = true;
  278. closed = false;
  279. }
  280. if (kb.Key == Reopen) {
  281. return ReopenSuggestions ();
  282. }
  283. if (closed || Suggestions.Count == 0) {
  284. Visible = false;
  285. return false;
  286. }
  287. if (kb.Key == Key.CursorDown) {
  288. MoveDown ();
  289. return true;
  290. }
  291. if (kb.Key == Key.CursorUp) {
  292. MoveUp ();
  293. return true;
  294. }
  295. if (kb.Key == SelectionKey) {
  296. return Select ();
  297. }
  298. if (kb.Key == CloseKey) {
  299. Close ();
  300. return true;
  301. }
  302. return false;
  303. }
  304. /// <summary>
  305. /// Handle mouse events before <see cref="HostControl"/> e.g. to make mouse events like
  306. /// report/click apply to the autocomplete control instead of changing the cursor position in
  307. /// the underlying text view.
  308. /// </summary>
  309. /// <param name="me">The mouse event.</param>
  310. /// <param name="fromHost">If was called from the popup or from the host.</param>
  311. /// <returns><c>true</c>if the mouse can be handled <c>false</c>otherwise.</returns>
  312. public virtual bool MouseEvent (MouseEvent me, bool fromHost = false)
  313. {
  314. if (fromHost) {
  315. GenerateSuggestions ();
  316. if (Visible && Suggestions.Count == 0) {
  317. Visible = false;
  318. HostControl?.SetNeedsDisplay ();
  319. return true;
  320. } else if (!Visible && Suggestions.Count > 0) {
  321. Visible = true;
  322. HostControl?.SetNeedsDisplay ();
  323. Application.UngrabMouse ();
  324. return false;
  325. } else {
  326. // not in the popup
  327. if (Visible && HostControl != null) {
  328. Visible = false;
  329. closed = false;
  330. }
  331. HostControl?.SetNeedsDisplay ();
  332. }
  333. return false;
  334. }
  335. if (popup == null || Suggestions.Count == 0) {
  336. ManipulatePopup ();
  337. return false;
  338. }
  339. if (me.Flags == MouseFlags.ReportMousePosition) {
  340. RenderSelectedIdxByMouse (me);
  341. return true;
  342. }
  343. if (me.Flags == MouseFlags.Button1Clicked) {
  344. SelectedIdx = me.Y - ScrollOffset;
  345. return Select ();
  346. }
  347. if (me.Flags == MouseFlags.WheeledDown) {
  348. MoveDown ();
  349. return true;
  350. }
  351. if (me.Flags == MouseFlags.WheeledUp) {
  352. MoveUp ();
  353. return true;
  354. }
  355. return false;
  356. }
  357. /// <summary>
  358. /// Render the current selection in the Autocomplete context menu by the mouse reporting.
  359. /// </summary>
  360. /// <param name="me"></param>
  361. protected void RenderSelectedIdxByMouse (MouseEvent me)
  362. {
  363. if (SelectedIdx != me.Y - ScrollOffset) {
  364. SelectedIdx = me.Y - ScrollOffset;
  365. if (LastPopupPos != null) {
  366. RenderOverlay ((Point)LastPopupPos);
  367. }
  368. }
  369. }
  370. /// <summary>
  371. /// Clears <see cref="Suggestions"/>
  372. /// </summary>
  373. public virtual void ClearSuggestions ()
  374. {
  375. Suggestions = Enumerable.Empty<string> ().ToList ().AsReadOnly ();
  376. }
  377. /// <summary>
  378. /// Populates <see cref="Suggestions"/> with all strings in <see cref="AllSuggestions"/> that
  379. /// match with the current cursor position/text in the <see cref="HostControl"/>
  380. /// </summary>
  381. public virtual void GenerateSuggestions ()
  382. {
  383. // if there is nothing to pick from
  384. if (AllSuggestions.Count == 0) {
  385. ClearSuggestions ();
  386. return;
  387. }
  388. var currentWord = GetCurrentWord ();
  389. if (string.IsNullOrWhiteSpace (currentWord)) {
  390. ClearSuggestions ();
  391. } else {
  392. Suggestions = AllSuggestions.Where (o =>
  393. o.StartsWith (currentWord, StringComparison.CurrentCultureIgnoreCase) &&
  394. !o.Equals (currentWord, StringComparison.CurrentCultureIgnoreCase)
  395. ).ToList ().AsReadOnly ();
  396. EnsureSelectedIdxIsValid ();
  397. }
  398. }
  399. /// <summary>
  400. /// Return true if the given symbol should be considered part of a word
  401. /// and can be contained in matches. Base behavior is to use <see cref="char.IsLetterOrDigit(char)"/>
  402. /// </summary>
  403. /// <param name="rune"></param>
  404. /// <returns></returns>
  405. public virtual bool IsWordChar (Rune rune)
  406. {
  407. return Char.IsLetterOrDigit ((char)rune);
  408. }
  409. /// <summary>
  410. /// Completes the autocomplete selection process. Called when user hits the <see cref="SelectionKey"/>.
  411. /// </summary>
  412. /// <returns></returns>
  413. protected bool Select ()
  414. {
  415. if (SelectedIdx >= 0 && SelectedIdx < Suggestions.Count) {
  416. var accepted = Suggestions [SelectedIdx];
  417. return InsertSelection (accepted);
  418. }
  419. return false;
  420. }
  421. /// <summary>
  422. /// Called when the user confirms a selection at the current cursor location in
  423. /// the <see cref="HostControl"/>. The <paramref name="accepted"/> string
  424. /// is the full autocomplete word to be inserted. Typically a host will have to
  425. /// remove some characters such that the <paramref name="accepted"/> string
  426. /// completes the word instead of simply being appended.
  427. /// </summary>
  428. /// <param name="accepted"></param>
  429. /// <returns>True if the insertion was possible otherwise false</returns>
  430. protected virtual bool InsertSelection (string accepted)
  431. {
  432. var typedSoFar = GetCurrentWord () ?? "";
  433. if (typedSoFar.Length < accepted.Length) {
  434. // delete the text
  435. for (int i = 0; i < typedSoFar.Length; i++) {
  436. DeleteTextBackwards ();
  437. }
  438. InsertText (accepted);
  439. return true;
  440. }
  441. return false;
  442. }
  443. /// <summary>
  444. /// Returns the currently selected word from the <see cref="HostControl"/>.
  445. /// <para>
  446. /// When overriding this method views can make use of <see cref="IdxToWord(List{Rune}, int)"/>
  447. /// </para>
  448. /// </summary>
  449. /// <returns></returns>
  450. protected abstract string GetCurrentWord ();
  451. /// <summary>
  452. /// <para>
  453. /// Given a <paramref name="line"/> of characters, returns the word which ends at <paramref name="idx"/>
  454. /// or null. Also returns null if the <paramref name="idx"/> is positioned in the middle of a word.
  455. /// </para>
  456. ///
  457. /// <para>Use this method to determine whether autocomplete should be shown when the cursor is at
  458. /// a given point in a line and to get the word from which suggestions should be generated.</para>
  459. /// </summary>
  460. /// <param name="line"></param>
  461. /// <param name="idx"></param>
  462. /// <returns></returns>
  463. protected virtual string IdxToWord (List<Rune> line, int idx)
  464. {
  465. StringBuilder sb = new StringBuilder ();
  466. // do not generate suggestions if the cursor is positioned in the middle of a word
  467. bool areMidWord;
  468. if (idx == line.Count) {
  469. // the cursor positioned at the very end of the line
  470. areMidWord = false;
  471. } else {
  472. // we are in the middle of a word if the cursor is over a letter/number
  473. areMidWord = IsWordChar (line [idx]);
  474. }
  475. // if we are in the middle of a word then there is no way to autocomplete that word
  476. if (areMidWord) {
  477. return null;
  478. }
  479. // we are at the end of a word. Work out what has been typed so far
  480. while (idx-- > 0) {
  481. if (IsWordChar (line [idx])) {
  482. sb.Insert (0, (char)line [idx]);
  483. } else {
  484. break;
  485. }
  486. }
  487. return sb.ToString ();
  488. }
  489. /// <summary>
  490. /// Deletes the text backwards before insert the selected text in the <see cref="HostControl"/>.
  491. /// </summary>
  492. protected abstract void DeleteTextBackwards ();
  493. /// <summary>
  494. /// Inser the selected text in the <see cref="HostControl"/>.
  495. /// </summary>
  496. /// <param name="accepted"></param>
  497. protected abstract void InsertText (string accepted);
  498. /// <summary>
  499. /// Closes the Autocomplete context menu if it is showing and <see cref="ClearSuggestions"/>
  500. /// </summary>
  501. protected void Close ()
  502. {
  503. ClearSuggestions ();
  504. Visible = false;
  505. closed = true;
  506. HostControl?.SetNeedsDisplay ();
  507. ManipulatePopup ();
  508. }
  509. /// <summary>
  510. /// Moves the selection in the Autocomplete context menu up one
  511. /// </summary>
  512. protected void MoveUp ()
  513. {
  514. SelectedIdx--;
  515. if (SelectedIdx < 0) {
  516. SelectedIdx = Suggestions.Count - 1;
  517. }
  518. EnsureSelectedIdxIsValid ();
  519. HostControl?.SetNeedsDisplay ();
  520. }
  521. /// <summary>
  522. /// Moves the selection in the Autocomplete context menu down one
  523. /// </summary>
  524. protected void MoveDown ()
  525. {
  526. SelectedIdx++;
  527. if (SelectedIdx > Suggestions.Count - 1) {
  528. SelectedIdx = 0;
  529. }
  530. EnsureSelectedIdxIsValid ();
  531. HostControl?.SetNeedsDisplay ();
  532. }
  533. /// <summary>
  534. /// Reopen the popup after it has been closed.
  535. /// </summary>
  536. /// <returns></returns>
  537. protected bool ReopenSuggestions ()
  538. {
  539. GenerateSuggestions ();
  540. if (Suggestions.Count > 0) {
  541. Visible = true;
  542. closed = false;
  543. HostControl?.SetNeedsDisplay ();
  544. return true;
  545. }
  546. return false;
  547. }
  548. }
  549. }