TextField.cs 53 KB

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