TextField.cs 58 KB

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