TextField.cs 58 KB

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