TextField.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  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 contentArea)
  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. Rectangle containerFrame = SuperView?.BoundsToScreen (SuperView.Viewport) ?? default (Rectangle);
  987. Rectangle thisFrame = BoundsToScreen (Viewport);
  988. if (pos > -1
  989. && col >= pos
  990. && pos < Frame.Width + offB
  991. && containerFrame.IntersectsWith (thisFrame))
  992. {
  993. RestoreCursorVisibility ();
  994. Move (col, 0);
  995. }
  996. else
  997. {
  998. HideCursorVisibility ();
  999. if (pos < 0)
  1000. {
  1001. Move (pos, 0);
  1002. }
  1003. else
  1004. {
  1005. Move (pos - offB, 0);
  1006. }
  1007. }
  1008. }
  1009. /// <summary>Redoes the latest changes.</summary>
  1010. public void Redo ()
  1011. {
  1012. if (ReadOnly)
  1013. {
  1014. return;
  1015. }
  1016. _historyText.Redo ();
  1017. //if (string.IsNullOrEmpty (Clipboard.Contents))
  1018. // return true;
  1019. //var clip = TextModel.ToRunes (Clipboard.Contents);
  1020. //if (clip is null)
  1021. // return true;
  1022. //if (point == text.Count) {
  1023. // point = text.Count;
  1024. // SetText(text.Concat(clip).ToList());
  1025. //} else {
  1026. // point += clip.Count;
  1027. // SetText(text.GetRange(0, oldCursorPos).Concat(clip).Concat(text.GetRange(oldCursorPos, text.Count - oldCursorPos)));
  1028. //}
  1029. //Adjust ();
  1030. }
  1031. /// <summary>Selects all text.</summary>
  1032. public void SelectAll ()
  1033. {
  1034. if (_text.Count == 0)
  1035. {
  1036. return;
  1037. }
  1038. _selectedStart = 0;
  1039. MoveEndExtend ();
  1040. SetNeedsDisplay ();
  1041. }
  1042. ///// <summary>
  1043. ///// Changed event, raised when the text has changed.
  1044. ///// <remarks>
  1045. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  1046. ///// <see cref="string"/> containing the old value.
  1047. ///// </remarks>
  1048. ///// </summary>
  1049. //public event EventHandler<StateEventArgs<string>> TextChanged;
  1050. /// <summary>Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.</summary>
  1051. public event EventHandler<StateEventArgs<string>> TextChanging;
  1052. /// <summary>Undoes the latest changes.</summary>
  1053. public void Undo ()
  1054. {
  1055. if (ReadOnly)
  1056. {
  1057. return;
  1058. }
  1059. _historyText.Undo ();
  1060. }
  1061. /// <summary>
  1062. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  1063. /// includes when it is empty.
  1064. /// </summary>
  1065. /// <returns></returns>
  1066. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  1067. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  1068. /// <returns></returns>
  1069. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  1070. private void Adjust ()
  1071. {
  1072. if (!IsAdded)
  1073. {
  1074. return;
  1075. }
  1076. int offB = OffSetBackground ();
  1077. bool need = NeedsDisplay || !Used;
  1078. if (_cursorPosition < ScrollOffset)
  1079. {
  1080. ScrollOffset = _cursorPosition;
  1081. need = true;
  1082. }
  1083. else if (Frame.Width > 0
  1084. && (ScrollOffset + _cursorPosition - (Frame.Width + offB) == 0
  1085. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Frame.Width + offB))
  1086. {
  1087. ScrollOffset = Math.Max (
  1088. TextModel.CalculateLeftColumn (
  1089. _text,
  1090. ScrollOffset,
  1091. _cursorPosition,
  1092. Frame.Width + offB
  1093. ),
  1094. 0
  1095. );
  1096. need = true;
  1097. }
  1098. if (need)
  1099. {
  1100. SetNeedsDisplay ();
  1101. }
  1102. else
  1103. {
  1104. PositionCursor ();
  1105. }
  1106. }
  1107. private MenuBarItem BuildContextMenuBarItem ()
  1108. {
  1109. return new MenuBarItem (
  1110. new MenuItem []
  1111. {
  1112. new (
  1113. Strings.ctxSelectAll,
  1114. "",
  1115. () => SelectAll (),
  1116. null,
  1117. null,
  1118. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  1119. ),
  1120. new (
  1121. Strings.ctxDeleteAll,
  1122. "",
  1123. () => DeleteAll (),
  1124. null,
  1125. null,
  1126. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  1127. ),
  1128. new (
  1129. Strings.ctxCopy,
  1130. "",
  1131. () => Copy (),
  1132. null,
  1133. null,
  1134. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  1135. ),
  1136. new (
  1137. Strings.ctxCut,
  1138. "",
  1139. () => Cut (),
  1140. null,
  1141. null,
  1142. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  1143. ),
  1144. new (
  1145. Strings.ctxPaste,
  1146. "",
  1147. () => Paste (),
  1148. null,
  1149. null,
  1150. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  1151. ),
  1152. new (
  1153. Strings.ctxUndo,
  1154. "",
  1155. () => Undo (),
  1156. null,
  1157. null,
  1158. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  1159. ),
  1160. new (
  1161. Strings.ctxRedo,
  1162. "",
  1163. () => Redo (),
  1164. null,
  1165. null,
  1166. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  1167. )
  1168. }
  1169. );
  1170. }
  1171. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.Replace (e.OldKey.KeyCode, e.NewKey.KeyCode); }
  1172. private List<Rune> DeleteSelectedText ()
  1173. {
  1174. SetSelectedStartSelectedLength ();
  1175. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1176. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1177. + StringExtensions.ToString (
  1178. _text.GetRange (
  1179. selStart + SelectedLength,
  1180. _text.Count - (selStart + SelectedLength)
  1181. )
  1182. );
  1183. ClearAllSelection ();
  1184. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1185. return newText.ToRuneList ();
  1186. }
  1187. private void GenerateSuggestions ()
  1188. {
  1189. List<RuneCell> currentLine = TextModel.ToRuneCellList (Text);
  1190. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1191. Autocomplete.Context = new AutocompleteContext (
  1192. currentLine,
  1193. cursorPosition,
  1194. Autocomplete.Context != null
  1195. ? Autocomplete.Context.Canceled
  1196. : false
  1197. );
  1198. Autocomplete.GenerateSuggestions (
  1199. Autocomplete.Context
  1200. );
  1201. }
  1202. private TextModel GetModel ()
  1203. {
  1204. var model = new TextModel ();
  1205. model.LoadString (Text);
  1206. return model;
  1207. }
  1208. private Attribute GetReadOnlyColor ()
  1209. {
  1210. ColorScheme cs = ColorScheme;
  1211. if (ColorScheme is null)
  1212. {
  1213. cs = new ColorScheme ();
  1214. }
  1215. if (cs.Disabled.Foreground == cs.Focus.Background)
  1216. {
  1217. return new Attribute (cs.Focus.Foreground, cs.Focus.Background);
  1218. }
  1219. return new Attribute (cs.Disabled.Foreground, cs.Focus.Background);
  1220. }
  1221. private void HideCursorVisibility ()
  1222. {
  1223. if (_desiredCursorVisibility != CursorVisibility.Invisible)
  1224. {
  1225. DesiredCursorVisibility = CursorVisibility.Invisible;
  1226. }
  1227. }
  1228. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItem obj)
  1229. {
  1230. if (obj is null)
  1231. {
  1232. return;
  1233. }
  1234. Text = TextModel.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1235. CursorPosition = obj.CursorPosition.X;
  1236. Adjust ();
  1237. }
  1238. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1239. {
  1240. _historyText.Add (
  1241. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  1242. new Point (_cursorPosition, 0)
  1243. );
  1244. List<Rune> newText = _text;
  1245. if (SelectedLength > 0)
  1246. {
  1247. newText = DeleteSelectedText ();
  1248. _preTextChangedCursorPos = _cursorPosition;
  1249. }
  1250. if (!usePreTextChangedCursorPos)
  1251. {
  1252. _preTextChangedCursorPos = _cursorPosition;
  1253. }
  1254. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1255. if (Used)
  1256. {
  1257. _cursorPosition++;
  1258. if (_cursorPosition == newText.Count + 1)
  1259. {
  1260. SetText (newText.Concat (kbstr).ToList ());
  1261. }
  1262. else
  1263. {
  1264. if (_preTextChangedCursorPos > newText.Count)
  1265. {
  1266. _preTextChangedCursorPos = newText.Count;
  1267. }
  1268. SetText (
  1269. newText.GetRange (0, _preTextChangedCursorPos)
  1270. .Concat (kbstr)
  1271. .Concat (
  1272. newText.GetRange (
  1273. _preTextChangedCursorPos,
  1274. Math.Min (
  1275. newText.Count - _preTextChangedCursorPos,
  1276. newText.Count
  1277. )
  1278. )
  1279. )
  1280. );
  1281. }
  1282. }
  1283. else
  1284. {
  1285. SetText (
  1286. newText.GetRange (0, _preTextChangedCursorPos)
  1287. .Concat (kbstr)
  1288. .Concat (
  1289. newText.GetRange (
  1290. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1291. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1292. )
  1293. )
  1294. );
  1295. _cursorPosition++;
  1296. }
  1297. Adjust ();
  1298. }
  1299. private void KillToEnd ()
  1300. {
  1301. if (ReadOnly)
  1302. {
  1303. return;
  1304. }
  1305. ClearAllSelection ();
  1306. if (_cursorPosition >= _text.Count)
  1307. {
  1308. return;
  1309. }
  1310. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1311. SetText (_text.GetRange (0, _cursorPosition));
  1312. Adjust ();
  1313. }
  1314. private void KillToStart ()
  1315. {
  1316. if (ReadOnly)
  1317. {
  1318. return;
  1319. }
  1320. ClearAllSelection ();
  1321. if (_cursorPosition == 0)
  1322. {
  1323. return;
  1324. }
  1325. SetClipboard (_text.GetRange (0, _cursorPosition));
  1326. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1327. _cursorPosition = 0;
  1328. Adjust ();
  1329. }
  1330. private void MoveEndExtend ()
  1331. {
  1332. if (_cursorPosition <= _text.Count)
  1333. {
  1334. int x = _cursorPosition;
  1335. _cursorPosition = _text.Count;
  1336. PrepareSelection (x, _cursorPosition - x);
  1337. }
  1338. }
  1339. private void MoveHome ()
  1340. {
  1341. ClearAllSelection ();
  1342. _cursorPosition = 0;
  1343. Adjust ();
  1344. }
  1345. private void MoveHomeExtend ()
  1346. {
  1347. if (_cursorPosition > 0)
  1348. {
  1349. int x = _cursorPosition;
  1350. _cursorPosition = 0;
  1351. PrepareSelection (x, _cursorPosition - x);
  1352. }
  1353. }
  1354. private void MoveLeft ()
  1355. {
  1356. ClearAllSelection ();
  1357. if (_cursorPosition > 0)
  1358. {
  1359. _cursorPosition--;
  1360. Adjust ();
  1361. }
  1362. }
  1363. private void MoveLeftExtend ()
  1364. {
  1365. if (_cursorPosition > 0)
  1366. {
  1367. PrepareSelection (_cursorPosition--, -1);
  1368. }
  1369. }
  1370. private void MoveRight ()
  1371. {
  1372. ClearAllSelection ();
  1373. if (_cursorPosition == _text.Count)
  1374. {
  1375. return;
  1376. }
  1377. _cursorPosition++;
  1378. Adjust ();
  1379. }
  1380. private void MoveRightExtend ()
  1381. {
  1382. if (_cursorPosition < _text.Count)
  1383. {
  1384. PrepareSelection (_cursorPosition++, 1);
  1385. }
  1386. }
  1387. private void MoveWordLeft ()
  1388. {
  1389. ClearAllSelection ();
  1390. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  1391. if (newPos is null)
  1392. {
  1393. return;
  1394. }
  1395. if (newPos.Value.col != -1)
  1396. {
  1397. _cursorPosition = newPos.Value.col;
  1398. }
  1399. Adjust ();
  1400. }
  1401. private void MoveWordLeftExtend ()
  1402. {
  1403. if (_cursorPosition > 0)
  1404. {
  1405. int x = Math.Min (
  1406. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1407. _text.Count
  1408. );
  1409. if (x > 0)
  1410. {
  1411. (int col, int row)? newPos = GetModel ().WordBackward (x, 0);
  1412. if (newPos is null)
  1413. {
  1414. return;
  1415. }
  1416. if (newPos.Value.col != -1)
  1417. {
  1418. _cursorPosition = newPos.Value.col;
  1419. }
  1420. PrepareSelection (x, newPos.Value.col - x);
  1421. }
  1422. }
  1423. }
  1424. private void MoveWordRight ()
  1425. {
  1426. ClearAllSelection ();
  1427. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  1428. if (newPos is null)
  1429. {
  1430. return;
  1431. }
  1432. if (newPos.Value.col != -1)
  1433. {
  1434. _cursorPosition = newPos.Value.col;
  1435. }
  1436. Adjust ();
  1437. }
  1438. private void MoveWordRightExtend ()
  1439. {
  1440. if (_cursorPosition < _text.Count)
  1441. {
  1442. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1443. (int col, int row)? newPos = GetModel ().WordForward (x, 0);
  1444. if (newPos is null)
  1445. {
  1446. return;
  1447. }
  1448. if (newPos.Value.col != -1)
  1449. {
  1450. _cursorPosition = newPos.Value.col;
  1451. }
  1452. PrepareSelection (x, newPos.Value.col - x);
  1453. }
  1454. }
  1455. // BUGBUG: This assumes Frame == Bounds. It's also not clear what the intention is. For now, changed to always return 0.
  1456. private int OffSetBackground ()
  1457. {
  1458. var offB = 0;
  1459. if (SuperView?.Frame.Right - Frame.Right < 0)
  1460. {
  1461. offB = SuperView.Frame.Right - Frame.Right - 1;
  1462. }
  1463. return 0;//offB;
  1464. }
  1465. private int PositionCursor (MouseEvent ev)
  1466. {
  1467. return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.X), false);
  1468. }
  1469. private int PositionCursor (int x, bool getX = true)
  1470. {
  1471. int pX = x;
  1472. if (getX)
  1473. {
  1474. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1475. }
  1476. if (ScrollOffset + pX > _text.Count)
  1477. {
  1478. _cursorPosition = _text.Count;
  1479. }
  1480. else if (ScrollOffset + pX < ScrollOffset)
  1481. {
  1482. _cursorPosition = 0;
  1483. }
  1484. else
  1485. {
  1486. _cursorPosition = ScrollOffset + pX;
  1487. }
  1488. return _cursorPosition;
  1489. }
  1490. private void PrepareSelection (int x, int direction = 0)
  1491. {
  1492. x = x + ScrollOffset < -1 ? 0 : x;
  1493. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1494. ? x
  1495. : _selectedStart;
  1496. if (_selectedStart > -1)
  1497. {
  1498. SelectedLength = Math.Abs (
  1499. x + direction <= _text.Count
  1500. ? x + direction - _selectedStart
  1501. : _text.Count - _selectedStart
  1502. );
  1503. SetSelectedStartSelectedLength ();
  1504. if (_start > -1 && SelectedLength > 0)
  1505. {
  1506. _selectedText = SelectedLength > 0
  1507. ? StringExtensions.ToString (
  1508. _text.GetRange (
  1509. _start < 0 ? 0 : _start,
  1510. SelectedLength > _text.Count
  1511. ? _text.Count
  1512. : SelectedLength
  1513. )
  1514. )
  1515. : "";
  1516. if (ScrollOffset > _start)
  1517. {
  1518. ScrollOffset = _start;
  1519. }
  1520. }
  1521. else if (_start > -1 && SelectedLength == 0)
  1522. {
  1523. _selectedText = null;
  1524. }
  1525. SetNeedsDisplay ();
  1526. }
  1527. else if (SelectedLength > 0 || _selectedText is { })
  1528. {
  1529. ClearAllSelection ();
  1530. }
  1531. Adjust ();
  1532. }
  1533. private void ProcessAutocomplete ()
  1534. {
  1535. if (_isDrawing)
  1536. {
  1537. return;
  1538. }
  1539. if (SelectedLength > 0)
  1540. {
  1541. return;
  1542. }
  1543. // draw autocomplete
  1544. GenerateSuggestions ();
  1545. var renderAt = new Point (
  1546. Autocomplete.Context.CursorPosition,
  1547. 0
  1548. );
  1549. Autocomplete.RenderOverlay (renderAt);
  1550. }
  1551. private void RenderCaption ()
  1552. {
  1553. if (HasFocus
  1554. || Caption == null
  1555. || Caption.Length == 0
  1556. || Text?.Length > 0)
  1557. {
  1558. return;
  1559. }
  1560. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  1561. Driver.SetAttribute (color);
  1562. Move (0, 0);
  1563. string render = Caption;
  1564. if (render.GetColumns () > Viewport.Width)
  1565. {
  1566. render = render [..Viewport.Width];
  1567. }
  1568. Driver.AddStr (render);
  1569. }
  1570. private void RestoreCursorVisibility ()
  1571. {
  1572. Application.Driver.GetCursorVisibility (out _visibility);
  1573. if (_desiredCursorVisibility != _savedCursorVisibility || _visibility != _savedCursorVisibility)
  1574. {
  1575. DesiredCursorVisibility = _savedCursorVisibility;
  1576. }
  1577. }
  1578. private void SetClipboard (IEnumerable<Rune> text)
  1579. {
  1580. if (!Secret)
  1581. {
  1582. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1583. }
  1584. }
  1585. private void SetOverwrite (bool overwrite)
  1586. {
  1587. Used = overwrite;
  1588. SetNeedsDisplay ();
  1589. }
  1590. private void SetSelectedStartSelectedLength ()
  1591. {
  1592. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1593. {
  1594. _start = _cursorPosition;
  1595. }
  1596. else
  1597. {
  1598. _start = SelectedStart;
  1599. }
  1600. }
  1601. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1602. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1603. private void ShowContextMenu ()
  1604. {
  1605. if (_currentCulture != Thread.CurrentThread.CurrentUICulture)
  1606. {
  1607. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1608. ContextMenu.MenuItems = BuildContextMenuBarItem ();
  1609. }
  1610. ContextMenu.Show ();
  1611. }
  1612. private void TextField_Initialized (object sender, EventArgs e)
  1613. {
  1614. _cursorPosition = Text.GetRuneCount ();
  1615. if (Viewport.Width > 0)
  1616. {
  1617. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1618. }
  1619. Autocomplete.HostControl = this;
  1620. Autocomplete.PopupInsideContainer = false;
  1621. }
  1622. private void TextField_LayoutComplete (object sender, LayoutEventArgs e)
  1623. {
  1624. // Don't let height > 1
  1625. if (Frame.Height > 1)
  1626. {
  1627. Height = 1;
  1628. }
  1629. }
  1630. }
  1631. /// <summary>
  1632. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1633. /// options. An implementation on a TextField.
  1634. /// </summary>
  1635. public class TextFieldAutocomplete : PopupAutocomplete
  1636. {
  1637. /// <inheritdoc/>
  1638. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1639. /// <inheritdoc/>
  1640. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1641. /// <inheritdoc/>
  1642. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1643. }