TextField.cs 58 KB

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