TextField.cs 55 KB

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