2
0

TextField.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  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 override bool OnMouseEvent (MouseEventArgs ev)
  651. {
  652. if (ev is { IsPressed: false, IsReleased: false }
  653. && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition)
  654. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  655. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  656. && !ev.Flags.HasFlag (ContextMenu.MouseFlags))
  657. {
  658. return false;
  659. }
  660. if (!CanFocus)
  661. {
  662. return true;
  663. }
  664. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition)
  665. {
  666. SetFocus ();
  667. }
  668. // Give autocomplete first opportunity to respond to mouse clicks
  669. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  670. {
  671. return true;
  672. }
  673. if (ev.Flags == MouseFlags.Button1Pressed)
  674. {
  675. EnsureHasFocus ();
  676. PositionCursor (ev);
  677. if (_isButtonReleased)
  678. {
  679. ClearAllSelection ();
  680. }
  681. _isButtonReleased = true;
  682. _isButtonPressed = true;
  683. }
  684. else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _isButtonPressed)
  685. {
  686. int x = PositionCursor (ev);
  687. _isButtonReleased = false;
  688. PrepareSelection (x);
  689. if (Application.MouseGrabView is null)
  690. {
  691. Application.GrabMouse (this);
  692. }
  693. }
  694. else if (ev.Flags == MouseFlags.Button1Released)
  695. {
  696. _isButtonReleased = true;
  697. _isButtonPressed = false;
  698. Application.UngrabMouse ();
  699. }
  700. else if (ev.Flags == MouseFlags.Button1DoubleClicked)
  701. {
  702. EnsureHasFocus ();
  703. int x = PositionCursor (ev);
  704. int sbw = x;
  705. if (x == _text.Count
  706. || (x > 0 && (char)_text [x - 1].Value != ' ')
  707. || (x > 0 && (char)_text [x].Value == ' '))
  708. {
  709. (int col, int row)? newPosBw = GetModel ().WordBackward (x, 0);
  710. if (newPosBw is null)
  711. {
  712. return true;
  713. }
  714. sbw = newPosBw.Value.col;
  715. }
  716. if (sbw != -1)
  717. {
  718. x = sbw;
  719. PositionCursor (x);
  720. }
  721. (int col, int row)? newPosFw = GetModel ().WordForward (x, 0);
  722. if (newPosFw is null)
  723. {
  724. return true;
  725. }
  726. ClearAllSelection ();
  727. if (newPosFw.Value.col != -1 && sbw != -1)
  728. {
  729. _cursorPosition = newPosFw.Value.col;
  730. }
  731. PrepareSelection (sbw, newPosFw.Value.col - sbw);
  732. }
  733. else if (ev.Flags == MouseFlags.Button1TripleClicked)
  734. {
  735. EnsureHasFocus ();
  736. PositionCursor (0);
  737. ClearAllSelection ();
  738. PrepareSelection (0, _text.Count);
  739. }
  740. else if (ev.Flags == ContextMenu.MouseFlags)
  741. {
  742. ShowContextMenu ();
  743. }
  744. //SetNeedsDisplay ();
  745. return true;
  746. void EnsureHasFocus ()
  747. {
  748. if (!HasFocus)
  749. {
  750. SetFocus ();
  751. }
  752. }
  753. }
  754. /// <summary>Moves cursor to the end of the typed text.</summary>
  755. public void MoveEnd ()
  756. {
  757. ClearAllSelection ();
  758. _cursorPosition = _text.Count;
  759. Adjust ();
  760. }
  761. /// <inheritdoc/>
  762. public override void OnDrawContent (Rectangle viewport)
  763. {
  764. _isDrawing = true;
  765. var selColor = new Attribute (GetFocusColor ().Background, GetFocusColor ().Foreground);
  766. SetSelectedStartSelectedLength ();
  767. Driver?.SetAttribute (GetNormalColor ());
  768. Move (0, 0);
  769. int p = ScrollOffset;
  770. var col = 0;
  771. int width = Viewport.Width + OffSetBackground ();
  772. int tcount = _text.Count;
  773. Attribute roc = GetReadOnlyColor ();
  774. for (int idx = p; idx < tcount; idx++)
  775. {
  776. Rune rune = _text [idx];
  777. int cols = rune.GetColumns ();
  778. if (idx == _cursorPosition && HasFocus && !Used && SelectedLength == 0 && !ReadOnly)
  779. {
  780. Driver?.SetAttribute (selColor);
  781. }
  782. else if (ReadOnly)
  783. {
  784. Driver?.SetAttribute (
  785. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  786. ? selColor
  787. : roc
  788. );
  789. }
  790. else if (!HasFocus && Enabled)
  791. {
  792. Driver?.SetAttribute (GetFocusColor ());
  793. }
  794. else if (!Enabled)
  795. {
  796. Driver?.SetAttribute (roc);
  797. }
  798. else
  799. {
  800. Driver?.SetAttribute (
  801. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  802. ? selColor
  803. : ColorScheme.Focus
  804. );
  805. }
  806. if (col + cols <= width)
  807. {
  808. Driver?.AddRune (Secret ? Glyphs.Dot : rune);
  809. }
  810. if (!TextModel.SetCol (ref col, width, cols))
  811. {
  812. break;
  813. }
  814. if (idx + 1 < tcount && col + _text [idx + 1].GetColumns () > width)
  815. {
  816. break;
  817. }
  818. }
  819. Driver?.SetAttribute (GetFocusColor ());
  820. for (int i = col; i < width; i++)
  821. {
  822. Driver?.AddRune ((Rune)' ');
  823. }
  824. PositionCursor ();
  825. RenderCaption ();
  826. DrawAutocomplete ();
  827. _isDrawing = false;
  828. }
  829. /// <inheritdoc/>
  830. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  831. {
  832. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  833. {
  834. Application.UngrabMouse ();
  835. }
  836. //if (SelectedLength != 0 && !(Application.MouseGrabView is MenuBar))
  837. // ClearAllSelection ();
  838. }
  839. /// <inheritdoc/>
  840. protected override bool OnKeyDown (Key key)
  841. {
  842. // Give autocomplete first opportunity to respond to key presses
  843. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (key))
  844. {
  845. return true;
  846. }
  847. return false;
  848. }
  849. /// <inheritdoc />
  850. protected override bool OnKeyDownNotHandled (Key a)
  851. {
  852. // Remember the cursor position because the new calculated cursor position is needed
  853. // to be set BEFORE the TextChanged event is triggered.
  854. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  855. _preTextChangedCursorPos = _cursorPosition;
  856. // Ignore other control characters.
  857. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  858. {
  859. return false;
  860. }
  861. if (ReadOnly)
  862. {
  863. return true;
  864. }
  865. InsertText (a, true);
  866. return true;
  867. }
  868. /// <summary>Virtual method that invoke the <see cref="TextChanging"/> event if it's defined.</summary>
  869. /// <param name="args">The event arguments.</param>
  870. /// <returns><see langword="true"/> if the event was cancelled.</returns>
  871. public bool OnTextChanging (CancelEventArgs<string> args)
  872. {
  873. TextChanging?.Invoke (this, args);
  874. return args.Cancel;
  875. }
  876. /// <summary>Paste the selected text from the clipboard.</summary>
  877. public virtual void Paste ()
  878. {
  879. if (ReadOnly || string.IsNullOrEmpty (Clipboard.Contents))
  880. {
  881. return;
  882. }
  883. SetSelectedStartSelectedLength ();
  884. int selStart = _start == -1 ? CursorPosition : _start;
  885. string cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  886. Text = StringExtensions.ToString (_text.GetRange (0, selStart))
  887. + cbTxt
  888. + StringExtensions.ToString (
  889. _text.GetRange (
  890. selStart + SelectedLength,
  891. _text.Count - (selStart + SelectedLength)
  892. )
  893. );
  894. _cursorPosition = Math.Min (selStart + cbTxt.GetRuneCount (), _text.Count);
  895. ClearAllSelection ();
  896. SetNeedsDisplay ();
  897. Adjust ();
  898. }
  899. /// <summary>Sets the cursor position.</summary>
  900. public override Point? PositionCursor ()
  901. {
  902. ProcessAutocomplete ();
  903. var col = 0;
  904. for (int idx = ScrollOffset < 0 ? 0 : ScrollOffset; idx < _text.Count; idx++)
  905. {
  906. if (idx == _cursorPosition)
  907. {
  908. break;
  909. }
  910. int cols = _text [idx].GetColumns ();
  911. TextModel.SetCol (ref col, Viewport.Width - 1, cols);
  912. }
  913. int pos = _cursorPosition - ScrollOffset + Math.Min (Viewport.X, 0);
  914. Move (pos, 0);
  915. return new Point (pos, 0);
  916. }
  917. /// <summary>Redoes the latest changes.</summary>
  918. public void Redo ()
  919. {
  920. if (ReadOnly)
  921. {
  922. return;
  923. }
  924. _historyText.Redo ();
  925. }
  926. /// <summary>Selects all text.</summary>
  927. public void SelectAll ()
  928. {
  929. if (_text.Count == 0)
  930. {
  931. return;
  932. }
  933. _selectedStart = 0;
  934. MoveEndExtend ();
  935. SetNeedsDisplay ();
  936. }
  937. ///// <summary>
  938. ///// Changed event, raised when the text has changed.
  939. ///// <remarks>
  940. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  941. ///// <see cref="string"/> containing the old value.
  942. ///// </remarks>
  943. ///// </summary>
  944. //public event EventHandler<StateEventArgs<string>> TextChanged;
  945. /// <summary>Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.</summary>
  946. public event EventHandler<CancelEventArgs<string>> TextChanging;
  947. /// <summary>Undoes the latest changes.</summary>
  948. public void Undo ()
  949. {
  950. if (ReadOnly)
  951. {
  952. return;
  953. }
  954. _historyText.Undo ();
  955. }
  956. /// <summary>
  957. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  958. /// includes when it is empty.
  959. /// </summary>
  960. /// <returns></returns>
  961. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  962. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  963. /// <returns></returns>
  964. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  965. private void Adjust ()
  966. {
  967. if (!IsAdded)
  968. {
  969. return;
  970. }
  971. // TODO: This is a lame prototype proving it should be easy for TextField to
  972. // TODO: support Width = Dim.Auto (DimAutoStyle: Content).
  973. //SetContentSize(new (TextModel.DisplaySize (_text).size, 1));
  974. int offB = OffSetBackground ();
  975. bool need = NeedsDisplay || !Used;
  976. if (_cursorPosition < ScrollOffset)
  977. {
  978. ScrollOffset = _cursorPosition;
  979. need = true;
  980. }
  981. else if (Viewport.Width > 0
  982. && (ScrollOffset + _cursorPosition - (Viewport.Width + offB) == 0
  983. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Viewport.Width + offB))
  984. {
  985. ScrollOffset = Math.Max (
  986. TextModel.CalculateLeftColumn (
  987. _text,
  988. ScrollOffset,
  989. _cursorPosition,
  990. Viewport.Width + offB
  991. ),
  992. 0
  993. );
  994. need = true;
  995. }
  996. if (need)
  997. {
  998. SetNeedsDisplay ();
  999. }
  1000. else
  1001. {
  1002. PositionCursor ();
  1003. }
  1004. }
  1005. private MenuBarItem BuildContextMenuBarItem ()
  1006. {
  1007. return new (
  1008. new MenuItem []
  1009. {
  1010. new (
  1011. Strings.ctxSelectAll,
  1012. "",
  1013. () => SelectAll (),
  1014. null,
  1015. null,
  1016. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  1017. ),
  1018. new (
  1019. Strings.ctxDeleteAll,
  1020. "",
  1021. () => DeleteAll (),
  1022. null,
  1023. null,
  1024. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  1025. ),
  1026. new (
  1027. Strings.ctxCopy,
  1028. "",
  1029. () => Copy (),
  1030. null,
  1031. null,
  1032. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  1033. ),
  1034. new (
  1035. Strings.ctxCut,
  1036. "",
  1037. () => Cut (),
  1038. null,
  1039. null,
  1040. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  1041. ),
  1042. new (
  1043. Strings.ctxPaste,
  1044. "",
  1045. () => Paste (),
  1046. null,
  1047. null,
  1048. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  1049. ),
  1050. new (
  1051. Strings.ctxUndo,
  1052. "",
  1053. () => Undo (),
  1054. null,
  1055. null,
  1056. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  1057. ),
  1058. new (
  1059. Strings.ctxRedo,
  1060. "",
  1061. () => Redo (),
  1062. null,
  1063. null,
  1064. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  1065. )
  1066. }
  1067. );
  1068. }
  1069. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.ReplaceKey (e.OldKey.KeyCode, e.NewKey.KeyCode); }
  1070. private List<Rune> DeleteSelectedText ()
  1071. {
  1072. SetSelectedStartSelectedLength ();
  1073. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1074. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1075. + StringExtensions.ToString (
  1076. _text.GetRange (
  1077. selStart + SelectedLength,
  1078. _text.Count - (selStart + SelectedLength)
  1079. )
  1080. );
  1081. ClearAllSelection ();
  1082. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1083. return newText.ToRuneList ();
  1084. }
  1085. private void GenerateSuggestions ()
  1086. {
  1087. List<Cell> currentLine = Cell.ToCellList (Text);
  1088. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1089. Autocomplete.Context = new (
  1090. currentLine,
  1091. cursorPosition,
  1092. Autocomplete.Context != null
  1093. ? Autocomplete.Context.Canceled
  1094. : false
  1095. );
  1096. Autocomplete.GenerateSuggestions (
  1097. Autocomplete.Context
  1098. );
  1099. }
  1100. private TextModel GetModel ()
  1101. {
  1102. var model = new TextModel ();
  1103. model.LoadString (Text);
  1104. return model;
  1105. }
  1106. private Attribute GetReadOnlyColor ()
  1107. {
  1108. ColorScheme cs = ColorScheme;
  1109. if (ColorScheme is null)
  1110. {
  1111. cs = new ();
  1112. }
  1113. if (cs.Disabled.Foreground == cs.Focus.Background)
  1114. {
  1115. return new (cs.Focus.Foreground, cs.Focus.Background);
  1116. }
  1117. return new (cs.Disabled.Foreground, cs.Focus.Background);
  1118. }
  1119. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItemEventArgs obj)
  1120. {
  1121. if (obj is null)
  1122. {
  1123. return;
  1124. }
  1125. Text = Cell.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1126. CursorPosition = obj.CursorPosition.X;
  1127. Adjust ();
  1128. }
  1129. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1130. {
  1131. _historyText.Add (
  1132. new () { Cell.ToCells (_text) },
  1133. new (_cursorPosition, 0)
  1134. );
  1135. List<Rune> newText = _text;
  1136. if (SelectedLength > 0)
  1137. {
  1138. newText = DeleteSelectedText ();
  1139. _preTextChangedCursorPos = _cursorPosition;
  1140. }
  1141. if (!usePreTextChangedCursorPos)
  1142. {
  1143. _preTextChangedCursorPos = _cursorPosition;
  1144. }
  1145. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1146. if (Used)
  1147. {
  1148. _cursorPosition++;
  1149. if (_cursorPosition == newText.Count + 1)
  1150. {
  1151. SetText (newText.Concat (kbstr).ToList ());
  1152. }
  1153. else
  1154. {
  1155. if (_preTextChangedCursorPos > newText.Count)
  1156. {
  1157. _preTextChangedCursorPos = newText.Count;
  1158. }
  1159. SetText (
  1160. newText.GetRange (0, _preTextChangedCursorPos)
  1161. .Concat (kbstr)
  1162. .Concat (
  1163. newText.GetRange (
  1164. _preTextChangedCursorPos,
  1165. Math.Min (
  1166. newText.Count - _preTextChangedCursorPos,
  1167. newText.Count
  1168. )
  1169. )
  1170. )
  1171. );
  1172. }
  1173. }
  1174. else
  1175. {
  1176. SetText (
  1177. newText.GetRange (0, _preTextChangedCursorPos)
  1178. .Concat (kbstr)
  1179. .Concat (
  1180. newText.GetRange (
  1181. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1182. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1183. )
  1184. )
  1185. );
  1186. _cursorPosition++;
  1187. }
  1188. Adjust ();
  1189. }
  1190. private void KillToEnd ()
  1191. {
  1192. if (ReadOnly)
  1193. {
  1194. return;
  1195. }
  1196. ClearAllSelection ();
  1197. if (_cursorPosition >= _text.Count)
  1198. {
  1199. return;
  1200. }
  1201. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1202. SetText (_text.GetRange (0, _cursorPosition));
  1203. Adjust ();
  1204. }
  1205. private void KillToStart ()
  1206. {
  1207. if (ReadOnly)
  1208. {
  1209. return;
  1210. }
  1211. ClearAllSelection ();
  1212. if (_cursorPosition == 0)
  1213. {
  1214. return;
  1215. }
  1216. SetClipboard (_text.GetRange (0, _cursorPosition));
  1217. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1218. _cursorPosition = 0;
  1219. Adjust ();
  1220. }
  1221. private void MoveEndExtend ()
  1222. {
  1223. if (_cursorPosition <= _text.Count)
  1224. {
  1225. int x = _cursorPosition;
  1226. _cursorPosition = _text.Count;
  1227. PrepareSelection (x, _cursorPosition - x);
  1228. }
  1229. }
  1230. private void MoveHome ()
  1231. {
  1232. ClearAllSelection ();
  1233. _cursorPosition = 0;
  1234. Adjust ();
  1235. }
  1236. private void MoveHomeExtend ()
  1237. {
  1238. if (_cursorPosition > 0)
  1239. {
  1240. int x = _cursorPosition;
  1241. _cursorPosition = 0;
  1242. PrepareSelection (x, _cursorPosition - x);
  1243. }
  1244. }
  1245. /// <summary>
  1246. /// Moves the cursor +/- the given <paramref name="distance"/>, clearing
  1247. /// any selection and returning true if any meaningful changes were made.
  1248. /// </summary>
  1249. /// <param name="distance">Distance to move the cursor, will be clamped to
  1250. /// text length. Positive for right, Negative for left.</param>
  1251. /// <returns></returns>
  1252. private bool Move (int distance)
  1253. {
  1254. var oldCursorPosition = _cursorPosition;
  1255. var hadSelection = _selectedText != null && _selectedText.Length > 0;
  1256. _cursorPosition = Math.Min (_text.Count, Math.Max (0, _cursorPosition + distance));
  1257. ClearAllSelection ();
  1258. Adjust ();
  1259. return _cursorPosition != oldCursorPosition || hadSelection;
  1260. }
  1261. private bool MoveLeft ()
  1262. {
  1263. return Move (-1);
  1264. }
  1265. private void MoveLeftExtend ()
  1266. {
  1267. if (_cursorPosition > 0)
  1268. {
  1269. PrepareSelection (_cursorPosition--, -1);
  1270. }
  1271. }
  1272. private bool MoveRight ()
  1273. {
  1274. return Move (1);
  1275. }
  1276. private void MoveRightExtend ()
  1277. {
  1278. if (_cursorPosition < _text.Count)
  1279. {
  1280. PrepareSelection (_cursorPosition++, 1);
  1281. }
  1282. }
  1283. private void MoveWordLeft ()
  1284. {
  1285. ClearAllSelection ();
  1286. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  1287. if (newPos is null)
  1288. {
  1289. return;
  1290. }
  1291. if (newPos.Value.col != -1)
  1292. {
  1293. _cursorPosition = newPos.Value.col;
  1294. }
  1295. Adjust ();
  1296. }
  1297. private void MoveWordLeftExtend ()
  1298. {
  1299. if (_cursorPosition > 0)
  1300. {
  1301. int x = Math.Min (
  1302. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1303. _text.Count
  1304. );
  1305. if (x > 0)
  1306. {
  1307. (int col, int row)? newPos = GetModel ().WordBackward (x, 0);
  1308. if (newPos is null)
  1309. {
  1310. return;
  1311. }
  1312. if (newPos.Value.col != -1)
  1313. {
  1314. _cursorPosition = newPos.Value.col;
  1315. }
  1316. PrepareSelection (x, newPos.Value.col - x);
  1317. }
  1318. }
  1319. }
  1320. private void MoveWordRight ()
  1321. {
  1322. ClearAllSelection ();
  1323. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  1324. if (newPos is null)
  1325. {
  1326. return;
  1327. }
  1328. if (newPos.Value.col != -1)
  1329. {
  1330. _cursorPosition = newPos.Value.col;
  1331. }
  1332. Adjust ();
  1333. }
  1334. private void MoveWordRightExtend ()
  1335. {
  1336. if (_cursorPosition < _text.Count)
  1337. {
  1338. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1339. (int col, int row)? newPos = GetModel ().WordForward (x, 0);
  1340. if (newPos is null)
  1341. {
  1342. return;
  1343. }
  1344. if (newPos.Value.col != -1)
  1345. {
  1346. _cursorPosition = newPos.Value.col;
  1347. }
  1348. PrepareSelection (x, newPos.Value.col - x);
  1349. }
  1350. }
  1351. // BUGBUG: This assumes Frame == Viewport. It's also not clear what the intention is. For now, changed to always return 0.
  1352. private int OffSetBackground ()
  1353. {
  1354. var offB = 0;
  1355. if (SuperView?.Frame.Right - Frame.Right < 0)
  1356. {
  1357. offB = SuperView.Frame.Right - Frame.Right - 1;
  1358. }
  1359. return 0; //offB;
  1360. }
  1361. private int PositionCursor (MouseEventArgs ev) { return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.Position.X), false); }
  1362. private int PositionCursor (int x, bool getX = true)
  1363. {
  1364. int pX = x;
  1365. if (getX)
  1366. {
  1367. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1368. }
  1369. if (ScrollOffset + pX > _text.Count)
  1370. {
  1371. _cursorPosition = _text.Count;
  1372. }
  1373. else if (ScrollOffset + pX < ScrollOffset)
  1374. {
  1375. _cursorPosition = 0;
  1376. }
  1377. else
  1378. {
  1379. _cursorPosition = ScrollOffset + pX;
  1380. }
  1381. return _cursorPosition;
  1382. }
  1383. private void PrepareSelection (int x, int direction = 0)
  1384. {
  1385. x = x + ScrollOffset < -1 ? 0 : x;
  1386. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1387. ? x
  1388. : _selectedStart;
  1389. if (_selectedStart > -1)
  1390. {
  1391. SelectedLength = Math.Abs (
  1392. x + direction <= _text.Count
  1393. ? x + direction - _selectedStart
  1394. : _text.Count - _selectedStart
  1395. );
  1396. SetSelectedStartSelectedLength ();
  1397. if (_start > -1 && SelectedLength > 0)
  1398. {
  1399. _selectedText = SelectedLength > 0
  1400. ? StringExtensions.ToString (
  1401. _text.GetRange (
  1402. _start < 0 ? 0 : _start,
  1403. SelectedLength > _text.Count
  1404. ? _text.Count
  1405. : SelectedLength
  1406. )
  1407. )
  1408. : "";
  1409. if (ScrollOffset > _start)
  1410. {
  1411. ScrollOffset = _start;
  1412. }
  1413. }
  1414. else if (_start > -1 && SelectedLength == 0)
  1415. {
  1416. _selectedText = null;
  1417. }
  1418. SetNeedsDisplay ();
  1419. }
  1420. else if (SelectedLength > 0 || _selectedText is { })
  1421. {
  1422. ClearAllSelection ();
  1423. }
  1424. Adjust ();
  1425. }
  1426. private void ProcessAutocomplete ()
  1427. {
  1428. if (_isDrawing)
  1429. {
  1430. return;
  1431. }
  1432. if (SelectedLength > 0)
  1433. {
  1434. return;
  1435. }
  1436. GenerateSuggestions ();
  1437. }
  1438. private void DrawAutocomplete ()
  1439. {
  1440. if (SelectedLength > 0)
  1441. {
  1442. return;
  1443. }
  1444. if (Autocomplete?.Context == null)
  1445. {
  1446. return;
  1447. }
  1448. var renderAt = new Point (
  1449. Autocomplete.Context.CursorPosition,
  1450. 0
  1451. );
  1452. Autocomplete.RenderOverlay (renderAt);
  1453. }
  1454. private void RenderCaption ()
  1455. {
  1456. if (HasFocus
  1457. || Caption == null
  1458. || Caption.Length == 0
  1459. || Text?.Length > 0)
  1460. {
  1461. return;
  1462. }
  1463. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  1464. Driver.SetAttribute (color);
  1465. Move (0, 0);
  1466. string render = Caption;
  1467. if (render.GetColumns () > Viewport.Width)
  1468. {
  1469. render = render [..Viewport.Width];
  1470. }
  1471. Driver.AddStr (render);
  1472. }
  1473. private void SetClipboard (IEnumerable<Rune> text)
  1474. {
  1475. if (!Secret)
  1476. {
  1477. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1478. }
  1479. }
  1480. private void SetOverwrite (bool overwrite)
  1481. {
  1482. Used = overwrite;
  1483. SetNeedsDisplay ();
  1484. }
  1485. private void SetSelectedStartSelectedLength ()
  1486. {
  1487. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1488. {
  1489. _start = _cursorPosition;
  1490. }
  1491. else
  1492. {
  1493. _start = SelectedStart;
  1494. }
  1495. }
  1496. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1497. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1498. private void ShowContextMenu ()
  1499. {
  1500. if (!Equals (_currentCulture, Thread.CurrentThread.CurrentUICulture))
  1501. {
  1502. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1503. }
  1504. ContextMenu.Show (BuildContextMenuBarItem ());
  1505. }
  1506. private void TextField_Added (object sender, SuperViewChangedEventArgs e)
  1507. {
  1508. if (Autocomplete.HostControl is null)
  1509. {
  1510. Autocomplete.HostControl = this;
  1511. Autocomplete.PopupInsideContainer = false;
  1512. }
  1513. }
  1514. private void TextField_Removed (object sender, SuperViewChangedEventArgs e) { Autocomplete.HostControl = null; }
  1515. private void TextField_Initialized (object sender, EventArgs e)
  1516. {
  1517. _cursorPosition = Text.GetRuneCount ();
  1518. if (Viewport.Width > 0)
  1519. {
  1520. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1521. }
  1522. if (Autocomplete.HostControl is null)
  1523. {
  1524. Autocomplete.HostControl = this;
  1525. Autocomplete.PopupInsideContainer = false;
  1526. }
  1527. }
  1528. }
  1529. /// <summary>
  1530. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1531. /// options. An implementation on a TextField.
  1532. /// </summary>
  1533. public class TextFieldAutocomplete : PopupAutocomplete
  1534. {
  1535. /// <inheritdoc/>
  1536. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1537. /// <inheritdoc/>
  1538. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1539. /// <inheritdoc/>
  1540. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1541. }