TextField.cs 56 KB

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