TextField.cs 55 KB

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