TextField.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874
  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. // Things this view knows how to do
  40. AddCommand (
  41. Command.DeleteCharRight,
  42. () =>
  43. {
  44. DeleteCharRight ();
  45. return true;
  46. }
  47. );
  48. AddCommand (
  49. Command.DeleteCharLeft,
  50. () =>
  51. {
  52. DeleteCharLeft (false);
  53. return true;
  54. }
  55. );
  56. AddCommand (
  57. Command.LeftHomeExtend,
  58. () =>
  59. {
  60. MoveHomeExtend ();
  61. return true;
  62. }
  63. );
  64. AddCommand (
  65. Command.RightEndExtend,
  66. () =>
  67. {
  68. MoveEndExtend ();
  69. return true;
  70. }
  71. );
  72. AddCommand (
  73. Command.LeftHome,
  74. () =>
  75. {
  76. MoveHome ();
  77. return true;
  78. }
  79. );
  80. AddCommand (
  81. Command.LeftExtend,
  82. () =>
  83. {
  84. MoveLeftExtend ();
  85. return true;
  86. }
  87. );
  88. AddCommand (
  89. Command.RightExtend,
  90. () =>
  91. {
  92. MoveRightExtend ();
  93. return true;
  94. }
  95. );
  96. AddCommand (
  97. Command.WordLeftExtend,
  98. () =>
  99. {
  100. MoveWordLeftExtend ();
  101. return true;
  102. }
  103. );
  104. AddCommand (
  105. Command.WordRightExtend,
  106. () =>
  107. {
  108. MoveWordRightExtend ();
  109. return true;
  110. }
  111. );
  112. AddCommand (Command.Left, () => MoveLeft ());
  113. AddCommand (
  114. Command.RightEnd,
  115. () =>
  116. {
  117. MoveEnd ();
  118. return true;
  119. }
  120. );
  121. AddCommand (Command.Right, () => MoveRight ());
  122. AddCommand (
  123. Command.CutToEndLine,
  124. () =>
  125. {
  126. KillToEnd ();
  127. return true;
  128. }
  129. );
  130. AddCommand (
  131. Command.CutToStartLine,
  132. () =>
  133. {
  134. KillToStart ();
  135. return true;
  136. }
  137. );
  138. AddCommand (
  139. Command.Undo,
  140. () =>
  141. {
  142. Undo ();
  143. return true;
  144. }
  145. );
  146. AddCommand (
  147. Command.Redo,
  148. () =>
  149. {
  150. Redo ();
  151. return true;
  152. }
  153. );
  154. AddCommand (
  155. Command.WordLeft,
  156. () =>
  157. {
  158. MoveWordLeft ();
  159. return true;
  160. }
  161. );
  162. AddCommand (
  163. Command.WordRight,
  164. () =>
  165. {
  166. MoveWordRight ();
  167. return true;
  168. }
  169. );
  170. AddCommand (
  171. Command.KillWordForwards,
  172. () =>
  173. {
  174. KillWordForwards ();
  175. return true;
  176. }
  177. );
  178. AddCommand (
  179. Command.KillWordBackwards,
  180. () =>
  181. {
  182. KillWordBackwards ();
  183. return true;
  184. }
  185. );
  186. AddCommand (
  187. Command.ToggleOverwrite,
  188. () =>
  189. {
  190. SetOverwrite (!Used);
  191. return true;
  192. }
  193. );
  194. AddCommand (
  195. Command.EnableOverwrite,
  196. () =>
  197. {
  198. SetOverwrite (true);
  199. return true;
  200. }
  201. );
  202. AddCommand (
  203. Command.DisableOverwrite,
  204. () =>
  205. {
  206. SetOverwrite (false);
  207. return true;
  208. }
  209. );
  210. AddCommand (
  211. Command.Copy,
  212. () =>
  213. {
  214. Copy ();
  215. return true;
  216. }
  217. );
  218. AddCommand (
  219. Command.Cut,
  220. () =>
  221. {
  222. Cut ();
  223. return true;
  224. }
  225. );
  226. AddCommand (
  227. Command.Paste,
  228. () =>
  229. {
  230. Paste ();
  231. return true;
  232. }
  233. );
  234. AddCommand (
  235. Command.SelectAll,
  236. () =>
  237. {
  238. SelectAll ();
  239. return true;
  240. }
  241. );
  242. AddCommand (
  243. Command.DeleteAll,
  244. () =>
  245. {
  246. DeleteAll ();
  247. return true;
  248. }
  249. );
  250. AddCommand (
  251. Command.ShowContextMenu,
  252. () =>
  253. {
  254. ShowContextMenu ();
  255. return true;
  256. }
  257. );
  258. // By Default pressing ENTER should be ignored (OnAccept will return false or null). Only cancel if the
  259. // event was fired and set Cancel = true.
  260. AddCommand (Command.Accept, () => OnAccept () == false);
  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.LeftHomeExtend);
  267. KeyBindings.Add (Key.Home.WithShift.WithCtrl, Command.LeftHomeExtend);
  268. KeyBindings.Add (Key.A.WithShift.WithCtrl, Command.LeftHomeExtend);
  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.LeftHome);
  273. KeyBindings.Add (Key.Home.WithCtrl, Command.LeftHome);
  274. KeyBindings.Add (Key.A.WithCtrl, Command.LeftHome);
  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 ContextMenu { Host = this, MenuItems = BuildContextMenuBarItem () };
  317. ContextMenu.KeyChanged += ContextMenu_KeyChanged;
  318. KeyBindings.Add (ContextMenu.Key, KeyBindingScope.HotKey, Command.ShowContextMenu);
  319. KeyBindings.Add (Key.Enter, Command.Accept);
  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 (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 List<List<RuneCell>> { TextModel.ToRuneCellList (oldText) },
  433. new Point (_cursorPosition, 0)
  434. );
  435. _historyText.Add (
  436. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  437. new Point (_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.HistoryTextItem"/> items updating the original text.</summary>
  471. public void ClearHistoryChanges () { _historyText.Clear (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 List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  518. new Point (_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 List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  565. new Point (_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 ()
  588. {
  589. ColorScheme cs = ColorScheme;
  590. if (ColorScheme is null)
  591. {
  592. cs = new ColorScheme ();
  593. }
  594. return Enabled ? cs.Focus : cs.Disabled;
  595. }
  596. /// <summary>
  597. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position exactly as if the user had just
  598. /// typed it
  599. /// </summary>
  600. /// <param name="toAdd">Text to add</param>
  601. /// <param name="useOldCursorPos">Use the previous cursor position.</param>
  602. public void InsertText (string toAdd, bool useOldCursorPos = true)
  603. {
  604. foreach (char ch in toAdd)
  605. {
  606. Key key;
  607. try
  608. {
  609. key = ch;
  610. }
  611. catch (Exception)
  612. {
  613. throw new ArgumentException (
  614. $"Cannot insert character '{ch}' because it does not map to a Key"
  615. );
  616. }
  617. InsertText (key, useOldCursorPos);
  618. }
  619. }
  620. /// <summary>Deletes word backwards.</summary>
  621. public virtual void KillWordBackwards ()
  622. {
  623. ClearAllSelection ();
  624. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  625. if (newPos is null)
  626. {
  627. return;
  628. }
  629. if (newPos.Value.col != -1)
  630. {
  631. SetText (
  632. _text.GetRange (0, newPos.Value.col)
  633. .Concat (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition))
  634. );
  635. _cursorPosition = newPos.Value.col;
  636. }
  637. Adjust ();
  638. }
  639. /// <summary>Deletes word forwards.</summary>
  640. public virtual void KillWordForwards ()
  641. {
  642. ClearAllSelection ();
  643. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  644. if (newPos is null)
  645. {
  646. return;
  647. }
  648. if (newPos.Value.col != -1)
  649. {
  650. SetText (
  651. _text.GetRange (0, _cursorPosition)
  652. .Concat (_text.GetRange (newPos.Value.col, _text.Count - newPos.Value.col))
  653. );
  654. }
  655. Adjust ();
  656. }
  657. /// <inheritdoc/>
  658. protected internal override bool OnMouseEvent (MouseEvent ev)
  659. {
  660. if (!ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  661. && !ev.Flags.HasFlag (MouseFlags.ReportMousePosition)
  662. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  663. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  664. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)
  665. && !ev.Flags.HasFlag (ContextMenu.MouseFlags))
  666. {
  667. return base.OnMouseEvent (ev);
  668. }
  669. if (!CanFocus)
  670. {
  671. return true;
  672. }
  673. if (!HasFocus && ev.Flags != MouseFlags.ReportMousePosition)
  674. {
  675. SetFocus ();
  676. }
  677. // Give autocomplete first opportunity to respond to mouse clicks
  678. if (SelectedLength == 0 && Autocomplete.OnMouseEvent (ev, true))
  679. {
  680. return true;
  681. }
  682. if (ev.Flags == MouseFlags.Button1Pressed)
  683. {
  684. EnsureHasFocus ();
  685. PositionCursor (ev);
  686. if (_isButtonReleased)
  687. {
  688. ClearAllSelection ();
  689. }
  690. _isButtonReleased = true;
  691. _isButtonPressed = true;
  692. }
  693. else if (ev.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _isButtonPressed)
  694. {
  695. int x = PositionCursor (ev);
  696. _isButtonReleased = false;
  697. PrepareSelection (x);
  698. if (Application.MouseGrabView is null)
  699. {
  700. Application.GrabMouse (this);
  701. }
  702. }
  703. else if (ev.Flags == MouseFlags.Button1Released)
  704. {
  705. _isButtonReleased = true;
  706. _isButtonPressed = false;
  707. Application.UngrabMouse ();
  708. }
  709. else if (ev.Flags == MouseFlags.Button1DoubleClicked)
  710. {
  711. EnsureHasFocus ();
  712. int x = PositionCursor (ev);
  713. int sbw = x;
  714. if (x == _text.Count
  715. || (x > 0 && (char)_text [x - 1].Value != ' ')
  716. || (x > 0 && (char)_text [x].Value == ' '))
  717. {
  718. (int col, int row)? newPosBw = GetModel ().WordBackward (x, 0);
  719. if (newPosBw is null)
  720. {
  721. return true;
  722. }
  723. sbw = newPosBw.Value.col;
  724. }
  725. if (sbw != -1)
  726. {
  727. x = sbw;
  728. PositionCursor (x);
  729. }
  730. (int col, int row)? newPosFw = GetModel ().WordForward (x, 0);
  731. if (newPosFw is null)
  732. {
  733. return true;
  734. }
  735. ClearAllSelection ();
  736. if (newPosFw.Value.col != -1 && sbw != -1)
  737. {
  738. _cursorPosition = newPosFw.Value.col;
  739. }
  740. PrepareSelection (sbw, newPosFw.Value.col - sbw);
  741. }
  742. else if (ev.Flags == MouseFlags.Button1TripleClicked)
  743. {
  744. EnsureHasFocus ();
  745. PositionCursor (0);
  746. ClearAllSelection ();
  747. PrepareSelection (0, _text.Count);
  748. }
  749. else if (ev.Flags == ContextMenu.MouseFlags)
  750. {
  751. ShowContextMenu ();
  752. }
  753. //SetNeedsDisplay ();
  754. return true;
  755. void EnsureHasFocus ()
  756. {
  757. if (!HasFocus)
  758. {
  759. SetFocus ();
  760. }
  761. }
  762. }
  763. /// <summary>Moves cursor to the end of the typed text.</summary>
  764. public void MoveEnd ()
  765. {
  766. ClearAllSelection ();
  767. _cursorPosition = _text.Count;
  768. Adjust ();
  769. }
  770. /// <inheritdoc/>
  771. public override void OnDrawContent (Rectangle viewport)
  772. {
  773. _isDrawing = true;
  774. var selColor = new Attribute (GetFocusColor ().Background, GetFocusColor ().Foreground);
  775. SetSelectedStartSelectedLength ();
  776. Driver?.SetAttribute (GetNormalColor ());
  777. Move (0, 0);
  778. int p = ScrollOffset;
  779. var col = 0;
  780. int width = Frame.Width + OffSetBackground ();
  781. int tcount = _text.Count;
  782. Attribute roc = GetReadOnlyColor ();
  783. for (int idx = p; idx < tcount; idx++)
  784. {
  785. Rune rune = _text [idx];
  786. int cols = rune.GetColumns ();
  787. if (idx == _cursorPosition && HasFocus && !Used && SelectedLength == 0 && !ReadOnly)
  788. {
  789. Driver?.SetAttribute (selColor);
  790. }
  791. else if (ReadOnly)
  792. {
  793. Driver?.SetAttribute (
  794. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  795. ? selColor
  796. : roc
  797. );
  798. }
  799. else if (!HasFocus && Enabled)
  800. {
  801. Driver?.SetAttribute (GetFocusColor ());
  802. }
  803. else if (!Enabled)
  804. {
  805. Driver?.SetAttribute (roc);
  806. }
  807. else
  808. {
  809. Driver?.SetAttribute (
  810. idx >= _start && SelectedLength > 0 && idx < _start + SelectedLength
  811. ? selColor
  812. : ColorScheme.Focus
  813. );
  814. }
  815. if (col + cols <= width)
  816. {
  817. Driver?.AddRune (Secret ? Glyphs.Dot : rune);
  818. }
  819. if (!TextModel.SetCol (ref col, width, cols))
  820. {
  821. break;
  822. }
  823. if (idx + 1 < tcount && col + _text [idx + 1].GetColumns () > width)
  824. {
  825. break;
  826. }
  827. }
  828. Driver.SetAttribute (GetFocusColor ());
  829. for (int i = col; i < width; i++)
  830. {
  831. Driver.AddRune ((Rune)' ');
  832. }
  833. PositionCursor ();
  834. RenderCaption ();
  835. ProcessAutocomplete ();
  836. _isDrawing = false;
  837. }
  838. /// <inheritdoc/>
  839. public override bool? OnInvokingKeyBindings (Key a, KeyBindingScope scope)
  840. {
  841. // Give autocomplete first opportunity to respond to key presses
  842. if (SelectedLength == 0 && Autocomplete.Suggestions.Count > 0 && Autocomplete.ProcessKey (a))
  843. {
  844. return true;
  845. }
  846. return base.OnInvokingKeyBindings (a, scope);
  847. }
  848. /// <inheritdoc/>
  849. public override bool OnLeave (View view)
  850. {
  851. if (Application.MouseGrabView is { } && Application.MouseGrabView == this)
  852. {
  853. Application.UngrabMouse ();
  854. }
  855. //if (SelectedLength != 0 && !(Application.MouseGrabView is MenuBar))
  856. // ClearAllSelection ();
  857. return base.OnLeave (view);
  858. }
  859. /// TODO: Flush out these docs
  860. /// <summary>
  861. /// Processes key presses for the <see cref="TextField"/>.
  862. /// <remarks>
  863. /// The <see cref="TextField"/> control responds to the following keys:
  864. /// <list type="table">
  865. /// <listheader>
  866. /// <term>Keys</term> <description>Function</description>
  867. /// </listheader>
  868. /// <item>
  869. /// <term><see cref="Key.Delete"/>, <see cref="Key.Backspace"/></term>
  870. /// <description>Deletes the character before cursor.</description>
  871. /// </item>
  872. /// </list>
  873. /// </remarks>
  874. /// </summary>
  875. /// <param name="a"></param>
  876. /// <returns></returns>
  877. public override bool OnProcessKeyDown (Key a)
  878. {
  879. // Remember the cursor position because the new calculated cursor position is needed
  880. // to be set BEFORE the TextChanged event is triggered.
  881. // Needed for the Elmish Wrapper issue https://github.com/DieselMeister/Terminal.Gui.Elmish/issues/2
  882. _preTextChangedCursorPos = _cursorPosition;
  883. // Ignore other control characters.
  884. if (!a.IsKeyCodeAtoZ && (a.KeyCode < KeyCode.Space || a.KeyCode > KeyCode.CharMask))
  885. {
  886. return false;
  887. }
  888. if (ReadOnly)
  889. {
  890. return true;
  891. }
  892. InsertText (a, true);
  893. return true;
  894. }
  895. /// <summary>Virtual method that invoke the <see cref="TextChanging"/> event if it's defined.</summary>
  896. /// <param name="args">The event arguments.</param>
  897. /// <returns><see langword="true"/> if the event was cancelled.</returns>
  898. public bool OnTextChanging (CancelEventArgs<string> args)
  899. {
  900. TextChanging?.Invoke (this, args);
  901. return args.Cancel;
  902. }
  903. /// <summary>Paste the selected text from the clipboard.</summary>
  904. public virtual void Paste ()
  905. {
  906. if (ReadOnly || string.IsNullOrEmpty (Clipboard.Contents))
  907. {
  908. return;
  909. }
  910. SetSelectedStartSelectedLength ();
  911. int selStart = _start == -1 ? CursorPosition : _start;
  912. string cbTxt = Clipboard.Contents.Split ("\n") [0] ?? "";
  913. Text = StringExtensions.ToString (_text.GetRange (0, selStart))
  914. + cbTxt
  915. + StringExtensions.ToString (
  916. _text.GetRange (
  917. selStart + SelectedLength,
  918. _text.Count - (selStart + SelectedLength)
  919. )
  920. );
  921. _cursorPosition = Math.Min (selStart + cbTxt.GetRuneCount (), _text.Count);
  922. ClearAllSelection ();
  923. SetNeedsDisplay ();
  924. Adjust ();
  925. }
  926. /// <summary>Sets the cursor position.</summary>
  927. public override Point? PositionCursor ()
  928. {
  929. ProcessAutocomplete ();
  930. var col = 0;
  931. for (int idx = ScrollOffset < 0 ? 0 : ScrollOffset; idx < _text.Count; idx++)
  932. {
  933. if (idx == _cursorPosition)
  934. {
  935. break;
  936. }
  937. int cols = _text [idx].GetColumns ();
  938. TextModel.SetCol (ref col, Frame.Width - 1, cols);
  939. }
  940. int pos = _cursorPosition - ScrollOffset + Math.Min (Frame.X, 0);
  941. Move (pos, 0);
  942. return new Point (pos, 0);
  943. }
  944. /// <summary>Redoes the latest changes.</summary>
  945. public void Redo ()
  946. {
  947. if (ReadOnly)
  948. {
  949. return;
  950. }
  951. _historyText.Redo ();
  952. }
  953. /// <summary>Selects all text.</summary>
  954. public void SelectAll ()
  955. {
  956. if (_text.Count == 0)
  957. {
  958. return;
  959. }
  960. _selectedStart = 0;
  961. MoveEndExtend ();
  962. SetNeedsDisplay ();
  963. }
  964. ///// <summary>
  965. ///// Changed event, raised when the text has changed.
  966. ///// <remarks>
  967. ///// This event is raised when the <see cref="Text"/> changes. The passed <see cref="EventArgs"/> is a
  968. ///// <see cref="string"/> containing the old value.
  969. ///// </remarks>
  970. ///// </summary>
  971. //public event EventHandler<StateEventArgs<string>> TextChanged;
  972. /// <summary>Changing event, raised before the <see cref="Text"/> changes and can be canceled or changing the new text.</summary>
  973. public event EventHandler<CancelEventArgs<string>> TextChanging;
  974. /// <summary>Undoes the latest changes.</summary>
  975. public void Undo ()
  976. {
  977. if (ReadOnly)
  978. {
  979. return;
  980. }
  981. _historyText.Undo ();
  982. }
  983. /// <summary>
  984. /// Returns <see langword="true"/> if the current cursor position is at the end of the <see cref="Text"/>. This
  985. /// includes when it is empty.
  986. /// </summary>
  987. /// <returns></returns>
  988. internal bool CursorIsAtEnd () { return CursorPosition == Text.Length; }
  989. /// <summary>Returns <see langword="true"/> if the current cursor position is at the start of the <see cref="TextField"/>.</summary>
  990. /// <returns></returns>
  991. internal bool CursorIsAtStart () { return CursorPosition <= 0; }
  992. private void Adjust ()
  993. {
  994. if (!IsAdded)
  995. {
  996. return;
  997. }
  998. // TODO: This is a lame prototype proving it should be easy for TextField to
  999. // TODO: support Width = Dim.Auto (DimAutoStyle: Content).
  1000. //SetContentSize(new (TextModel.DisplaySize (_text).size, 1));
  1001. int offB = OffSetBackground ();
  1002. bool need = NeedsDisplay || !Used;
  1003. if (_cursorPosition < ScrollOffset)
  1004. {
  1005. ScrollOffset = _cursorPosition;
  1006. need = true;
  1007. }
  1008. else if (Frame.Width > 0
  1009. && (ScrollOffset + _cursorPosition - (Frame.Width + offB) == 0
  1010. || TextModel.DisplaySize (_text, ScrollOffset, _cursorPosition).size >= Frame.Width + offB))
  1011. {
  1012. ScrollOffset = Math.Max (
  1013. TextModel.CalculateLeftColumn (
  1014. _text,
  1015. ScrollOffset,
  1016. _cursorPosition,
  1017. Frame.Width + offB
  1018. ),
  1019. 0
  1020. );
  1021. need = true;
  1022. }
  1023. if (need)
  1024. {
  1025. SetNeedsDisplay ();
  1026. }
  1027. else
  1028. {
  1029. PositionCursor ();
  1030. }
  1031. }
  1032. private MenuBarItem BuildContextMenuBarItem ()
  1033. {
  1034. return new MenuBarItem (
  1035. new MenuItem []
  1036. {
  1037. new (
  1038. Strings.ctxSelectAll,
  1039. "",
  1040. () => SelectAll (),
  1041. null,
  1042. null,
  1043. (KeyCode)KeyBindings.GetKeyFromCommands (Command.SelectAll)
  1044. ),
  1045. new (
  1046. Strings.ctxDeleteAll,
  1047. "",
  1048. () => DeleteAll (),
  1049. null,
  1050. null,
  1051. (KeyCode)KeyBindings.GetKeyFromCommands (Command.DeleteAll)
  1052. ),
  1053. new (
  1054. Strings.ctxCopy,
  1055. "",
  1056. () => Copy (),
  1057. null,
  1058. null,
  1059. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Copy)
  1060. ),
  1061. new (
  1062. Strings.ctxCut,
  1063. "",
  1064. () => Cut (),
  1065. null,
  1066. null,
  1067. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Cut)
  1068. ),
  1069. new (
  1070. Strings.ctxPaste,
  1071. "",
  1072. () => Paste (),
  1073. null,
  1074. null,
  1075. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Paste)
  1076. ),
  1077. new (
  1078. Strings.ctxUndo,
  1079. "",
  1080. () => Undo (),
  1081. null,
  1082. null,
  1083. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Undo)
  1084. ),
  1085. new (
  1086. Strings.ctxRedo,
  1087. "",
  1088. () => Redo (),
  1089. null,
  1090. null,
  1091. (KeyCode)KeyBindings.GetKeyFromCommands (Command.Redo)
  1092. )
  1093. }
  1094. );
  1095. }
  1096. private void ContextMenu_KeyChanged (object sender, KeyChangedEventArgs e)
  1097. {
  1098. KeyBindings.ReplaceKey (e.OldKey.KeyCode, e.NewKey.KeyCode);
  1099. }
  1100. private List<Rune> DeleteSelectedText ()
  1101. {
  1102. SetSelectedStartSelectedLength ();
  1103. int selStart = SelectedStart > -1 ? _start : _cursorPosition;
  1104. string newText = StringExtensions.ToString (_text.GetRange (0, selStart))
  1105. + StringExtensions.ToString (
  1106. _text.GetRange (
  1107. selStart + SelectedLength,
  1108. _text.Count - (selStart + SelectedLength)
  1109. )
  1110. );
  1111. ClearAllSelection ();
  1112. _cursorPosition = selStart >= newText.GetRuneCount () ? newText.GetRuneCount () : selStart;
  1113. return newText.ToRuneList ();
  1114. }
  1115. private void GenerateSuggestions ()
  1116. {
  1117. List<RuneCell> currentLine = TextModel.ToRuneCellList (Text);
  1118. int cursorPosition = Math.Min (CursorPosition, currentLine.Count);
  1119. Autocomplete.Context = new AutocompleteContext (
  1120. currentLine,
  1121. cursorPosition,
  1122. Autocomplete.Context != null
  1123. ? Autocomplete.Context.Canceled
  1124. : false
  1125. );
  1126. Autocomplete.GenerateSuggestions (
  1127. Autocomplete.Context
  1128. );
  1129. }
  1130. private TextModel GetModel ()
  1131. {
  1132. var model = new TextModel ();
  1133. model.LoadString (Text);
  1134. return model;
  1135. }
  1136. private Attribute GetReadOnlyColor ()
  1137. {
  1138. ColorScheme cs = ColorScheme;
  1139. if (ColorScheme is null)
  1140. {
  1141. cs = new ColorScheme ();
  1142. }
  1143. if (cs.Disabled.Foreground == cs.Focus.Background)
  1144. {
  1145. return new Attribute (cs.Focus.Foreground, cs.Focus.Background);
  1146. }
  1147. return new Attribute (cs.Disabled.Foreground, cs.Focus.Background);
  1148. }
  1149. private void HistoryText_ChangeText (object sender, HistoryText.HistoryTextItem obj)
  1150. {
  1151. if (obj is null)
  1152. {
  1153. return;
  1154. }
  1155. Text = TextModel.ToString (obj?.Lines [obj.CursorPosition.Y]);
  1156. CursorPosition = obj.CursorPosition.X;
  1157. Adjust ();
  1158. }
  1159. private void InsertText (Key a, bool usePreTextChangedCursorPos)
  1160. {
  1161. _historyText.Add (
  1162. new List<List<RuneCell>> { TextModel.ToRuneCells (_text) },
  1163. new Point (_cursorPosition, 0)
  1164. );
  1165. List<Rune> newText = _text;
  1166. if (SelectedLength > 0)
  1167. {
  1168. newText = DeleteSelectedText ();
  1169. _preTextChangedCursorPos = _cursorPosition;
  1170. }
  1171. if (!usePreTextChangedCursorPos)
  1172. {
  1173. _preTextChangedCursorPos = _cursorPosition;
  1174. }
  1175. StringRuneEnumerator kbstr = a.AsRune.ToString ().EnumerateRunes ();
  1176. if (Used)
  1177. {
  1178. _cursorPosition++;
  1179. if (_cursorPosition == newText.Count + 1)
  1180. {
  1181. SetText (newText.Concat (kbstr).ToList ());
  1182. }
  1183. else
  1184. {
  1185. if (_preTextChangedCursorPos > newText.Count)
  1186. {
  1187. _preTextChangedCursorPos = newText.Count;
  1188. }
  1189. SetText (
  1190. newText.GetRange (0, _preTextChangedCursorPos)
  1191. .Concat (kbstr)
  1192. .Concat (
  1193. newText.GetRange (
  1194. _preTextChangedCursorPos,
  1195. Math.Min (
  1196. newText.Count - _preTextChangedCursorPos,
  1197. newText.Count
  1198. )
  1199. )
  1200. )
  1201. );
  1202. }
  1203. }
  1204. else
  1205. {
  1206. SetText (
  1207. newText.GetRange (0, _preTextChangedCursorPos)
  1208. .Concat (kbstr)
  1209. .Concat (
  1210. newText.GetRange (
  1211. Math.Min (_preTextChangedCursorPos + 1, newText.Count),
  1212. Math.Max (newText.Count - _preTextChangedCursorPos - 1, 0)
  1213. )
  1214. )
  1215. );
  1216. _cursorPosition++;
  1217. }
  1218. Adjust ();
  1219. }
  1220. private void KillToEnd ()
  1221. {
  1222. if (ReadOnly)
  1223. {
  1224. return;
  1225. }
  1226. ClearAllSelection ();
  1227. if (_cursorPosition >= _text.Count)
  1228. {
  1229. return;
  1230. }
  1231. SetClipboard (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1232. SetText (_text.GetRange (0, _cursorPosition));
  1233. Adjust ();
  1234. }
  1235. private void KillToStart ()
  1236. {
  1237. if (ReadOnly)
  1238. {
  1239. return;
  1240. }
  1241. ClearAllSelection ();
  1242. if (_cursorPosition == 0)
  1243. {
  1244. return;
  1245. }
  1246. SetClipboard (_text.GetRange (0, _cursorPosition));
  1247. SetText (_text.GetRange (_cursorPosition, _text.Count - _cursorPosition));
  1248. _cursorPosition = 0;
  1249. Adjust ();
  1250. }
  1251. private void MoveEndExtend ()
  1252. {
  1253. if (_cursorPosition <= _text.Count)
  1254. {
  1255. int x = _cursorPosition;
  1256. _cursorPosition = _text.Count;
  1257. PrepareSelection (x, _cursorPosition - x);
  1258. }
  1259. }
  1260. private void MoveHome ()
  1261. {
  1262. ClearAllSelection ();
  1263. _cursorPosition = 0;
  1264. Adjust ();
  1265. }
  1266. private void MoveHomeExtend ()
  1267. {
  1268. if (_cursorPosition > 0)
  1269. {
  1270. int x = _cursorPosition;
  1271. _cursorPosition = 0;
  1272. PrepareSelection (x, _cursorPosition - x);
  1273. }
  1274. }
  1275. private bool MoveLeft ()
  1276. {
  1277. if (_cursorPosition > 0)
  1278. {
  1279. ClearAllSelection ();
  1280. _cursorPosition--;
  1281. Adjust ();
  1282. return true;
  1283. }
  1284. return false;
  1285. }
  1286. private void MoveLeftExtend ()
  1287. {
  1288. if (_cursorPosition > 0)
  1289. {
  1290. PrepareSelection (_cursorPosition--, -1);
  1291. }
  1292. }
  1293. private bool MoveRight ()
  1294. {
  1295. if (_cursorPosition == _text.Count)
  1296. {
  1297. return false;
  1298. }
  1299. ClearAllSelection ();
  1300. _cursorPosition++;
  1301. Adjust ();
  1302. return true;
  1303. }
  1304. private void MoveRightExtend ()
  1305. {
  1306. if (_cursorPosition < _text.Count)
  1307. {
  1308. PrepareSelection (_cursorPosition++, 1);
  1309. }
  1310. }
  1311. private void MoveWordLeft ()
  1312. {
  1313. ClearAllSelection ();
  1314. (int col, int row)? newPos = GetModel ().WordBackward (_cursorPosition, 0);
  1315. if (newPos is null)
  1316. {
  1317. return;
  1318. }
  1319. if (newPos.Value.col != -1)
  1320. {
  1321. _cursorPosition = newPos.Value.col;
  1322. }
  1323. Adjust ();
  1324. }
  1325. private void MoveWordLeftExtend ()
  1326. {
  1327. if (_cursorPosition > 0)
  1328. {
  1329. int x = Math.Min (
  1330. _start > -1 && _start > _cursorPosition ? _start : _cursorPosition,
  1331. _text.Count
  1332. );
  1333. if (x > 0)
  1334. {
  1335. (int col, int row)? newPos = GetModel ().WordBackward (x, 0);
  1336. if (newPos is null)
  1337. {
  1338. return;
  1339. }
  1340. if (newPos.Value.col != -1)
  1341. {
  1342. _cursorPosition = newPos.Value.col;
  1343. }
  1344. PrepareSelection (x, newPos.Value.col - x);
  1345. }
  1346. }
  1347. }
  1348. private void MoveWordRight ()
  1349. {
  1350. ClearAllSelection ();
  1351. (int col, int row)? newPos = GetModel ().WordForward (_cursorPosition, 0);
  1352. if (newPos is null)
  1353. {
  1354. return;
  1355. }
  1356. if (newPos.Value.col != -1)
  1357. {
  1358. _cursorPosition = newPos.Value.col;
  1359. }
  1360. Adjust ();
  1361. }
  1362. private void MoveWordRightExtend ()
  1363. {
  1364. if (_cursorPosition < _text.Count)
  1365. {
  1366. int x = _start > -1 && _start > _cursorPosition ? _start : _cursorPosition;
  1367. (int col, int row)? newPos = GetModel ().WordForward (x, 0);
  1368. if (newPos is null)
  1369. {
  1370. return;
  1371. }
  1372. if (newPos.Value.col != -1)
  1373. {
  1374. _cursorPosition = newPos.Value.col;
  1375. }
  1376. PrepareSelection (x, newPos.Value.col - x);
  1377. }
  1378. }
  1379. // BUGBUG: This assumes Frame == Viewport. It's also not clear what the intention is. For now, changed to always return 0.
  1380. private int OffSetBackground ()
  1381. {
  1382. var offB = 0;
  1383. if (SuperView?.Frame.Right - Frame.Right < 0)
  1384. {
  1385. offB = SuperView.Frame.Right - Frame.Right - 1;
  1386. }
  1387. return 0;//offB;
  1388. }
  1389. private int PositionCursor (MouseEvent ev)
  1390. {
  1391. return PositionCursor (TextModel.GetColFromX (_text, ScrollOffset, ev.Position.X), false);
  1392. }
  1393. private int PositionCursor (int x, bool getX = true)
  1394. {
  1395. int pX = x;
  1396. if (getX)
  1397. {
  1398. pX = TextModel.GetColFromX (_text, ScrollOffset, x);
  1399. }
  1400. if (ScrollOffset + pX > _text.Count)
  1401. {
  1402. _cursorPosition = _text.Count;
  1403. }
  1404. else if (ScrollOffset + pX < ScrollOffset)
  1405. {
  1406. _cursorPosition = 0;
  1407. }
  1408. else
  1409. {
  1410. _cursorPosition = ScrollOffset + pX;
  1411. }
  1412. return _cursorPosition;
  1413. }
  1414. private void PrepareSelection (int x, int direction = 0)
  1415. {
  1416. x = x + ScrollOffset < -1 ? 0 : x;
  1417. _selectedStart = _selectedStart == -1 && _text.Count > 0 && x >= 0 && x <= _text.Count
  1418. ? x
  1419. : _selectedStart;
  1420. if (_selectedStart > -1)
  1421. {
  1422. SelectedLength = Math.Abs (
  1423. x + direction <= _text.Count
  1424. ? x + direction - _selectedStart
  1425. : _text.Count - _selectedStart
  1426. );
  1427. SetSelectedStartSelectedLength ();
  1428. if (_start > -1 && SelectedLength > 0)
  1429. {
  1430. _selectedText = SelectedLength > 0
  1431. ? StringExtensions.ToString (
  1432. _text.GetRange (
  1433. _start < 0 ? 0 : _start,
  1434. SelectedLength > _text.Count
  1435. ? _text.Count
  1436. : SelectedLength
  1437. )
  1438. )
  1439. : "";
  1440. if (ScrollOffset > _start)
  1441. {
  1442. ScrollOffset = _start;
  1443. }
  1444. }
  1445. else if (_start > -1 && SelectedLength == 0)
  1446. {
  1447. _selectedText = null;
  1448. }
  1449. SetNeedsDisplay ();
  1450. }
  1451. else if (SelectedLength > 0 || _selectedText is { })
  1452. {
  1453. ClearAllSelection ();
  1454. }
  1455. Adjust ();
  1456. }
  1457. private void ProcessAutocomplete ()
  1458. {
  1459. if (_isDrawing)
  1460. {
  1461. return;
  1462. }
  1463. if (SelectedLength > 0)
  1464. {
  1465. return;
  1466. }
  1467. // draw autocomplete
  1468. GenerateSuggestions ();
  1469. var renderAt = new Point (
  1470. Autocomplete.Context.CursorPosition,
  1471. 0
  1472. );
  1473. Autocomplete.RenderOverlay (renderAt);
  1474. }
  1475. private void RenderCaption ()
  1476. {
  1477. if (HasFocus
  1478. || Caption == null
  1479. || Caption.Length == 0
  1480. || Text?.Length > 0)
  1481. {
  1482. return;
  1483. }
  1484. var color = new Attribute (CaptionColor, GetNormalColor ().Background);
  1485. Driver.SetAttribute (color);
  1486. Move (0, 0);
  1487. string render = Caption;
  1488. if (render.GetColumns () > Viewport.Width)
  1489. {
  1490. render = render [..Viewport.Width];
  1491. }
  1492. Driver.AddStr (render);
  1493. }
  1494. private void SetClipboard (IEnumerable<Rune> text)
  1495. {
  1496. if (!Secret)
  1497. {
  1498. Clipboard.Contents = StringExtensions.ToString (text.ToList ());
  1499. }
  1500. }
  1501. private void SetOverwrite (bool overwrite)
  1502. {
  1503. Used = overwrite;
  1504. SetNeedsDisplay ();
  1505. }
  1506. private void SetSelectedStartSelectedLength ()
  1507. {
  1508. if (SelectedStart > -1 && _cursorPosition < SelectedStart)
  1509. {
  1510. _start = _cursorPosition;
  1511. }
  1512. else
  1513. {
  1514. _start = SelectedStart;
  1515. }
  1516. }
  1517. private void SetText (List<Rune> newText) { Text = StringExtensions.ToString (newText); }
  1518. private void SetText (IEnumerable<Rune> newText) { SetText (newText.ToList ()); }
  1519. private void ShowContextMenu ()
  1520. {
  1521. if (_currentCulture != Thread.CurrentThread.CurrentUICulture)
  1522. {
  1523. _currentCulture = Thread.CurrentThread.CurrentUICulture;
  1524. ContextMenu.MenuItems = BuildContextMenuBarItem ();
  1525. }
  1526. ContextMenu.Show ();
  1527. }
  1528. private void TextField_Initialized (object sender, EventArgs e)
  1529. {
  1530. _cursorPosition = Text.GetRuneCount ();
  1531. if (Viewport.Width > 0)
  1532. {
  1533. ScrollOffset = _cursorPosition > Viewport.Width + 1 ? _cursorPosition - Viewport.Width + 1 : 0;
  1534. }
  1535. Autocomplete.HostControl = this;
  1536. Autocomplete.PopupInsideContainer = false;
  1537. }
  1538. }
  1539. /// <summary>
  1540. /// Renders an overlay on another view at a given point that allows selecting from a range of 'autocomplete'
  1541. /// options. An implementation on a TextField.
  1542. /// </summary>
  1543. public class TextFieldAutocomplete : PopupAutocomplete
  1544. {
  1545. /// <inheritdoc/>
  1546. protected override void DeleteTextBackwards () { ((TextField)HostControl).DeleteCharLeft (false); }
  1547. /// <inheritdoc/>
  1548. protected override void InsertText (string accepted) { ((TextField)HostControl).InsertText (accepted, false); }
  1549. /// <inheritdoc/>
  1550. protected override void SetCursorPosition (int column) { ((TextField)HostControl).CursorPosition = column; }
  1551. }