TextField.cs 56 KB

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