PopupAutocomplete.cs 13 KB

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