TextField.cs 55 KB

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