TextField.cs 54 KB

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