TextField.cs 54 KB

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