TextField.cs 55 KB

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