TextView.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. //
  2. // TextView.cs: multi-line text editing
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. //
  8. // TODO:
  9. // In ReadOnly mode backspace/space behave like pageup/pagedown
  10. // Attributed text on spans
  11. // Replace insertion with Insert method
  12. // String accumulation (Control-k, control-k is not preserving the last new line, see StringToRunes
  13. // Alt-D, Alt-Backspace
  14. // API to set the cursor position
  15. // API to scroll to a particular place
  16. // keybindings to go to top/bottom
  17. // public API to insert, remove ranges
  18. // Add word forward/word backwards commands
  19. // Save buffer API
  20. // Mouse
  21. //
  22. // Desirable:
  23. // Move all the text manipulation into the TextModel
  24. using System;
  25. using System.Collections.Generic;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Text;
  29. using NStack;
  30. using Rune = System.Rune;
  31. namespace Terminal.Gui {
  32. class TextModel {
  33. List<List<Rune>> lines = new List<List<Rune>> ();
  34. public bool LoadFile (string file)
  35. {
  36. if (file == null)
  37. throw new ArgumentNullException (nameof (file));
  38. try {
  39. FilePath = file;
  40. var stream = File.OpenRead (file);
  41. } catch {
  42. return false;
  43. }
  44. LoadStream (File.OpenRead (file));
  45. return true;
  46. }
  47. public bool CloseFile ()
  48. {
  49. if (FilePath == null)
  50. throw new ArgumentNullException (nameof (FilePath));
  51. try {
  52. FilePath = null;
  53. lines = new List<List<Rune>> ();
  54. } catch {
  55. return false;
  56. }
  57. return true;
  58. }
  59. // Turns the ustring into runes, this does not split the
  60. // contents on a newline if it is present.
  61. internal static List<Rune> ToRunes (ustring str)
  62. {
  63. List<Rune> runes = new List<Rune> ();
  64. foreach (var x in str.ToRunes ()) {
  65. runes.Add (x);
  66. }
  67. return runes;
  68. }
  69. // Splits a string into a List that contains a List<Rune> for each line
  70. public static List<List<Rune>> StringToRunes (ustring content)
  71. {
  72. var lines = new List<List<Rune>> ();
  73. int start = 0, i = 0;
  74. // BUGBUG: I think this is buggy w.r.t Unicode. content.Length is bytes, and content[i] is bytes
  75. // and content[i] == 10 may be the middle of a Rune.
  76. for (; i < content.Length; i++) {
  77. if (content [i] == 10) {
  78. if (i - start > 0)
  79. lines.Add (ToRunes (content [start, i]));
  80. else
  81. lines.Add (ToRunes (ustring.Empty));
  82. start = i + 1;
  83. }
  84. }
  85. if (i - start >= 0)
  86. lines.Add (ToRunes (content [start, null]));
  87. return lines;
  88. }
  89. void Append (List<byte> line)
  90. {
  91. var str = ustring.Make (line.ToArray ());
  92. lines.Add (ToRunes (str));
  93. }
  94. public void LoadStream (Stream input)
  95. {
  96. if (input == null)
  97. throw new ArgumentNullException (nameof (input));
  98. lines = new List<List<Rune>> ();
  99. var buff = new BufferedStream (input);
  100. int v;
  101. var line = new List<byte> ();
  102. while ((v = buff.ReadByte ()) != -1) {
  103. if (v == 10) {
  104. Append (line);
  105. line.Clear ();
  106. continue;
  107. }
  108. line.Add ((byte)v);
  109. }
  110. if (line.Count > 0)
  111. Append (line);
  112. }
  113. public void LoadString (ustring content)
  114. {
  115. lines = StringToRunes (content);
  116. }
  117. public override string ToString ()
  118. {
  119. var sb = new StringBuilder ();
  120. for (int i = 0; i < lines.Count; i++) {
  121. sb.Append (ustring.Make (lines[i]));
  122. if ((i + 1) < lines.Count) {
  123. sb.AppendLine ();
  124. }
  125. }
  126. return sb.ToString ();
  127. }
  128. public string FilePath { get; set; }
  129. /// <summary>
  130. /// The number of text lines in the model
  131. /// </summary>
  132. public int Count => lines.Count;
  133. /// <summary>
  134. /// Returns the specified line as a List of Rune
  135. /// </summary>
  136. /// <returns>The line.</returns>
  137. /// <param name="line">Line number to retrieve.</param>
  138. public List<Rune> GetLine (int line) => line < Count ? lines [line] : lines [Count - 1];
  139. /// <summary>
  140. /// Adds a line to the model at the specified position.
  141. /// </summary>
  142. /// <param name="pos">Line number where the line will be inserted.</param>
  143. /// <param name="runes">The line of text, as a List of Rune.</param>
  144. public void AddLine (int pos, List<Rune> runes)
  145. {
  146. lines.Insert (pos, runes);
  147. }
  148. /// <summary>
  149. /// Removes the line at the specified position
  150. /// </summary>
  151. /// <param name="pos">Position.</param>
  152. public void RemoveLine (int pos)
  153. {
  154. lines.RemoveAt (pos);
  155. }
  156. /// <summary>
  157. /// Returns the maximum line length of the visible lines.
  158. /// </summary>
  159. /// <param name="first">The first line.</param>
  160. /// <param name="last">The last line.</param>
  161. public int GetMaxVisibleLine (int first, int last)
  162. {
  163. int maxLength = 0;
  164. last = last < lines.Count ? last : lines.Count;
  165. for (int i = first; i < last; i++) {
  166. var l = GetLine (i).Count;
  167. if (l > maxLength) {
  168. maxLength = l;
  169. }
  170. }
  171. return maxLength;
  172. }
  173. internal static int SetCol (int col, int width, int cols)
  174. {
  175. if (col + cols <= width) {
  176. col += cols;
  177. }
  178. return col;
  179. }
  180. internal static int GetColFromX (List<Rune> t, int start, int x)
  181. {
  182. if (x < 0) {
  183. return x;
  184. }
  185. int size = start;
  186. var pX = x + start;
  187. for (int i = start; i < t.Count; i++) {
  188. var r = t [i];
  189. size += Rune.ColumnWidth (r);
  190. if (i == pX || (size > pX)) {
  191. return i - start;
  192. }
  193. }
  194. return t.Count - start;
  195. }
  196. // Returns the size and length in a range of the string.
  197. internal static (int size, int length) DisplaySize (List<Rune> t, int start = -1, int end = -1, bool checkNextRune = true)
  198. {
  199. if (t == null || t.Count == 0) {
  200. return (0, 0);
  201. }
  202. int size = 0;
  203. int len = 0;
  204. int tcount = end == -1 ? t.Count : end > t.Count ? t.Count : end;
  205. int i = start == -1 ? 0 : start;
  206. for (; i < tcount; i++) {
  207. var rune = t [i];
  208. size += Rune.ColumnWidth (rune);
  209. len += Rune.RuneLen (rune);
  210. if (checkNextRune && i == tcount - 1 && t.Count > tcount && Rune.ColumnWidth (t [i + 1]) > 1) {
  211. size += Rune.ColumnWidth (t [i + 1]);
  212. len += Rune.RuneLen (t [i + 1]);
  213. }
  214. }
  215. return (size, len);
  216. }
  217. // Returns the left column in a range of the string.
  218. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int currentColumn)
  219. {
  220. if (t == null) {
  221. return 0;
  222. }
  223. (var dSize, _) = TextModel.DisplaySize (t, start, end);
  224. if (dSize < width) {
  225. return start;
  226. }
  227. int size = 0;
  228. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  229. int col = 0;
  230. for (int i = tcount; i > start; i--) {
  231. var rune = t [i];
  232. var s = Rune.ColumnWidth (rune);
  233. size += s;
  234. if (size >= dSize - width) {
  235. col = tcount - i + start;
  236. if (start == 0 || col == start || (currentColumn == t.Count && (currentColumn - col > width))) {
  237. col++;
  238. }
  239. break;
  240. }
  241. }
  242. return col;
  243. }
  244. }
  245. /// <summary>
  246. /// Multi-line text editing <see cref="View"/>
  247. /// </summary>
  248. /// <remarks>
  249. /// <para>
  250. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  251. /// with it with the standard Emacs commands for movement or the arrow
  252. /// keys.
  253. /// </para>
  254. /// <list type="table">
  255. /// <listheader>
  256. /// <term>Shortcut</term>
  257. /// <description>Action performed</description>
  258. /// </listheader>
  259. /// <item>
  260. /// <term>Left cursor, Control-b</term>
  261. /// <description>
  262. /// Moves the editing point left.
  263. /// </description>
  264. /// </item>
  265. /// <item>
  266. /// <term>Right cursor, Control-f</term>
  267. /// <description>
  268. /// Moves the editing point right.
  269. /// </description>
  270. /// </item>
  271. /// <item>
  272. /// <term>Alt-b</term>
  273. /// <description>
  274. /// Moves one word back.
  275. /// </description>
  276. /// </item>
  277. /// <item>
  278. /// <term>Alt-f</term>
  279. /// <description>
  280. /// Moves one word forward.
  281. /// </description>
  282. /// </item>
  283. /// <item>
  284. /// <term>Up cursor, Control-p</term>
  285. /// <description>
  286. /// Moves the editing point one line up.
  287. /// </description>
  288. /// </item>
  289. /// <item>
  290. /// <term>Down cursor, Control-n</term>
  291. /// <description>
  292. /// Moves the editing point one line down
  293. /// </description>
  294. /// </item>
  295. /// <item>
  296. /// <term>Home key, Control-a</term>
  297. /// <description>
  298. /// Moves the cursor to the beginning of the line.
  299. /// </description>
  300. /// </item>
  301. /// <item>
  302. /// <term>End key, Control-e</term>
  303. /// <description>
  304. /// Moves the cursor to the end of the line.
  305. /// </description>
  306. /// </item>
  307. /// <item>
  308. /// <term>Control-Home</term>
  309. /// <description>
  310. /// Scrolls to the first line and moves the cursor there.
  311. /// </description>
  312. /// </item>
  313. /// <item>
  314. /// <term>Control-End</term>
  315. /// <description>
  316. /// Scrolls to the last line and moves the cursor there.
  317. /// </description>
  318. /// </item>
  319. /// <item>
  320. /// <term>Delete, Control-d</term>
  321. /// <description>
  322. /// Deletes the character in front of the cursor.
  323. /// </description>
  324. /// </item>
  325. /// <item>
  326. /// <term>Backspace</term>
  327. /// <description>
  328. /// Deletes the character behind the cursor.
  329. /// </description>
  330. /// </item>
  331. /// <item>
  332. /// <term>Control-k</term>
  333. /// <description>
  334. /// Deletes the text until the end of the line and replaces the kill buffer
  335. /// with the deleted text. You can paste this text in a different place by
  336. /// using Control-y.
  337. /// </description>
  338. /// </item>
  339. /// <item>
  340. /// <term>Control-y</term>
  341. /// <description>
  342. /// Pastes the content of the kill ring into the current position.
  343. /// </description>
  344. /// </item>
  345. /// <item>
  346. /// <term>Alt-d</term>
  347. /// <description>
  348. /// Deletes the word above the cursor and adds it to the kill ring. You
  349. /// can paste the contents of the kill ring with Control-y.
  350. /// </description>
  351. /// </item>
  352. /// <item>
  353. /// <term>Control-q</term>
  354. /// <description>
  355. /// Quotes the next input character, to prevent the normal processing of
  356. /// key handling to take place.
  357. /// </description>
  358. /// </item>
  359. /// </list>
  360. /// </remarks>
  361. public class TextView : View {
  362. TextModel model = new TextModel ();
  363. int topRow;
  364. int leftColumn;
  365. int currentRow;
  366. int currentColumn;
  367. int selectionStartColumn, selectionStartRow;
  368. bool selecting;
  369. //bool used;
  370. /// <summary>
  371. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  372. /// </summary>
  373. public event Action TextChanged;
  374. #if false
  375. /// <summary>
  376. /// Changed event, raised when the text has clicked.
  377. /// </summary>
  378. /// <remarks>
  379. /// Client code can hook up to this event, it is
  380. /// raised when the text in the entry changes.
  381. /// </remarks>
  382. public Action Changed;
  383. #endif
  384. /// <summary>
  385. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  386. /// </summary>
  387. /// <remarks>
  388. /// </remarks>
  389. public TextView (Rect frame) : base (frame)
  390. {
  391. CanFocus = true;
  392. }
  393. /// <summary>
  394. /// Initializes a <see cref="TextView"/> on the specified area,
  395. /// with dimensions controlled with the X, Y, Width and Height properties.
  396. /// </summary>
  397. public TextView () : base ()
  398. {
  399. CanFocus = true;
  400. }
  401. void ResetPosition ()
  402. {
  403. topRow = leftColumn = currentRow = currentColumn = 0;
  404. }
  405. /// <summary>
  406. /// Sets or gets the text in the <see cref="TextView"/>.
  407. /// </summary>
  408. /// <remarks>
  409. /// </remarks>
  410. public override ustring Text {
  411. get {
  412. return model.ToString ();
  413. }
  414. set {
  415. ResetPosition ();
  416. model.LoadString (value);
  417. TextChanged?.Invoke ();
  418. SetNeedsDisplay ();
  419. }
  420. }
  421. ///<inheritdoc/>
  422. public override Rect Frame {
  423. get => base.Frame;
  424. set {
  425. base.Frame = value;
  426. Adjust ();
  427. }
  428. }
  429. /// <summary>
  430. /// Loads the contents of the file into the <see cref="TextView"/>.
  431. /// </summary>
  432. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  433. /// <param name="path">Path to the file to load.</param>
  434. public bool LoadFile (string path)
  435. {
  436. if (path == null)
  437. throw new ArgumentNullException (nameof (path));
  438. ResetPosition ();
  439. var res = model.LoadFile (path);
  440. SetNeedsDisplay ();
  441. return res;
  442. }
  443. /// <summary>
  444. /// Loads the contents of the stream into the <see cref="TextView"/>.
  445. /// </summary>
  446. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  447. /// <param name="stream">Stream to load the contents from.</param>
  448. public void LoadStream (Stream stream)
  449. {
  450. if (stream == null)
  451. throw new ArgumentNullException (nameof (stream));
  452. ResetPosition ();
  453. model.LoadStream (stream);
  454. SetNeedsDisplay ();
  455. }
  456. /// <summary>
  457. /// Closes the contents of the stream into the <see cref="TextView"/>.
  458. /// </summary>
  459. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  460. public bool CloseFile ()
  461. {
  462. ResetPosition ();
  463. var res = model.CloseFile ();
  464. SetNeedsDisplay ();
  465. return res;
  466. }
  467. /// <summary>
  468. /// Gets the current cursor row.
  469. /// </summary>
  470. public int CurrentRow => currentRow;
  471. /// <summary>
  472. /// Gets the cursor column.
  473. /// </summary>
  474. /// <value>The cursor column.</value>
  475. public int CurrentColumn => currentColumn;
  476. /// <summary>
  477. /// Positions the cursor on the current row and column
  478. /// </summary>
  479. public override void PositionCursor ()
  480. {
  481. if (selecting) {
  482. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  483. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  484. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  485. }
  486. var line = model.GetLine (currentRow);
  487. var retreat = 0;
  488. var col = 0;
  489. if (line.Count > 0) {
  490. retreat = Math.Max ((SpecialRune (line [Math.Max (CurrentColumn - leftColumn - 1, 0)])
  491. ? 1 : 0), 0);
  492. for (int idx = leftColumn < 0 ? 0 : leftColumn; idx < line.Count; idx++) {
  493. if (idx == CurrentColumn)
  494. break;
  495. var cols = Rune.ColumnWidth (line [idx]);
  496. col += cols - 1;
  497. }
  498. }
  499. var ccol = CurrentColumn - leftColumn - retreat + col;
  500. if (leftColumn <= CurrentColumn && ccol < Frame.Width
  501. && topRow <= CurrentRow && CurrentRow - topRow < Frame.Height) {
  502. Move (ccol, CurrentRow - topRow);
  503. }
  504. }
  505. void ClearRegion (int left, int top, int right, int bottom)
  506. {
  507. for (int row = top; row < bottom; row++) {
  508. Move (left, row);
  509. for (int col = left; col < right; col++)
  510. AddRune (col, row, ' ');
  511. }
  512. }
  513. void ColorNormal ()
  514. {
  515. Driver.SetAttribute (ColorScheme.Normal);
  516. }
  517. void ColorSelection ()
  518. {
  519. if (HasFocus)
  520. Driver.SetAttribute (ColorScheme.Focus);
  521. else
  522. Driver.SetAttribute (ColorScheme.Normal);
  523. }
  524. bool isReadOnly = false;
  525. /// <summary>
  526. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  527. /// </summary>
  528. /// <value>Boolean value(Default false)</value>
  529. public bool ReadOnly {
  530. get => isReadOnly;
  531. set {
  532. isReadOnly = value;
  533. }
  534. }
  535. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  536. void GetEncodedRegionBounds (out long start, out long end)
  537. {
  538. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  539. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  540. if (selection > point) {
  541. start = point;
  542. end = selection;
  543. } else {
  544. start = selection;
  545. end = point;
  546. }
  547. }
  548. bool PointInSelection (int col, int row)
  549. {
  550. long start, end;
  551. GetEncodedRegionBounds (out start, out end);
  552. var q = ((long)(uint)row << 32) | (uint)col;
  553. return q >= start && q <= end;
  554. }
  555. //
  556. // Returns a ustring with the text in the selected
  557. // region.
  558. //
  559. ustring GetRegion ()
  560. {
  561. long start, end;
  562. GetEncodedRegionBounds (out start, out end);
  563. int startRow = (int)(start >> 32);
  564. var maxrow = ((int)(end >> 32));
  565. int startCol = (int)(start & 0xffffffff);
  566. var endCol = (int)(end & 0xffffffff);
  567. var line = model.GetLine (startRow);
  568. if (startRow == maxrow)
  569. return StringFromRunes (line.GetRange (startCol, endCol));
  570. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  571. for (int row = startRow + 1; row < maxrow; row++) {
  572. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  573. }
  574. line = model.GetLine (maxrow);
  575. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  576. return res;
  577. }
  578. //
  579. // Clears the contents of the selected region
  580. //
  581. void ClearRegion ()
  582. {
  583. long start, end;
  584. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  585. GetEncodedRegionBounds (out start, out end);
  586. int startRow = (int)(start >> 32);
  587. var maxrow = ((int)(end >> 32));
  588. int startCol = (int)(start & 0xffffffff);
  589. var endCol = (int)(end & 0xffffffff);
  590. var line = model.GetLine (startRow);
  591. if (startRow == maxrow) {
  592. line.RemoveRange (startCol, endCol - startCol);
  593. currentColumn = startCol;
  594. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  595. return;
  596. }
  597. line.RemoveRange (startCol, line.Count - startCol);
  598. var line2 = model.GetLine (maxrow);
  599. line.AddRange (line2.Skip (endCol));
  600. for (int row = startRow + 1; row <= maxrow; row++) {
  601. model.RemoveLine (startRow + 1);
  602. }
  603. if (currentEncoded == end) {
  604. currentRow -= maxrow - (startRow);
  605. }
  606. currentColumn = startCol;
  607. SetNeedsDisplay ();
  608. }
  609. ///<inheritdoc/>
  610. public override void Redraw (Rect bounds)
  611. {
  612. ColorNormal ();
  613. int bottom = bounds.Bottom;
  614. int right = bounds.Right;
  615. for (int row = bounds.Top; row < bottom; row++) {
  616. int textLine = topRow + row;
  617. if (textLine >= model.Count) {
  618. ColorNormal ();
  619. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  620. continue;
  621. }
  622. var line = model.GetLine (textLine);
  623. int lineRuneCount = line.Count;
  624. if (line.Count < bounds.Left) {
  625. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  626. continue;
  627. }
  628. Move (bounds.Left, row);
  629. var col = 0;
  630. for (int idx = bounds.Left; idx < right; idx++) {
  631. var lineCol = leftColumn + idx;
  632. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  633. var cols = Rune.ColumnWidth (rune);
  634. if (selecting && PointInSelection (idx, row)) {
  635. ColorSelection ();
  636. } else {
  637. ColorNormal ();
  638. }
  639. if (!SpecialRune (rune)) {
  640. AddRune (col, row, rune);
  641. }
  642. col = TextModel.SetCol (col, bounds.Right, cols);
  643. }
  644. }
  645. PositionCursor ();
  646. }
  647. bool SpecialRune (Rune rune)
  648. {
  649. switch (rune) {
  650. case (uint)Key.Enter:
  651. case 0xd:
  652. return true;
  653. default:
  654. return false; }
  655. }
  656. ///<inheritdoc/>
  657. public override bool CanFocus {
  658. get => base.CanFocus;
  659. set { base.CanFocus = value; }
  660. }
  661. void SetClipboard (ustring text)
  662. {
  663. Clipboard.Contents = text;
  664. }
  665. void AppendClipboard (ustring text)
  666. {
  667. Clipboard.Contents = Clipboard.Contents + text;
  668. }
  669. void Insert (Rune rune)
  670. {
  671. var line = GetCurrentLine ();
  672. line.Insert (currentColumn, rune);
  673. var prow = currentRow - topRow;
  674. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  675. }
  676. ustring StringFromRunes (List<Rune> runes)
  677. {
  678. if (runes == null)
  679. throw new ArgumentNullException (nameof (runes));
  680. int size = 0;
  681. foreach (var rune in runes) {
  682. size += Utf8.RuneLen (rune);
  683. }
  684. var encoded = new byte [size];
  685. int offset = 0;
  686. foreach (var rune in runes) {
  687. offset += Utf8.EncodeRune (rune, encoded, offset);
  688. }
  689. return ustring.Make (encoded);
  690. }
  691. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  692. void InsertText (ustring text)
  693. {
  694. if (ustring.IsNullOrEmpty (text)) {
  695. return;
  696. }
  697. var lines = TextModel.StringToRunes (text);
  698. if (lines.Count == 0) {
  699. return;
  700. }
  701. var line = GetCurrentLine ();
  702. // Optimize single line
  703. if (lines.Count == 1) {
  704. line.InsertRange (currentColumn, lines [0]);
  705. currentColumn += lines [0].Count;
  706. if (currentColumn - leftColumn > Frame.Width) {
  707. leftColumn = currentColumn - Frame.Width + 1;
  708. }
  709. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  710. return;
  711. }
  712. // Keep a copy of the rest of the line
  713. var restCount = line.Count - currentColumn;
  714. var rest = line.GetRange (currentColumn, restCount);
  715. line.RemoveRange (currentColumn, restCount);
  716. // First line is inserted at the current location, the rest is appended
  717. line.InsertRange (currentColumn, lines [0]);
  718. for (int i = 1; i < lines.Count; i++) {
  719. model.AddLine (currentRow + i, lines [i]);
  720. }
  721. var last = model.GetLine (currentRow + lines.Count - 1);
  722. var lastp = last.Count;
  723. last.InsertRange (last.Count, rest);
  724. // Now adjust column and row positions
  725. currentRow += lines.Count - 1;
  726. currentColumn = lastp;
  727. Adjust ();
  728. }
  729. // The column we are tracking, or -1 if we are not tracking any column
  730. int columnTrack = -1;
  731. // Tries to snap the cursor to the tracking column
  732. void TrackColumn ()
  733. {
  734. // Now track the column
  735. var line = GetCurrentLine ();
  736. if (line.Count < columnTrack)
  737. currentColumn = line.Count;
  738. else if (columnTrack != -1)
  739. currentColumn = columnTrack;
  740. else if (currentColumn > line.Count)
  741. currentColumn = line.Count;
  742. Adjust ();
  743. }
  744. void Adjust ()
  745. {
  746. var offB = OffSetBackground ();
  747. var line = GetCurrentLine ();
  748. bool need = false;
  749. if (currentColumn < leftColumn) {
  750. leftColumn = currentColumn;
  751. need = true;
  752. } else if (currentColumn - leftColumn > Frame.Width + offB.width ||
  753. TextModel.DisplaySize (line, leftColumn, currentColumn).size >= Frame.Width + offB.width) {
  754. leftColumn = Math.Max (TextModel.CalculateLeftColumn (line, leftColumn,
  755. currentColumn, Frame.Width - 1 + offB.width, currentColumn), 0);
  756. need = true;
  757. }
  758. if (currentRow < topRow) {
  759. topRow = currentRow;
  760. need = true;
  761. } else if (currentRow - topRow >= Frame.Height + offB.height) {
  762. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1, 0), currentRow);
  763. need = true;
  764. }
  765. if (need) {
  766. SetNeedsDisplay ();
  767. } else {
  768. PositionCursor ();
  769. }
  770. }
  771. (int width, int height) OffSetBackground ()
  772. {
  773. int w = 0;
  774. int h = 0;
  775. if (SuperView?.Frame.Right - Frame.Right < 0) {
  776. w = SuperView.Frame.Right - Frame.Right - 1;
  777. }
  778. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  779. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  780. }
  781. return (w, h);
  782. }
  783. /// <summary>
  784. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  785. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  786. /// </summary>
  787. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  788. /// if the value is negative it will be reset to zero</param>
  789. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  790. public void ScrollTo (int idx, bool isRow = true)
  791. {
  792. if (idx < 0) {
  793. idx = 0;
  794. }
  795. if (isRow) {
  796. topRow = idx > model.Count - 1 ? model.Count - 1 : idx;
  797. } else {
  798. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height);
  799. leftColumn = idx > maxlength - 1 ? maxlength - 1 : idx;
  800. }
  801. SetNeedsDisplay ();
  802. }
  803. bool lastWasKill;
  804. ///<inheritdoc/>
  805. public override bool ProcessKey (KeyEvent kb)
  806. {
  807. int restCount;
  808. List<Rune> rest;
  809. // Handle some state here - whether the last command was a kill
  810. // operation and the column tracking (up/down)
  811. switch (kb.Key) {
  812. case Key.N | Key.CtrlMask:
  813. case Key.CursorDown:
  814. case Key.P | Key.CtrlMask:
  815. case Key.CursorUp:
  816. lastWasKill = false;
  817. break;
  818. case Key.K | Key.CtrlMask:
  819. break;
  820. default:
  821. lastWasKill = false;
  822. columnTrack = -1;
  823. break;
  824. }
  825. // Dispatch the command.
  826. switch (kb.Key) {
  827. case Key.PageDown:
  828. case Key.V | Key.CtrlMask:
  829. int nPageDnShift = Frame.Height - 1;
  830. if (currentRow < model.Count) {
  831. if (columnTrack == -1)
  832. columnTrack = currentColumn;
  833. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  834. if (topRow < currentRow - nPageDnShift) {
  835. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  836. SetNeedsDisplay ();
  837. }
  838. TrackColumn ();
  839. PositionCursor ();
  840. }
  841. break;
  842. case Key.PageUp:
  843. case ((int)'V' + Key.AltMask):
  844. int nPageUpShift = Frame.Height - 1;
  845. if (currentRow > 0) {
  846. if (columnTrack == -1)
  847. columnTrack = currentColumn;
  848. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  849. if (currentRow < topRow) {
  850. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  851. SetNeedsDisplay ();
  852. }
  853. TrackColumn ();
  854. PositionCursor ();
  855. }
  856. break;
  857. case Key.N | Key.CtrlMask:
  858. case Key.CursorDown:
  859. MoveDown ();
  860. break;
  861. case Key.P | Key.CtrlMask:
  862. case Key.CursorUp:
  863. MoveUp ();
  864. break;
  865. case Key.F | Key.CtrlMask:
  866. case Key.CursorRight:
  867. var currentLine = GetCurrentLine ();
  868. if (currentColumn < currentLine.Count) {
  869. currentColumn++;
  870. } else {
  871. if (currentRow + 1 < model.Count) {
  872. currentRow++;
  873. currentColumn = 0;
  874. if (currentRow >= topRow + Frame.Height) {
  875. topRow++;
  876. }
  877. }
  878. }
  879. Adjust ();
  880. break;
  881. case Key.B | Key.CtrlMask:
  882. case Key.CursorLeft:
  883. if (currentColumn > 0) {
  884. currentColumn--;
  885. } else {
  886. if (currentRow > 0) {
  887. currentRow--;
  888. if (currentRow < topRow) {
  889. topRow--;
  890. }
  891. currentLine = GetCurrentLine ();
  892. currentColumn = currentLine.Count;
  893. }
  894. }
  895. Adjust ();
  896. break;
  897. case Key.Delete:
  898. case Key.Backspace:
  899. if (isReadOnly)
  900. break;
  901. if (currentColumn > 0) {
  902. // Delete backwards
  903. currentLine = GetCurrentLine ();
  904. currentLine.RemoveAt (currentColumn - 1);
  905. currentColumn--;
  906. if (currentColumn < leftColumn) {
  907. leftColumn--;
  908. SetNeedsDisplay ();
  909. } else
  910. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  911. } else {
  912. // Merges the current line with the previous one.
  913. if (currentRow == 0)
  914. return true;
  915. var prowIdx = currentRow - 1;
  916. var prevRow = model.GetLine (prowIdx);
  917. var prevCount = prevRow.Count;
  918. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  919. model.RemoveLine (currentRow);
  920. currentRow--;
  921. currentColumn = prevCount;
  922. Adjust ();
  923. }
  924. break;
  925. // Home, C-A
  926. case Key.Home:
  927. case Key.A | Key.CtrlMask:
  928. currentColumn = 0;
  929. Adjust ();
  930. break;
  931. case Key.DeleteChar:
  932. case Key.D | Key.CtrlMask: // Delete
  933. if (isReadOnly)
  934. break;
  935. currentLine = GetCurrentLine ();
  936. if (currentColumn == currentLine.Count) {
  937. if (currentRow + 1 == model.Count)
  938. break;
  939. var nextLine = model.GetLine (currentRow + 1);
  940. currentLine.AddRange (nextLine);
  941. model.RemoveLine (currentRow + 1);
  942. var sr = currentRow - topRow;
  943. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  944. } else {
  945. currentLine.RemoveAt (currentColumn);
  946. var r = currentRow - topRow;
  947. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  948. }
  949. break;
  950. case Key.End:
  951. case Key.E | Key.CtrlMask: // End
  952. currentLine = GetCurrentLine ();
  953. currentColumn = currentLine.Count;
  954. int pcol = leftColumn;
  955. Adjust ();
  956. break;
  957. case Key.K | Key.CtrlMask: // kill-to-end
  958. if (isReadOnly)
  959. break;
  960. currentLine = GetCurrentLine ();
  961. if (currentLine.Count == 0) {
  962. model.RemoveLine (currentRow);
  963. var val = ustring.Make ((Rune)'\n');
  964. if (lastWasKill)
  965. AppendClipboard (val);
  966. else
  967. SetClipboard (val);
  968. } else {
  969. restCount = currentLine.Count - currentColumn;
  970. rest = currentLine.GetRange (currentColumn, restCount);
  971. var val = StringFromRunes (rest);
  972. if (lastWasKill)
  973. AppendClipboard (val);
  974. else
  975. SetClipboard (val);
  976. currentLine.RemoveRange (currentColumn, restCount);
  977. }
  978. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  979. lastWasKill = true;
  980. break;
  981. case Key.Y | Key.CtrlMask: // Control-y, yank
  982. if (isReadOnly)
  983. break;
  984. InsertText (Clipboard.Contents);
  985. selecting = false;
  986. break;
  987. case Key.Space | Key.CtrlMask:
  988. selecting = true;
  989. selectionStartColumn = currentColumn;
  990. selectionStartRow = currentRow;
  991. break;
  992. case ((int)'W' + Key.AltMask):
  993. case Key.W | Key.CtrlMask:
  994. SetClipboard (GetRegion ());
  995. if (!isReadOnly)
  996. ClearRegion ();
  997. selecting = false;
  998. break;
  999. case Key.CtrlMask | Key.CursorLeft:
  1000. case (Key)((int)'B' + Key.AltMask):
  1001. var newPos = WordBackward (currentColumn, currentRow);
  1002. if (newPos.HasValue) {
  1003. currentColumn = newPos.Value.col;
  1004. currentRow = newPos.Value.row;
  1005. }
  1006. Adjust ();
  1007. break;
  1008. case Key.CtrlMask | Key.CursorRight:
  1009. case (Key)((int)'F' + Key.AltMask):
  1010. newPos = WordForward (currentColumn, currentRow);
  1011. if (newPos.HasValue) {
  1012. currentColumn = newPos.Value.col;
  1013. currentRow = newPos.Value.row;
  1014. }
  1015. Adjust ();
  1016. break;
  1017. case Key.Enter:
  1018. if (isReadOnly)
  1019. break;
  1020. currentLine = GetCurrentLine ();
  1021. restCount = currentLine.Count - currentColumn;
  1022. rest = currentLine.GetRange (currentColumn, restCount);
  1023. currentLine.RemoveRange (currentColumn, restCount);
  1024. model.AddLine (currentRow + 1, rest);
  1025. currentRow++;
  1026. bool fullNeedsDisplay = false;
  1027. if (currentRow >= topRow + Frame.Height) {
  1028. topRow++;
  1029. fullNeedsDisplay = true;
  1030. }
  1031. currentColumn = 0;
  1032. if (currentColumn < leftColumn) {
  1033. fullNeedsDisplay = true;
  1034. leftColumn = 0;
  1035. }
  1036. if (fullNeedsDisplay)
  1037. SetNeedsDisplay ();
  1038. else
  1039. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  1040. break;
  1041. case Key.CtrlMask | Key.End:
  1042. MoveEnd ();
  1043. break;
  1044. case Key.CtrlMask | Key.Home:
  1045. MoveHome ();
  1046. break;
  1047. default:
  1048. // Ignore control characters and other special keys
  1049. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  1050. return false;
  1051. //So that special keys like tab can be processed
  1052. if (isReadOnly)
  1053. return true;
  1054. Insert ((uint)kb.Key);
  1055. currentColumn++;
  1056. if (currentColumn >= leftColumn + Frame.Width) {
  1057. leftColumn++;
  1058. SetNeedsDisplay ();
  1059. }
  1060. PositionCursor ();
  1061. return true;
  1062. }
  1063. return true;
  1064. }
  1065. void MoveUp ()
  1066. {
  1067. if (currentRow > 0) {
  1068. if (columnTrack == -1) {
  1069. columnTrack = currentColumn;
  1070. }
  1071. currentRow--;
  1072. if (currentRow < topRow) {
  1073. topRow--;
  1074. SetNeedsDisplay ();
  1075. }
  1076. TrackColumn ();
  1077. PositionCursor ();
  1078. }
  1079. }
  1080. void MoveDown ()
  1081. {
  1082. if (currentRow + 1 < model.Count) {
  1083. if (columnTrack == -1) {
  1084. columnTrack = currentColumn;
  1085. }
  1086. currentRow++;
  1087. if (currentRow >= topRow + Frame.Height) {
  1088. topRow++;
  1089. SetNeedsDisplay ();
  1090. }
  1091. TrackColumn ();
  1092. PositionCursor ();
  1093. } else if (currentRow > Frame.Height) {
  1094. Adjust ();
  1095. }
  1096. }
  1097. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  1098. {
  1099. if (col < 0 || row < 0)
  1100. yield break;
  1101. if (row >= model.Count)
  1102. yield break;
  1103. var line = GetCurrentLine ();
  1104. if (col >= line.Count)
  1105. yield break;
  1106. while (row < model.Count) {
  1107. for (int c = col; c < line.Count; c++) {
  1108. yield return (c, row, line [c]);
  1109. }
  1110. col = 0;
  1111. row++;
  1112. line = GetCurrentLine ();
  1113. }
  1114. }
  1115. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  1116. /// <summary>
  1117. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  1118. /// </summary>
  1119. public void MoveEnd ()
  1120. {
  1121. currentRow = model.Count - 1;
  1122. TrackColumn ();
  1123. PositionCursor ();
  1124. }
  1125. /// <summary>
  1126. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  1127. /// </summary>
  1128. public void MoveHome ()
  1129. {
  1130. currentRow = 0;
  1131. TrackColumn ();
  1132. PositionCursor ();
  1133. }
  1134. bool MoveNext (ref int col, ref int row, out Rune rune)
  1135. {
  1136. var line = model.GetLine (row);
  1137. if (col + 1 < line.Count) {
  1138. col++;
  1139. rune = line [col];
  1140. return true;
  1141. }
  1142. while (row + 1 < model.Count) {
  1143. col = 0;
  1144. row++;
  1145. line = model.GetLine (row);
  1146. if (line.Count > 0) {
  1147. rune = line [0];
  1148. return true;
  1149. }
  1150. }
  1151. rune = 0;
  1152. return false;
  1153. }
  1154. bool MovePrev (ref int col, ref int row, out Rune rune)
  1155. {
  1156. var line = model.GetLine (row);
  1157. if (col > 0) {
  1158. col--;
  1159. rune = line [col];
  1160. return true;
  1161. }
  1162. if (row == 0) {
  1163. rune = 0;
  1164. return false;
  1165. }
  1166. while (row > 0) {
  1167. row--;
  1168. line = model.GetLine (row);
  1169. col = line.Count - 1;
  1170. if (col >= 0) {
  1171. rune = line [col];
  1172. return true;
  1173. }
  1174. }
  1175. rune = 0;
  1176. return false;
  1177. }
  1178. (int col, int row)? WordForward (int fromCol, int fromRow)
  1179. {
  1180. var col = fromCol;
  1181. var row = fromRow;
  1182. try {
  1183. var rune = RuneAt (col, row);
  1184. var srow = row;
  1185. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1186. while (MoveNext (ref col, ref row, out rune)) {
  1187. if (Rune.IsLetterOrDigit (rune))
  1188. break;
  1189. }
  1190. while (MoveNext (ref col, ref row, out rune)) {
  1191. if (!Rune.IsLetterOrDigit (rune))
  1192. break;
  1193. }
  1194. } else {
  1195. while (MoveNext (ref col, ref row, out rune)) {
  1196. if (!Rune.IsLetterOrDigit (rune))
  1197. break;
  1198. }
  1199. }
  1200. if (fromCol != col || fromRow != row)
  1201. return (col, row);
  1202. return null;
  1203. } catch (Exception) {
  1204. return null;
  1205. }
  1206. }
  1207. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1208. {
  1209. if (fromRow == 0 && fromCol == 0)
  1210. return null;
  1211. var col = fromCol;
  1212. var row = fromRow;
  1213. try {
  1214. var rune = RuneAt (col, row);
  1215. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1216. while (MovePrev (ref col, ref row, out rune)) {
  1217. if (Rune.IsLetterOrDigit (rune))
  1218. break;
  1219. }
  1220. while (MovePrev (ref col, ref row, out rune)) {
  1221. if (!Rune.IsLetterOrDigit (rune))
  1222. break;
  1223. }
  1224. } else {
  1225. while (MovePrev (ref col, ref row, out rune)) {
  1226. if (!Rune.IsLetterOrDigit (rune))
  1227. break;
  1228. }
  1229. }
  1230. if (fromCol != col || fromRow != row)
  1231. return (col, row);
  1232. return null;
  1233. } catch (Exception) {
  1234. return null;
  1235. }
  1236. }
  1237. ///<inheritdoc/>
  1238. public override bool MouseEvent (MouseEvent ev)
  1239. {
  1240. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  1241. !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)) {
  1242. return false;
  1243. }
  1244. if (!CanFocus) {
  1245. return true;
  1246. }
  1247. if (!HasFocus) {
  1248. SetFocus ();
  1249. }
  1250. if (ev.Flags == MouseFlags.Button1Clicked) {
  1251. if (model.Count > 0) {
  1252. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1253. if (ev.Y > maxCursorPositionableLine) {
  1254. currentRow = maxCursorPositionableLine;
  1255. } else {
  1256. currentRow = ev.Y + topRow;
  1257. }
  1258. var r = GetCurrentLine ();
  1259. var idx = TextModel.GetColFromX (r, leftColumn, ev.X);
  1260. if (idx - leftColumn >= r.Count) {
  1261. currentColumn = r.Count - leftColumn;
  1262. } else {
  1263. currentColumn = idx + leftColumn;
  1264. }
  1265. }
  1266. PositionCursor ();
  1267. } else if (ev.Flags == MouseFlags.WheeledDown) {
  1268. lastWasKill = false;
  1269. columnTrack = currentColumn;
  1270. ScrollTo (topRow + 1);
  1271. } else if (ev.Flags == MouseFlags.WheeledUp) {
  1272. lastWasKill = false;
  1273. columnTrack = currentColumn;
  1274. ScrollTo (topRow - 1);
  1275. } else if (ev.Flags == MouseFlags.WheeledRight) {
  1276. lastWasKill = false;
  1277. columnTrack = currentColumn;
  1278. ScrollTo (leftColumn + 1, false);
  1279. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  1280. lastWasKill = false;
  1281. columnTrack = currentColumn;
  1282. ScrollTo (leftColumn - 1, false);
  1283. }
  1284. return true;
  1285. }
  1286. }
  1287. }