TextField.cs 55 KB

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