TextField.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  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. /// <summary>
  347. /// Gets or sets the text to render in control when no value has been entered yet and the <see cref="View"/> does
  348. /// not yet have input focus.
  349. /// </summary>
  350. public string Caption { get; set; }
  351. /// <summary>Gets or sets the foreground <see cref="Color"/> to use when rendering <see cref="Caption"/>.</summary>
  352. public Color CaptionColor { get; set; }
  353. /// <summary>Get the <see cref="ContextMenu"/> for this view.</summary>
  354. public ContextMenu ContextMenu { get; }
  355. /// <summary>Sets or gets the current cursor position.</summary>
  356. public virtual int CursorPosition
  357. {
  358. get => _cursorPosition;
  359. set
  360. {
  361. if (value < 0)
  362. {
  363. _cursorPosition = 0;
  364. }
  365. else if (value > _text.Count)
  366. {
  367. _cursorPosition = _text.Count;
  368. }
  369. else
  370. {
  371. _cursorPosition = value;
  372. }
  373. PrepareSelection (_selectedStart, _cursorPosition - _selectedStart);
  374. }
  375. }
  376. /// <summary>Get / Set the wished cursor when the field is focused</summary>
  377. public CursorVisibility DesiredCursorVisibility
  378. {
  379. get => _desiredCursorVisibility;
  380. set
  381. {
  382. if ((_desiredCursorVisibility != value || _visibility != value) && HasFocus)
  383. {
  384. Application.Driver.SetCursorVisibility (value);
  385. }
  386. _desiredCursorVisibility = _visibility = value;
  387. }
  388. }
  389. /// <summary>
  390. /// Indicates whatever the text has history changes or not. <see langword="true"/> if the text has history changes
  391. /// <see langword="false"/> otherwise.
  392. /// </summary>
  393. public bool HasHistoryChanges => _historyText.HasHistoryChanges;
  394. /// <summary>
  395. /// Indicates whatever the text was changed or not. <see langword="true"/> if the text was changed
  396. /// <see langword="false"/> otherwise.
  397. /// </summary>
  398. public bool IsDirty => _historyText.IsDirty (Text);
  399. /// <summary>If set to true its not allow any changes in the text.</summary>
  400. public bool ReadOnly { get; set; }
  401. /// <summary>Gets the left offset position.</summary>
  402. public int ScrollOffset { get; private set; }
  403. /// <summary>
  404. /// Sets the secret property.
  405. /// <remarks>This makes the text entry suitable for entering passwords.</remarks>
  406. /// </summary>
  407. public bool Secret { get; set; }
  408. /// <summary>Length of the selected text.</summary>
  409. public int SelectedLength { get; private set; }
  410. /// <summary>Start position of the selected text.</summary>
  411. public int SelectedStart
  412. {
  413. get => _selectedStart;
  414. set
  415. {
  416. if (value < -1)
  417. {
  418. _selectedStart = -1;
  419. }
  420. else if (value > _text.Count)
  421. {
  422. _selectedStart = _text.Count;
  423. }
  424. else
  425. {
  426. _selectedStart = value;
  427. }
  428. PrepareSelection (_selectedStart, _cursorPosition - _selectedStart);
  429. }
  430. }
  431. /// <summary>The selected text.</summary>
  432. public string SelectedText
  433. {
  434. get => Secret ? null : _selectedText;
  435. private set => _selectedText = value;
  436. }
  437. /// <summary>Sets or gets the text held by the view.</summary>
  438. public new string Text
  439. {
  440. get => StringExtensions.ToString (_text);
  441. set
  442. {
  443. var oldText = StringExtensions.ToString (_text);
  444. if (oldText == value)
  445. {
  446. return;
  447. }
  448. StateEventArgs<string> newText = OnTextChanging (value.Replace ("\t", "").Split ("\n") [0]);
  449. if (newText.Cancel)
  450. {
  451. if (_cursorPosition > _text.Count)
  452. {
  453. _cursorPosition = _text.Count;
  454. }
  455. return;
  456. }
  457. ClearAllSelection ();
  458. _text = newText.NewValue.EnumerateRunes ().ToList ();
  459. if (!Secret && !_historyText.IsFromHistory)
  460. {
  461. _historyText.Add (
  462. new List<List<RuneCell>> { TextModel.ToRuneCellList (oldText) },
  463. new Point (_cursorPosition, 0)
  464. );
  465. _historyText.Add (
  466. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  467. new Point (_cursorPosition, 0),
  468. HistoryText.LineStatus.Replaced
  469. );
  470. }
  471. OnTextChanged (oldText, StringExtensions.ToString (_text));
  472. ProcessAutocomplete ();
  473. if (_cursorPosition > _text.Count)
  474. {
  475. _cursorPosition = Math.Max (TextModel.DisplaySize (_text, 0).size - 1, 0);
  476. }
  477. Adjust ();
  478. SetNeedsDisplay ();
  479. }
  480. }
  481. /// <summary>
  482. /// Tracks whether the text field should be considered "used", that is, that the user has moved in the entry, so
  483. /// new input should be appended at the cursor position, rather than clearing the entry
  484. /// </summary>
  485. public bool Used { get; set; }
  486. /// <summary>Clear the selected text.</summary>
  487. public void ClearAllSelection ()
  488. {
  489. if (_selectedStart == -1 && SelectedLength == 0 && string.IsNullOrEmpty (_selectedText))
  490. {
  491. return;
  492. }
  493. _selectedStart = -1;
  494. SelectedLength = 0;
  495. _selectedText = null;
  496. _start = 0;
  497. SelectedLength = 0;
  498. SetNeedsDisplay ();
  499. }
  500. /// <summary>Allows clearing the <see cref="HistoryText.HistoryTextItem"/> items updating the original text.</summary>
  501. public void ClearHistoryChanges () { _historyText.Clear (Text); }
  502. /// <summary>Copy the selected text to the clipboard.</summary>
  503. public virtual void Copy ()
  504. {
  505. if (Secret || SelectedLength == 0)
  506. {
  507. return;
  508. }
  509. Clipboard.Contents = SelectedText;
  510. }
  511. /// <summary>Cut the selected text to the clipboard.</summary>
  512. public virtual void Cut ()
  513. {
  514. if (ReadOnly || Secret || SelectedLength == 0)
  515. {
  516. return;
  517. }
  518. Clipboard.Contents = SelectedText;
  519. List<Rune> newText = DeleteSelectedText ();
  520. Text = StringExtensions.ToString (newText);
  521. Adjust ();
  522. }
  523. /// <summary>Deletes all text.</summary>
  524. public void DeleteAll ()
  525. {
  526. if (_text.Count == 0)
  527. {
  528. return;
  529. }
  530. _selectedStart = 0;
  531. MoveEndExtend ();
  532. DeleteCharLeft (false);
  533. SetNeedsDisplay ();
  534. }
  535. /// <summary>Deletes the character to the left.</summary>
  536. /// <param name="usePreTextChangedCursorPos">
  537. /// If set to <see langword="true">true</see> use the cursor position cached ;
  538. /// otherwise use <see cref="CursorPosition"/>. use .
  539. /// </param>
  540. public virtual void DeleteCharLeft (bool usePreTextChangedCursorPos)
  541. {
  542. if (ReadOnly)
  543. {
  544. return;
  545. }
  546. _historyText.Add (
  547. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  548. new Point (_cursorPosition, 0)
  549. );
  550. if (SelectedLength == 0)
  551. {
  552. if (_cursorPosition == 0)
  553. {
  554. return;
  555. }
  556. if (!usePreTextChangedCursorPos)
  557. {
  558. _preTextChangedCursorPos = _cursorPosition;
  559. }
  560. _cursorPosition--;
  561. if (_preTextChangedCursorPos < _text.Count)
  562. {
  563. SetText (
  564. _text.GetRange (0, _preTextChangedCursorPos - 1)
  565. .Concat (
  566. _text.GetRange (
  567. _preTextChangedCursorPos,
  568. _text.Count - _preTextChangedCursorPos
  569. )
  570. )
  571. );
  572. }
  573. else
  574. {
  575. SetText (_text.GetRange (0, _preTextChangedCursorPos - 1));
  576. }
  577. Adjust ();
  578. }
  579. else
  580. {
  581. List<Rune> newText = DeleteSelectedText ();
  582. Text = StringExtensions.ToString (newText);
  583. Adjust ();
  584. }
  585. }
  586. /// <summary>Deletes the character to the right.</summary>
  587. public virtual void DeleteCharRight ()
  588. {
  589. if (ReadOnly)
  590. {
  591. return;
  592. }
  593. _historyText.Add (
  594. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  595. new Point (_cursorPosition, 0)
  596. );
  597. if (SelectedLength == 0)
  598. {
  599. if (_text.Count == 0 || _text.Count == _cursorPosition)
  600. {
  601. return;
  602. }
  603. SetText (
  604. _text.GetRange (0, _cursorPosition)
  605. .Concat (_text.GetRange (_cursorPosition + 1, _text.Count - (_cursorPosition + 1)))
  606. );
  607. Adjust ();
  608. }
  609. else
  610. {
  611. List<Rune> newText = DeleteSelectedText ();
  612. Text = StringExtensions.ToString (newText);
  613. Adjust ();
  614. }
  615. }
  616. /// <inheritdoc/>
  617. public override Attribute GetNormalColor ()
  618. {
  619. ColorScheme cs = ColorScheme;
  620. if (ColorScheme is null)
  621. {
  622. cs = new ColorScheme ();
  623. }
  624. return Enabled ? cs.Focus : cs.Disabled;
  625. }
  626. /// <summary>
  627. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position exactly as if the user had just
  628. /// typed it
  629. /// </summary>
  630. /// <param name="toAdd">Text to add</param>
  631. /// <param name="useOldCursorPos">Use the previous cursor position.</param>
  632. public void InsertText (string toAdd, bool useOldCursorPos = true)
  633. {
  634. foreach (char ch in toAdd)
  635. {
  636. KeyCode key;
  637. try
  638. {
  639. key = (KeyCode)ch;
  640. }
  641. catch (Exception)
  642. {
  643. throw new ArgumentException (
  644. $"Cannot insert character '{ch}' because it does not map to a Key"
  645. );
  646. }
  647. InsertText (new Key { KeyCode = key }, useOldCursorPos);
  648. }
  649. }
  650. /// <summary>Deletes word backwards.</summary>
  651. public virtual void KillWordBackwards ()
  652. {
  653. ClearAllSelection ();
  654. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  655. if (newPos is null)
  656. {
  657. return;
  658. }
  659. if (newPos.Value.col != -1)
  660. {
  661. SetText (
  662. _text.GetRange (0, newPos.Value.col)
  663. .Concat (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition))
  664. );
  665. _cursorPosition = newPos.Value.col;
  666. }
  667. Adjust ();
  668. }
  669. /// <summary>Deletes word forwards.</summary>
  670. public virtual void KillWordForwards ()
  671. {
  672. ClearAllSelection ();
  673. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  674. if (newPos is null)
  675. {
  676. return;
  677. }
  678. if (newPos.Value.col != -1)
  679. {
  680. SetText (
  681. _text.GetRange (0, _cursorPosition)
  682. .Concat (_text.GetRange (newPos.Value.col, _text.Count - newPos.Value.col))
  683. );
  684. }
  685. Adjust ();
  686. }
  687. /// <inheritdoc/>
  688. protected internal override bool OnMouseEvent (MouseEvent ev)
  689. {
  690. if (!ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  691. && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition)
  692. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  693. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  694. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  695. && !ev.Flags.HasFlag (ContextMenu.MouseFlags))
  696. {
  697. return base.OnMouseEvent (ev);
  698. }
  699. if (!CanFocus)
  700. {
  701. return true;
  702. }
  703. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition)
  704. {
  705. SetFocus ();
  706. }
  707. // Give autocomplete first opportunity to respond to mouse clicks
  708. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  709. {
  710. return true;
  711. }
  712. if (ev.Flags == MouseFlags.Button1Pressed)
  713. {
  714. EnsureHasFocus ();
  715. PositionCursor (ev);
  716. if (_isButtonReleased)
  717. {
  718. ClearAllSelection ();
  719. }
  720. _isButtonReleased = true;
  721. _isButtonPressed = true;
  722. }
  723. else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _isButtonPressed)
  724. {
  725. int x = PositionCursor (ev);
  726. _isButtonReleased = false;
  727. PrepareSelection (x);
  728. if (Application.MouseGrabView is null)
  729. {
  730. Application.GrabMouse (this);
  731. }
  732. }
  733. else if (ev.Flags == MouseFlags.Button1Released)
  734. {
  735. _isButtonReleased = true;
  736. _isButtonPressed = false;
  737. Application.UngrabMouse ();
  738. }
  739. else if (ev.Flags == MouseFlags.Button1DoubleClicked)
  740. {
  741. EnsureHasFocus ();
  742. int x = PositionCursor (ev);
  743. int sbw = x;
  744. if (x == _text.Count
  745. || (x > 0 && (char)_text [x - 1].Value != ' ')
  746. || (x > 0 && (char)_text [x].Value == ' '))
  747. {
  748. (int col, int row)? newPosBw = GetModel ().WordBackward (x, 0);
  749. if (newPosBw is null)
  750. {
  751. return true;
  752. }
  753. sbw = newPosBw.Value.col;
  754. }
  755. if (sbw != -1)
  756. {
  757. x = sbw;
  758. PositionCursor (x);
  759. }
  760. (int col, int row)? newPosFw = GetModel ().WordForward (x, 0);
  761. if (newPosFw is null)
  762. {
  763. return true;
  764. }
  765. ClearAllSelection ();
  766. if (newPosFw.Value.col != -1 && sbw != -1)
  767. {
  768. _cursorPosition = newPosFw.Value.col;
  769. }
  770. PrepareSelection (sbw, newPosFw.Value.col - sbw);
  771. }
  772. else if (ev.Flags == MouseFlags.Button1TripleClicked)
  773. {
  774. EnsureHasFocus ();
  775. PositionCursor (0);
  776. ClearAllSelection ();
  777. PrepareSelection (0, _text.Count);
  778. }
  779. else if (ev.Flags == ContextMenu.MouseFlags)
  780. {
  781. ShowContextMenu ();
  782. }
  783. SetNeedsDisplay ();
  784. return true;
  785. void EnsureHasFocus ()
  786. {
  787. if (!HasFocus)
  788. {
  789. SetFocus ();
  790. }
  791. }
  792. }
  793. /// <summary>Moves cursor to the end of the typed text.</summary>
  794. public void MoveEnd ()
  795. {
  796. ClearAllSelection ();
  797. _cursorPosition = _text.Count;
  798. Adjust ();
  799. }
  800. /// <inheritdoc/>
  801. public override void OnDrawContent (Rectangle viewport)
  802. {
  803. _isDrawing = true;
  804. var selColor = new Attribute (GetFocusColor ().Background, GetFocusColor ().Foreground);
  805. SetSelectedStartSelectedLength ();
  806. Driver?.SetAttribute (GetNormalColor ());
  807. Move (0, 0);
  808. int p = ScrollOffset;
  809. var col = 0;
  810. int width = Frame.Width + OffSetBackground ();
  811. int tcount = _text.Count;
  812. Attribute roc = GetReadOnlyColor ();
  813. for (int idx = p; idx < tcount; idx++)
  814. {
  815. Rune rune = _text [idx];
  816. int cols = rune.GetColumns ();
  817. if (idx == _cursorPosition && HasFocus && !Used && SelectedLength == 0 && !ReadOnly)
  818. {
  819. Driver?.SetAttribute (selColor);
  820. }
  821. else if (ReadOnly)
  822. {
  823. Driver?.SetAttribute (
  824. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  825. ? selColor
  826. : roc
  827. );
  828. }
  829. else if (!HasFocus && Enabled)
  830. {
  831. Driver?.SetAttribute (GetFocusColor ());
  832. }
  833. else if (!Enabled)
  834. {
  835. Driver?.SetAttribute (roc);
  836. }
  837. else
  838. {
  839. Driver?.SetAttribute (
  840. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  841. ? selColor
  842. : ColorScheme.Focus
  843. );
  844. }
  845. if (col + cols <= width)
  846. {
  847. Driver?.AddRune (Secret ? Glyphs.Dot : rune);
  848. }
  849. if (!TextModel.SetCol (ref col, width, cols))
  850. {
  851. break;
  852. }
  853. if (idx + 1 < tcount && col + _text [idx + 1].GetColumns () > width)
  854. {
  855. break;
  856. }
  857. }
  858. Driver.SetAttribute (GetFocusColor ());
  859. for (int i = col; i < width; i++)
  860. {
  861. Driver.AddRune ((Rune)' ');
  862. }
  863. PositionCursor ();
  864. RenderCaption ();
  865. ProcessAutocomplete ();
  866. _isDrawing = false;
  867. }
  868. /// <inheritdoc/>
  869. public override bool OnEnter (View view)
  870. {
  871. if (IsInitialized)
  872. {
  873. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  874. }
  875. return base.OnEnter (view);
  876. }
  877. /// <inheritdoc/>
  878. public override bool? OnInvokingKeyBindings (Key a)
  879. {
  880. // Give autocomplete first opportunity to respond to key presses
  881. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (a))
  882. {
  883. return true;
  884. }
  885. return base.OnInvokingKeyBindings (a);
  886. }
  887. /// <inheritdoc/>
  888. public override bool OnLeave (View view)
  889. {
  890. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  891. {
  892. Application.UngrabMouse ();
  893. }
  894. //if (SelectedLength != 0 && !(Application.MouseGrabView is MenuBar))
  895. // ClearAllSelection ();
  896. return base.OnLeave (view);
  897. }
  898. /// TODO: Flush out these docs
  899. /// <summary>
  900. /// Processes key presses for the <see cref="TextField"/>.
  901. /// <remarks>
  902. /// The <see cref="TextField"/> control responds to the following keys:
  903. /// <list type="table">
  904. /// <listheader>
  905. /// <term>Keys</term> <description>Function</description>
  906. /// </listheader>
  907. /// <item>
  908. /// <term><see cref="Key.Delete"/>, <see cref="Key.Backspace"/></term>
  909. /// <description>Deletes the character before cursor.</description>
  910. /// </item>
  911. /// </list>
  912. /// </remarks>
  913. /// </summary>
  914. /// <param name="a"></param>
  915. /// <returns></returns>
  916. public override bool OnProcessKeyDown (Key a)
  917. {
  918. // Remember the cursor position because the new calculated cursor position is needed
  919. // to be set BEFORE the TextChanged event is triggered.
  920. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  921. _preTextChangedCursorPos = _cursorPosition;
  922. // Ignore other control characters.
  923. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  924. {
  925. return false;
  926. }
  927. if (ReadOnly)
  928. {
  929. return true;
  930. }
  931. InsertText (a, true);
  932. return true;
  933. }
  934. /// <summary>Virtual method that invoke the <see cref="TextChanging"/> event if it's defined.</summary>
  935. /// <param name="newText">The new text to be replaced.</param>
  936. /// <returns>Returns the <see cref="StringEventArgs"/></returns>
  937. public virtual StateEventArgs<string> OnTextChanging (string newText)
  938. {
  939. StateEventArgs<string> ev = new (string.Empty, newText);
  940. TextChanging?.Invoke (this, ev);
  941. return ev;
  942. }
  943. /// <summary>Paste the selected text from the clipboard.</summary>
  944. public virtual void Paste ()
  945. {
  946. if (ReadOnly || string.IsNullOrEmpty (Clipboard.Contents))
  947. {
  948. return;
  949. }
  950. SetSelectedStartSelectedLength ();
  951. int selStart = _start == -1 ? CursorPosition : _start;
  952. string cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  953. Text = StringExtensions.ToString (_text.GetRange (0, selStart))
  954. + cbTxt
  955. + StringExtensions.ToString (
  956. _text.GetRange (
  957. selStart + SelectedLength,
  958. _text.Count - (selStart + SelectedLength)
  959. )
  960. );
  961. _cursorPosition = Math.Min (selStart + cbTxt.GetRuneCount (), _text.Count);
  962. ClearAllSelection ();
  963. SetNeedsDisplay ();
  964. Adjust ();
  965. }
  966. /// <summary>Sets the cursor position.</summary>
  967. public override void PositionCursor ()
  968. {
  969. if (!IsInitialized)
  970. {
  971. return;
  972. }
  973. ProcessAutocomplete ();
  974. var col = 0;
  975. for (int idx = ScrollOffset < 0 ? 0 : ScrollOffset; idx < _text.Count; idx++)
  976. {
  977. if (idx == _cursorPosition)
  978. {
  979. break;
  980. }
  981. int cols = _text [idx].GetColumns ();
  982. TextModel.SetCol (ref col, Frame.Width - 1, cols);
  983. }
  984. int pos = _cursorPosition - ScrollOffset + Math.Min (Frame.X, 0);
  985. int offB = OffSetBackground ();
  986. bool isVisibleInViewport = IsViewLocationVisibleInViewport (col, Viewport.Y);
  987. if (isVisibleInViewport
  988. && pos > -1
  989. && col >= pos
  990. && pos < Frame.Width + offB)
  991. {
  992. RestoreCursorVisibility ();
  993. Move (col, 0);
  994. }
  995. else
  996. {
  997. HideCursorVisibility ();
  998. if (pos < 0)
  999. {
  1000. Move (pos, 0);
  1001. }
  1002. else
  1003. {
  1004. Move (pos - offB, 0);
  1005. }
  1006. }
  1007. }
  1008. /// <summary>Redoes the latest changes.</summary>
  1009. public void Redo ()
  1010. {
  1011. if (ReadOnly)
  1012. {
  1013. return;
  1014. }
  1015. _historyText.Redo ();
  1016. //if (string.IsNullOrEmpty (Clipboard.Contents))
  1017. // return true;
  1018. //var clip = TextModel.ToRunes (Clipboard.Contents);
  1019. //if (clip is null)
  1020. // return true;
  1021. //if (point == text.Count) {
  1022. // point = text.Count;
  1023. // SetText(text.Concat(clip).ToList());
  1024. //} else {
  1025. // point += clip.Count;
  1026. // SetText(text.GetRange(0, oldCursorPos).Concat(clip).Concat(text.GetRange(oldCursorPos, text.Count - oldCursorPos)));
  1027. //}
  1028. //Adjust ();
  1029. }
  1030. /// <summary>Selects all text.</summary>
  1031. public void SelectAll ()
  1032. {
  1033. if (_text.Count == 0)
  1034. {
  1035. return;
  1036. }
  1037. _selectedStart = 0;
  1038. MoveEndExtend ();
  1039. SetNeedsDisplay ();
  1040. }
  1041. ///// <summary>
  1042. ///// Changed event, raised when the text has changed.
  1043. ///// <remarks>
  1044. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  1045. ///// <see cref="string"/> containing the old value.
  1046. ///// </remarks>
  1047. ///// </summary>
  1048. //public event EventHandler<StateEventArgs<string>> TextChanged;
  1049. /// <summary>Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.</summary>
  1050. public event EventHandler<StateEventArgs<string>> TextChanging;
  1051. /// <summary>Undoes the latest changes.</summary>
  1052. public void Undo ()
  1053. {
  1054. if (ReadOnly)
  1055. {
  1056. return;
  1057. }
  1058. _historyText.Undo ();
  1059. }
  1060. /// <summary>
  1061. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  1062. /// includes when it is empty.
  1063. /// </summary>
  1064. /// <returns></returns>
  1065. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  1066. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  1067. /// <returns></returns>
  1068. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  1069. private void Adjust ()
  1070. {
  1071. if (!IsAdded)
  1072. {
  1073. return;
  1074. }
  1075. int offB = OffSetBackground ();
  1076. bool need = NeedsDisplay || !Used;
  1077. if (_cursorPosition < ScrollOffset)
  1078. {
  1079. ScrollOffset = _cursorPosition;
  1080. need = true;
  1081. }
  1082. else if (Frame.Width > 0
  1083. && (ScrollOffset + _cursorPosition - (Frame.Width + offB) == 0
  1084. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Frame.Width + offB))
  1085. {
  1086. ScrollOffset = Math.Max (
  1087. TextModel.CalculateLeftColumn (
  1088. _text,
  1089. ScrollOffset,
  1090. _cursorPosition,
  1091. Frame.Width + offB
  1092. ),
  1093. 0
  1094. );
  1095. need = true;
  1096. }
  1097. if (need)
  1098. {
  1099. SetNeedsDisplay ();
  1100. }
  1101. else
  1102. {
  1103. PositionCursor ();
  1104. }
  1105. }
  1106. private MenuBarItem BuildContextMenuBarItem ()
  1107. {
  1108. return new MenuBarItem (
  1109. new MenuItem []
  1110. {
  1111. new (
  1112. Strings.ctxSelectAll,
  1113. "",
  1114. () => SelectAll (),
  1115. null,
  1116. null,
  1117. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  1118. ),
  1119. new (
  1120. Strings.ctxDeleteAll,
  1121. "",
  1122. () => DeleteAll (),
  1123. null,
  1124. null,
  1125. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  1126. ),
  1127. new (
  1128. Strings.ctxCopy,
  1129. "",
  1130. () => Copy (),
  1131. null,
  1132. null,
  1133. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  1134. ),
  1135. new (
  1136. Strings.ctxCut,
  1137. "",
  1138. () => Cut (),
  1139. null,
  1140. null,
  1141. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  1142. ),
  1143. new (
  1144. Strings.ctxPaste,
  1145. "",
  1146. () => Paste (),
  1147. null,
  1148. null,
  1149. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  1150. ),
  1151. new (
  1152. Strings.ctxUndo,
  1153. "",
  1154. () => Undo (),
  1155. null,
  1156. null,
  1157. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  1158. ),
  1159. new (
  1160. Strings.ctxRedo,
  1161. "",
  1162. () => Redo (),
  1163. null,
  1164. null,
  1165. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  1166. )
  1167. }
  1168. );
  1169. }
  1170. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.Replace (e.OldKey.KeyCode, e.NewKey.KeyCode); }
  1171. private List<Rune> DeleteSelectedText ()
  1172. {
  1173. SetSelectedStartSelectedLength ();
  1174. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1175. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1176. + StringExtensions.ToString (
  1177. _text.GetRange (
  1178. selStart + SelectedLength,
  1179. _text.Count - (selStart + SelectedLength)
  1180. )
  1181. );
  1182. ClearAllSelection ();
  1183. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1184. return newText.ToRuneList ();
  1185. }
  1186. private void GenerateSuggestions ()
  1187. {
  1188. List<RuneCell> currentLine = TextModel.ToRuneCellList (Text);
  1189. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1190. Autocomplete.Context = new AutocompleteContext (
  1191. currentLine,
  1192. cursorPosition,
  1193. Autocomplete.Context != null
  1194. ? Autocomplete.Context.Canceled
  1195. : false
  1196. );
  1197. Autocomplete.GenerateSuggestions (
  1198. Autocomplete.Context
  1199. );
  1200. }
  1201. private TextModel GetModel ()
  1202. {
  1203. var model = new TextModel ();
  1204. model.LoadString (Text);
  1205. return model;
  1206. }
  1207. private Attribute GetReadOnlyColor ()
  1208. {
  1209. ColorScheme cs = ColorScheme;
  1210. if (ColorScheme is null)
  1211. {
  1212. cs = new ColorScheme ();
  1213. }
  1214. if (cs.Disabled.Foreground == cs.Focus.Background)
  1215. {
  1216. return new Attribute (cs.Focus.Foreground, cs.Focus.Background);
  1217. }
  1218. return new Attribute (cs.Disabled.Foreground, cs.Focus.Background);
  1219. }
  1220. private void HideCursorVisibility ()
  1221. {
  1222. if (_desiredCursorVisibility != CursorVisibility.Invisible)
  1223. {
  1224. DesiredCursorVisibility = CursorVisibility.Invisible;
  1225. }
  1226. }
  1227. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItem obj)
  1228. {
  1229. if (obj is null)
  1230. {
  1231. return;
  1232. }
  1233. Text = TextModel.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1234. CursorPosition = obj.CursorPosition.X;
  1235. Adjust ();
  1236. }
  1237. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1238. {
  1239. _historyText.Add (
  1240. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  1241. new Point (_cursorPosition, 0)
  1242. );
  1243. List<Rune> newText = _text;
  1244. if (SelectedLength > 0)
  1245. {
  1246. newText = DeleteSelectedText ();
  1247. _preTextChangedCursorPos = _cursorPosition;
  1248. }
  1249. if (!usePreTextChangedCursorPos)
  1250. {
  1251. _preTextChangedCursorPos = _cursorPosition;
  1252. }
  1253. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1254. if (Used)
  1255. {
  1256. _cursorPosition++;
  1257. if (_cursorPosition == newText.Count + 1)
  1258. {
  1259. SetText (newText.Concat (kbstr).ToList ());
  1260. }
  1261. else
  1262. {
  1263. if (_preTextChangedCursorPos > newText.Count)
  1264. {
  1265. _preTextChangedCursorPos = newText.Count;
  1266. }
  1267. SetText (
  1268. newText.GetRange (0, _preTextChangedCursorPos)
  1269. .Concat (kbstr)
  1270. .Concat (
  1271. newText.GetRange (
  1272. _preTextChangedCursorPos,
  1273. Math.Min (
  1274. newText.Count - _preTextChangedCursorPos,
  1275. newText.Count
  1276. )
  1277. )
  1278. )
  1279. );
  1280. }
  1281. }
  1282. else
  1283. {
  1284. SetText (
  1285. newText.GetRange (0, _preTextChangedCursorPos)
  1286. .Concat (kbstr)
  1287. .Concat (
  1288. newText.GetRange (
  1289. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1290. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1291. )
  1292. )
  1293. );
  1294. _cursorPosition++;
  1295. }
  1296. Adjust ();
  1297. }
  1298. private void KillToEnd ()
  1299. {
  1300. if (ReadOnly)
  1301. {
  1302. return;
  1303. }
  1304. ClearAllSelection ();
  1305. if (_cursorPosition >= _text.Count)
  1306. {
  1307. return;
  1308. }
  1309. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1310. SetText (_text.GetRange (0, _cursorPosition));
  1311. Adjust ();
  1312. }
  1313. private void KillToStart ()
  1314. {
  1315. if (ReadOnly)
  1316. {
  1317. return;
  1318. }
  1319. ClearAllSelection ();
  1320. if (_cursorPosition == 0)
  1321. {
  1322. return;
  1323. }
  1324. SetClipboard (_text.GetRange (0, _cursorPosition));
  1325. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1326. _cursorPosition = 0;
  1327. Adjust ();
  1328. }
  1329. private void MoveEndExtend ()
  1330. {
  1331. if (_cursorPosition <= _text.Count)
  1332. {
  1333. int x = _cursorPosition;
  1334. _cursorPosition = _text.Count;
  1335. PrepareSelection (x, _cursorPosition - x);
  1336. }
  1337. }
  1338. private void MoveHome ()
  1339. {
  1340. ClearAllSelection ();
  1341. _cursorPosition = 0;
  1342. Adjust ();
  1343. }
  1344. private void MoveHomeExtend ()
  1345. {
  1346. if (_cursorPosition > 0)
  1347. {
  1348. int x = _cursorPosition;
  1349. _cursorPosition = 0;
  1350. PrepareSelection (x, _cursorPosition - x);
  1351. }
  1352. }
  1353. private void MoveLeft ()
  1354. {
  1355. ClearAllSelection ();
  1356. if (_cursorPosition > 0)
  1357. {
  1358. _cursorPosition--;
  1359. Adjust ();
  1360. }
  1361. }
  1362. private void MoveLeftExtend ()
  1363. {
  1364. if (_cursorPosition > 0)
  1365. {
  1366. PrepareSelection (_cursorPosition--, -1);
  1367. }
  1368. }
  1369. private void MoveRight ()
  1370. {
  1371. ClearAllSelection ();
  1372. if (_cursorPosition == _text.Count)
  1373. {
  1374. return;
  1375. }
  1376. _cursorPosition++;
  1377. Adjust ();
  1378. }
  1379. private void MoveRightExtend ()
  1380. {
  1381. if (_cursorPosition < _text.Count)
  1382. {
  1383. PrepareSelection (_cursorPosition++, 1);
  1384. }
  1385. }
  1386. private void MoveWordLeft ()
  1387. {
  1388. ClearAllSelection ();
  1389. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  1390. if (newPos is null)
  1391. {
  1392. return;
  1393. }
  1394. if (newPos.Value.col != -1)
  1395. {
  1396. _cursorPosition = newPos.Value.col;
  1397. }
  1398. Adjust ();
  1399. }
  1400. private void MoveWordLeftExtend ()
  1401. {
  1402. if (_cursorPosition > 0)
  1403. {
  1404. int x = Math.Min (
  1405. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1406. _text.Count
  1407. );
  1408. if (x > 0)
  1409. {
  1410. (int col, int row)? newPos = GetModel ().WordBackward (x, 0);
  1411. if (newPos is null)
  1412. {
  1413. return;
  1414. }
  1415. if (newPos.Value.col != -1)
  1416. {
  1417. _cursorPosition = newPos.Value.col;
  1418. }
  1419. PrepareSelection (x, newPos.Value.col - x);
  1420. }
  1421. }
  1422. }
  1423. private void MoveWordRight ()
  1424. {
  1425. ClearAllSelection ();
  1426. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  1427. if (newPos is null)
  1428. {
  1429. return;
  1430. }
  1431. if (newPos.Value.col != -1)
  1432. {
  1433. _cursorPosition = newPos.Value.col;
  1434. }
  1435. Adjust ();
  1436. }
  1437. private void MoveWordRightExtend ()
  1438. {
  1439. if (_cursorPosition < _text.Count)
  1440. {
  1441. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1442. (int col, int row)? newPos = GetModel ().WordForward (x, 0);
  1443. if (newPos is null)
  1444. {
  1445. return;
  1446. }
  1447. if (newPos.Value.col != -1)
  1448. {
  1449. _cursorPosition = newPos.Value.col;
  1450. }
  1451. PrepareSelection (x, newPos.Value.col - x);
  1452. }
  1453. }
  1454. // BUGBUG: This assumes Frame == Viewport. It's also not clear what the intention is. For now, changed to always return 0.
  1455. private int OffSetBackground ()
  1456. {
  1457. var offB = 0;
  1458. if (SuperView?.Frame.Right - Frame.Right < 0)
  1459. {
  1460. offB = SuperView.Frame.Right - Frame.Right - 1;
  1461. }
  1462. return 0;//offB;
  1463. }
  1464. private int PositionCursor (MouseEvent ev)
  1465. {
  1466. return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.X), false);
  1467. }
  1468. private int PositionCursor (int x, bool getX = true)
  1469. {
  1470. int pX = x;
  1471. if (getX)
  1472. {
  1473. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1474. }
  1475. if (ScrollOffset + pX > _text.Count)
  1476. {
  1477. _cursorPosition = _text.Count;
  1478. }
  1479. else if (ScrollOffset + pX < ScrollOffset)
  1480. {
  1481. _cursorPosition = 0;
  1482. }
  1483. else
  1484. {
  1485. _cursorPosition = ScrollOffset + pX;
  1486. }
  1487. return _cursorPosition;
  1488. }
  1489. private void PrepareSelection (int x, int direction = 0)
  1490. {
  1491. x = x + ScrollOffset < -1 ? 0 : x;
  1492. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1493. ? x
  1494. : _selectedStart;
  1495. if (_selectedStart > -1)
  1496. {
  1497. SelectedLength = Math.Abs (
  1498. x + direction <= _text.Count
  1499. ? x + direction - _selectedStart
  1500. : _text.Count - _selectedStart
  1501. );
  1502. SetSelectedStartSelectedLength ();
  1503. if (_start > -1 && SelectedLength > 0)
  1504. {
  1505. _selectedText = SelectedLength > 0
  1506. ? StringExtensions.ToString (
  1507. _text.GetRange (
  1508. _start < 0 ? 0 : _start,
  1509. SelectedLength > _text.Count
  1510. ? _text.Count
  1511. : SelectedLength
  1512. )
  1513. )
  1514. : "";
  1515. if (ScrollOffset > _start)
  1516. {
  1517. ScrollOffset = _start;
  1518. }
  1519. }
  1520. else if (_start > -1 && SelectedLength == 0)
  1521. {
  1522. _selectedText = null;
  1523. }
  1524. SetNeedsDisplay ();
  1525. }
  1526. else if (SelectedLength > 0 || _selectedText is { })
  1527. {
  1528. ClearAllSelection ();
  1529. }
  1530. Adjust ();
  1531. }
  1532. private void ProcessAutocomplete ()
  1533. {
  1534. if (_isDrawing)
  1535. {
  1536. return;
  1537. }
  1538. if (SelectedLength > 0)
  1539. {
  1540. return;
  1541. }
  1542. // draw autocomplete
  1543. GenerateSuggestions ();
  1544. var renderAt = new Point (
  1545. Autocomplete.Context.CursorPosition,
  1546. 0
  1547. );
  1548. Autocomplete.RenderOverlay (renderAt);
  1549. }
  1550. private void RenderCaption ()
  1551. {
  1552. if (HasFocus
  1553. || Caption == null
  1554. || Caption.Length == 0
  1555. || Text?.Length > 0)
  1556. {
  1557. return;
  1558. }
  1559. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  1560. Driver.SetAttribute (color);
  1561. Move (0, 0);
  1562. string render = Caption;
  1563. if (render.GetColumns () > Viewport.Width)
  1564. {
  1565. render = render [..Viewport.Width];
  1566. }
  1567. Driver.AddStr (render);
  1568. }
  1569. private void RestoreCursorVisibility ()
  1570. {
  1571. Application.Driver.GetCursorVisibility (out _visibility);
  1572. if (_desiredCursorVisibility != _savedCursorVisibility || _visibility != _savedCursorVisibility)
  1573. {
  1574. DesiredCursorVisibility = _savedCursorVisibility;
  1575. }
  1576. }
  1577. private void SetClipboard (IEnumerable<Rune> text)
  1578. {
  1579. if (!Secret)
  1580. {
  1581. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1582. }
  1583. }
  1584. private void SetOverwrite (bool overwrite)
  1585. {
  1586. Used = overwrite;
  1587. SetNeedsDisplay ();
  1588. }
  1589. private void SetSelectedStartSelectedLength ()
  1590. {
  1591. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1592. {
  1593. _start = _cursorPosition;
  1594. }
  1595. else
  1596. {
  1597. _start = SelectedStart;
  1598. }
  1599. }
  1600. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1601. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1602. private void ShowContextMenu ()
  1603. {
  1604. if (_currentCulture != Thread.CurrentThread.CurrentUICulture)
  1605. {
  1606. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1607. ContextMenu.MenuItems = BuildContextMenuBarItem ();
  1608. }
  1609. ContextMenu.Show ();
  1610. }
  1611. private void TextField_Initialized (object sender, EventArgs e)
  1612. {
  1613. _cursorPosition = Text.GetRuneCount ();
  1614. if (Viewport.Width > 0)
  1615. {
  1616. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1617. }
  1618. Autocomplete.HostControl = this;
  1619. Autocomplete.PopupInsideContainer = false;
  1620. }
  1621. private void TextField_LayoutComplete (object sender, LayoutEventArgs e)
  1622. {
  1623. // Don't let height > 1
  1624. if (Frame.Height > 1)
  1625. {
  1626. Height = 1;
  1627. }
  1628. }
  1629. }
  1630. /// <summary>
  1631. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1632. /// options. An implementation on a TextField.
  1633. /// </summary>
  1634. public class TextFieldAutocomplete : PopupAutocomplete
  1635. {
  1636. /// <inheritdoc/>
  1637. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1638. /// <inheritdoc/>
  1639. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1640. /// <inheritdoc/>
  1641. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1642. }