TextField.cs 55 KB

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