TextField.cs 55 KB

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