TextField.cs 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. using System.Globalization;
  2. namespace Terminal.Gui.Views;
  3. /// <summary>Single-line text editor.</summary>
  4. /// <remarks>The <see cref="TextField"/> <see cref="View"/> provides editing functionality and mouse support.</remarks>
  5. public class TextField : View, IDesignable
  6. {
  7. private readonly HistoryText _historyText;
  8. private CultureInfo _currentCulture;
  9. private int _cursorPosition;
  10. private bool _isButtonPressed;
  11. private bool _isButtonReleased;
  12. private bool _isDrawing;
  13. private int _preTextChangedCursorPos;
  14. private int _selectedStart; // -1 represents there is no text selection.
  15. private string _selectedText;
  16. private int _start;
  17. private List<Rune> _text;
  18. /// <summary>
  19. /// Initializes a new instance of the <see cref="TextField"/> class.
  20. /// </summary>
  21. public TextField ()
  22. {
  23. _historyText = new ();
  24. _isButtonReleased = true;
  25. _selectedStart = -1;
  26. _text = new ();
  27. // TODO: Determine if this is a good choice. Previously this was hard coded to
  28. // TODO: DarkGray which was NOT a good choice.
  29. CaptionColor = GetAttributeForRole (VisualRole.Normal).Foreground.GetBrighterColor();
  30. ReadOnly = false;
  31. Autocomplete = new TextFieldAutocomplete ();
  32. Height = Dim.Auto (DimAutoStyle.Text, 1);
  33. CanFocus = true;
  34. CursorVisibility = CursorVisibility.Default;
  35. Used = true;
  36. WantMousePositionReports = true;
  37. // By default, disable hotkeys (in case someome sets Title)
  38. HotKeySpecifier = new ('\xffff');
  39. _historyText.ChangeText += HistoryText_ChangeText;
  40. Initialized += TextField_Initialized;
  41. SuperViewChanged += TextField_SuperViewChanged;
  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 (true);
  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.CursorLeft.WithShift, Command.LeftExtend);
  275. KeyBindings.Add (Key.CursorUp.WithShift, Command.LeftExtend);
  276. KeyBindings.Add (Key.CursorRight.WithShift, Command.RightExtend);
  277. KeyBindings.Add (Key.CursorDown.WithShift, Command.RightExtend);
  278. KeyBindings.Add (Key.CursorLeft.WithShift.WithCtrl, Command.WordLeftExtend);
  279. KeyBindings.Add (Key.CursorUp.WithShift.WithCtrl, Command.WordLeftExtend);
  280. KeyBindings.Add (Key.CursorRight.WithShift.WithCtrl, Command.WordRightExtend);
  281. KeyBindings.Add (Key.CursorDown.WithShift.WithCtrl, Command.WordRightExtend);
  282. KeyBindings.Add (Key.CursorLeft, Command.Left);
  283. KeyBindings.Add (Key.B.WithCtrl, Command.Left);
  284. KeyBindings.Add (Key.End, Command.RightEnd);
  285. KeyBindings.Add (Key.End.WithCtrl, Command.RightEnd);
  286. KeyBindings.Add (Key.E.WithCtrl, Command.RightEnd);
  287. KeyBindings.Add (Key.CursorRight, Command.Right);
  288. KeyBindings.Add (Key.F.WithCtrl, Command.Right);
  289. KeyBindings.Add (Key.K.WithCtrl, Command.CutToEndLine);
  290. KeyBindings.Add (Key.K.WithCtrl.WithShift, Command.CutToStartLine);
  291. KeyBindings.Add (Key.Z.WithCtrl, Command.Undo);
  292. KeyBindings.Add (Key.Y.WithCtrl, Command.Redo);
  293. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.WordLeft);
  294. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.WordLeft);
  295. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.WordRight);
  296. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.WordRight);
  297. #if UNIX_KEY_BINDINGS
  298. KeyBindings.Add (Key.F.WithShift.WithAlt, Command.WordRightExtend);
  299. KeyBindings.Add (Key.K.WithAlt, Command.CutToStartLine);
  300. KeyBindings.Add (Key.B.WithShift.WithAlt, Command.WordLeftExtend);
  301. KeyBindings.Add (Key.B.WithAlt, Command.WordLeft);
  302. KeyBindings.Add (Key.F.WithAlt, Command.WordRight);
  303. KeyBindings.Add (Key.Backspace.WithAlt, Command.Undo);
  304. #endif
  305. KeyBindings.Add (Key.Delete.WithCtrl, Command.KillWordForwards);
  306. KeyBindings.Add (Key.Backspace.WithCtrl, Command.KillWordBackwards);
  307. KeyBindings.Add (Key.InsertChar, Command.ToggleOverwrite);
  308. KeyBindings.Add (Key.C.WithCtrl, Command.Copy);
  309. KeyBindings.Add (Key.X.WithCtrl, Command.Cut);
  310. KeyBindings.Add (Key.V.WithCtrl, Command.Paste);
  311. KeyBindings.Add (Key.A.WithCtrl, Command.SelectAll);
  312. KeyBindings.Add (Key.R.WithCtrl, Command.DeleteAll);
  313. KeyBindings.Add (Key.D.WithCtrl.WithShift, Command.DeleteAll);
  314. KeyBindings.Remove (Key.Space);
  315. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  316. CreateContextMenu ();
  317. KeyBindings.Add (ContextMenu.Key, Command.Context);
  318. }
  319. /// <summary>
  320. /// Provides autocomplete context menu based on suggestions at the current cursor position. Configure
  321. /// <see cref="ISuggestionGenerator"/> to enable this feature.
  322. /// </summary>
  323. public IAutocomplete Autocomplete { get; set; }
  324. /// <summary>
  325. /// Gets or sets the text to render in control when no value has been entered yet and the <see cref="View"/> does
  326. /// not yet have input focus.
  327. /// </summary>
  328. public string Caption { get; set; }
  329. /// <summary>Gets or sets the foreground <see cref="Color"/> to use when rendering <see cref="Caption"/>.</summary>
  330. public Color CaptionColor { get; set; }
  331. /// <summary>Get the Context Menu for this view.</summary>
  332. [CanBeNull]
  333. public PopoverMenu ContextMenu { get; private set; }
  334. /// <summary>Sets or gets the current cursor position.</summary>
  335. public virtual int CursorPosition
  336. {
  337. get => _cursorPosition;
  338. set
  339. {
  340. if (value < 0)
  341. {
  342. _cursorPosition = 0;
  343. }
  344. else if (value > _text.Count)
  345. {
  346. _cursorPosition = _text.Count;
  347. }
  348. else
  349. {
  350. _cursorPosition = value;
  351. }
  352. PrepareSelection (_selectedStart, _cursorPosition - _selectedStart);
  353. }
  354. }
  355. /// <summary>
  356. /// Indicates whatever the text has history changes or not. <see langword="true"/> if the text has history changes
  357. /// <see langword="false"/> otherwise.
  358. /// </summary>
  359. public bool HasHistoryChanges => _historyText.HasHistoryChanges;
  360. /// <summary>
  361. /// Indicates whatever the text was changed or not. <see langword="true"/> if the text was changed
  362. /// <see langword="false"/> otherwise.
  363. /// </summary>
  364. public bool IsDirty => _historyText.IsDirty ([Cell.StringToCells (Text)]);
  365. /// <summary>If set to true its not allow any changes in the text.</summary>
  366. public bool ReadOnly { get; set; }
  367. /// <summary>Gets the left offset position.</summary>
  368. public int ScrollOffset { get; private set; }
  369. /// <summary>
  370. /// Sets the secret property.
  371. /// <remarks>This makes the text entry suitable for entering passwords.</remarks>
  372. /// </summary>
  373. public bool Secret { get; set; }
  374. /// <summary>Length of the selected text.</summary>
  375. public int SelectedLength { get; private set; }
  376. /// <summary>Start position of the selected text.</summary>
  377. public int SelectedStart
  378. {
  379. get => _selectedStart;
  380. set
  381. {
  382. if (value < -1)
  383. {
  384. _selectedStart = -1;
  385. }
  386. else if (value > _text.Count)
  387. {
  388. _selectedStart = _text.Count;
  389. }
  390. else
  391. {
  392. _selectedStart = value;
  393. }
  394. PrepareSelection (_selectedStart, _cursorPosition - _selectedStart);
  395. }
  396. }
  397. /// <summary>The selected text.</summary>
  398. public string SelectedText
  399. {
  400. get => Secret ? null : _selectedText;
  401. private set => _selectedText = value;
  402. }
  403. /// <summary>Sets or gets the text held by the view.</summary>
  404. public new string Text
  405. {
  406. get => StringExtensions.ToString (_text);
  407. set
  408. {
  409. var oldText = StringExtensions.ToString (_text);
  410. if (oldText == value)
  411. {
  412. return;
  413. }
  414. string newText = value.Replace ("\t", "").Split ("\n") [0];
  415. ResultEventArgs<string> args = new (newText);
  416. RaiseTextChanging (args);
  417. if (args.Handled)
  418. {
  419. if (_cursorPosition > _text.Count)
  420. {
  421. _cursorPosition = _text.Count;
  422. }
  423. return;
  424. }
  425. ClearAllSelection ();
  426. // Note we use NewValue here; TextChanging subscribers may have changed it
  427. _text = args.Result.EnumerateRunes ().ToList ();
  428. if (!Secret && !_historyText.IsFromHistory)
  429. {
  430. _historyText.Add (
  431. [Cell.ToCellList (oldText)],
  432. new (_cursorPosition, 0)
  433. );
  434. _historyText.Add (
  435. [Cell.ToCells (_text)],
  436. new (_cursorPosition, 0),
  437. TextEditingLineStatus.Replaced
  438. );
  439. }
  440. OnTextChanged ();
  441. ProcessAutocomplete ();
  442. if (_cursorPosition > _text.Count)
  443. {
  444. _cursorPosition = Math.Max (TextModel.DisplaySize (_text, 0).size - 1, 0);
  445. }
  446. Adjust ();
  447. SetNeedsDraw ();
  448. }
  449. }
  450. /// <summary>
  451. /// Tracks whether the text field should be considered "used", that is, that the user has moved in the entry, so
  452. /// new input should be appended at the cursor position, rather than clearing the entry
  453. /// </summary>
  454. public bool Used { get; set; }
  455. /// <summary>
  456. /// Gets or sets whether the word forward and word backward navigation should use the same or equivalent rune type.
  457. /// Default is <c>false</c> meaning using equivalent rune type.
  458. /// </summary>
  459. public bool UseSameRuneTypeForWords { get; set; }
  460. /// <summary>
  461. /// Gets or sets whether the word navigation should select only the word itself without spaces around it or with the
  462. /// spaces at right.
  463. /// Default is <c>false</c> meaning that the spaces at right are included in the selection.
  464. /// </summary>
  465. public bool SelectWordOnlyOnDoubleClick { get; set; }
  466. /// <summary>Clear the selected text.</summary>
  467. public void ClearAllSelection ()
  468. {
  469. if (_selectedStart == -1 && SelectedLength == 0 && string.IsNullOrEmpty (_selectedText))
  470. {
  471. return;
  472. }
  473. _selectedStart = -1;
  474. SelectedLength = 0;
  475. _selectedText = null;
  476. _start = 0;
  477. SelectedLength = 0;
  478. SetNeedsDraw ();
  479. }
  480. /// <summary>Clears the history.</summary>
  481. public void ClearHistoryChanges () { _historyText.Clear ([Cell.StringToCells (Text)]); }
  482. /// <summary>Copy the selected text to the clipboard.</summary>
  483. public virtual void Copy ()
  484. {
  485. if (Secret || SelectedLength == 0)
  486. {
  487. return;
  488. }
  489. Clipboard.Contents = SelectedText;
  490. }
  491. /// <summary>Cut the selected text to the clipboard.</summary>
  492. public virtual void Cut ()
  493. {
  494. if (ReadOnly || Secret || SelectedLength == 0)
  495. {
  496. return;
  497. }
  498. Clipboard.Contents = SelectedText;
  499. List<Rune> newText = DeleteSelectedText ();
  500. Text = StringExtensions.ToString (newText);
  501. Adjust ();
  502. }
  503. /// <summary>Deletes all text.</summary>
  504. public void DeleteAll ()
  505. {
  506. if (_text.Count == 0)
  507. {
  508. return;
  509. }
  510. _selectedStart = 0;
  511. MoveEndExtend ();
  512. DeleteCharLeft (false);
  513. SetNeedsDraw ();
  514. }
  515. /// <summary>Deletes the character to the left.</summary>
  516. /// <param name="usePreTextChangedCursorPos">
  517. /// If set to <see langword="true">true</see> use the cursor position cached ;
  518. /// otherwise use <see cref="CursorPosition"/>. use .
  519. /// </param>
  520. public virtual void DeleteCharLeft (bool usePreTextChangedCursorPos)
  521. {
  522. if (ReadOnly)
  523. {
  524. return;
  525. }
  526. _historyText.Add (
  527. new () { Cell.ToCells (_text) },
  528. new (_cursorPosition, 0)
  529. );
  530. if (SelectedLength == 0)
  531. {
  532. if (_cursorPosition == 0)
  533. {
  534. return;
  535. }
  536. if (!usePreTextChangedCursorPos)
  537. {
  538. _preTextChangedCursorPos = _cursorPosition;
  539. }
  540. _cursorPosition--;
  541. if (_preTextChangedCursorPos < _text.Count)
  542. {
  543. SetText (
  544. _text.GetRange (0, _preTextChangedCursorPos - 1)
  545. .Concat (
  546. _text.GetRange (
  547. _preTextChangedCursorPos,
  548. _text.Count - _preTextChangedCursorPos
  549. )
  550. )
  551. );
  552. }
  553. else
  554. {
  555. SetText (_text.GetRange (0, _preTextChangedCursorPos - 1));
  556. }
  557. Adjust ();
  558. }
  559. else
  560. {
  561. List<Rune> newText = DeleteSelectedText ();
  562. Text = StringExtensions.ToString (newText);
  563. Adjust ();
  564. }
  565. }
  566. /// <summary>Deletes the character to the right.</summary>
  567. public virtual void DeleteCharRight ()
  568. {
  569. if (ReadOnly)
  570. {
  571. return;
  572. }
  573. _historyText.Add (
  574. new () { Cell.ToCells (_text) },
  575. new (_cursorPosition, 0)
  576. );
  577. if (SelectedLength == 0)
  578. {
  579. if (_text.Count == 0 || _text.Count == _cursorPosition)
  580. {
  581. return;
  582. }
  583. SetText (
  584. _text.GetRange (0, _cursorPosition)
  585. .Concat (_text.GetRange (_cursorPosition + 1, _text.Count - (_cursorPosition + 1)))
  586. );
  587. Adjust ();
  588. }
  589. else
  590. {
  591. List<Rune> newText = DeleteSelectedText ();
  592. Text = StringExtensions.ToString (newText);
  593. Adjust ();
  594. }
  595. }
  596. /// <inheritdoc/>
  597. protected override bool OnGettingAttributeForRole (in VisualRole role, ref Attribute currentAttribute)
  598. {
  599. if (role == VisualRole.Normal)
  600. {
  601. currentAttribute = GetAttributeForRole (VisualRole.Focus);
  602. return true;
  603. }
  604. return base.OnGettingAttributeForRole (role, ref currentAttribute);
  605. }
  606. /// <summary>
  607. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position exactly as if the user had just
  608. /// typed it
  609. /// </summary>
  610. /// <param name="toAdd">Text to add</param>
  611. /// <param name="useOldCursorPos">Use the previous cursor position.</param>
  612. public void InsertText (string toAdd, bool useOldCursorPos = true)
  613. {
  614. foreach (Rune rune in toAdd.EnumerateRunes ())
  615. {
  616. // All rune can be mapped to a Key and no exception will throw here because
  617. // EnumerateRunes will replace a surrogate char with the Rune.ReplacementChar
  618. Key key = rune.Value;
  619. InsertText (key, useOldCursorPos);
  620. }
  621. }
  622. /// <summary>Deletes word backwards.</summary>
  623. public virtual void KillWordBackwards ()
  624. {
  625. ClearAllSelection ();
  626. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0, UseSameRuneTypeForWords);
  627. if (newPos is null)
  628. {
  629. return;
  630. }
  631. if (newPos.Value.col != -1)
  632. {
  633. SetText (
  634. _text.GetRange (0, newPos.Value.col)
  635. .Concat (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition))
  636. );
  637. _cursorPosition = newPos.Value.col;
  638. }
  639. Adjust ();
  640. }
  641. /// <summary>Deletes word forwards.</summary>
  642. public virtual void KillWordForwards ()
  643. {
  644. ClearAllSelection ();
  645. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0, UseSameRuneTypeForWords);
  646. if (newPos is null)
  647. {
  648. return;
  649. }
  650. if (newPos.Value.col != -1)
  651. {
  652. SetText (
  653. _text.GetRange (0, _cursorPosition)
  654. .Concat (_text.GetRange (newPos.Value.col, _text.Count - newPos.Value.col))
  655. );
  656. }
  657. Adjust ();
  658. }
  659. /// <inheritdoc/>
  660. protected override bool OnMouseEvent (MouseEventArgs ev)
  661. {
  662. if (ev is { IsPressed: false, IsReleased: false }
  663. && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition)
  664. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  665. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  666. && !ev.Flags.HasFlag (ContextMenu!.MouseFlags))
  667. {
  668. return false;
  669. }
  670. if (!CanFocus)
  671. {
  672. return true;
  673. }
  674. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition)
  675. {
  676. SetFocus ();
  677. }
  678. // Give autocomplete first opportunity to respond to mouse clicks
  679. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  680. {
  681. return true;
  682. }
  683. if (ev.Flags == MouseFlags.Button1Pressed)
  684. {
  685. EnsureHasFocus ();
  686. PositionCursor (ev);
  687. if (_isButtonReleased)
  688. {
  689. ClearAllSelection ();
  690. }
  691. _isButtonReleased = true;
  692. _isButtonPressed = true;
  693. }
  694. else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _isButtonPressed)
  695. {
  696. int x = PositionCursor (ev);
  697. _isButtonReleased = false;
  698. PrepareSelection (x);
  699. if (Application.Mouse.MouseGrabView is null)
  700. {
  701. Application.Mouse.GrabMouse (this);
  702. }
  703. }
  704. else if (ev.Flags == MouseFlags.Button1Released)
  705. {
  706. _isButtonReleased = true;
  707. _isButtonPressed = false;
  708. Application.Mouse.UngrabMouse ();
  709. }
  710. else if (ev.Flags == MouseFlags.Button1DoubleClicked)
  711. {
  712. EnsureHasFocus ();
  713. int x = PositionCursor (ev);
  714. (int startCol, int col, int row)? newPos = GetModel ().ProcessDoubleClickSelection (x, x, 0, UseSameRuneTypeForWords, SelectWordOnlyOnDoubleClick);
  715. if (newPos is null)
  716. {
  717. return true;
  718. }
  719. SelectedStart = newPos.Value.startCol;
  720. CursorPosition = newPos.Value.col;
  721. }
  722. else if (ev.Flags == MouseFlags.Button1TripleClicked)
  723. {
  724. EnsureHasFocus ();
  725. PositionCursor (0);
  726. ClearAllSelection ();
  727. PrepareSelection (0, _text.Count);
  728. }
  729. else if (ev.Flags == ContextMenu!.MouseFlags)
  730. {
  731. PositionCursor (ev);
  732. ShowContextMenu (false);
  733. }
  734. //SetNeedsDraw ();
  735. return true;
  736. void EnsureHasFocus ()
  737. {
  738. if (!HasFocus)
  739. {
  740. SetFocus ();
  741. }
  742. }
  743. }
  744. /// <summary>Moves cursor to the end of the typed text.</summary>
  745. public void MoveEnd ()
  746. {
  747. ClearAllSelection ();
  748. _cursorPosition = _text.Count;
  749. Adjust ();
  750. }
  751. /// <inheritdoc/>
  752. protected override bool OnDrawingContent ()
  753. {
  754. _isDrawing = true;
  755. // Cache attributes as GetAttributeForRole might raise events
  756. Attribute selectedAttribute = new Attribute (GetAttributeForRole (VisualRole.Active));
  757. Attribute readonlyAttribute = GetAttributeForRole (VisualRole.ReadOnly);
  758. Attribute normalAttribute = GetAttributeForRole (VisualRole.Editable);
  759. SetSelectedStartSelectedLength ();
  760. SetAttribute (GetAttributeForRole (VisualRole.Normal));
  761. Move (0, 0);
  762. int p = ScrollOffset;
  763. var col = 0;
  764. int width = Viewport.Width + OffSetBackground ();
  765. int tcount = _text.Count;
  766. for (int idx = p; idx < tcount; idx++)
  767. {
  768. Rune rune = _text [idx];
  769. int cols = rune.GetColumns ();
  770. if (!Enabled)
  771. {
  772. // Disabled
  773. SetAttributeForRole (VisualRole.Disabled);
  774. }
  775. else if (idx == _cursorPosition && HasFocus && !Used && SelectedLength == 0 && !ReadOnly)
  776. {
  777. // Selected text
  778. SetAttribute (selectedAttribute);
  779. }
  780. else if (ReadOnly)
  781. {
  782. SetAttribute (
  783. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  784. ? selectedAttribute
  785. : readonlyAttribute
  786. );
  787. }
  788. else if (!HasFocus && Enabled)
  789. {
  790. // Normal text
  791. SetAttribute (normalAttribute);
  792. }
  793. else
  794. {
  795. SetAttribute (
  796. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  797. ? selectedAttribute
  798. : normalAttribute
  799. );
  800. }
  801. if (col + cols <= width)
  802. {
  803. AddRune (Secret ? Glyphs.Dot : rune);
  804. }
  805. if (!TextModel.SetCol (ref col, width, cols))
  806. {
  807. break;
  808. }
  809. if (idx + 1 < tcount && col + _text [idx + 1].GetColumns () > width)
  810. {
  811. break;
  812. }
  813. }
  814. SetAttribute (normalAttribute);
  815. // Fill rest of line with spaces
  816. for (int i = col; i < width; i++)
  817. {
  818. AddRune ((Rune)' ');
  819. }
  820. PositionCursor ();
  821. RenderCaption ();
  822. _isDrawing = false;
  823. return true;
  824. }
  825. /// <inheritdoc/>
  826. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  827. {
  828. if (Application.Mouse.MouseGrabView is { } && Application.Mouse.MouseGrabView == this)
  829. {
  830. Application.Mouse.UngrabMouse ();
  831. }
  832. //if (SelectedLength != 0 && !(Application.Mouse.MouseGrabView is MenuBar))
  833. // ClearAllSelection ();
  834. }
  835. /// <inheritdoc/>
  836. protected override bool OnKeyDown (Key key)
  837. {
  838. // Give autocomplete first opportunity to respond to key presses
  839. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (key))
  840. {
  841. return true;
  842. }
  843. return false;
  844. }
  845. /// <inheritdoc/>
  846. protected override bool OnKeyDownNotHandled (Key a)
  847. {
  848. // Remember the cursor position because the new calculated cursor position is needed
  849. // to be set BEFORE the TextChanged event is triggered.
  850. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  851. _preTextChangedCursorPos = _cursorPosition;
  852. // Ignore other control characters.
  853. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  854. {
  855. return false;
  856. }
  857. if (ReadOnly)
  858. {
  859. return true;
  860. }
  861. InsertText (a, true);
  862. return true;
  863. }
  864. /// <summary>Raises the <see cref="TextChanging"/> event, enabling canceling the change or adjusting the text.</summary>
  865. /// <param name="args">The event arguments.</param>
  866. /// <returns><see langword="true"/> if the event was cancelled or the text was adjusted by the event.</returns>
  867. public bool RaiseTextChanging (ResultEventArgs<string> args)
  868. {
  869. // TODO: CWP: Add an OnTextChanging protected virtual method that can be overridden to handle text changing events.
  870. TextChanging?.Invoke (this, args);
  871. return args.Handled;
  872. }
  873. /// <summary>Raised before <see cref="Text"/> changes. The change can be canceled the text adjusted.</summary>
  874. public event EventHandler<ResultEventArgs<string>> TextChanging;
  875. /// <summary>Paste the selected text from the clipboard.</summary>
  876. public virtual void Paste ()
  877. {
  878. if (ReadOnly)
  879. {
  880. return;
  881. }
  882. string cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  883. if (string.IsNullOrEmpty (cbTxt))
  884. {
  885. return;
  886. }
  887. SetSelectedStartSelectedLength ();
  888. int selStart = _start == -1 ? CursorPosition : _start;
  889. Text = StringExtensions.ToString (_text.GetRange (0, selStart))
  890. + cbTxt
  891. + StringExtensions.ToString (
  892. _text.GetRange (
  893. selStart + SelectedLength,
  894. _text.Count - (selStart + SelectedLength)
  895. )
  896. );
  897. _cursorPosition = Math.Min (selStart + cbTxt.GetRuneCount (), _text.Count);
  898. ClearAllSelection ();
  899. SetNeedsDraw ();
  900. Adjust ();
  901. }
  902. /// <summary>Sets the cursor position.</summary>
  903. public override Point? PositionCursor ()
  904. {
  905. ProcessAutocomplete ();
  906. var col = 0;
  907. for (int idx = ScrollOffset < 0 ? 0 : ScrollOffset; idx < _text.Count; idx++)
  908. {
  909. if (idx == _cursorPosition)
  910. {
  911. break;
  912. }
  913. int cols = _text [idx].GetColumns ();
  914. TextModel.SetCol (ref col, Viewport.Width - 1, cols);
  915. }
  916. int pos = col + Math.Min (Viewport.X, 0);
  917. Move (pos, 0);
  918. return new Point (pos, 0);
  919. }
  920. /// <summary>Redoes the latest changes.</summary>
  921. public void Redo ()
  922. {
  923. if (ReadOnly)
  924. {
  925. return;
  926. }
  927. _historyText.Redo ();
  928. }
  929. /// <summary>Selects all text.</summary>
  930. public void SelectAll ()
  931. {
  932. if (_text.Count == 0)
  933. {
  934. return;
  935. }
  936. _selectedStart = 0;
  937. MoveEndExtend ();
  938. SetNeedsDraw ();
  939. }
  940. ///// <summary>
  941. ///// Changed event, raised when the text has changed.
  942. ///// <remarks>
  943. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  944. ///// <see cref="string"/> containing the old value.
  945. ///// </remarks>
  946. ///// </summary>
  947. //public event EventHandler<StateEventArgs<string>> TextChanged;
  948. /// <summary>Undoes the latest changes.</summary>
  949. public void Undo ()
  950. {
  951. if (ReadOnly)
  952. {
  953. return;
  954. }
  955. _historyText.Undo ();
  956. }
  957. /// <summary>
  958. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  959. /// includes when it is empty.
  960. /// </summary>
  961. /// <returns></returns>
  962. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  963. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  964. /// <returns></returns>
  965. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  966. private void Adjust ()
  967. {
  968. if (SuperView is null)
  969. {
  970. return;
  971. }
  972. // TODO: This is a lame prototype proving it should be easy for TextField to
  973. // TODO: support Width = Dim.Auto (DimAutoStyle: Content).
  974. //SetContentSize(new (TextModel.DisplaySize (_text).size, 1));
  975. int offB = OffSetBackground ();
  976. bool need = NeedsDraw || !Used;
  977. if (_cursorPosition < ScrollOffset)
  978. {
  979. ScrollOffset = _cursorPosition;
  980. need = true;
  981. }
  982. else if (Viewport.Width > 0
  983. && (ScrollOffset + _cursorPosition - (Viewport.Width + offB) == 0
  984. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Viewport.Width + offB))
  985. {
  986. ScrollOffset = Math.Max (
  987. TextModel.CalculateLeftColumn (
  988. _text,
  989. ScrollOffset,
  990. _cursorPosition,
  991. Viewport.Width + offB
  992. ),
  993. 0
  994. );
  995. need = true;
  996. }
  997. if (need)
  998. {
  999. SetNeedsDraw ();
  1000. }
  1001. else
  1002. {
  1003. PositionCursor ();
  1004. }
  1005. }
  1006. private void CreateContextMenu ()
  1007. {
  1008. DisposeContextMenu ();
  1009. PopoverMenu menu = new (
  1010. new List<MenuItemv2>
  1011. {
  1012. new (this, Command.SelectAll, Strings.ctxSelectAll),
  1013. new (this, Command.DeleteAll, Strings.ctxDeleteAll),
  1014. new (this, Command.Copy, Strings.ctxCopy),
  1015. new (this, Command.Cut, Strings.ctxCut),
  1016. new (this, Command.Paste, Strings.ctxPaste),
  1017. new (this, Command.Undo, Strings.ctxUndo),
  1018. new (this, Command.Redo, Strings.ctxRedo)
  1019. });
  1020. HotKeyBindings.Remove (menu.Key);
  1021. HotKeyBindings.Add (menu.Key, Command.Context);
  1022. menu.KeyChanged += ContextMenu_KeyChanged;
  1023. ContextMenu = menu;
  1024. }
  1025. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.Replace (e.OldKey.KeyCode, e.NewKey.KeyCode); }
  1026. private List<Rune> DeleteSelectedText ()
  1027. {
  1028. SetSelectedStartSelectedLength ();
  1029. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1030. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1031. + StringExtensions.ToString (
  1032. _text.GetRange (
  1033. selStart + SelectedLength,
  1034. _text.Count - (selStart + SelectedLength)
  1035. )
  1036. );
  1037. ClearAllSelection ();
  1038. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1039. return newText.ToRuneList ();
  1040. }
  1041. private void GenerateSuggestions ()
  1042. {
  1043. List<Cell> currentLine = Cell.ToCellList (Text);
  1044. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1045. Autocomplete.Context = new (
  1046. currentLine,
  1047. cursorPosition,
  1048. Autocomplete.Context != null
  1049. ? Autocomplete.Context.Canceled
  1050. : false
  1051. );
  1052. Autocomplete.GenerateSuggestions (
  1053. Autocomplete.Context
  1054. );
  1055. }
  1056. private TextModel GetModel ()
  1057. {
  1058. var model = new TextModel ();
  1059. model.LoadString (Text);
  1060. return model;
  1061. }
  1062. private void HistoryText_ChangeText (object sender, HistoryTextItemEventArgs obj)
  1063. {
  1064. if (obj is null)
  1065. {
  1066. return;
  1067. }
  1068. Text = Cell.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1069. CursorPosition = obj.CursorPosition.X;
  1070. Adjust ();
  1071. }
  1072. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1073. {
  1074. _historyText.Add (
  1075. new () { Cell.ToCells (_text) },
  1076. new (_cursorPosition, 0)
  1077. );
  1078. List<Rune> newText = _text;
  1079. if (SelectedLength > 0)
  1080. {
  1081. newText = DeleteSelectedText ();
  1082. _preTextChangedCursorPos = _cursorPosition;
  1083. }
  1084. if (!usePreTextChangedCursorPos)
  1085. {
  1086. _preTextChangedCursorPos = _cursorPosition;
  1087. }
  1088. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1089. if (Used)
  1090. {
  1091. _cursorPosition++;
  1092. if (_cursorPosition == newText.Count + 1)
  1093. {
  1094. SetText (newText.Concat (kbstr).ToList ());
  1095. }
  1096. else
  1097. {
  1098. if (_preTextChangedCursorPos > newText.Count)
  1099. {
  1100. _preTextChangedCursorPos = newText.Count;
  1101. }
  1102. SetText (
  1103. newText.GetRange (0, _preTextChangedCursorPos)
  1104. .Concat (kbstr)
  1105. .Concat (
  1106. newText.GetRange (
  1107. _preTextChangedCursorPos,
  1108. Math.Min (
  1109. newText.Count - _preTextChangedCursorPos,
  1110. newText.Count
  1111. )
  1112. )
  1113. )
  1114. );
  1115. }
  1116. }
  1117. else
  1118. {
  1119. SetText (
  1120. newText.GetRange (0, _preTextChangedCursorPos)
  1121. .Concat (kbstr)
  1122. .Concat (
  1123. newText.GetRange (
  1124. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1125. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1126. )
  1127. )
  1128. );
  1129. _cursorPosition++;
  1130. }
  1131. Adjust ();
  1132. }
  1133. private void KillToEnd ()
  1134. {
  1135. if (ReadOnly)
  1136. {
  1137. return;
  1138. }
  1139. ClearAllSelection ();
  1140. if (_cursorPosition >= _text.Count)
  1141. {
  1142. return;
  1143. }
  1144. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1145. SetText (_text.GetRange (0, _cursorPosition));
  1146. Adjust ();
  1147. }
  1148. private void KillToStart ()
  1149. {
  1150. if (ReadOnly)
  1151. {
  1152. return;
  1153. }
  1154. ClearAllSelection ();
  1155. if (_cursorPosition == 0)
  1156. {
  1157. return;
  1158. }
  1159. SetClipboard (_text.GetRange (0, _cursorPosition));
  1160. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1161. _cursorPosition = 0;
  1162. Adjust ();
  1163. }
  1164. private void MoveEndExtend ()
  1165. {
  1166. if (_cursorPosition <= _text.Count)
  1167. {
  1168. int x = _cursorPosition;
  1169. _cursorPosition = _text.Count;
  1170. PrepareSelection (x, _cursorPosition - x);
  1171. }
  1172. }
  1173. private void MoveHome ()
  1174. {
  1175. ClearAllSelection ();
  1176. _cursorPosition = 0;
  1177. Adjust ();
  1178. }
  1179. private void MoveHomeExtend ()
  1180. {
  1181. if (_cursorPosition > 0)
  1182. {
  1183. int x = _cursorPosition;
  1184. _cursorPosition = 0;
  1185. PrepareSelection (x, _cursorPosition - x);
  1186. }
  1187. }
  1188. /// <summary>
  1189. /// Moves the cursor +/- the given <paramref name="distance"/>, clearing
  1190. /// any selection and returning true if any meaningful changes were made.
  1191. /// </summary>
  1192. /// <param name="distance">
  1193. /// Distance to move the cursor, will be clamped to
  1194. /// text length. Positive for right, Negative for left.
  1195. /// </param>
  1196. /// <returns></returns>
  1197. private bool Move (int distance)
  1198. {
  1199. int oldCursorPosition = _cursorPosition;
  1200. bool hadSelection = _selectedText != null && _selectedText.Length > 0;
  1201. _cursorPosition = Math.Min (_text.Count, Math.Max (0, _cursorPosition + distance));
  1202. ClearAllSelection ();
  1203. Adjust ();
  1204. return _cursorPosition != oldCursorPosition || hadSelection;
  1205. }
  1206. private bool MoveLeft () { return Move (-1); }
  1207. private void MoveLeftExtend ()
  1208. {
  1209. if (_cursorPosition > 0)
  1210. {
  1211. PrepareSelection (_cursorPosition--, -1);
  1212. }
  1213. }
  1214. private bool MoveRight () { return Move (1); }
  1215. private void MoveRightExtend ()
  1216. {
  1217. if (_cursorPosition < _text.Count)
  1218. {
  1219. PrepareSelection (_cursorPosition++, 1);
  1220. }
  1221. }
  1222. private void MoveWordLeft ()
  1223. {
  1224. ClearAllSelection ();
  1225. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0, UseSameRuneTypeForWords);
  1226. if (newPos is null)
  1227. {
  1228. return;
  1229. }
  1230. if (newPos.Value.col != -1)
  1231. {
  1232. _cursorPosition = newPos.Value.col;
  1233. }
  1234. Adjust ();
  1235. }
  1236. private void MoveWordLeftExtend ()
  1237. {
  1238. if (_cursorPosition > 0)
  1239. {
  1240. int x = Math.Min (
  1241. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1242. _text.Count
  1243. );
  1244. if (x > 0)
  1245. {
  1246. (int col, int row)? newPos = GetModel ().WordBackward (x, 0, UseSameRuneTypeForWords);
  1247. if (newPos is null)
  1248. {
  1249. return;
  1250. }
  1251. if (newPos.Value.col != -1)
  1252. {
  1253. _cursorPosition = newPos.Value.col;
  1254. }
  1255. PrepareSelection (x, newPos.Value.col - x);
  1256. }
  1257. }
  1258. }
  1259. private void MoveWordRight ()
  1260. {
  1261. ClearAllSelection ();
  1262. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0, UseSameRuneTypeForWords);
  1263. if (newPos is null)
  1264. {
  1265. return;
  1266. }
  1267. if (newPos.Value.col != -1)
  1268. {
  1269. _cursorPosition = newPos.Value.col;
  1270. }
  1271. Adjust ();
  1272. }
  1273. private void MoveWordRightExtend ()
  1274. {
  1275. if (_cursorPosition < _text.Count)
  1276. {
  1277. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1278. (int col, int row)? newPos = GetModel ().WordForward (x, 0, UseSameRuneTypeForWords);
  1279. if (newPos is null)
  1280. {
  1281. return;
  1282. }
  1283. if (newPos.Value.col != -1)
  1284. {
  1285. _cursorPosition = newPos.Value.col;
  1286. }
  1287. PrepareSelection (x, newPos.Value.col - x);
  1288. }
  1289. }
  1290. // BUGBUG: This assumes Frame == Viewport. It's also not clear what the intention is. For now, changed to always return 0.
  1291. private int OffSetBackground ()
  1292. {
  1293. var offB = 0;
  1294. if (SuperView?.Frame.Right - Frame.Right < 0)
  1295. {
  1296. offB = SuperView.Frame.Right - Frame.Right - 1;
  1297. }
  1298. return 0; //offB;
  1299. }
  1300. private int PositionCursor (MouseEventArgs ev) { return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.Position.X), false); }
  1301. private int PositionCursor (int x, bool getX = true)
  1302. {
  1303. int pX = x;
  1304. if (getX)
  1305. {
  1306. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1307. }
  1308. if (ScrollOffset + pX > _text.Count)
  1309. {
  1310. _cursorPosition = _text.Count;
  1311. }
  1312. else if (ScrollOffset + pX < ScrollOffset)
  1313. {
  1314. _cursorPosition = 0;
  1315. }
  1316. else
  1317. {
  1318. _cursorPosition = ScrollOffset + pX;
  1319. }
  1320. return _cursorPosition;
  1321. }
  1322. private void PrepareSelection (int x, int direction = 0)
  1323. {
  1324. x = x + ScrollOffset < -1 ? 0 : x;
  1325. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1326. ? x
  1327. : _selectedStart;
  1328. if (_selectedStart > -1)
  1329. {
  1330. SelectedLength = Math.Abs (
  1331. x + direction <= _text.Count
  1332. ? x + direction - _selectedStart
  1333. : _text.Count - _selectedStart
  1334. );
  1335. SetSelectedStartSelectedLength ();
  1336. if (_start > -1 && SelectedLength > 0)
  1337. {
  1338. _selectedText = SelectedLength > 0
  1339. ? StringExtensions.ToString (
  1340. _text.GetRange (
  1341. _start < 0 ? 0 : _start,
  1342. SelectedLength > _text.Count
  1343. ? _text.Count
  1344. : SelectedLength
  1345. )
  1346. )
  1347. : "";
  1348. if (ScrollOffset > _start)
  1349. {
  1350. ScrollOffset = _start;
  1351. }
  1352. }
  1353. else if (_start > -1 && SelectedLength == 0)
  1354. {
  1355. _selectedText = null;
  1356. }
  1357. SetNeedsDraw ();
  1358. }
  1359. else if (SelectedLength > 0 || _selectedText is { })
  1360. {
  1361. ClearAllSelection ();
  1362. }
  1363. Adjust ();
  1364. }
  1365. private void ProcessAutocomplete ()
  1366. {
  1367. if (_isDrawing)
  1368. {
  1369. return;
  1370. }
  1371. if (SelectedLength > 0)
  1372. {
  1373. return;
  1374. }
  1375. GenerateSuggestions ();
  1376. DrawAutocomplete ();
  1377. }
  1378. private void DrawAutocomplete ()
  1379. {
  1380. if (SelectedLength > 0)
  1381. {
  1382. return;
  1383. }
  1384. if (Autocomplete?.Context == null)
  1385. {
  1386. return;
  1387. }
  1388. var renderAt = new Point (
  1389. Autocomplete.Context.CursorPosition,
  1390. 0
  1391. );
  1392. Autocomplete.RenderOverlay (renderAt);
  1393. }
  1394. private void RenderCaption ()
  1395. {
  1396. if (HasFocus
  1397. || Caption == null
  1398. || Caption.Length == 0
  1399. || Text?.Length > 0)
  1400. {
  1401. return;
  1402. }
  1403. var color = new Attribute (CaptionColor, GetAttributeForRole (VisualRole.Editable).Background, GetAttributeForRole (VisualRole.Editable).Style);
  1404. SetAttribute (color);
  1405. Move (0, 0);
  1406. string render = Caption;
  1407. if (render.GetColumns () > Viewport.Width)
  1408. {
  1409. render = render [..Viewport.Width];
  1410. }
  1411. AddStr (render);
  1412. }
  1413. private void SetClipboard (IEnumerable<Rune> text)
  1414. {
  1415. if (!Secret)
  1416. {
  1417. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1418. }
  1419. }
  1420. private void SetOverwrite (bool overwrite)
  1421. {
  1422. Used = overwrite;
  1423. SetNeedsDraw ();
  1424. }
  1425. private void SetSelectedStartSelectedLength ()
  1426. {
  1427. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1428. {
  1429. _start = _cursorPosition;
  1430. }
  1431. else
  1432. {
  1433. _start = SelectedStart;
  1434. }
  1435. }
  1436. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1437. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1438. private void ShowContextMenu (bool keyboard)
  1439. {
  1440. if (!Equals (_currentCulture, Thread.CurrentThread.CurrentUICulture))
  1441. {
  1442. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1443. if (ContextMenu is { })
  1444. {
  1445. CreateContextMenu ();
  1446. }
  1447. }
  1448. if (keyboard)
  1449. {
  1450. ContextMenu?.MakeVisible (ViewportToScreen (new Point (_cursorPosition - ScrollOffset, 1)));
  1451. }
  1452. else
  1453. {
  1454. ContextMenu?.MakeVisible ();
  1455. }
  1456. }
  1457. private void TextField_SuperViewChanged (object sender, SuperViewChangedEventArgs e)
  1458. {
  1459. if (e.SuperView is { })
  1460. {
  1461. if (Autocomplete.HostControl is null)
  1462. {
  1463. Autocomplete.HostControl = this;
  1464. Autocomplete.PopupInsideContainer = false;
  1465. }
  1466. }
  1467. else
  1468. {
  1469. Autocomplete.HostControl = null;
  1470. }
  1471. }
  1472. private void TextField_Initialized (object sender, EventArgs e)
  1473. {
  1474. _cursorPosition = Text.GetRuneCount ();
  1475. if (Viewport.Width > 0)
  1476. {
  1477. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1478. }
  1479. if (Autocomplete.HostControl is null)
  1480. {
  1481. Autocomplete.HostControl = this;
  1482. Autocomplete.PopupInsideContainer = false;
  1483. }
  1484. }
  1485. private void DisposeContextMenu ()
  1486. {
  1487. if (ContextMenu is { })
  1488. {
  1489. ContextMenu.Visible = false;
  1490. ContextMenu.KeyChanged -= ContextMenu_KeyChanged;
  1491. ContextMenu.Dispose ();
  1492. ContextMenu = null;
  1493. }
  1494. }
  1495. /// <inheritdoc />
  1496. public bool EnableForDesign ()
  1497. {
  1498. Text = "This is a test.";
  1499. Caption = "Caption";
  1500. return true;
  1501. }
  1502. /// <inheritdoc/>
  1503. protected override void Dispose (bool disposing)
  1504. {
  1505. if (disposing)
  1506. {
  1507. DisposeContextMenu ();
  1508. }
  1509. base.Dispose (disposing);
  1510. }
  1511. }
  1512. /// <summary>
  1513. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1514. /// options. An implementation on a TextField.
  1515. /// </summary>
  1516. public class TextFieldAutocomplete : PopupAutocomplete
  1517. {
  1518. /// <inheritdoc/>
  1519. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1520. /// <inheritdoc/>
  1521. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1522. /// <inheritdoc/>
  1523. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1524. }