TextField.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. //
  2. // TextField.cs: single-line text editor with Emacs keybindings
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Linq;
  11. using System.Threading;
  12. using NStack;
  13. using Terminal.Gui.Resources;
  14. using Rune = System.Rune;
  15. namespace Terminal.Gui {
  16. /// <summary>
  17. /// Single-line text entry <see cref="View"/>
  18. /// </summary>
  19. /// <remarks>
  20. /// The <see cref="TextField"/> <see cref="View"/> provides editing functionality and mouse support.
  21. /// </remarks>
  22. public class TextField : View {
  23. List<Rune> text;
  24. int first, point;
  25. int selectedStart = -1; // -1 represents there is no text selection.
  26. ustring selectedText;
  27. HistoryText historyText = new HistoryText ();
  28. CultureInfo currentCulture;
  29. /// <summary>
  30. /// Gets or sets the text to render in control when no value has
  31. /// been entered yet and the <see cref="View"/> does not yet have
  32. /// input focus.
  33. /// </summary>
  34. public ustring Caption { get; set; }
  35. /// <summary>
  36. /// Gets or sets the foreground <see cref="Color"/> to use when
  37. /// rendering <see cref="Caption"/>.
  38. /// </summary>
  39. public Color CaptionColor { get; set; } = Color.DarkGray;
  40. /// <summary>
  41. /// Tracks whether the text field should be considered "used", that is, that the user has moved in the entry, so new input should be appended at the cursor position, rather than clearing the entry
  42. /// </summary>
  43. public bool Used { get; set; }
  44. /// <summary>
  45. /// If set to true its not allow any changes in the text.
  46. /// </summary>
  47. public bool ReadOnly { get; set; } = false;
  48. /// <summary>
  49. /// Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.
  50. /// </summary>
  51. public event EventHandler<TextChangingEventArgs> TextChanging;
  52. /// <summary>
  53. /// Changed event, raised when the text has changed.
  54. /// </summary>
  55. /// <remarks>
  56. /// This event is raised when the <see cref="Text"/> changes.
  57. /// </remarks>
  58. /// <remarks>
  59. /// The passed <see cref="EventArgs"/> is a <see cref="NStack.ustring"/> containing the old value.
  60. /// </remarks>
  61. public event EventHandler<TextChangedEventArgs> TextChanged;
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="TextField"/> class using <see cref="LayoutStyle.Computed"/> positioning.
  64. /// </summary>
  65. /// <param name="text">Initial text contents.</param>
  66. public TextField (string text) : this (ustring.Make (text)) { }
  67. /// <summary>
  68. /// Initializes a new instance of the <see cref="TextField"/> class using <see cref="LayoutStyle.Computed"/> positioning.
  69. /// </summary>
  70. public TextField () : this (string.Empty) { }
  71. /// <summary>
  72. /// Initializes a new instance of the <see cref="TextField"/> class using <see cref="LayoutStyle.Computed"/> positioning.
  73. /// </summary>
  74. /// <param name="text">Initial text contents.</param>
  75. public TextField (ustring text) : base (text)
  76. {
  77. Initialize (text, text.RuneCount + 1);
  78. }
  79. /// <summary>
  80. /// Initializes a new instance of the <see cref="TextField"/> class using <see cref="LayoutStyle.Absolute"/> positioning.
  81. /// </summary>
  82. /// <param name="x">The x coordinate.</param>
  83. /// <param name="y">The y coordinate.</param>
  84. /// <param name="w">The width.</param>
  85. /// <param name="text">Initial text contents.</param>
  86. public TextField (int x, int y, int w, ustring text) : base (new Rect (x, y, w, 1))
  87. {
  88. Initialize (text, w);
  89. }
  90. void Initialize (ustring text, int w)
  91. {
  92. Height = 1;
  93. if (text == null)
  94. text = "";
  95. this.text = TextModel.ToRunes (text.Split ("\n") [0]);
  96. point = text.RuneCount;
  97. first = point > w + 1 ? point - w + 1 : 0;
  98. CanFocus = true;
  99. Used = true;
  100. WantMousePositionReports = true;
  101. savedCursorVisibility = desiredCursorVisibility;
  102. historyText.ChangeText += HistoryText_ChangeText;
  103. Initialized += TextField_Initialized;
  104. // Things this view knows how to do
  105. AddCommand (Command.DeleteCharRight, () => { DeleteCharRight (); return true; });
  106. AddCommand (Command.DeleteCharLeft, () => { DeleteCharLeft (); return true; });
  107. AddCommand (Command.LeftHomeExtend, () => { MoveHomeExtend (); return true; });
  108. AddCommand (Command.RightEndExtend, () => { MoveEndExtend (); return true; });
  109. AddCommand (Command.LeftHome, () => { MoveHome (); return true; });
  110. AddCommand (Command.LeftExtend, () => { MoveLeftExtend (); return true; });
  111. AddCommand (Command.RightExtend, () => { MoveRightExtend (); return true; });
  112. AddCommand (Command.WordLeftExtend, () => { MoveWordLeftExtend (); return true; });
  113. AddCommand (Command.WordRightExtend, () => { MoveWordRightExtend (); return true; });
  114. AddCommand (Command.Left, () => { MoveLeft (); return true; });
  115. AddCommand (Command.RightEnd, () => { MoveEnd (); return true; });
  116. AddCommand (Command.Right, () => { MoveRight (); return true; });
  117. AddCommand (Command.CutToEndLine, () => { KillToEnd (); return true; });
  118. AddCommand (Command.CutToStartLine, () => { KillToStart (); return true; });
  119. AddCommand (Command.Undo, () => { UndoChanges (); return true; });
  120. AddCommand (Command.Redo, () => { RedoChanges (); return true; });
  121. AddCommand (Command.WordLeft, () => { MoveWordLeft (); return true; });
  122. AddCommand (Command.WordRight, () => { MoveWordRight (); return true; });
  123. AddCommand (Command.KillWordForwards, () => { KillWordForwards (); return true; });
  124. AddCommand (Command.KillWordBackwards, () => { KillWordBackwards (); return true; });
  125. AddCommand (Command.ToggleOverwrite, () => { SetOverwrite (!Used); return true; });
  126. AddCommand (Command.EnableOverwrite, () => { SetOverwrite (true); return true; });
  127. AddCommand (Command.DisableOverwrite, () => { SetOverwrite (false); return true; });
  128. AddCommand (Command.Copy, () => { Copy (); return true; });
  129. AddCommand (Command.Cut, () => { Cut (); return true; });
  130. AddCommand (Command.Paste, () => { Paste (); return true; });
  131. AddCommand (Command.SelectAll, () => { SelectAll (); return true; });
  132. AddCommand (Command.DeleteAll, () => { DeleteAll (); return true; });
  133. AddCommand (Command.Accept, () => { ShowContextMenu (); return true; });
  134. // Default keybindings for this view
  135. AddKeyBinding (Key.DeleteChar, Command.DeleteCharRight);
  136. AddKeyBinding (Key.D | Key.CtrlMask, Command.DeleteCharRight);
  137. AddKeyBinding (Key.Delete, Command.DeleteCharLeft);
  138. AddKeyBinding (Key.Backspace, Command.DeleteCharLeft);
  139. AddKeyBinding (Key.Home | Key.ShiftMask, Command.LeftHomeExtend);
  140. AddKeyBinding (Key.Home | Key.ShiftMask | Key.CtrlMask, Command.LeftHomeExtend);
  141. AddKeyBinding (Key.A | Key.ShiftMask | Key.CtrlMask, Command.LeftHomeExtend);
  142. AddKeyBinding (Key.End | Key.ShiftMask, Command.RightEndExtend);
  143. AddKeyBinding (Key.End | Key.ShiftMask | Key.CtrlMask, Command.RightEndExtend);
  144. AddKeyBinding (Key.E | Key.ShiftMask | Key.CtrlMask, Command.RightEndExtend);
  145. AddKeyBinding (Key.Home, Command.LeftHome);
  146. AddKeyBinding (Key.Home | Key.CtrlMask, Command.LeftHome);
  147. AddKeyBinding (Key.A | Key.CtrlMask, Command.LeftHome);
  148. AddKeyBinding (Key.CursorLeft | Key.ShiftMask, Command.LeftExtend);
  149. AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LeftExtend);
  150. AddKeyBinding (Key.CursorRight | Key.ShiftMask, Command.RightExtend);
  151. AddKeyBinding (Key.CursorDown | Key.ShiftMask, Command.RightExtend);
  152. AddKeyBinding (Key.CursorLeft | Key.ShiftMask | Key.CtrlMask, Command.WordLeftExtend);
  153. AddKeyBinding (Key.CursorUp | Key.ShiftMask | Key.CtrlMask, Command.WordLeftExtend);
  154. AddKeyBinding ((Key)((int)'B' + Key.ShiftMask | Key.AltMask), Command.WordLeftExtend);
  155. AddKeyBinding (Key.CursorRight | Key.ShiftMask | Key.CtrlMask, Command.WordRightExtend);
  156. AddKeyBinding (Key.CursorDown | Key.ShiftMask | Key.CtrlMask, Command.WordRightExtend);
  157. AddKeyBinding ((Key)((int)'F' + Key.ShiftMask | Key.AltMask), Command.WordRightExtend);
  158. AddKeyBinding (Key.CursorLeft, Command.Left);
  159. AddKeyBinding (Key.B | Key.CtrlMask, Command.Left);
  160. AddKeyBinding (Key.End, Command.RightEnd);
  161. AddKeyBinding (Key.End | Key.CtrlMask, Command.RightEnd);
  162. AddKeyBinding (Key.E | Key.CtrlMask, Command.RightEnd);
  163. AddKeyBinding (Key.CursorRight, Command.Right);
  164. AddKeyBinding (Key.F | Key.CtrlMask, Command.Right);
  165. AddKeyBinding (Key.K | Key.CtrlMask, Command.CutToEndLine);
  166. AddKeyBinding (Key.K | Key.AltMask, Command.CutToStartLine);
  167. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Undo);
  168. AddKeyBinding (Key.Backspace | Key.AltMask, Command.Undo);
  169. AddKeyBinding (Key.Y | Key.CtrlMask, Command.Redo);
  170. AddKeyBinding (Key.CursorLeft | Key.CtrlMask, Command.WordLeft);
  171. AddKeyBinding (Key.CursorUp | Key.CtrlMask, Command.WordLeft);
  172. AddKeyBinding ((Key)((int)'B' + Key.AltMask), Command.WordLeft);
  173. AddKeyBinding (Key.CursorRight | Key.CtrlMask, Command.WordRight);
  174. AddKeyBinding (Key.CursorDown | Key.CtrlMask, Command.WordRight);
  175. AddKeyBinding ((Key)((int)'F' + Key.AltMask), Command.WordRight);
  176. AddKeyBinding (Key.DeleteChar | Key.CtrlMask, Command.KillWordForwards);
  177. AddKeyBinding (Key.Backspace | Key.CtrlMask, Command.KillWordBackwards);
  178. AddKeyBinding (Key.InsertChar, Command.ToggleOverwrite);
  179. AddKeyBinding (Key.C | Key.CtrlMask, Command.Copy);
  180. AddKeyBinding (Key.X | Key.CtrlMask, Command.Cut);
  181. AddKeyBinding (Key.V | Key.CtrlMask, Command.Paste);
  182. AddKeyBinding (Key.T | Key.CtrlMask, Command.SelectAll);
  183. AddKeyBinding (Key.R | Key.CtrlMask, Command.DeleteAll);
  184. AddKeyBinding (Key.D | Key.CtrlMask | Key.ShiftMask, Command.DeleteAll);
  185. currentCulture = Thread.CurrentThread.CurrentUICulture;
  186. ContextMenu = new ContextMenu (this, BuildContextMenuBarItem ());
  187. ContextMenu.KeyChanged += ContextMenu_KeyChanged;
  188. AddKeyBinding (ContextMenu.Key, Command.Accept);
  189. }
  190. private MenuBarItem BuildContextMenuBarItem ()
  191. {
  192. return new MenuBarItem (new MenuItem [] {
  193. new MenuItem (Strings.ctxSelectAll, "", () => SelectAll (), null, null, GetKeyFromCommand (Command.SelectAll)),
  194. new MenuItem (Strings.ctxDeleteAll, "", () => DeleteAll (), null, null, GetKeyFromCommand (Command.DeleteAll)),
  195. new MenuItem (Strings.ctxCopy, "", () => Copy (), null, null, GetKeyFromCommand (Command.Copy)),
  196. new MenuItem (Strings.ctxCut, "", () => Cut (), null, null, GetKeyFromCommand (Command.Cut)),
  197. new MenuItem (Strings.ctxPaste, "", () => Paste (), null, null, GetKeyFromCommand (Command.Paste)),
  198. new MenuItem (Strings.ctxUndo, "", () => UndoChanges (), null, null, GetKeyFromCommand (Command.Undo)),
  199. new MenuItem (Strings.ctxRedo, "", () => RedoChanges (), null, null, GetKeyFromCommand (Command.Redo)),
  200. });
  201. }
  202. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e)
  203. {
  204. ReplaceKeyBinding (e.OldKey, e.NewKey);
  205. }
  206. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItem obj)
  207. {
  208. if (obj == null)
  209. return;
  210. Text = ustring.Make (obj?.Lines [obj.CursorPosition.Y]);
  211. CursorPosition = obj.CursorPosition.X;
  212. Adjust ();
  213. }
  214. void TextField_Initialized (object sender, EventArgs e)
  215. {
  216. Autocomplete.HostControl = this;
  217. Autocomplete.PopupInsideContainer = false;
  218. }
  219. ///<inheritdoc/>
  220. public override bool OnEnter (View view)
  221. {
  222. if (IsInitialized) {
  223. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  224. }
  225. return base.OnEnter (view);
  226. }
  227. ///<inheritdoc/>
  228. public override bool OnLeave (View view)
  229. {
  230. if (Application.MouseGrabView != null && Application.MouseGrabView == this)
  231. Application.UngrabMouse ();
  232. //if (SelectedLength != 0 && !(Application.MouseGrabView is MenuBar))
  233. // ClearAllSelection ();
  234. return base.OnLeave (view);
  235. }
  236. /// <summary>
  237. /// Provides autocomplete context menu based on suggestions at the current cursor
  238. /// position. Configure <see cref="ISuggestionGenerator"/> to enable this feature.
  239. /// </summary>
  240. public IAutocomplete Autocomplete { get; set; } = new TextFieldAutocomplete ();
  241. ///<inheritdoc/>
  242. public override Rect Frame {
  243. get => base.Frame;
  244. set {
  245. base.Frame = value;
  246. Adjust ();
  247. }
  248. }
  249. /// <summary>
  250. /// Sets or gets the text held by the view.
  251. /// </summary>
  252. /// <remarks>
  253. /// </remarks>
  254. public new ustring Text {
  255. get {
  256. return ustring.Make (text);
  257. }
  258. set {
  259. var oldText = ustring.Make (text);
  260. if (oldText == value)
  261. return;
  262. var newText = OnTextChanging (value.Replace ("\t", "").Split ("\n") [0]);
  263. if (newText.Cancel) {
  264. if (point > text.Count) {
  265. point = text.Count;
  266. }
  267. return;
  268. }
  269. ClearAllSelection ();
  270. text = TextModel.ToRunes (newText.NewText);
  271. if (!Secret && !historyText.IsFromHistory) {
  272. historyText.Add (new List<List<Rune>> () { oldText.ToRuneList () },
  273. new Point (point, 0));
  274. historyText.Add (new List<List<Rune>> () { text }, new Point (point, 0)
  275. , HistoryText.LineStatus.Replaced);
  276. }
  277. TextChanged?.Invoke (this, new TextChangedEventArgs (oldText));
  278. if (point > text.Count) {
  279. point = Math.Max (TextModel.DisplaySize (text, 0).size - 1, 0);
  280. }
  281. Adjust ();
  282. SetNeedsDisplay ();
  283. }
  284. }
  285. /// <summary>
  286. /// Sets the secret property.
  287. /// </summary>
  288. /// <remarks>
  289. /// This makes the text entry suitable for entering passwords.
  290. /// </remarks>
  291. public bool Secret { get; set; }
  292. /// <summary>
  293. /// Sets or gets the current cursor position.
  294. /// </summary>
  295. public virtual int CursorPosition {
  296. get { return point; }
  297. set {
  298. if (value < 0) {
  299. point = 0;
  300. } else if (value > text.Count) {
  301. point = text.Count;
  302. } else {
  303. point = value;
  304. }
  305. PrepareSelection (selectedStart, point - selectedStart);
  306. }
  307. }
  308. /// <summary>
  309. /// Gets the left offset position.
  310. /// </summary>
  311. public int ScrollOffset => first;
  312. /// <summary>
  313. /// Indicates whatever the text was changed or not.
  314. /// <see langword="true"/> if the text was changed <see langword="false"/> otherwise.
  315. /// </summary>
  316. public bool IsDirty => historyText.IsDirty (Text);
  317. /// <summary>
  318. /// Indicates whatever the text has history changes or not.
  319. /// <see langword="true"/> if the text has history changes <see langword="false"/> otherwise.
  320. /// </summary>
  321. public bool HasHistoryChanges => historyText.HasHistoryChanges;
  322. /// <summary>
  323. /// Get the <see cref="ContextMenu"/> for this view.
  324. /// </summary>
  325. public ContextMenu ContextMenu { get; private set; }
  326. /// <summary>
  327. /// Sets the cursor position.
  328. /// </summary>
  329. public override void PositionCursor ()
  330. {
  331. var col = 0;
  332. for (int idx = first < 0 ? 0 : first; idx < text.Count; idx++) {
  333. if (idx == point)
  334. break;
  335. var cols = Rune.ColumnWidth (text [idx]);
  336. TextModel.SetCol (ref col, Frame.Width - 1, cols);
  337. }
  338. var pos = point - first + Math.Min (Frame.X, 0);
  339. var offB = OffSetBackground ();
  340. var containerFrame = SuperView?.ViewToScreen (SuperView.Bounds) ?? default;
  341. var thisFrame = ViewToScreen (Bounds);
  342. if (pos > -1 && col >= pos && pos < Frame.Width + offB
  343. && containerFrame.IntersectsWith (thisFrame)) {
  344. RestoreCursorVisibility ();
  345. Move (col, 0);
  346. } else {
  347. HideCursorVisibility ();
  348. if (pos < 0) {
  349. Move (pos, 0, false);
  350. } else {
  351. Move (pos - offB, 0, false);
  352. }
  353. }
  354. }
  355. CursorVisibility savedCursorVisibility;
  356. void HideCursorVisibility ()
  357. {
  358. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  359. DesiredCursorVisibility = CursorVisibility.Invisible;
  360. }
  361. }
  362. void RestoreCursorVisibility ()
  363. {
  364. if (desiredCursorVisibility != savedCursorVisibility) {
  365. DesiredCursorVisibility = savedCursorVisibility;
  366. }
  367. }
  368. ///<inheritdoc/>
  369. public override void Redraw (Rect bounds)
  370. {
  371. var selColor = new Attribute (ColorScheme.Focus.Background, ColorScheme.Focus.Foreground);
  372. SetSelectedStartSelectedLength ();
  373. Driver.SetAttribute (GetNormalColor ());
  374. Move (0, 0);
  375. int p = first;
  376. int col = 0;
  377. int width = Frame.Width + OffSetBackground ();
  378. var tcount = text.Count;
  379. var roc = GetReadOnlyColor ();
  380. for (int idx = p; idx < tcount; idx++) {
  381. var rune = text [idx];
  382. var cols = Rune.ColumnWidth (rune);
  383. if (idx == point && HasFocus && !Used && length == 0 && !ReadOnly) {
  384. Driver.SetAttribute (selColor);
  385. } else if (ReadOnly) {
  386. Driver.SetAttribute (idx >= start && length > 0 && idx < start + length ? selColor : roc);
  387. } else if (!HasFocus && Enabled) {
  388. Driver.SetAttribute (ColorScheme.Focus);
  389. } else if (!Enabled) {
  390. Driver.SetAttribute (roc);
  391. } else {
  392. Driver.SetAttribute (idx >= start && length > 0 && idx < start + length ? selColor : ColorScheme.Focus);
  393. }
  394. if (col + cols <= width) {
  395. Driver.AddRune ((Rune)(Secret ? '*' : rune));
  396. }
  397. if (!TextModel.SetCol (ref col, width, cols)) {
  398. break;
  399. }
  400. if (idx + 1 < tcount && col + Rune.ColumnWidth (text [idx + 1]) > width) {
  401. break;
  402. }
  403. }
  404. Driver.SetAttribute (ColorScheme.Focus);
  405. for (int i = col; i < width; i++) {
  406. Driver.AddRune (' ');
  407. }
  408. PositionCursor ();
  409. RenderCaption ();
  410. if (SelectedLength > 0)
  411. return;
  412. // draw autocomplete
  413. GenerateSuggestions ();
  414. var renderAt = new Point (
  415. CursorPosition - ScrollOffset, 0);
  416. Autocomplete.RenderOverlay (renderAt);
  417. }
  418. private void RenderCaption ()
  419. {
  420. if (HasFocus || Caption == null || Caption.Length == 0
  421. || Text?.Length > 0) {
  422. return;
  423. }
  424. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  425. Driver.SetAttribute (color);
  426. Move (0, 0);
  427. var render = Caption;
  428. if (render.ConsoleWidth > Bounds.Width) {
  429. render = render.RuneSubstring (0, Bounds.Width);
  430. }
  431. Driver.AddStr (render);
  432. }
  433. private void GenerateSuggestions ()
  434. {
  435. var currentLine = Text.ToRuneList ();
  436. var cursorPosition = Math.Min (this.CursorPosition, currentLine.Count);
  437. Autocomplete.GenerateSuggestions (
  438. new AutocompleteContext (currentLine, cursorPosition)
  439. );
  440. }
  441. /// <inheritdoc/>
  442. public override Attribute GetNormalColor ()
  443. {
  444. return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
  445. }
  446. Attribute GetReadOnlyColor ()
  447. {
  448. if (ColorScheme.Disabled.Foreground == ColorScheme.Focus.Background) {
  449. return new Attribute (ColorScheme.Focus.Foreground, ColorScheme.Focus.Background);
  450. }
  451. return new Attribute (ColorScheme.Disabled.Foreground, ColorScheme.Focus.Background);
  452. }
  453. void Adjust ()
  454. {
  455. if (!IsAdded)
  456. return;
  457. int offB = OffSetBackground ();
  458. if (point < first) {
  459. first = point;
  460. } else if (Frame.Width > 0 && (first + point - (Frame.Width + offB) == 0 ||
  461. TextModel.DisplaySize (text, first, point).size >= Frame.Width + offB)) {
  462. first = Math.Max (TextModel.CalculateLeftColumn (text, first,
  463. point, Frame.Width + offB), 0);
  464. }
  465. SetNeedsDisplay ();
  466. }
  467. int OffSetBackground ()
  468. {
  469. int offB = 0;
  470. if (SuperView?.Frame.Right - Frame.Right < 0) {
  471. offB = SuperView.Frame.Right - Frame.Right - 1;
  472. }
  473. return offB;
  474. }
  475. void SetText (List<Rune> newText)
  476. {
  477. Text = ustring.Make (newText);
  478. }
  479. void SetText (IEnumerable<Rune> newText)
  480. {
  481. SetText (newText.ToList ());
  482. }
  483. ///<inheritdoc/>
  484. public override bool CanFocus {
  485. get => base.CanFocus;
  486. set { base.CanFocus = value; }
  487. }
  488. void SetClipboard (IEnumerable<Rune> text)
  489. {
  490. if (!Secret)
  491. Clipboard.Contents = ustring.Make (text.ToList ());
  492. }
  493. int oldCursorPos;
  494. /// <summary>
  495. /// Processes key presses for the <see cref="TextField"/>.
  496. /// </summary>
  497. /// <param name="kb"></param>
  498. /// <returns></returns>
  499. /// <remarks>
  500. /// The <see cref="TextField"/> control responds to the following keys:
  501. /// <list type="table">
  502. /// <listheader>
  503. /// <term>Keys</term>
  504. /// <description>Function</description>
  505. /// </listheader>
  506. /// <item>
  507. /// <term><see cref="Key.Delete"/>, <see cref="Key.Backspace"/></term>
  508. /// <description>Deletes the character before cursor.</description>
  509. /// </item>
  510. /// </list>
  511. /// </remarks>
  512. public override bool ProcessKey (KeyEvent kb)
  513. {
  514. // remember current cursor position
  515. // because the new calculated cursor position is needed to be set BEFORE the change event is triggest
  516. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  517. oldCursorPos = point;
  518. // Give autocomplete first opportunity to respond to key presses
  519. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (kb)) {
  520. return true;
  521. }
  522. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (kb),
  523. new KeyModifiers () { Alt = kb.IsAlt, Ctrl = kb.IsCtrl, Shift = kb.IsShift }));
  524. if (result != null)
  525. return (bool)result;
  526. // Ignore other control characters.
  527. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  528. return false;
  529. if (ReadOnly)
  530. return true;
  531. InsertText (kb);
  532. return true;
  533. }
  534. void InsertText (KeyEvent kb, bool useOldCursorPos = true)
  535. {
  536. historyText.Add (new List<List<Rune>> () { text }, new Point (point, 0));
  537. List<Rune> newText = text;
  538. if (length > 0) {
  539. newText = DeleteSelectedText ();
  540. oldCursorPos = point;
  541. }
  542. if (!useOldCursorPos) {
  543. oldCursorPos = point;
  544. }
  545. var kbstr = TextModel.ToRunes (ustring.Make ((uint)kb.Key));
  546. if (Used) {
  547. point++;
  548. if (point == newText.Count + 1) {
  549. SetText (newText.Concat (kbstr).ToList ());
  550. } else {
  551. if (oldCursorPos > newText.Count) {
  552. oldCursorPos = newText.Count;
  553. }
  554. SetText (newText.GetRange (0, oldCursorPos).Concat (kbstr).Concat (newText.GetRange (oldCursorPos, Math.Min (newText.Count - oldCursorPos, newText.Count))));
  555. }
  556. } else {
  557. SetText (newText.GetRange (0, oldCursorPos).Concat (kbstr).Concat (newText.GetRange (Math.Min (oldCursorPos + 1, newText.Count), Math.Max (newText.Count - oldCursorPos - 1, 0))));
  558. point++;
  559. }
  560. Adjust ();
  561. }
  562. void SetOverwrite (bool overwrite)
  563. {
  564. Used = overwrite;
  565. SetNeedsDisplay ();
  566. }
  567. TextModel GetModel ()
  568. {
  569. var model = new TextModel ();
  570. model.LoadString (Text);
  571. return model;
  572. }
  573. /// <summary>
  574. /// Deletes word backwards.
  575. /// </summary>
  576. public virtual void KillWordBackwards ()
  577. {
  578. ClearAllSelection ();
  579. var newPos = GetModel ().WordBackward (point, 0);
  580. if (newPos == null) return;
  581. if (newPos.Value.col != -1) {
  582. SetText (text.GetRange (0, newPos.Value.col).Concat (text.GetRange (point, text.Count - point)));
  583. point = newPos.Value.col;
  584. }
  585. Adjust ();
  586. }
  587. /// <summary>
  588. /// Deletes word forwards.
  589. /// </summary>
  590. public virtual void KillWordForwards ()
  591. {
  592. ClearAllSelection ();
  593. var newPos = GetModel ().WordForward (point, 0);
  594. if (newPos == null) return;
  595. if (newPos.Value.col != -1) {
  596. SetText (text.GetRange (0, point).Concat (text.GetRange (newPos.Value.col, text.Count - newPos.Value.col)));
  597. }
  598. Adjust ();
  599. }
  600. void MoveWordRight ()
  601. {
  602. ClearAllSelection ();
  603. var newPos = GetModel ().WordForward (point, 0);
  604. if (newPos == null) return;
  605. if (newPos.Value.col != -1)
  606. point = newPos.Value.col;
  607. Adjust ();
  608. }
  609. void MoveWordLeft ()
  610. {
  611. ClearAllSelection ();
  612. var newPos = GetModel ().WordBackward (point, 0);
  613. if (newPos == null) return;
  614. if (newPos.Value.col != -1)
  615. point = newPos.Value.col;
  616. Adjust ();
  617. }
  618. void RedoChanges ()
  619. {
  620. if (ReadOnly)
  621. return;
  622. historyText.Redo ();
  623. //if (ustring.IsNullOrEmpty (Clipboard.Contents))
  624. // return true;
  625. //var clip = TextModel.ToRunes (Clipboard.Contents);
  626. //if (clip == null)
  627. // return true;
  628. //if (point == text.Count) {
  629. // point = text.Count;
  630. // SetText(text.Concat(clip).ToList());
  631. //} else {
  632. // point += clip.Count;
  633. // SetText(text.GetRange(0, oldCursorPos).Concat(clip).Concat(text.GetRange(oldCursorPos, text.Count - oldCursorPos)));
  634. //}
  635. //Adjust ();
  636. }
  637. void UndoChanges ()
  638. {
  639. if (ReadOnly)
  640. return;
  641. historyText.Undo ();
  642. }
  643. void KillToStart ()
  644. {
  645. if (ReadOnly)
  646. return;
  647. ClearAllSelection ();
  648. if (point == 0)
  649. return;
  650. SetClipboard (text.GetRange (0, point));
  651. SetText (text.GetRange (point, text.Count - point));
  652. point = 0;
  653. Adjust ();
  654. }
  655. void KillToEnd ()
  656. {
  657. if (ReadOnly)
  658. return;
  659. ClearAllSelection ();
  660. if (point >= text.Count)
  661. return;
  662. SetClipboard (text.GetRange (point, text.Count - point));
  663. SetText (text.GetRange (0, point));
  664. Adjust ();
  665. }
  666. void MoveRight ()
  667. {
  668. ClearAllSelection ();
  669. if (point == text.Count)
  670. return;
  671. point++;
  672. Adjust ();
  673. }
  674. /// <summary>
  675. /// Moves cursor to the end of the typed text.
  676. /// </summary>
  677. public void MoveEnd ()
  678. {
  679. ClearAllSelection ();
  680. point = text.Count;
  681. Adjust ();
  682. }
  683. void MoveLeft ()
  684. {
  685. ClearAllSelection ();
  686. if (point > 0) {
  687. point--;
  688. Adjust ();
  689. }
  690. }
  691. void MoveWordRightExtend ()
  692. {
  693. if (point < text.Count) {
  694. int x = start > -1 && start > point ? start : point;
  695. var newPos = GetModel ().WordForward (x, 0);
  696. if (newPos == null) return;
  697. if (newPos.Value.col != -1)
  698. point = newPos.Value.col;
  699. PrepareSelection (x, newPos.Value.col - x);
  700. }
  701. }
  702. void MoveWordLeftExtend ()
  703. {
  704. if (point > 0) {
  705. int x = Math.Min (start > -1 && start > point ? start : point, text.Count);
  706. if (x > 0) {
  707. var newPos = GetModel ().WordBackward (x, 0);
  708. if (newPos == null) return;
  709. if (newPos.Value.col != -1)
  710. point = newPos.Value.col;
  711. PrepareSelection (x, newPos.Value.col - x);
  712. }
  713. }
  714. }
  715. void MoveRightExtend ()
  716. {
  717. if (point < text.Count) {
  718. PrepareSelection (point++, 1);
  719. }
  720. }
  721. void MoveLeftExtend ()
  722. {
  723. if (point > 0) {
  724. PrepareSelection (point--, -1);
  725. }
  726. }
  727. void MoveHome ()
  728. {
  729. ClearAllSelection ();
  730. point = 0;
  731. Adjust ();
  732. }
  733. void MoveEndExtend ()
  734. {
  735. if (point <= text.Count) {
  736. int x = point;
  737. point = text.Count;
  738. PrepareSelection (x, point - x);
  739. }
  740. }
  741. void MoveHomeExtend ()
  742. {
  743. if (point > 0) {
  744. int x = point;
  745. point = 0;
  746. PrepareSelection (x, point - x);
  747. }
  748. }
  749. /// <summary>
  750. /// Deletes the left character.
  751. /// </summary>
  752. public virtual void DeleteCharLeft (bool useOldCursorPos = true)
  753. {
  754. if (ReadOnly)
  755. return;
  756. historyText.Add (new List<List<Rune>> () { text }, new Point (point, 0));
  757. if (length == 0) {
  758. if (point == 0)
  759. return;
  760. if (!useOldCursorPos) {
  761. oldCursorPos = point;
  762. }
  763. point--;
  764. if (oldCursorPos < text.Count) {
  765. SetText (text.GetRange (0, oldCursorPos - 1).Concat (text.GetRange (oldCursorPos, text.Count - oldCursorPos)));
  766. } else {
  767. SetText (text.GetRange (0, oldCursorPos - 1));
  768. }
  769. Adjust ();
  770. } else {
  771. var newText = DeleteSelectedText ();
  772. Text = ustring.Make (newText);
  773. Adjust ();
  774. }
  775. }
  776. /// <summary>
  777. /// Deletes the right character.
  778. /// </summary>
  779. public virtual void DeleteCharRight ()
  780. {
  781. if (ReadOnly)
  782. return;
  783. historyText.Add (new List<List<Rune>> () { text }, new Point (point, 0));
  784. if (length == 0) {
  785. if (text.Count == 0 || text.Count == point)
  786. return;
  787. SetText (text.GetRange (0, point).Concat (text.GetRange (point + 1, text.Count - (point + 1))));
  788. Adjust ();
  789. } else {
  790. var newText = DeleteSelectedText ();
  791. Text = ustring.Make (newText);
  792. Adjust ();
  793. }
  794. }
  795. void ShowContextMenu ()
  796. {
  797. if (currentCulture != Thread.CurrentThread.CurrentUICulture) {
  798. currentCulture = Thread.CurrentThread.CurrentUICulture;
  799. ContextMenu.MenuItems = BuildContextMenuBarItem ();
  800. }
  801. ContextMenu.Show ();
  802. }
  803. /// <summary>
  804. /// Selects all text.
  805. /// </summary>
  806. public void SelectAll ()
  807. {
  808. if (text.Count == 0) {
  809. return;
  810. }
  811. selectedStart = 0;
  812. MoveEndExtend ();
  813. SetNeedsDisplay ();
  814. }
  815. /// <summary>
  816. /// Deletes all text.
  817. /// </summary>
  818. public void DeleteAll ()
  819. {
  820. if (text.Count == 0) {
  821. return;
  822. }
  823. selectedStart = 0;
  824. MoveEndExtend ();
  825. DeleteCharLeft ();
  826. SetNeedsDisplay ();
  827. }
  828. /// <summary>
  829. /// Start position of the selected text.
  830. /// </summary>
  831. public int SelectedStart {
  832. get => selectedStart;
  833. set {
  834. if (value < -1) {
  835. selectedStart = -1;
  836. } else if (value > text.Count) {
  837. selectedStart = text.Count;
  838. } else {
  839. selectedStart = value;
  840. }
  841. PrepareSelection (selectedStart, point - selectedStart);
  842. }
  843. }
  844. /// <summary>
  845. /// Length of the selected text.
  846. /// </summary>
  847. public int SelectedLength { get => length; }
  848. /// <summary>
  849. /// The selected text.
  850. /// </summary>
  851. public ustring SelectedText {
  852. get => Secret ? null : selectedText;
  853. private set => selectedText = value;
  854. }
  855. int start, length;
  856. bool isButtonPressed;
  857. bool isButtonReleased = true;
  858. ///<inheritdoc/>
  859. public override bool MouseEvent (MouseEvent ev)
  860. {
  861. if (!ev.Flags.HasFlag (MouseFlags.Button1Pressed) && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition) &&
  862. !ev.Flags.HasFlag (MouseFlags.Button1Released) && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked) &&
  863. !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked) && !ev.Flags.HasFlag (ContextMenu.MouseFlags)) {
  864. return false;
  865. }
  866. if (!CanFocus) {
  867. return true;
  868. }
  869. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition) {
  870. SetFocus ();
  871. }
  872. // Give autocomplete first opportunity to respond to mouse clicks
  873. if (SelectedLength == 0 && Autocomplete.MouseEvent (ev, true)) {
  874. return true;
  875. }
  876. if (ev.Flags == MouseFlags.Button1Pressed) {
  877. EnsureHasFocus ();
  878. PositionCursor (ev);
  879. if (isButtonReleased) {
  880. ClearAllSelection ();
  881. }
  882. isButtonReleased = true;
  883. isButtonPressed = true;
  884. } else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && isButtonPressed) {
  885. int x = PositionCursor (ev);
  886. isButtonReleased = false;
  887. PrepareSelection (x);
  888. if (Application.MouseGrabView == null) {
  889. Application.GrabMouse (this);
  890. }
  891. } else if (ev.Flags == MouseFlags.Button1Released) {
  892. isButtonReleased = true;
  893. isButtonPressed = false;
  894. Application.UngrabMouse ();
  895. } else if (ev.Flags == MouseFlags.Button1DoubleClicked) {
  896. EnsureHasFocus ();
  897. int x = PositionCursor (ev);
  898. int sbw = x;
  899. if (x == text.Count || (x > 0 && (char)text [x - 1] != ' ')
  900. || (x > 0 && (char)text [x] == ' ')) {
  901. var newPosBw = GetModel ().WordBackward (x, 0);
  902. sbw = newPosBw.Value.col;
  903. }
  904. if (sbw != -1) {
  905. x = sbw;
  906. PositionCursor (x);
  907. }
  908. var newPosFw = GetModel ().WordForward (x, 0);
  909. ClearAllSelection ();
  910. if (newPosFw.Value.col != -1 && sbw != -1) {
  911. point = newPosFw.Value.col;
  912. }
  913. PrepareSelection (sbw, newPosFw.Value.col - sbw);
  914. } else if (ev.Flags == MouseFlags.Button1TripleClicked) {
  915. EnsureHasFocus ();
  916. PositionCursor (0);
  917. ClearAllSelection ();
  918. PrepareSelection (0, text.Count);
  919. } else if (ev.Flags == ContextMenu.MouseFlags) {
  920. ShowContextMenu ();
  921. }
  922. SetNeedsDisplay ();
  923. return true;
  924. void EnsureHasFocus ()
  925. {
  926. if (!HasFocus) {
  927. SetFocus ();
  928. }
  929. }
  930. }
  931. int PositionCursor (MouseEvent ev)
  932. {
  933. // We could also set the cursor position.
  934. int x;
  935. var pX = TextModel.GetColFromX (text, first, ev.X);
  936. if (text.Count == 0) {
  937. x = pX - ev.OfX;
  938. } else {
  939. x = pX;
  940. }
  941. return PositionCursor (x, false);
  942. }
  943. int PositionCursor (int x, bool getX = true)
  944. {
  945. int pX = x;
  946. if (getX) {
  947. pX = TextModel.GetColFromX (text, first, x);
  948. }
  949. if (first + pX > text.Count) {
  950. point = text.Count;
  951. } else if (first + pX < first) {
  952. point = 0;
  953. } else {
  954. point = first + pX;
  955. }
  956. return point;
  957. }
  958. void PrepareSelection (int x, int direction = 0)
  959. {
  960. x = x + first < -1 ? 0 : x;
  961. selectedStart = selectedStart == -1 && text.Count > 0 && x >= 0 && x <= text.Count ? x : selectedStart;
  962. if (selectedStart > -1) {
  963. length = Math.Abs (x + direction <= text.Count ? x + direction - selectedStart : text.Count - selectedStart);
  964. SetSelectedStartSelectedLength ();
  965. if (start > -1 && length > 0) {
  966. selectedText = length > 0 ? ustring.Make (text).ToString ().Substring (
  967. start < 0 ? 0 : start, length > text.Count ? text.Count : length) : "";
  968. if (first > start) {
  969. first = start;
  970. }
  971. } else if (start > -1 && length == 0) {
  972. selectedText = null;
  973. }
  974. } else if (length > 0 || selectedText != null) {
  975. ClearAllSelection ();
  976. }
  977. Adjust ();
  978. }
  979. /// <summary>
  980. /// Clear the selected text.
  981. /// </summary>
  982. public void ClearAllSelection ()
  983. {
  984. if (selectedStart == -1 && length == 0 && selectedText == "")
  985. return;
  986. selectedStart = -1;
  987. length = 0;
  988. selectedText = null;
  989. start = 0;
  990. length = 0;
  991. SetNeedsDisplay ();
  992. }
  993. void SetSelectedStartSelectedLength ()
  994. {
  995. if (SelectedStart > -1 && point < SelectedStart) {
  996. start = point;
  997. } else {
  998. start = SelectedStart;
  999. }
  1000. }
  1001. /// <summary>
  1002. /// Copy the selected text to the clipboard.
  1003. /// </summary>
  1004. public virtual void Copy ()
  1005. {
  1006. if (Secret || length == 0)
  1007. return;
  1008. Clipboard.Contents = SelectedText;
  1009. }
  1010. /// <summary>
  1011. /// Cut the selected text to the clipboard.
  1012. /// </summary>
  1013. public virtual void Cut ()
  1014. {
  1015. if (ReadOnly || Secret || length == 0)
  1016. return;
  1017. Clipboard.Contents = SelectedText;
  1018. var newText = DeleteSelectedText ();
  1019. Text = ustring.Make (newText);
  1020. Adjust ();
  1021. }
  1022. List<Rune> DeleteSelectedText ()
  1023. {
  1024. ustring actualText = Text;
  1025. SetSelectedStartSelectedLength ();
  1026. int selStart = SelectedStart > -1 ? start : point;
  1027. (var _, var len) = TextModel.DisplaySize (text, 0, selStart, false);
  1028. (var _, var len2) = TextModel.DisplaySize (text, selStart, selStart + length, false);
  1029. (var _, var len3) = TextModel.DisplaySize (text, selStart + length, actualText.RuneCount, false);
  1030. var newText = actualText [0, len] +
  1031. actualText [len + len2, len + len2 + len3];
  1032. ClearAllSelection ();
  1033. point = selStart >= newText.RuneCount ? newText.RuneCount : selStart;
  1034. return newText.ToRuneList ();
  1035. }
  1036. /// <summary>
  1037. /// Paste the selected text from the clipboard.
  1038. /// </summary>
  1039. public virtual void Paste ()
  1040. {
  1041. if (ReadOnly || ustring.IsNullOrEmpty (Clipboard.Contents)) {
  1042. return;
  1043. }
  1044. SetSelectedStartSelectedLength ();
  1045. int selStart = start == -1 ? CursorPosition : start;
  1046. ustring actualText = Text;
  1047. (int _, int len) = TextModel.DisplaySize (text, 0, selStart, false);
  1048. (var _, var len2) = TextModel.DisplaySize (text, selStart, selStart + length, false);
  1049. (var _, var len3) = TextModel.DisplaySize (text, selStart + length, actualText.RuneCount, false);
  1050. ustring cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  1051. Text = actualText [0, len] +
  1052. cbTxt +
  1053. actualText [len + len2, len + len2 + len3];
  1054. point = selStart + cbTxt.RuneCount;
  1055. ClearAllSelection ();
  1056. SetNeedsDisplay ();
  1057. Adjust ();
  1058. }
  1059. /// <summary>
  1060. /// Virtual method that invoke the <see cref="TextChanging"/> event if it's defined.
  1061. /// </summary>
  1062. /// <param name="newText">The new text to be replaced.</param>
  1063. /// <returns>Returns the <see cref="TextChangingEventArgs"/></returns>
  1064. public virtual TextChangingEventArgs OnTextChanging (ustring newText)
  1065. {
  1066. var ev = new TextChangingEventArgs (newText);
  1067. TextChanging?.Invoke (this, ev);
  1068. return ev;
  1069. }
  1070. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1071. /// <summary>
  1072. /// Get / Set the wished cursor when the field is focused
  1073. /// </summary>
  1074. public CursorVisibility DesiredCursorVisibility {
  1075. get => desiredCursorVisibility;
  1076. set {
  1077. if (desiredCursorVisibility != value && HasFocus) {
  1078. Application.Driver.SetCursorVisibility (value);
  1079. }
  1080. desiredCursorVisibility = value;
  1081. }
  1082. }
  1083. /// <summary>
  1084. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position
  1085. /// exactly as if the user had just typed it
  1086. /// </summary>
  1087. /// <param name="toAdd">Text to add</param>
  1088. /// <param name="useOldCursorPos">If uses the <see cref="oldCursorPos"/>.</param>
  1089. public void InsertText (string toAdd, bool useOldCursorPos = true)
  1090. {
  1091. foreach (var ch in toAdd) {
  1092. Key key;
  1093. try {
  1094. key = (Key)ch;
  1095. } catch (Exception) {
  1096. throw new ArgumentException ($"Cannot insert character '{ch}' because it does not map to a Key");
  1097. }
  1098. InsertText (new KeyEvent () { Key = key }, useOldCursorPos);
  1099. }
  1100. }
  1101. /// <summary>
  1102. /// Allows clearing the <see cref="HistoryText.HistoryTextItem"/> items updating the original text.
  1103. /// </summary>
  1104. public void ClearHistoryChanges ()
  1105. {
  1106. historyText.Clear (Text);
  1107. }
  1108. /// <summary>
  1109. /// Returns <see langword="true"/> if the current cursor position is
  1110. /// at the end of the <see cref="Text"/>. This includes when it is empty.
  1111. /// </summary>
  1112. /// <returns></returns>
  1113. internal bool CursorIsAtEnd ()
  1114. {
  1115. return CursorPosition == Text.Length;
  1116. }
  1117. /// <summary>
  1118. /// Returns <see langword="true"/> if the current cursor position is
  1119. /// at the start of the <see cref="TextField"/>.
  1120. /// </summary>
  1121. /// <returns></returns>
  1122. internal bool CursorIsAtStart ()
  1123. {
  1124. return CursorPosition <= 0;
  1125. }
  1126. }
  1127. /// <summary>
  1128. /// Renders an overlay on another view at a given point that allows selecting
  1129. /// from a range of 'autocomplete' options.
  1130. /// An implementation on a TextField.
  1131. /// </summary>
  1132. public class TextFieldAutocomplete : PopupAutocomplete {
  1133. /// <inheritdoc/>
  1134. protected override void DeleteTextBackwards ()
  1135. {
  1136. ((TextField)HostControl).DeleteCharLeft (false);
  1137. }
  1138. /// <inheritdoc/>
  1139. protected override void InsertText (string accepted)
  1140. {
  1141. ((TextField)HostControl).InsertText (accepted, false);
  1142. }
  1143. }
  1144. }