TextField.cs 56 KB

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