TextField.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. using System.Globalization;
  2. using Terminal.Gui.Resources;
  3. namespace Terminal.Gui;
  4. /// <summary>Single-line text entry <see cref="View"/></summary>
  5. /// <remarks>The <see cref="TextField"/> <see cref="View"/> provides editing functionality and mouse support.</remarks>
  6. public class TextField : View
  7. {
  8. private readonly HistoryText _historyText;
  9. private CultureInfo _currentCulture;
  10. private int _cursorPosition;
  11. private bool _isButtonPressed;
  12. private bool _isButtonReleased;
  13. private bool _isDrawing;
  14. private int _preTextChangedCursorPos;
  15. private int _selectedStart; // -1 represents there is no text selection.
  16. private string _selectedText;
  17. private int _start;
  18. private List<Rune> _text;
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="TextField"/> class.
  21. /// </summary>
  22. public TextField ()
  23. {
  24. _historyText = new ();
  25. _isButtonReleased = true;
  26. _selectedStart = -1;
  27. _text = new ();
  28. CaptionColor = new (Color.DarkGray);
  29. ReadOnly = false;
  30. Autocomplete = new TextFieldAutocomplete ();
  31. Height = Dim.Auto (DimAutoStyle.Text, 1);
  32. CanFocus = true;
  33. CursorVisibility = CursorVisibility.Default;
  34. Used = true;
  35. WantMousePositionReports = true;
  36. // By default, disable hotkeys (in case someome sets Title)
  37. HotKeySpecifier = new ('\xffff');
  38. _historyText.ChangeText += HistoryText_ChangeText;
  39. Initialized += TextField_Initialized;
  40. Added += TextField_Added;
  41. Removed += TextField_Removed;
  42. // Things this view knows how to do
  43. AddCommand (
  44. Command.DeleteCharRight,
  45. () =>
  46. {
  47. DeleteCharRight ();
  48. return true;
  49. }
  50. );
  51. AddCommand (
  52. Command.DeleteCharLeft,
  53. () =>
  54. {
  55. DeleteCharLeft (false);
  56. return true;
  57. }
  58. );
  59. AddCommand (
  60. Command.LeftStartExtend,
  61. () =>
  62. {
  63. MoveHomeExtend ();
  64. return true;
  65. }
  66. );
  67. AddCommand (
  68. Command.RightEndExtend,
  69. () =>
  70. {
  71. MoveEndExtend ();
  72. return true;
  73. }
  74. );
  75. AddCommand (
  76. Command.LeftStart,
  77. () =>
  78. {
  79. MoveHome ();
  80. return true;
  81. }
  82. );
  83. AddCommand (
  84. Command.LeftExtend,
  85. () =>
  86. {
  87. MoveLeftExtend ();
  88. return true;
  89. }
  90. );
  91. AddCommand (
  92. Command.RightExtend,
  93. () =>
  94. {
  95. MoveRightExtend ();
  96. return true;
  97. }
  98. );
  99. AddCommand (
  100. Command.WordLeftExtend,
  101. () =>
  102. {
  103. MoveWordLeftExtend ();
  104. return true;
  105. }
  106. );
  107. AddCommand (
  108. Command.WordRightExtend,
  109. () =>
  110. {
  111. MoveWordRightExtend ();
  112. return true;
  113. }
  114. );
  115. AddCommand (Command.Left, () => MoveLeft ());
  116. AddCommand (
  117. Command.RightEnd,
  118. () =>
  119. {
  120. MoveEnd ();
  121. return true;
  122. }
  123. );
  124. AddCommand (Command.Right, () => MoveRight ());
  125. AddCommand (
  126. Command.CutToEndLine,
  127. () =>
  128. {
  129. KillToEnd ();
  130. return true;
  131. }
  132. );
  133. AddCommand (
  134. Command.CutToStartLine,
  135. () =>
  136. {
  137. KillToStart ();
  138. return true;
  139. }
  140. );
  141. AddCommand (
  142. Command.Undo,
  143. () =>
  144. {
  145. Undo ();
  146. return true;
  147. }
  148. );
  149. AddCommand (
  150. Command.Redo,
  151. () =>
  152. {
  153. Redo ();
  154. return true;
  155. }
  156. );
  157. AddCommand (
  158. Command.WordLeft,
  159. () =>
  160. {
  161. MoveWordLeft ();
  162. return true;
  163. }
  164. );
  165. AddCommand (
  166. Command.WordRight,
  167. () =>
  168. {
  169. MoveWordRight ();
  170. return true;
  171. }
  172. );
  173. AddCommand (
  174. Command.KillWordForwards,
  175. () =>
  176. {
  177. KillWordForwards ();
  178. return true;
  179. }
  180. );
  181. AddCommand (
  182. Command.KillWordBackwards,
  183. () =>
  184. {
  185. KillWordBackwards ();
  186. return true;
  187. }
  188. );
  189. AddCommand (
  190. Command.ToggleOverwrite,
  191. () =>
  192. {
  193. SetOverwrite (!Used);
  194. return true;
  195. }
  196. );
  197. AddCommand (
  198. Command.EnableOverwrite,
  199. () =>
  200. {
  201. SetOverwrite (true);
  202. return true;
  203. }
  204. );
  205. AddCommand (
  206. Command.DisableOverwrite,
  207. () =>
  208. {
  209. SetOverwrite (false);
  210. return true;
  211. }
  212. );
  213. AddCommand (
  214. Command.Copy,
  215. () =>
  216. {
  217. Copy ();
  218. return true;
  219. }
  220. );
  221. AddCommand (
  222. Command.Cut,
  223. () =>
  224. {
  225. Cut ();
  226. return true;
  227. }
  228. );
  229. AddCommand (
  230. Command.Paste,
  231. () =>
  232. {
  233. Paste ();
  234. return true;
  235. }
  236. );
  237. AddCommand (
  238. Command.SelectAll,
  239. () =>
  240. {
  241. SelectAll ();
  242. return true;
  243. }
  244. );
  245. AddCommand (
  246. Command.DeleteAll,
  247. () =>
  248. {
  249. DeleteAll ();
  250. return true;
  251. }
  252. );
  253. AddCommand (
  254. Command.Context,
  255. () =>
  256. {
  257. ShowContextMenu ();
  258. return true;
  259. }
  260. );
  261. // Default keybindings for this view
  262. // We follow this as closely as possible: https://en.wikipedia.org/wiki/Table_of_keyboard_shortcuts
  263. KeyBindings.Add (Key.Delete, Command.DeleteCharRight);
  264. KeyBindings.Add (Key.D.WithCtrl, Command.DeleteCharRight);
  265. KeyBindings.Add (Key.Backspace, Command.DeleteCharLeft);
  266. KeyBindings.Add (Key.Home.WithShift, Command.LeftStartExtend);
  267. KeyBindings.Add (Key.Home.WithShift.WithCtrl, Command.LeftStartExtend);
  268. KeyBindings.Add (Key.A.WithShift.WithCtrl, Command.LeftStartExtend);
  269. KeyBindings.Add (Key.End.WithShift, Command.RightEndExtend);
  270. KeyBindings.Add (Key.End.WithShift.WithCtrl, Command.RightEndExtend);
  271. KeyBindings.Add (Key.E.WithShift.WithCtrl, Command.RightEndExtend);
  272. KeyBindings.Add (Key.Home, Command.LeftStart);
  273. KeyBindings.Add (Key.Home.WithCtrl, Command.LeftStart);
  274. KeyBindings.Add (Key.A.WithCtrl, Command.LeftStart);
  275. KeyBindings.Add (Key.CursorLeft.WithShift, Command.LeftExtend);
  276. KeyBindings.Add (Key.CursorUp.WithShift, Command.LeftExtend);
  277. KeyBindings.Add (Key.CursorRight.WithShift, Command.RightExtend);
  278. KeyBindings.Add (Key.CursorDown.WithShift, Command.RightExtend);
  279. KeyBindings.Add (Key.CursorLeft.WithShift.WithCtrl, Command.WordLeftExtend);
  280. KeyBindings.Add (Key.CursorUp.WithShift.WithCtrl, Command.WordLeftExtend);
  281. KeyBindings.Add (Key.CursorRight.WithShift.WithCtrl, Command.WordRightExtend);
  282. KeyBindings.Add (Key.CursorDown.WithShift.WithCtrl, Command.WordRightExtend);
  283. KeyBindings.Add (Key.CursorLeft, Command.Left);
  284. KeyBindings.Add (Key.B.WithCtrl, Command.Left);
  285. KeyBindings.Add (Key.End, Command.RightEnd);
  286. KeyBindings.Add (Key.End.WithCtrl, Command.RightEnd);
  287. KeyBindings.Add (Key.E.WithCtrl, Command.RightEnd);
  288. KeyBindings.Add (Key.CursorRight, Command.Right);
  289. KeyBindings.Add (Key.F.WithCtrl, Command.Right);
  290. KeyBindings.Add (Key.K.WithCtrl, Command.CutToEndLine);
  291. KeyBindings.Add (Key.K.WithCtrl.WithShift, Command.CutToStartLine);
  292. KeyBindings.Add (Key.Z.WithCtrl, Command.Undo);
  293. KeyBindings.Add (Key.Y.WithCtrl, Command.Redo);
  294. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.WordLeft);
  295. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.WordLeft);
  296. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.WordRight);
  297. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.WordRight);
  298. #if UNIX_KEY_BINDINGS
  299. KeyBindings.Add (Key.F.WithShift.WithAlt, Command.WordRightExtend);
  300. KeyBindings.Add (Key.K.WithAlt, Command.CutToStartLine);
  301. KeyBindings.Add (Key.B.WithShift.WithAlt, Command.WordLeftExtend);
  302. KeyBindings.Add (Key.B.WithAlt, Command.WordLeft);
  303. KeyBindings.Add (Key.F.WithAlt, Command.WordRight);
  304. KeyBindings.Add (Key.Backspace.WithAlt, Command.Undo);
  305. #endif
  306. KeyBindings.Add (Key.Delete.WithCtrl, Command.KillWordForwards);
  307. KeyBindings.Add (Key.Backspace.WithCtrl, Command.KillWordBackwards);
  308. KeyBindings.Add (Key.InsertChar, Command.ToggleOverwrite);
  309. KeyBindings.Add (Key.C.WithCtrl, Command.Copy);
  310. KeyBindings.Add (Key.X.WithCtrl, Command.Cut);
  311. KeyBindings.Add (Key.V.WithCtrl, Command.Paste);
  312. KeyBindings.Add (Key.T.WithCtrl, Command.SelectAll);
  313. KeyBindings.Add (Key.R.WithCtrl, Command.DeleteAll);
  314. KeyBindings.Add (Key.D.WithCtrl.WithShift, Command.DeleteAll);
  315. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  316. ContextMenu = new() { Host = this };
  317. ContextMenu.KeyChanged += ContextMenu_KeyChanged;
  318. KeyBindings.Add (ContextMenu.Key, KeyBindingScope.HotKey, Command.Context);
  319. KeyBindings.Remove (Key.Space);
  320. }
  321. /// <summary>
  322. /// Provides autocomplete context menu based on suggestions at the current cursor position. Configure
  323. /// <see cref="ISuggestionGenerator"/> to enable this feature.
  324. /// </summary>
  325. public IAutocomplete Autocomplete { get; set; }
  326. /// <summary>
  327. /// Gets or sets the text to render in control when no value has been entered yet and the <see cref="View"/> does
  328. /// not yet have input focus.
  329. /// </summary>
  330. public string Caption { get; set; }
  331. /// <summary>Gets or sets the foreground <see cref="Color"/> to use when rendering <see cref="Caption"/>.</summary>
  332. public Color CaptionColor { get; set; }
  333. /// <summary>Get the <see cref="ContextMenu"/> for this view.</summary>
  334. public ContextMenu ContextMenu { get; }
  335. /// <summary>Sets or gets the current cursor position.</summary>
  336. public virtual int CursorPosition
  337. {
  338. get => _cursorPosition;
  339. set
  340. {
  341. if (value < 0)
  342. {
  343. _cursorPosition = 0;
  344. }
  345. else if (value > _text.Count)
  346. {
  347. _cursorPosition = _text.Count;
  348. }
  349. else
  350. {
  351. _cursorPosition = value;
  352. }
  353. PrepareSelection (_selectedStart, _cursorPosition - _selectedStart);
  354. }
  355. }
  356. /// <summary>
  357. /// Indicates whatever the text has history changes or not. <see langword="true"/> if the text has history changes
  358. /// <see langword="false"/> otherwise.
  359. /// </summary>
  360. public bool HasHistoryChanges => _historyText.HasHistoryChanges;
  361. /// <summary>
  362. /// Indicates whatever the text was changed or not. <see langword="true"/> if the text was changed
  363. /// <see langword="false"/> otherwise.
  364. /// </summary>
  365. public bool IsDirty => _historyText.IsDirty ([Cell.StringToCells (Text)]);
  366. /// <summary>If set to true its not allow any changes in the text.</summary>
  367. public bool ReadOnly { get; set; }
  368. /// <summary>Gets the left offset position.</summary>
  369. public int ScrollOffset { get; private set; }
  370. /// <summary>
  371. /// Sets the secret property.
  372. /// <remarks>This makes the text entry suitable for entering passwords.</remarks>
  373. /// </summary>
  374. public bool Secret { get; set; }
  375. /// <summary>Length of the selected text.</summary>
  376. public int SelectedLength { get; private set; }
  377. /// <summary>Start position of the selected text.</summary>
  378. public int SelectedStart
  379. {
  380. get => _selectedStart;
  381. set
  382. {
  383. if (value < -1)
  384. {
  385. _selectedStart = -1;
  386. }
  387. else if (value > _text.Count)
  388. {
  389. _selectedStart = _text.Count;
  390. }
  391. else
  392. {
  393. _selectedStart = value;
  394. }
  395. PrepareSelection (_selectedStart, _cursorPosition - _selectedStart);
  396. }
  397. }
  398. /// <summary>The selected text.</summary>
  399. public string SelectedText
  400. {
  401. get => Secret ? null : _selectedText;
  402. private set => _selectedText = value;
  403. }
  404. /// <summary>Sets or gets the text held by the view.</summary>
  405. public new string Text
  406. {
  407. get => StringExtensions.ToString (_text);
  408. set
  409. {
  410. var oldText = StringExtensions.ToString (_text);
  411. if (oldText == value)
  412. {
  413. return;
  414. }
  415. string newText = value.Replace ("\t", "").Split ("\n") [0];
  416. CancelEventArgs<string> args = new (ref oldText, ref newText);
  417. OnTextChanging (args);
  418. if (args.Cancel)
  419. {
  420. if (_cursorPosition > _text.Count)
  421. {
  422. _cursorPosition = _text.Count;
  423. }
  424. return;
  425. }
  426. ClearAllSelection ();
  427. // Note we use NewValue here; TextChanging subscribers may have changed it
  428. _text = args.NewValue.EnumerateRunes ().ToList ();
  429. if (!Secret && !_historyText.IsFromHistory)
  430. {
  431. _historyText.Add (
  432. new () { Cell.ToCellList (oldText) },
  433. new (_cursorPosition, 0)
  434. );
  435. _historyText.Add (
  436. new () { Cell.ToCells (_text) },
  437. new (_cursorPosition, 0),
  438. HistoryText.LineStatus.Replaced
  439. );
  440. }
  441. OnTextChanged ();
  442. ProcessAutocomplete ();
  443. if (_cursorPosition > _text.Count)
  444. {
  445. _cursorPosition = Math.Max (TextModel.DisplaySize (_text, 0).size - 1, 0);
  446. }
  447. Adjust ();
  448. SetNeedsDisplay ();
  449. }
  450. }
  451. /// <summary>
  452. /// Tracks whether the text field should be considered "used", that is, that the user has moved in the entry, so
  453. /// new input should be appended at the cursor position, rather than clearing the entry
  454. /// </summary>
  455. public bool Used { get; set; }
  456. /// <summary>Clear the selected text.</summary>
  457. public void ClearAllSelection ()
  458. {
  459. if (_selectedStart == -1 && SelectedLength == 0 && string.IsNullOrEmpty (_selectedText))
  460. {
  461. return;
  462. }
  463. _selectedStart = -1;
  464. SelectedLength = 0;
  465. _selectedText = null;
  466. _start = 0;
  467. SelectedLength = 0;
  468. SetNeedsDisplay ();
  469. }
  470. /// <summary>Allows clearing the <see cref="HistoryText.HistoryTextItemEventArgs"/> items updating the original text.</summary>
  471. public void ClearHistoryChanges () { _historyText.Clear ([Cell.StringToCells (Text)]); }
  472. /// <summary>Copy the selected text to the clipboard.</summary>
  473. public virtual void Copy ()
  474. {
  475. if (Secret || SelectedLength == 0)
  476. {
  477. return;
  478. }
  479. Clipboard.Contents = SelectedText;
  480. }
  481. /// <summary>Cut the selected text to the clipboard.</summary>
  482. public virtual void Cut ()
  483. {
  484. if (ReadOnly || Secret || SelectedLength == 0)
  485. {
  486. return;
  487. }
  488. Clipboard.Contents = SelectedText;
  489. List<Rune> newText = DeleteSelectedText ();
  490. Text = StringExtensions.ToString (newText);
  491. Adjust ();
  492. }
  493. /// <summary>Deletes all text.</summary>
  494. public void DeleteAll ()
  495. {
  496. if (_text.Count == 0)
  497. {
  498. return;
  499. }
  500. _selectedStart = 0;
  501. MoveEndExtend ();
  502. DeleteCharLeft (false);
  503. SetNeedsDisplay ();
  504. }
  505. /// <summary>Deletes the character to the left.</summary>
  506. /// <param name="usePreTextChangedCursorPos">
  507. /// If set to <see langword="true">true</see> use the cursor position cached ;
  508. /// otherwise use <see cref="CursorPosition"/>. use .
  509. /// </param>
  510. public virtual void DeleteCharLeft (bool usePreTextChangedCursorPos)
  511. {
  512. if (ReadOnly)
  513. {
  514. return;
  515. }
  516. _historyText.Add (
  517. new () { Cell.ToCells (_text) },
  518. new (_cursorPosition, 0)
  519. );
  520. if (SelectedLength == 0)
  521. {
  522. if (_cursorPosition == 0)
  523. {
  524. return;
  525. }
  526. if (!usePreTextChangedCursorPos)
  527. {
  528. _preTextChangedCursorPos = _cursorPosition;
  529. }
  530. _cursorPosition--;
  531. if (_preTextChangedCursorPos < _text.Count)
  532. {
  533. SetText (
  534. _text.GetRange (0, _preTextChangedCursorPos - 1)
  535. .Concat (
  536. _text.GetRange (
  537. _preTextChangedCursorPos,
  538. _text.Count - _preTextChangedCursorPos
  539. )
  540. )
  541. );
  542. }
  543. else
  544. {
  545. SetText (_text.GetRange (0, _preTextChangedCursorPos - 1));
  546. }
  547. Adjust ();
  548. }
  549. else
  550. {
  551. List<Rune> newText = DeleteSelectedText ();
  552. Text = StringExtensions.ToString (newText);
  553. Adjust ();
  554. }
  555. }
  556. /// <summary>Deletes the character to the right.</summary>
  557. public virtual void DeleteCharRight ()
  558. {
  559. if (ReadOnly)
  560. {
  561. return;
  562. }
  563. _historyText.Add (
  564. new () { Cell.ToCells (_text) },
  565. new (_cursorPosition, 0)
  566. );
  567. if (SelectedLength == 0)
  568. {
  569. if (_text.Count == 0 || _text.Count == _cursorPosition)
  570. {
  571. return;
  572. }
  573. SetText (
  574. _text.GetRange (0, _cursorPosition)
  575. .Concat (_text.GetRange (_cursorPosition + 1, _text.Count - (_cursorPosition + 1)))
  576. );
  577. Adjust ();
  578. }
  579. else
  580. {
  581. List<Rune> newText = DeleteSelectedText ();
  582. Text = StringExtensions.ToString (newText);
  583. Adjust ();
  584. }
  585. }
  586. /// <inheritdoc/>
  587. public override Attribute GetNormalColor () { return GetFocusColor (); }
  588. /// <summary>
  589. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position exactly as if the user had just
  590. /// typed it
  591. /// </summary>
  592. /// <param name="toAdd">Text to add</param>
  593. /// <param name="useOldCursorPos">Use the previous cursor position.</param>
  594. public void InsertText (string toAdd, bool useOldCursorPos = true)
  595. {
  596. foreach (char ch in toAdd)
  597. {
  598. Key key;
  599. try
  600. {
  601. key = ch;
  602. }
  603. catch (Exception)
  604. {
  605. throw new ArgumentException (
  606. $"Cannot insert character '{ch}' because it does not map to a Key"
  607. );
  608. }
  609. InsertText (key, useOldCursorPos);
  610. }
  611. }
  612. /// <summary>Deletes word backwards.</summary>
  613. public virtual void KillWordBackwards ()
  614. {
  615. ClearAllSelection ();
  616. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  617. if (newPos is null)
  618. {
  619. return;
  620. }
  621. if (newPos.Value.col != -1)
  622. {
  623. SetText (
  624. _text.GetRange (0, newPos.Value.col)
  625. .Concat (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition))
  626. );
  627. _cursorPosition = newPos.Value.col;
  628. }
  629. Adjust ();
  630. }
  631. /// <summary>Deletes word forwards.</summary>
  632. public virtual void KillWordForwards ()
  633. {
  634. ClearAllSelection ();
  635. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  636. if (newPos is null)
  637. {
  638. return;
  639. }
  640. if (newPos.Value.col != -1)
  641. {
  642. SetText (
  643. _text.GetRange (0, _cursorPosition)
  644. .Concat (_text.GetRange (newPos.Value.col, _text.Count - newPos.Value.col))
  645. );
  646. }
  647. Adjust ();
  648. }
  649. /// <inheritdoc/>
  650. protected internal override bool OnMouseEvent (MouseEvent ev)
  651. {
  652. if (!ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  653. && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition)
  654. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  655. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  656. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  657. && !ev.Flags.HasFlag (ContextMenu.MouseFlags))
  658. {
  659. return base.OnMouseEvent (ev);
  660. }
  661. if (!CanFocus)
  662. {
  663. return true;
  664. }
  665. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition)
  666. {
  667. SetFocus ();
  668. }
  669. // Give autocomplete first opportunity to respond to mouse clicks
  670. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  671. {
  672. return true;
  673. }
  674. if (ev.Flags == MouseFlags.Button1Pressed)
  675. {
  676. EnsureHasFocus ();
  677. PositionCursor (ev);
  678. if (_isButtonReleased)
  679. {
  680. ClearAllSelection ();
  681. }
  682. _isButtonReleased = true;
  683. _isButtonPressed = true;
  684. }
  685. else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _isButtonPressed)
  686. {
  687. int x = PositionCursor (ev);
  688. _isButtonReleased = false;
  689. PrepareSelection (x);
  690. if (Application.MouseGrabView is null)
  691. {
  692. Application.GrabMouse (this);
  693. }
  694. }
  695. else if (ev.Flags == MouseFlags.Button1Released)
  696. {
  697. _isButtonReleased = true;
  698. _isButtonPressed = false;
  699. Application.UngrabMouse ();
  700. }
  701. else if (ev.Flags == MouseFlags.Button1DoubleClicked)
  702. {
  703. EnsureHasFocus ();
  704. int x = PositionCursor (ev);
  705. int sbw = x;
  706. if (x == _text.Count
  707. || (x > 0 && (char)_text [x - 1].Value != ' ')
  708. || (x > 0 && (char)_text [x].Value == ' '))
  709. {
  710. (int col, int row)? newPosBw = GetModel ().WordBackward (x, 0);
  711. if (newPosBw is null)
  712. {
  713. return true;
  714. }
  715. sbw = newPosBw.Value.col;
  716. }
  717. if (sbw != -1)
  718. {
  719. x = sbw;
  720. PositionCursor (x);
  721. }
  722. (int col, int row)? newPosFw = GetModel ().WordForward (x, 0);
  723. if (newPosFw is null)
  724. {
  725. return true;
  726. }
  727. ClearAllSelection ();
  728. if (newPosFw.Value.col != -1 && sbw != -1)
  729. {
  730. _cursorPosition = newPosFw.Value.col;
  731. }
  732. PrepareSelection (sbw, newPosFw.Value.col - sbw);
  733. }
  734. else if (ev.Flags == MouseFlags.Button1TripleClicked)
  735. {
  736. EnsureHasFocus ();
  737. PositionCursor (0);
  738. ClearAllSelection ();
  739. PrepareSelection (0, _text.Count);
  740. }
  741. else if (ev.Flags == ContextMenu.MouseFlags)
  742. {
  743. ShowContextMenu ();
  744. }
  745. //SetNeedsDisplay ();
  746. return true;
  747. void EnsureHasFocus ()
  748. {
  749. if (!HasFocus)
  750. {
  751. SetFocus ();
  752. }
  753. }
  754. }
  755. /// <summary>Moves cursor to the end of the typed text.</summary>
  756. public void MoveEnd ()
  757. {
  758. ClearAllSelection ();
  759. _cursorPosition = _text.Count;
  760. Adjust ();
  761. }
  762. /// <inheritdoc/>
  763. public override void OnDrawContent (Rectangle viewport)
  764. {
  765. _isDrawing = true;
  766. var selColor = new Attribute (GetFocusColor ().Background, GetFocusColor ().Foreground);
  767. SetSelectedStartSelectedLength ();
  768. Driver?.SetAttribute (GetNormalColor ());
  769. Move (0, 0);
  770. int p = ScrollOffset;
  771. var col = 0;
  772. int width = Viewport.Width + OffSetBackground ();
  773. int tcount = _text.Count;
  774. Attribute roc = GetReadOnlyColor ();
  775. for (int idx = p; idx < tcount; idx++)
  776. {
  777. Rune rune = _text [idx];
  778. int cols = rune.GetColumns ();
  779. if (idx == _cursorPosition && HasFocus && !Used && SelectedLength == 0 && !ReadOnly)
  780. {
  781. Driver?.SetAttribute (selColor);
  782. }
  783. else if (ReadOnly)
  784. {
  785. Driver?.SetAttribute (
  786. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  787. ? selColor
  788. : roc
  789. );
  790. }
  791. else if (!HasFocus && Enabled)
  792. {
  793. Driver?.SetAttribute (GetFocusColor ());
  794. }
  795. else if (!Enabled)
  796. {
  797. Driver?.SetAttribute (roc);
  798. }
  799. else
  800. {
  801. Driver?.SetAttribute (
  802. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  803. ? selColor
  804. : ColorScheme.Focus
  805. );
  806. }
  807. if (col + cols <= width)
  808. {
  809. Driver?.AddRune (Secret ? Glyphs.Dot : rune);
  810. }
  811. if (!TextModel.SetCol (ref col, width, cols))
  812. {
  813. break;
  814. }
  815. if (idx + 1 < tcount && col + _text [idx + 1].GetColumns () > width)
  816. {
  817. break;
  818. }
  819. }
  820. Driver.SetAttribute (GetFocusColor ());
  821. for (int i = col; i < width; i++)
  822. {
  823. Driver.AddRune ((Rune)' ');
  824. }
  825. PositionCursor ();
  826. RenderCaption ();
  827. DrawAutocomplete ();
  828. _isDrawing = false;
  829. }
  830. /// <inheritdoc/>
  831. public override bool? OnInvokingKeyBindings (Key a, KeyBindingScope scope)
  832. {
  833. // Give autocomplete first opportunity to respond to key presses
  834. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (a))
  835. {
  836. return true;
  837. }
  838. return base.OnInvokingKeyBindings (a, scope);
  839. }
  840. /// <inheritdoc/>
  841. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  842. {
  843. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  844. {
  845. Application.UngrabMouse ();
  846. }
  847. //if (SelectedLength != 0 && !(Application.MouseGrabView is MenuBar))
  848. // ClearAllSelection ();
  849. }
  850. /// TODO: Flush out these docs
  851. /// <summary>
  852. /// Processes key presses for the <see cref="TextField"/>.
  853. /// <remarks>
  854. /// The <see cref="TextField"/> control responds to the following keys:
  855. /// <list type="table">
  856. /// <listheader>
  857. /// <term>Keys</term> <description>Function</description>
  858. /// </listheader>
  859. /// <item>
  860. /// <term><see cref="Key.Delete"/>, <see cref="Key.Backspace"/></term>
  861. /// <description>Deletes the character before cursor.</description>
  862. /// </item>
  863. /// </list>
  864. /// </remarks>
  865. /// </summary>
  866. /// <param name="a"></param>
  867. /// <returns></returns>
  868. public override bool OnProcessKeyDown (Key a)
  869. {
  870. // Remember the cursor position because the new calculated cursor position is needed
  871. // to be set BEFORE the TextChanged event is triggered.
  872. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  873. _preTextChangedCursorPos = _cursorPosition;
  874. // Ignore other control characters.
  875. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  876. {
  877. return false;
  878. }
  879. if (ReadOnly)
  880. {
  881. return true;
  882. }
  883. InsertText (a, true);
  884. return true;
  885. }
  886. /// <summary>Virtual method that invoke the <see cref="TextChanging"/> event if it's defined.</summary>
  887. /// <param name="args">The event arguments.</param>
  888. /// <returns><see langword="true"/> if the event was cancelled.</returns>
  889. public bool OnTextChanging (CancelEventArgs<string> args)
  890. {
  891. TextChanging?.Invoke (this, args);
  892. return args.Cancel;
  893. }
  894. /// <summary>Paste the selected text from the clipboard.</summary>
  895. public virtual void Paste ()
  896. {
  897. if (ReadOnly || string.IsNullOrEmpty (Clipboard.Contents))
  898. {
  899. return;
  900. }
  901. SetSelectedStartSelectedLength ();
  902. int selStart = _start == -1 ? CursorPosition : _start;
  903. string cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  904. Text = StringExtensions.ToString (_text.GetRange (0, selStart))
  905. + cbTxt
  906. + StringExtensions.ToString (
  907. _text.GetRange (
  908. selStart + SelectedLength,
  909. _text.Count - (selStart + SelectedLength)
  910. )
  911. );
  912. _cursorPosition = Math.Min (selStart + cbTxt.GetRuneCount (), _text.Count);
  913. ClearAllSelection ();
  914. SetNeedsDisplay ();
  915. Adjust ();
  916. }
  917. /// <summary>Sets the cursor position.</summary>
  918. public override Point? PositionCursor ()
  919. {
  920. ProcessAutocomplete ();
  921. var col = 0;
  922. for (int idx = ScrollOffset < 0 ? 0 : ScrollOffset; idx < _text.Count; idx++)
  923. {
  924. if (idx == _cursorPosition)
  925. {
  926. break;
  927. }
  928. int cols = _text [idx].GetColumns ();
  929. TextModel.SetCol (ref col, Viewport.Width - 1, cols);
  930. }
  931. int pos = _cursorPosition - ScrollOffset + Math.Min (Viewport.X, 0);
  932. Move (pos, 0);
  933. return new Point (pos, 0);
  934. }
  935. /// <summary>Redoes the latest changes.</summary>
  936. public void Redo ()
  937. {
  938. if (ReadOnly)
  939. {
  940. return;
  941. }
  942. _historyText.Redo ();
  943. }
  944. /// <summary>Selects all text.</summary>
  945. public void SelectAll ()
  946. {
  947. if (_text.Count == 0)
  948. {
  949. return;
  950. }
  951. _selectedStart = 0;
  952. MoveEndExtend ();
  953. SetNeedsDisplay ();
  954. }
  955. ///// <summary>
  956. ///// Changed event, raised when the text has changed.
  957. ///// <remarks>
  958. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  959. ///// <see cref="string"/> containing the old value.
  960. ///// </remarks>
  961. ///// </summary>
  962. //public event EventHandler<StateEventArgs<string>> TextChanged;
  963. /// <summary>Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.</summary>
  964. public event EventHandler<CancelEventArgs<string>> TextChanging;
  965. /// <summary>Undoes the latest changes.</summary>
  966. public void Undo ()
  967. {
  968. if (ReadOnly)
  969. {
  970. return;
  971. }
  972. _historyText.Undo ();
  973. }
  974. /// <summary>
  975. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  976. /// includes when it is empty.
  977. /// </summary>
  978. /// <returns></returns>
  979. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  980. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  981. /// <returns></returns>
  982. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  983. private void Adjust ()
  984. {
  985. if (!IsAdded)
  986. {
  987. return;
  988. }
  989. // TODO: This is a lame prototype proving it should be easy for TextField to
  990. // TODO: support Width = Dim.Auto (DimAutoStyle: Content).
  991. //SetContentSize(new (TextModel.DisplaySize (_text).size, 1));
  992. int offB = OffSetBackground ();
  993. bool need = NeedsDisplay || !Used;
  994. if (_cursorPosition < ScrollOffset)
  995. {
  996. ScrollOffset = _cursorPosition;
  997. need = true;
  998. }
  999. else if (Viewport.Width > 0
  1000. && (ScrollOffset + _cursorPosition - (Viewport.Width + offB) == 0
  1001. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Viewport.Width + offB))
  1002. {
  1003. ScrollOffset = Math.Max (
  1004. TextModel.CalculateLeftColumn (
  1005. _text,
  1006. ScrollOffset,
  1007. _cursorPosition,
  1008. Viewport.Width + offB
  1009. ),
  1010. 0
  1011. );
  1012. need = true;
  1013. }
  1014. if (need)
  1015. {
  1016. SetNeedsDisplay ();
  1017. }
  1018. else
  1019. {
  1020. PositionCursor ();
  1021. }
  1022. }
  1023. private MenuBarItem BuildContextMenuBarItem ()
  1024. {
  1025. return new (
  1026. new MenuItem []
  1027. {
  1028. new (
  1029. Strings.ctxSelectAll,
  1030. "",
  1031. () => SelectAll (),
  1032. null,
  1033. null,
  1034. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  1035. ),
  1036. new (
  1037. Strings.ctxDeleteAll,
  1038. "",
  1039. () => DeleteAll (),
  1040. null,
  1041. null,
  1042. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  1043. ),
  1044. new (
  1045. Strings.ctxCopy,
  1046. "",
  1047. () => Copy (),
  1048. null,
  1049. null,
  1050. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  1051. ),
  1052. new (
  1053. Strings.ctxCut,
  1054. "",
  1055. () => Cut (),
  1056. null,
  1057. null,
  1058. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  1059. ),
  1060. new (
  1061. Strings.ctxPaste,
  1062. "",
  1063. () => Paste (),
  1064. null,
  1065. null,
  1066. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  1067. ),
  1068. new (
  1069. Strings.ctxUndo,
  1070. "",
  1071. () => Undo (),
  1072. null,
  1073. null,
  1074. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  1075. ),
  1076. new (
  1077. Strings.ctxRedo,
  1078. "",
  1079. () => Redo (),
  1080. null,
  1081. null,
  1082. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  1083. )
  1084. }
  1085. );
  1086. }
  1087. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.ReplaceKey (e.OldKey.KeyCode, e.NewKey.KeyCode); }
  1088. private List<Rune> DeleteSelectedText ()
  1089. {
  1090. SetSelectedStartSelectedLength ();
  1091. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1092. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1093. + StringExtensions.ToString (
  1094. _text.GetRange (
  1095. selStart + SelectedLength,
  1096. _text.Count - (selStart + SelectedLength)
  1097. )
  1098. );
  1099. ClearAllSelection ();
  1100. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1101. return newText.ToRuneList ();
  1102. }
  1103. private void GenerateSuggestions ()
  1104. {
  1105. List<Cell> currentLine = Cell.ToCellList (Text);
  1106. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1107. Autocomplete.Context = new (
  1108. currentLine,
  1109. cursorPosition,
  1110. Autocomplete.Context != null
  1111. ? Autocomplete.Context.Canceled
  1112. : false
  1113. );
  1114. Autocomplete.GenerateSuggestions (
  1115. Autocomplete.Context
  1116. );
  1117. }
  1118. private TextModel GetModel ()
  1119. {
  1120. var model = new TextModel ();
  1121. model.LoadString (Text);
  1122. return model;
  1123. }
  1124. private Attribute GetReadOnlyColor ()
  1125. {
  1126. ColorScheme cs = ColorScheme;
  1127. if (ColorScheme is null)
  1128. {
  1129. cs = new ();
  1130. }
  1131. if (cs.Disabled.Foreground == cs.Focus.Background)
  1132. {
  1133. return new (cs.Focus.Foreground, cs.Focus.Background);
  1134. }
  1135. return new (cs.Disabled.Foreground, cs.Focus.Background);
  1136. }
  1137. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItemEventArgs obj)
  1138. {
  1139. if (obj is null)
  1140. {
  1141. return;
  1142. }
  1143. Text = Cell.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1144. CursorPosition = obj.CursorPosition.X;
  1145. Adjust ();
  1146. }
  1147. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1148. {
  1149. _historyText.Add (
  1150. new () { Cell.ToCells (_text) },
  1151. new (_cursorPosition, 0)
  1152. );
  1153. List<Rune> newText = _text;
  1154. if (SelectedLength > 0)
  1155. {
  1156. newText = DeleteSelectedText ();
  1157. _preTextChangedCursorPos = _cursorPosition;
  1158. }
  1159. if (!usePreTextChangedCursorPos)
  1160. {
  1161. _preTextChangedCursorPos = _cursorPosition;
  1162. }
  1163. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1164. if (Used)
  1165. {
  1166. _cursorPosition++;
  1167. if (_cursorPosition == newText.Count + 1)
  1168. {
  1169. SetText (newText.Concat (kbstr).ToList ());
  1170. }
  1171. else
  1172. {
  1173. if (_preTextChangedCursorPos > newText.Count)
  1174. {
  1175. _preTextChangedCursorPos = newText.Count;
  1176. }
  1177. SetText (
  1178. newText.GetRange (0, _preTextChangedCursorPos)
  1179. .Concat (kbstr)
  1180. .Concat (
  1181. newText.GetRange (
  1182. _preTextChangedCursorPos,
  1183. Math.Min (
  1184. newText.Count - _preTextChangedCursorPos,
  1185. newText.Count
  1186. )
  1187. )
  1188. )
  1189. );
  1190. }
  1191. }
  1192. else
  1193. {
  1194. SetText (
  1195. newText.GetRange (0, _preTextChangedCursorPos)
  1196. .Concat (kbstr)
  1197. .Concat (
  1198. newText.GetRange (
  1199. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1200. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1201. )
  1202. )
  1203. );
  1204. _cursorPosition++;
  1205. }
  1206. Adjust ();
  1207. }
  1208. private void KillToEnd ()
  1209. {
  1210. if (ReadOnly)
  1211. {
  1212. return;
  1213. }
  1214. ClearAllSelection ();
  1215. if (_cursorPosition >= _text.Count)
  1216. {
  1217. return;
  1218. }
  1219. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1220. SetText (_text.GetRange (0, _cursorPosition));
  1221. Adjust ();
  1222. }
  1223. private void KillToStart ()
  1224. {
  1225. if (ReadOnly)
  1226. {
  1227. return;
  1228. }
  1229. ClearAllSelection ();
  1230. if (_cursorPosition == 0)
  1231. {
  1232. return;
  1233. }
  1234. SetClipboard (_text.GetRange (0, _cursorPosition));
  1235. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1236. _cursorPosition = 0;
  1237. Adjust ();
  1238. }
  1239. private void MoveEndExtend ()
  1240. {
  1241. if (_cursorPosition <= _text.Count)
  1242. {
  1243. int x = _cursorPosition;
  1244. _cursorPosition = _text.Count;
  1245. PrepareSelection (x, _cursorPosition - x);
  1246. }
  1247. }
  1248. private void MoveHome ()
  1249. {
  1250. ClearAllSelection ();
  1251. _cursorPosition = 0;
  1252. Adjust ();
  1253. }
  1254. private void MoveHomeExtend ()
  1255. {
  1256. if (_cursorPosition > 0)
  1257. {
  1258. int x = _cursorPosition;
  1259. _cursorPosition = 0;
  1260. PrepareSelection (x, _cursorPosition - x);
  1261. }
  1262. }
  1263. private bool MoveLeft ()
  1264. {
  1265. if (_cursorPosition > 0)
  1266. {
  1267. ClearAllSelection ();
  1268. _cursorPosition--;
  1269. Adjust ();
  1270. return true;
  1271. }
  1272. return false;
  1273. }
  1274. private void MoveLeftExtend ()
  1275. {
  1276. if (_cursorPosition > 0)
  1277. {
  1278. PrepareSelection (_cursorPosition--, -1);
  1279. }
  1280. }
  1281. private bool MoveRight ()
  1282. {
  1283. if (_cursorPosition == _text.Count)
  1284. {
  1285. return false;
  1286. }
  1287. ClearAllSelection ();
  1288. _cursorPosition++;
  1289. Adjust ();
  1290. return true;
  1291. }
  1292. private void MoveRightExtend ()
  1293. {
  1294. if (_cursorPosition < _text.Count)
  1295. {
  1296. PrepareSelection (_cursorPosition++, 1);
  1297. }
  1298. }
  1299. private void MoveWordLeft ()
  1300. {
  1301. ClearAllSelection ();
  1302. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  1303. if (newPos is null)
  1304. {
  1305. return;
  1306. }
  1307. if (newPos.Value.col != -1)
  1308. {
  1309. _cursorPosition = newPos.Value.col;
  1310. }
  1311. Adjust ();
  1312. }
  1313. private void MoveWordLeftExtend ()
  1314. {
  1315. if (_cursorPosition > 0)
  1316. {
  1317. int x = Math.Min (
  1318. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1319. _text.Count
  1320. );
  1321. if (x > 0)
  1322. {
  1323. (int col, int row)? newPos = GetModel ().WordBackward (x, 0);
  1324. if (newPos is null)
  1325. {
  1326. return;
  1327. }
  1328. if (newPos.Value.col != -1)
  1329. {
  1330. _cursorPosition = newPos.Value.col;
  1331. }
  1332. PrepareSelection (x, newPos.Value.col - x);
  1333. }
  1334. }
  1335. }
  1336. private void MoveWordRight ()
  1337. {
  1338. ClearAllSelection ();
  1339. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  1340. if (newPos is null)
  1341. {
  1342. return;
  1343. }
  1344. if (newPos.Value.col != -1)
  1345. {
  1346. _cursorPosition = newPos.Value.col;
  1347. }
  1348. Adjust ();
  1349. }
  1350. private void MoveWordRightExtend ()
  1351. {
  1352. if (_cursorPosition < _text.Count)
  1353. {
  1354. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1355. (int col, int row)? newPos = GetModel ().WordForward (x, 0);
  1356. if (newPos is null)
  1357. {
  1358. return;
  1359. }
  1360. if (newPos.Value.col != -1)
  1361. {
  1362. _cursorPosition = newPos.Value.col;
  1363. }
  1364. PrepareSelection (x, newPos.Value.col - x);
  1365. }
  1366. }
  1367. // BUGBUG: This assumes Frame == Viewport. It's also not clear what the intention is. For now, changed to always return 0.
  1368. private int OffSetBackground ()
  1369. {
  1370. var offB = 0;
  1371. if (SuperView?.Frame.Right - Frame.Right < 0)
  1372. {
  1373. offB = SuperView.Frame.Right - Frame.Right - 1;
  1374. }
  1375. return 0; //offB;
  1376. }
  1377. private int PositionCursor (MouseEvent ev) { return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.Position.X), false); }
  1378. private int PositionCursor (int x, bool getX = true)
  1379. {
  1380. int pX = x;
  1381. if (getX)
  1382. {
  1383. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1384. }
  1385. if (ScrollOffset + pX > _text.Count)
  1386. {
  1387. _cursorPosition = _text.Count;
  1388. }
  1389. else if (ScrollOffset + pX < ScrollOffset)
  1390. {
  1391. _cursorPosition = 0;
  1392. }
  1393. else
  1394. {
  1395. _cursorPosition = ScrollOffset + pX;
  1396. }
  1397. return _cursorPosition;
  1398. }
  1399. private void PrepareSelection (int x, int direction = 0)
  1400. {
  1401. x = x + ScrollOffset < -1 ? 0 : x;
  1402. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1403. ? x
  1404. : _selectedStart;
  1405. if (_selectedStart > -1)
  1406. {
  1407. SelectedLength = Math.Abs (
  1408. x + direction <= _text.Count
  1409. ? x + direction - _selectedStart
  1410. : _text.Count - _selectedStart
  1411. );
  1412. SetSelectedStartSelectedLength ();
  1413. if (_start > -1 && SelectedLength > 0)
  1414. {
  1415. _selectedText = SelectedLength > 0
  1416. ? StringExtensions.ToString (
  1417. _text.GetRange (
  1418. _start < 0 ? 0 : _start,
  1419. SelectedLength > _text.Count
  1420. ? _text.Count
  1421. : SelectedLength
  1422. )
  1423. )
  1424. : "";
  1425. if (ScrollOffset > _start)
  1426. {
  1427. ScrollOffset = _start;
  1428. }
  1429. }
  1430. else if (_start > -1 && SelectedLength == 0)
  1431. {
  1432. _selectedText = null;
  1433. }
  1434. SetNeedsDisplay ();
  1435. }
  1436. else if (SelectedLength > 0 || _selectedText is { })
  1437. {
  1438. ClearAllSelection ();
  1439. }
  1440. Adjust ();
  1441. }
  1442. private void ProcessAutocomplete ()
  1443. {
  1444. if (_isDrawing)
  1445. {
  1446. return;
  1447. }
  1448. if (SelectedLength > 0)
  1449. {
  1450. return;
  1451. }
  1452. GenerateSuggestions ();
  1453. }
  1454. private void DrawAutocomplete ()
  1455. {
  1456. if (SelectedLength > 0)
  1457. {
  1458. return;
  1459. }
  1460. if (Autocomplete?.Context == null)
  1461. {
  1462. return;
  1463. }
  1464. var renderAt = new Point (
  1465. Autocomplete.Context.CursorPosition,
  1466. 0
  1467. );
  1468. Autocomplete.RenderOverlay (renderAt);
  1469. }
  1470. private void RenderCaption ()
  1471. {
  1472. if (HasFocus
  1473. || Caption == null
  1474. || Caption.Length == 0
  1475. || Text?.Length > 0)
  1476. {
  1477. return;
  1478. }
  1479. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  1480. Driver.SetAttribute (color);
  1481. Move (0, 0);
  1482. string render = Caption;
  1483. if (render.GetColumns () > Viewport.Width)
  1484. {
  1485. render = render [..Viewport.Width];
  1486. }
  1487. Driver.AddStr (render);
  1488. }
  1489. private void SetClipboard (IEnumerable<Rune> text)
  1490. {
  1491. if (!Secret)
  1492. {
  1493. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1494. }
  1495. }
  1496. private void SetOverwrite (bool overwrite)
  1497. {
  1498. Used = overwrite;
  1499. SetNeedsDisplay ();
  1500. }
  1501. private void SetSelectedStartSelectedLength ()
  1502. {
  1503. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1504. {
  1505. _start = _cursorPosition;
  1506. }
  1507. else
  1508. {
  1509. _start = SelectedStart;
  1510. }
  1511. }
  1512. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1513. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1514. private void ShowContextMenu ()
  1515. {
  1516. if (!Equals (_currentCulture, Thread.CurrentThread.CurrentUICulture))
  1517. {
  1518. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1519. }
  1520. ContextMenu.Show (BuildContextMenuBarItem ());
  1521. }
  1522. private void TextField_Added (object sender, SuperViewChangedEventArgs e)
  1523. {
  1524. if (Autocomplete.HostControl is null)
  1525. {
  1526. Autocomplete.HostControl = this;
  1527. Autocomplete.PopupInsideContainer = false;
  1528. }
  1529. }
  1530. private void TextField_Removed (object sender, SuperViewChangedEventArgs e) { Autocomplete.HostControl = null; }
  1531. private void TextField_Initialized (object sender, EventArgs e)
  1532. {
  1533. _cursorPosition = Text.GetRuneCount ();
  1534. if (Viewport.Width > 0)
  1535. {
  1536. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1537. }
  1538. if (Autocomplete.HostControl is null)
  1539. {
  1540. Autocomplete.HostControl = this;
  1541. Autocomplete.PopupInsideContainer = false;
  1542. }
  1543. }
  1544. }
  1545. /// <summary>
  1546. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1547. /// options. An implementation on a TextField.
  1548. /// </summary>
  1549. public class TextFieldAutocomplete : PopupAutocomplete
  1550. {
  1551. /// <inheritdoc/>
  1552. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1553. /// <inheritdoc/>
  1554. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1555. /// <inheritdoc/>
  1556. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1557. }