PopupAutocomplete.cs 13 KB

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