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