TextField.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865
  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.CursorLeft.WithShift, Command.LeftExtend);
  275. KeyBindings.Add (Key.CursorUp.WithShift, Command.LeftExtend);
  276. KeyBindings.Add (Key.CursorRight.WithShift, Command.RightExtend);
  277. KeyBindings.Add (Key.CursorDown.WithShift, Command.RightExtend);
  278. KeyBindings.Add (Key.CursorLeft.WithShift.WithCtrl, Command.WordLeftExtend);
  279. KeyBindings.Add (Key.CursorUp.WithShift.WithCtrl, Command.WordLeftExtend);
  280. KeyBindings.Add (Key.CursorRight.WithShift.WithCtrl, Command.WordRightExtend);
  281. KeyBindings.Add (Key.CursorDown.WithShift.WithCtrl, Command.WordRightExtend);
  282. KeyBindings.Add (Key.CursorLeft, Command.Left);
  283. KeyBindings.Add (Key.B.WithCtrl, Command.Left);
  284. KeyBindings.Add (Key.End, Command.RightEnd);
  285. KeyBindings.Add (Key.End.WithCtrl, Command.RightEnd);
  286. KeyBindings.Add (Key.E.WithCtrl, Command.RightEnd);
  287. KeyBindings.Add (Key.CursorRight, Command.Right);
  288. KeyBindings.Add (Key.F.WithCtrl, Command.Right);
  289. KeyBindings.Add (Key.K.WithCtrl, Command.CutToEndLine);
  290. KeyBindings.Add (Key.K.WithCtrl.WithShift, Command.CutToStartLine);
  291. KeyBindings.Add (Key.Z.WithCtrl, Command.Undo);
  292. KeyBindings.Add (Key.Y.WithCtrl, Command.Redo);
  293. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.WordLeft);
  294. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.WordLeft);
  295. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.WordRight);
  296. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.WordRight);
  297. #if UNIX_KEY_BINDINGS
  298. KeyBindings.Add (Key.F.WithShift.WithAlt, Command.WordRightExtend);
  299. KeyBindings.Add (Key.K.WithAlt, Command.CutToStartLine);
  300. KeyBindings.Add (Key.B.WithShift.WithAlt, Command.WordLeftExtend);
  301. KeyBindings.Add (Key.B.WithAlt, Command.WordLeft);
  302. KeyBindings.Add (Key.F.WithAlt, Command.WordRight);
  303. KeyBindings.Add (Key.Backspace.WithAlt, Command.Undo);
  304. #endif
  305. KeyBindings.Add (Key.Delete.WithCtrl, Command.KillWordForwards);
  306. KeyBindings.Add (Key.Backspace.WithCtrl, Command.KillWordBackwards);
  307. KeyBindings.Add (Key.InsertChar, Command.ToggleOverwrite);
  308. KeyBindings.Add (Key.C.WithCtrl, Command.Copy);
  309. KeyBindings.Add (Key.X.WithCtrl, Command.Cut);
  310. KeyBindings.Add (Key.V.WithCtrl, Command.Paste);
  311. KeyBindings.Add (Key.A.WithCtrl, Command.SelectAll);
  312. KeyBindings.Add (Key.R.WithCtrl, Command.DeleteAll);
  313. KeyBindings.Add (Key.D.WithCtrl.WithShift, Command.DeleteAll);
  314. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  315. ContextMenu = new () { Host = this };
  316. ContextMenu.KeyChanged += ContextMenu_KeyChanged;
  317. KeyBindings.Add (ContextMenu.Key, KeyBindingScope.HotKey, Command.Context);
  318. KeyBindings.Remove (Key.Space);
  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 ([Cell.StringToCells (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 () { Cell.ToCellList (oldText) },
  432. new (_cursorPosition, 0)
  433. );
  434. _historyText.Add (
  435. new () { Cell.ToCells (_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. SetNeedsDraw ();
  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. SetNeedsDraw ();
  468. }
  469. /// <summary>Allows clearing the <see cref="HistoryText.HistoryTextItemEventArgs"/> items updating the original text.</summary>
  470. public void ClearHistoryChanges () { _historyText.Clear ([Cell.StringToCells (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. SetNeedsDraw ();
  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 () { Cell.ToCells (_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 () { Cell.ToCells (_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 override bool OnMouseEvent (MouseEventArgs ev)
  650. {
  651. if (ev is { IsPressed: false, IsReleased: false }
  652. && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition)
  653. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  654. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  655. && !ev.Flags.HasFlag (ContextMenu.MouseFlags))
  656. {
  657. return false;
  658. }
  659. if (!CanFocus)
  660. {
  661. return true;
  662. }
  663. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition)
  664. {
  665. SetFocus ();
  666. }
  667. // Give autocomplete first opportunity to respond to mouse clicks
  668. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  669. {
  670. return true;
  671. }
  672. if (ev.Flags == MouseFlags.Button1Pressed)
  673. {
  674. EnsureHasFocus ();
  675. PositionCursor (ev);
  676. if (_isButtonReleased)
  677. {
  678. ClearAllSelection ();
  679. }
  680. _isButtonReleased = true;
  681. _isButtonPressed = true;
  682. }
  683. else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _isButtonPressed)
  684. {
  685. int x = PositionCursor (ev);
  686. _isButtonReleased = false;
  687. PrepareSelection (x);
  688. if (Application.MouseGrabView is null)
  689. {
  690. Application.GrabMouse (this);
  691. }
  692. }
  693. else if (ev.Flags == MouseFlags.Button1Released)
  694. {
  695. _isButtonReleased = true;
  696. _isButtonPressed = false;
  697. Application.UngrabMouse ();
  698. }
  699. else if (ev.Flags == MouseFlags.Button1DoubleClicked)
  700. {
  701. EnsureHasFocus ();
  702. int x = PositionCursor (ev);
  703. int sbw = x;
  704. if (x == _text.Count
  705. || (x > 0 && (char)_text [x - 1].Value != ' ')
  706. || (x > 0 && (char)_text [x].Value == ' '))
  707. {
  708. (int col, int row)? newPosBw = GetModel ().WordBackward (x, 0);
  709. if (newPosBw is null)
  710. {
  711. return true;
  712. }
  713. sbw = newPosBw.Value.col;
  714. }
  715. if (sbw != -1)
  716. {
  717. x = sbw;
  718. PositionCursor (x);
  719. }
  720. (int col, int row)? newPosFw = GetModel ().WordForward (x, 0);
  721. if (newPosFw is null)
  722. {
  723. return true;
  724. }
  725. ClearAllSelection ();
  726. if (newPosFw.Value.col != -1 && sbw != -1)
  727. {
  728. _cursorPosition = newPosFw.Value.col;
  729. }
  730. PrepareSelection (sbw, newPosFw.Value.col - sbw);
  731. }
  732. else if (ev.Flags == MouseFlags.Button1TripleClicked)
  733. {
  734. EnsureHasFocus ();
  735. PositionCursor (0);
  736. ClearAllSelection ();
  737. PrepareSelection (0, _text.Count);
  738. }
  739. else if (ev.Flags == ContextMenu.MouseFlags)
  740. {
  741. ShowContextMenu ();
  742. }
  743. //SetNeedsDraw ();
  744. return true;
  745. void EnsureHasFocus ()
  746. {
  747. if (!HasFocus)
  748. {
  749. SetFocus ();
  750. }
  751. }
  752. }
  753. /// <summary>Moves cursor to the end of the typed text.</summary>
  754. public void MoveEnd ()
  755. {
  756. ClearAllSelection ();
  757. _cursorPosition = _text.Count;
  758. Adjust ();
  759. }
  760. /// <inheritdoc/>
  761. protected override bool OnDrawingContent ()
  762. {
  763. _isDrawing = true;
  764. var selColor = new Attribute (GetFocusColor ().Background, GetFocusColor ().Foreground);
  765. SetSelectedStartSelectedLength ();
  766. SetAttribute (GetNormalColor ());
  767. Move (0, 0);
  768. int p = ScrollOffset;
  769. var col = 0;
  770. int width = Viewport.Width + OffSetBackground ();
  771. int tcount = _text.Count;
  772. Attribute roc = GetReadOnlyColor ();
  773. for (int idx = p; idx < tcount; idx++)
  774. {
  775. Rune rune = _text [idx];
  776. int cols = rune.GetColumns ();
  777. if (idx == _cursorPosition && HasFocus && !Used && SelectedLength == 0 && !ReadOnly)
  778. {
  779. SetAttribute (selColor);
  780. }
  781. else if (ReadOnly)
  782. {
  783. SetAttribute (
  784. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  785. ? selColor
  786. : roc
  787. );
  788. }
  789. else if (!HasFocus && Enabled)
  790. {
  791. SetAttribute (GetFocusColor ());
  792. }
  793. else if (!Enabled)
  794. {
  795. SetAttribute (roc);
  796. }
  797. else
  798. {
  799. SetAttribute (
  800. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  801. ? selColor
  802. : ColorScheme.Focus
  803. );
  804. }
  805. if (col + cols <= width)
  806. {
  807. Driver?.AddRune (Secret ? Glyphs.Dot : rune);
  808. }
  809. if (!TextModel.SetCol (ref col, width, cols))
  810. {
  811. break;
  812. }
  813. if (idx + 1 < tcount && col + _text [idx + 1].GetColumns () > width)
  814. {
  815. break;
  816. }
  817. }
  818. SetAttribute (GetFocusColor ());
  819. for (int i = col; i < width; i++)
  820. {
  821. Driver?.AddRune ((Rune)' ');
  822. }
  823. PositionCursor ();
  824. RenderCaption ();
  825. DrawAutocomplete ();
  826. _isDrawing = false;
  827. return true;
  828. }
  829. /// <inheritdoc/>
  830. protected override void OnHasFocusChanged (bool newHasFocus, View previousFocusedView, View view)
  831. {
  832. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  833. {
  834. Application.UngrabMouse ();
  835. }
  836. //if (SelectedLength != 0 && !(Application.MouseGrabView is MenuBar))
  837. // ClearAllSelection ();
  838. }
  839. /// <inheritdoc/>
  840. protected override bool OnKeyDown (Key key)
  841. {
  842. // Give autocomplete first opportunity to respond to key presses
  843. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (key))
  844. {
  845. return true;
  846. }
  847. return false;
  848. }
  849. /// <inheritdoc />
  850. protected override bool OnKeyDownNotHandled (Key a)
  851. {
  852. // Remember the cursor position because the new calculated cursor position is needed
  853. // to be set BEFORE the TextChanged event is triggered.
  854. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  855. _preTextChangedCursorPos = _cursorPosition;
  856. // Ignore other control characters.
  857. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  858. {
  859. return false;
  860. }
  861. if (ReadOnly)
  862. {
  863. return true;
  864. }
  865. InsertText (a, true);
  866. return true;
  867. }
  868. /// <summary>Virtual method that invoke the <see cref="TextChanging"/> event if it's defined.</summary>
  869. /// <param name="args">The event arguments.</param>
  870. /// <returns><see langword="true"/> if the event was cancelled.</returns>
  871. public bool OnTextChanging (CancelEventArgs<string> args)
  872. {
  873. TextChanging?.Invoke (this, args);
  874. return args.Cancel;
  875. }
  876. /// <summary>Paste the selected text from the clipboard.</summary>
  877. public virtual void Paste ()
  878. {
  879. if (ReadOnly || string.IsNullOrEmpty (Clipboard.Contents))
  880. {
  881. return;
  882. }
  883. SetSelectedStartSelectedLength ();
  884. int selStart = _start == -1 ? CursorPosition : _start;
  885. string cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  886. Text = StringExtensions.ToString (_text.GetRange (0, selStart))
  887. + cbTxt
  888. + StringExtensions.ToString (
  889. _text.GetRange (
  890. selStart + SelectedLength,
  891. _text.Count - (selStart + SelectedLength)
  892. )
  893. );
  894. _cursorPosition = Math.Min (selStart + cbTxt.GetRuneCount (), _text.Count);
  895. ClearAllSelection ();
  896. SetNeedsDraw ();
  897. Adjust ();
  898. }
  899. /// <summary>Sets the cursor position.</summary>
  900. public override Point? PositionCursor ()
  901. {
  902. ProcessAutocomplete ();
  903. var col = 0;
  904. for (int idx = ScrollOffset < 0 ? 0 : ScrollOffset; idx < _text.Count; idx++)
  905. {
  906. if (idx == _cursorPosition)
  907. {
  908. break;
  909. }
  910. int cols = _text [idx].GetColumns ();
  911. TextModel.SetCol (ref col, Viewport.Width - 1, cols);
  912. }
  913. int pos = _cursorPosition - ScrollOffset + Math.Min (Viewport.X, 0);
  914. Move (pos, 0);
  915. return new Point (pos, 0);
  916. }
  917. /// <summary>Redoes the latest changes.</summary>
  918. public void Redo ()
  919. {
  920. if (ReadOnly)
  921. {
  922. return;
  923. }
  924. _historyText.Redo ();
  925. }
  926. /// <summary>Selects all text.</summary>
  927. public void SelectAll ()
  928. {
  929. if (_text.Count == 0)
  930. {
  931. return;
  932. }
  933. _selectedStart = 0;
  934. MoveEndExtend ();
  935. SetNeedsDraw ();
  936. }
  937. ///// <summary>
  938. ///// Changed event, raised when the text has changed.
  939. ///// <remarks>
  940. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  941. ///// <see cref="string"/> containing the old value.
  942. ///// </remarks>
  943. ///// </summary>
  944. //public event EventHandler<StateEventArgs<string>> TextChanged;
  945. /// <summary>Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.</summary>
  946. public event EventHandler<CancelEventArgs<string>> TextChanging;
  947. /// <summary>Undoes the latest changes.</summary>
  948. public void Undo ()
  949. {
  950. if (ReadOnly)
  951. {
  952. return;
  953. }
  954. _historyText.Undo ();
  955. }
  956. /// <summary>
  957. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  958. /// includes when it is empty.
  959. /// </summary>
  960. /// <returns></returns>
  961. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  962. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  963. /// <returns></returns>
  964. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  965. private void Adjust ()
  966. {
  967. if (!IsAdded)
  968. {
  969. return;
  970. }
  971. // TODO: This is a lame prototype proving it should be easy for TextField to
  972. // TODO: support Width = Dim.Auto (DimAutoStyle: Content).
  973. //SetContentSize(new (TextModel.DisplaySize (_text).size, 1));
  974. int offB = OffSetBackground ();
  975. bool need = NeedsDraw || !Used;
  976. if (_cursorPosition < ScrollOffset)
  977. {
  978. ScrollOffset = _cursorPosition;
  979. need = true;
  980. }
  981. else if (Viewport.Width > 0
  982. && (ScrollOffset + _cursorPosition - (Viewport.Width + offB) == 0
  983. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Viewport.Width + offB))
  984. {
  985. ScrollOffset = Math.Max (
  986. TextModel.CalculateLeftColumn (
  987. _text,
  988. ScrollOffset,
  989. _cursorPosition,
  990. Viewport.Width + offB
  991. ),
  992. 0
  993. );
  994. need = true;
  995. }
  996. if (need)
  997. {
  998. SetNeedsDraw ();
  999. }
  1000. else
  1001. {
  1002. PositionCursor ();
  1003. }
  1004. }
  1005. private MenuBarItem BuildContextMenuBarItem ()
  1006. {
  1007. return new (
  1008. new MenuItem []
  1009. {
  1010. new (
  1011. Strings.ctxSelectAll,
  1012. "",
  1013. () => SelectAll (),
  1014. null,
  1015. null,
  1016. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  1017. ),
  1018. new (
  1019. Strings.ctxDeleteAll,
  1020. "",
  1021. () => DeleteAll (),
  1022. null,
  1023. null,
  1024. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  1025. ),
  1026. new (
  1027. Strings.ctxCopy,
  1028. "",
  1029. () => Copy (),
  1030. null,
  1031. null,
  1032. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  1033. ),
  1034. new (
  1035. Strings.ctxCut,
  1036. "",
  1037. () => Cut (),
  1038. null,
  1039. null,
  1040. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  1041. ),
  1042. new (
  1043. Strings.ctxPaste,
  1044. "",
  1045. () => Paste (),
  1046. null,
  1047. null,
  1048. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  1049. ),
  1050. new (
  1051. Strings.ctxUndo,
  1052. "",
  1053. () => Undo (),
  1054. null,
  1055. null,
  1056. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  1057. ),
  1058. new (
  1059. Strings.ctxRedo,
  1060. "",
  1061. () => Redo (),
  1062. null,
  1063. null,
  1064. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  1065. )
  1066. }
  1067. );
  1068. }
  1069. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e) { KeyBindings.ReplaceKey (e.OldKey.KeyCode, e.NewKey.KeyCode); }
  1070. private List<Rune> DeleteSelectedText ()
  1071. {
  1072. SetSelectedStartSelectedLength ();
  1073. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1074. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1075. + StringExtensions.ToString (
  1076. _text.GetRange (
  1077. selStart + SelectedLength,
  1078. _text.Count - (selStart + SelectedLength)
  1079. )
  1080. );
  1081. ClearAllSelection ();
  1082. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1083. return newText.ToRuneList ();
  1084. }
  1085. private void GenerateSuggestions ()
  1086. {
  1087. List<Cell> currentLine = Cell.ToCellList (Text);
  1088. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1089. Autocomplete.Context = new (
  1090. currentLine,
  1091. cursorPosition,
  1092. Autocomplete.Context != null
  1093. ? Autocomplete.Context.Canceled
  1094. : false
  1095. );
  1096. Autocomplete.GenerateSuggestions (
  1097. Autocomplete.Context
  1098. );
  1099. }
  1100. private TextModel GetModel ()
  1101. {
  1102. var model = new TextModel ();
  1103. model.LoadString (Text);
  1104. return model;
  1105. }
  1106. private Attribute GetReadOnlyColor ()
  1107. {
  1108. ColorScheme cs = ColorScheme;
  1109. if (ColorScheme is null)
  1110. {
  1111. cs = new ();
  1112. }
  1113. if (cs.Disabled.Foreground == cs.Focus.Background)
  1114. {
  1115. return new (cs.Focus.Foreground, cs.Focus.Background);
  1116. }
  1117. return new (cs.Disabled.Foreground, cs.Focus.Background);
  1118. }
  1119. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItemEventArgs obj)
  1120. {
  1121. if (obj is null)
  1122. {
  1123. return;
  1124. }
  1125. Text = Cell.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1126. CursorPosition = obj.CursorPosition.X;
  1127. Adjust ();
  1128. }
  1129. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1130. {
  1131. _historyText.Add (
  1132. new () { Cell.ToCells (_text) },
  1133. new (_cursorPosition, 0)
  1134. );
  1135. List<Rune> newText = _text;
  1136. if (SelectedLength > 0)
  1137. {
  1138. newText = DeleteSelectedText ();
  1139. _preTextChangedCursorPos = _cursorPosition;
  1140. }
  1141. if (!usePreTextChangedCursorPos)
  1142. {
  1143. _preTextChangedCursorPos = _cursorPosition;
  1144. }
  1145. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1146. if (Used)
  1147. {
  1148. _cursorPosition++;
  1149. if (_cursorPosition == newText.Count + 1)
  1150. {
  1151. SetText (newText.Concat (kbstr).ToList ());
  1152. }
  1153. else
  1154. {
  1155. if (_preTextChangedCursorPos > newText.Count)
  1156. {
  1157. _preTextChangedCursorPos = newText.Count;
  1158. }
  1159. SetText (
  1160. newText.GetRange (0, _preTextChangedCursorPos)
  1161. .Concat (kbstr)
  1162. .Concat (
  1163. newText.GetRange (
  1164. _preTextChangedCursorPos,
  1165. Math.Min (
  1166. newText.Count - _preTextChangedCursorPos,
  1167. newText.Count
  1168. )
  1169. )
  1170. )
  1171. );
  1172. }
  1173. }
  1174. else
  1175. {
  1176. SetText (
  1177. newText.GetRange (0, _preTextChangedCursorPos)
  1178. .Concat (kbstr)
  1179. .Concat (
  1180. newText.GetRange (
  1181. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1182. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1183. )
  1184. )
  1185. );
  1186. _cursorPosition++;
  1187. }
  1188. Adjust ();
  1189. }
  1190. private void KillToEnd ()
  1191. {
  1192. if (ReadOnly)
  1193. {
  1194. return;
  1195. }
  1196. ClearAllSelection ();
  1197. if (_cursorPosition >= _text.Count)
  1198. {
  1199. return;
  1200. }
  1201. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1202. SetText (_text.GetRange (0, _cursorPosition));
  1203. Adjust ();
  1204. }
  1205. private void KillToStart ()
  1206. {
  1207. if (ReadOnly)
  1208. {
  1209. return;
  1210. }
  1211. ClearAllSelection ();
  1212. if (_cursorPosition == 0)
  1213. {
  1214. return;
  1215. }
  1216. SetClipboard (_text.GetRange (0, _cursorPosition));
  1217. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1218. _cursorPosition = 0;
  1219. Adjust ();
  1220. }
  1221. private void MoveEndExtend ()
  1222. {
  1223. if (_cursorPosition <= _text.Count)
  1224. {
  1225. int x = _cursorPosition;
  1226. _cursorPosition = _text.Count;
  1227. PrepareSelection (x, _cursorPosition - x);
  1228. }
  1229. }
  1230. private void MoveHome ()
  1231. {
  1232. ClearAllSelection ();
  1233. _cursorPosition = 0;
  1234. Adjust ();
  1235. }
  1236. private void MoveHomeExtend ()
  1237. {
  1238. if (_cursorPosition > 0)
  1239. {
  1240. int x = _cursorPosition;
  1241. _cursorPosition = 0;
  1242. PrepareSelection (x, _cursorPosition - x);
  1243. }
  1244. }
  1245. /// <summary>
  1246. /// Moves the cursor +/- the given <paramref name="distance"/>, clearing
  1247. /// any selection and returning true if any meaningful changes were made.
  1248. /// </summary>
  1249. /// <param name="distance">Distance to move the cursor, will be clamped to
  1250. /// text length. Positive for right, Negative for left.</param>
  1251. /// <returns></returns>
  1252. private bool Move (int distance)
  1253. {
  1254. var oldCursorPosition = _cursorPosition;
  1255. var hadSelection = _selectedText != null && _selectedText.Length > 0;
  1256. _cursorPosition = Math.Min (_text.Count, Math.Max (0, _cursorPosition + distance));
  1257. ClearAllSelection ();
  1258. Adjust ();
  1259. return _cursorPosition != oldCursorPosition || hadSelection;
  1260. }
  1261. private bool MoveLeft ()
  1262. {
  1263. return Move (-1);
  1264. }
  1265. private void MoveLeftExtend ()
  1266. {
  1267. if (_cursorPosition > 0)
  1268. {
  1269. PrepareSelection (_cursorPosition--, -1);
  1270. }
  1271. }
  1272. private bool MoveRight ()
  1273. {
  1274. return Move (1);
  1275. }
  1276. private void MoveRightExtend ()
  1277. {
  1278. if (_cursorPosition < _text.Count)
  1279. {
  1280. PrepareSelection (_cursorPosition++, 1);
  1281. }
  1282. }
  1283. private void MoveWordLeft ()
  1284. {
  1285. ClearAllSelection ();
  1286. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  1287. if (newPos is null)
  1288. {
  1289. return;
  1290. }
  1291. if (newPos.Value.col != -1)
  1292. {
  1293. _cursorPosition = newPos.Value.col;
  1294. }
  1295. Adjust ();
  1296. }
  1297. private void MoveWordLeftExtend ()
  1298. {
  1299. if (_cursorPosition > 0)
  1300. {
  1301. int x = Math.Min (
  1302. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1303. _text.Count
  1304. );
  1305. if (x > 0)
  1306. {
  1307. (int col, int row)? newPos = GetModel ().WordBackward (x, 0);
  1308. if (newPos is null)
  1309. {
  1310. return;
  1311. }
  1312. if (newPos.Value.col != -1)
  1313. {
  1314. _cursorPosition = newPos.Value.col;
  1315. }
  1316. PrepareSelection (x, newPos.Value.col - x);
  1317. }
  1318. }
  1319. }
  1320. private void MoveWordRight ()
  1321. {
  1322. ClearAllSelection ();
  1323. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  1324. if (newPos is null)
  1325. {
  1326. return;
  1327. }
  1328. if (newPos.Value.col != -1)
  1329. {
  1330. _cursorPosition = newPos.Value.col;
  1331. }
  1332. Adjust ();
  1333. }
  1334. private void MoveWordRightExtend ()
  1335. {
  1336. if (_cursorPosition < _text.Count)
  1337. {
  1338. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1339. (int col, int row)? newPos = GetModel ().WordForward (x, 0);
  1340. if (newPos is null)
  1341. {
  1342. return;
  1343. }
  1344. if (newPos.Value.col != -1)
  1345. {
  1346. _cursorPosition = newPos.Value.col;
  1347. }
  1348. PrepareSelection (x, newPos.Value.col - x);
  1349. }
  1350. }
  1351. // BUGBUG: This assumes Frame == Viewport. It's also not clear what the intention is. For now, changed to always return 0.
  1352. private int OffSetBackground ()
  1353. {
  1354. var offB = 0;
  1355. if (SuperView?.Frame.Right - Frame.Right < 0)
  1356. {
  1357. offB = SuperView.Frame.Right - Frame.Right - 1;
  1358. }
  1359. return 0; //offB;
  1360. }
  1361. private int PositionCursor (MouseEventArgs ev) { return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.Position.X), false); }
  1362. private int PositionCursor (int x, bool getX = true)
  1363. {
  1364. int pX = x;
  1365. if (getX)
  1366. {
  1367. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1368. }
  1369. if (ScrollOffset + pX > _text.Count)
  1370. {
  1371. _cursorPosition = _text.Count;
  1372. }
  1373. else if (ScrollOffset + pX < ScrollOffset)
  1374. {
  1375. _cursorPosition = 0;
  1376. }
  1377. else
  1378. {
  1379. _cursorPosition = ScrollOffset + pX;
  1380. }
  1381. return _cursorPosition;
  1382. }
  1383. private void PrepareSelection (int x, int direction = 0)
  1384. {
  1385. x = x + ScrollOffset < -1 ? 0 : x;
  1386. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1387. ? x
  1388. : _selectedStart;
  1389. if (_selectedStart > -1)
  1390. {
  1391. SelectedLength = Math.Abs (
  1392. x + direction <= _text.Count
  1393. ? x + direction - _selectedStart
  1394. : _text.Count - _selectedStart
  1395. );
  1396. SetSelectedStartSelectedLength ();
  1397. if (_start > -1 && SelectedLength > 0)
  1398. {
  1399. _selectedText = SelectedLength > 0
  1400. ? StringExtensions.ToString (
  1401. _text.GetRange (
  1402. _start < 0 ? 0 : _start,
  1403. SelectedLength > _text.Count
  1404. ? _text.Count
  1405. : SelectedLength
  1406. )
  1407. )
  1408. : "";
  1409. if (ScrollOffset > _start)
  1410. {
  1411. ScrollOffset = _start;
  1412. }
  1413. }
  1414. else if (_start > -1 && SelectedLength == 0)
  1415. {
  1416. _selectedText = null;
  1417. }
  1418. SetNeedsDraw ();
  1419. }
  1420. else if (SelectedLength > 0 || _selectedText is { })
  1421. {
  1422. ClearAllSelection ();
  1423. }
  1424. Adjust ();
  1425. }
  1426. private void ProcessAutocomplete ()
  1427. {
  1428. if (_isDrawing)
  1429. {
  1430. return;
  1431. }
  1432. if (SelectedLength > 0)
  1433. {
  1434. return;
  1435. }
  1436. GenerateSuggestions ();
  1437. }
  1438. private void DrawAutocomplete ()
  1439. {
  1440. if (SelectedLength > 0)
  1441. {
  1442. return;
  1443. }
  1444. if (Autocomplete?.Context == null)
  1445. {
  1446. return;
  1447. }
  1448. var renderAt = new Point (
  1449. Autocomplete.Context.CursorPosition,
  1450. 0
  1451. );
  1452. Autocomplete.RenderOverlay (renderAt);
  1453. }
  1454. private void RenderCaption ()
  1455. {
  1456. if (HasFocus
  1457. || Caption == null
  1458. || Caption.Length == 0
  1459. || Text?.Length > 0)
  1460. {
  1461. return;
  1462. }
  1463. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  1464. SetAttribute (color);
  1465. Move (0, 0);
  1466. string render = Caption;
  1467. if (render.GetColumns () > Viewport.Width)
  1468. {
  1469. render = render [..Viewport.Width];
  1470. }
  1471. Driver?.AddStr (render);
  1472. }
  1473. private void SetClipboard (IEnumerable<Rune> text)
  1474. {
  1475. if (!Secret)
  1476. {
  1477. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1478. }
  1479. }
  1480. private void SetOverwrite (bool overwrite)
  1481. {
  1482. Used = overwrite;
  1483. SetNeedsDraw ();
  1484. }
  1485. private void SetSelectedStartSelectedLength ()
  1486. {
  1487. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1488. {
  1489. _start = _cursorPosition;
  1490. }
  1491. else
  1492. {
  1493. _start = SelectedStart;
  1494. }
  1495. }
  1496. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1497. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1498. private void ShowContextMenu ()
  1499. {
  1500. if (!Equals (_currentCulture, Thread.CurrentThread.CurrentUICulture))
  1501. {
  1502. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1503. }
  1504. ContextMenu.Show (BuildContextMenuBarItem ());
  1505. }
  1506. private void TextField_Added (object sender, SuperViewChangedEventArgs e)
  1507. {
  1508. if (Autocomplete.HostControl is null)
  1509. {
  1510. Autocomplete.HostControl = this;
  1511. Autocomplete.PopupInsideContainer = false;
  1512. }
  1513. }
  1514. private void TextField_Removed (object sender, SuperViewChangedEventArgs e) { Autocomplete.HostControl = null; }
  1515. private void TextField_Initialized (object sender, EventArgs e)
  1516. {
  1517. _cursorPosition = Text.GetRuneCount ();
  1518. if (Viewport.Width > 0)
  1519. {
  1520. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1521. }
  1522. if (Autocomplete.HostControl is null)
  1523. {
  1524. Autocomplete.HostControl = this;
  1525. Autocomplete.PopupInsideContainer = false;
  1526. }
  1527. }
  1528. }
  1529. /// <summary>
  1530. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1531. /// options. An implementation on a TextField.
  1532. /// </summary>
  1533. public class TextFieldAutocomplete : PopupAutocomplete
  1534. {
  1535. /// <inheritdoc/>
  1536. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1537. /// <inheritdoc/>
  1538. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1539. /// <inheritdoc/>
  1540. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1541. }