TextField.cs 54 KB

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