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