TextField.cs 53 KB

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