TextView.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184
  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. // ASCII code 10 = Line Feed.
  75. for (; i < content.Length; i++) {
  76. if (content [i] == 10) {
  77. if (i - start > 0)
  78. lines.Add (ToRunes (content [start, i]));
  79. else
  80. lines.Add (ToRunes (ustring.Empty));
  81. start = i + 1;
  82. }
  83. }
  84. if (i - start >= 0)
  85. lines.Add (ToRunes (content [start, null]));
  86. return lines;
  87. }
  88. void Append (List<byte> line)
  89. {
  90. var str = ustring.Make (line.ToArray ());
  91. lines.Add (ToRunes (str));
  92. }
  93. public void LoadStream (Stream input)
  94. {
  95. if (input == null)
  96. throw new ArgumentNullException (nameof (input));
  97. lines = new List<List<Rune>> ();
  98. var buff = new BufferedStream (input);
  99. int v;
  100. var line = new List<byte> ();
  101. while ((v = buff.ReadByte ()) != -1) {
  102. if (v == 10) {
  103. Append (line);
  104. line.Clear ();
  105. continue;
  106. }
  107. line.Add ((byte)v);
  108. }
  109. if (line.Count > 0)
  110. Append (line);
  111. }
  112. public void LoadString (ustring content)
  113. {
  114. lines = StringToRunes (content);
  115. }
  116. public override string ToString ()
  117. {
  118. var sb = new StringBuilder ();
  119. for (int i = 0; i < lines.Count; i++) {
  120. sb.Append (ustring.Make (lines [i]));
  121. if ((i + 1) < lines.Count) {
  122. sb.AppendLine ();
  123. }
  124. }
  125. return sb.ToString ();
  126. }
  127. public string FilePath { get; set; }
  128. /// <summary>
  129. /// The number of text lines in the model
  130. /// </summary>
  131. public int Count => lines.Count;
  132. /// <summary>
  133. /// Returns the specified line as a List of Rune
  134. /// </summary>
  135. /// <returns>The line.</returns>
  136. /// <param name="line">Line number to retrieve.</param>
  137. public List<Rune> GetLine (int line)
  138. {
  139. if (lines.Count > 0) {
  140. if (line < Count) {
  141. return lines [line];
  142. } else {
  143. return lines [Count - 1];
  144. }
  145. } else {
  146. lines.Add (new List<Rune> ());
  147. return lines [0];
  148. }
  149. }
  150. /// <summary>
  151. /// Adds a line to the model at the specified position.
  152. /// </summary>
  153. /// <param name="pos">Line number where the line will be inserted.</param>
  154. /// <param name="runes">The line of text, as a List of Rune.</param>
  155. public void AddLine (int pos, List<Rune> runes)
  156. {
  157. lines.Insert (pos, runes);
  158. }
  159. /// <summary>
  160. /// Removes the line at the specified position
  161. /// </summary>
  162. /// <param name="pos">Position.</param>
  163. public void RemoveLine (int pos)
  164. {
  165. if (lines.Count > 0) {
  166. lines.RemoveAt (pos);
  167. }
  168. }
  169. /// <summary>
  170. /// Returns the maximum line length of the visible lines.
  171. /// </summary>
  172. /// <param name="first">The first line.</param>
  173. /// <param name="last">The last line.</param>
  174. public int GetMaxVisibleLine (int first, int last)
  175. {
  176. int maxLength = 0;
  177. last = last < lines.Count ? last : lines.Count;
  178. for (int i = first; i < last; i++) {
  179. var l = GetLine (i).Count;
  180. if (l > maxLength) {
  181. maxLength = l;
  182. }
  183. }
  184. return maxLength;
  185. }
  186. internal static int SetCol (int col, int width, int cols)
  187. {
  188. if (col + cols <= width) {
  189. col += cols;
  190. }
  191. return col;
  192. }
  193. internal static int GetColFromX (List<Rune> t, int start, int x)
  194. {
  195. if (x < 0) {
  196. return x;
  197. }
  198. int size = start;
  199. var pX = x + start;
  200. for (int i = start; i < t.Count; i++) {
  201. var r = t [i];
  202. size += Rune.ColumnWidth (r);
  203. if (i == pX || (size > pX)) {
  204. return i - start;
  205. }
  206. }
  207. return t.Count - start;
  208. }
  209. // Returns the size and length in a range of the string.
  210. internal static (int size, int length) DisplaySize (List<Rune> t, int start = -1, int end = -1, bool checkNextRune = true)
  211. {
  212. if (t == null || t.Count == 0) {
  213. return (0, 0);
  214. }
  215. int size = 0;
  216. int len = 0;
  217. int tcount = end == -1 ? t.Count : end > t.Count ? t.Count : end;
  218. int i = start == -1 ? 0 : start;
  219. for (; i < tcount; i++) {
  220. var rune = t [i];
  221. size += Rune.ColumnWidth (rune);
  222. len += Rune.RuneLen (rune);
  223. if (checkNextRune && i == tcount - 1 && t.Count > tcount && Rune.ColumnWidth (t [i + 1]) > 1) {
  224. size += Rune.ColumnWidth (t [i + 1]);
  225. len += Rune.RuneLen (t [i + 1]);
  226. }
  227. }
  228. return (size, len);
  229. }
  230. // Returns the left column in a range of the string.
  231. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int currentColumn)
  232. {
  233. if (t == null) {
  234. return 0;
  235. }
  236. (var dSize, _) = TextModel.DisplaySize (t, start, end);
  237. if (dSize < width) {
  238. return start;
  239. }
  240. int size = 0;
  241. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  242. int col = 0;
  243. for (int i = tcount; i > start; i--) {
  244. var rune = t [i];
  245. var s = Rune.ColumnWidth (rune);
  246. size += s;
  247. if (size >= dSize - width) {
  248. col = tcount - i + start;
  249. if (start == 0 || col == start || (currentColumn == t.Count && (currentColumn - col > width))) {
  250. col++;
  251. }
  252. break;
  253. }
  254. }
  255. return col;
  256. }
  257. }
  258. class WordWrapManager {
  259. class WrappedLine {
  260. public int ModelLine;
  261. public int Row;
  262. public int RowIndex;
  263. public int ColWidth;
  264. }
  265. List<WrappedLine> wrappedModelLines = new List<WrappedLine> ();
  266. int frameWidth;
  267. bool isWrapModelRefreshing;
  268. public TextModel Model { get; private set; }
  269. public WordWrapManager (TextModel model)
  270. {
  271. Model = model;
  272. }
  273. public TextModel WrapModel (int width, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  274. int row = 0, int col = 0, int startRow = 0, int startCol = 0)
  275. {
  276. frameWidth = width;
  277. var modelRow = isWrapModelRefreshing ? row : GetModelLineFromWrappedLines (row);
  278. var modelCol = isWrapModelRefreshing ? col : GetModelColFromWrappedLines (row, col);
  279. var modelStartRow = isWrapModelRefreshing ? startRow : GetModelLineFromWrappedLines (startRow);
  280. var modelStartCol = isWrapModelRefreshing ? startCol : GetModelColFromWrappedLines (startRow, startCol);
  281. var wrappedModel = new TextModel ();
  282. int lines = 0;
  283. nRow = 0;
  284. nCol = 0;
  285. nStartRow = 0;
  286. nStartCol = 0;
  287. bool isRowAndColSetted = row == 0 && col == 0;
  288. bool isStartRowAndColSetted = startRow == 0 && startCol == 0;
  289. List<WrappedLine> wModelLines = new List<WrappedLine> ();
  290. for (int i = 0; i < Model.Count; i++) {
  291. var line = Model.GetLine (i);
  292. var wrappedLines = ToListRune (
  293. TextFormatter.Format (ustring.Make (line), width, TextAlignment.Left, true, true));
  294. int sumColWidth = 0;
  295. for (int j = 0; j < wrappedLines.Count; j++) {
  296. var wrapLine = wrappedLines [j];
  297. if (!isRowAndColSetted && modelRow == i) {
  298. if (nCol + wrapLine.Count <= modelCol) {
  299. nCol += wrapLine.Count;
  300. nRow = lines;
  301. if (nCol == modelCol) {
  302. nCol = wrapLine.Count;
  303. isRowAndColSetted = true;
  304. } else if (j == wrappedLines.Count - 1) {
  305. nCol = wrapLine.Count - j + modelCol - nCol;
  306. isRowAndColSetted = true;
  307. }
  308. } else {
  309. var offset = nCol + wrapLine.Count - modelCol;
  310. nCol = wrapLine.Count - offset;
  311. nRow = lines;
  312. isRowAndColSetted = true;
  313. }
  314. }
  315. if (!isStartRowAndColSetted && modelStartRow == i) {
  316. if (nStartCol + wrapLine.Count <= modelStartCol) {
  317. nStartCol += wrapLine.Count;
  318. nStartRow = lines;
  319. if (nStartCol == modelStartCol) {
  320. nStartCol = wrapLine.Count;
  321. isStartRowAndColSetted = true;
  322. } else if (j == wrappedLines.Count - 1) {
  323. nStartCol = wrapLine.Count - j + modelStartCol - nStartCol;
  324. isStartRowAndColSetted = true;
  325. }
  326. } else {
  327. var offset = nStartCol + wrapLine.Count - modelStartCol;
  328. nStartCol = wrapLine.Count - offset;
  329. nStartRow = lines;
  330. isStartRowAndColSetted = true;
  331. }
  332. }
  333. wrappedModel.AddLine (lines, wrapLine);
  334. sumColWidth += wrapLine.Count;
  335. var wrappedLine = new WrappedLine () {
  336. ModelLine = i,
  337. Row = lines,
  338. RowIndex = j,
  339. ColWidth = wrapLine.Count,
  340. };
  341. wModelLines.Add (wrappedLine);
  342. lines++;
  343. }
  344. }
  345. wrappedModelLines = wModelLines;
  346. return wrappedModel;
  347. }
  348. public List<List<Rune>> ToListRune (List<ustring> textList)
  349. {
  350. var runesList = new List<List<Rune>> ();
  351. foreach (var text in textList) {
  352. runesList.Add (text.ToRuneList ());
  353. }
  354. return runesList;
  355. }
  356. public int GetModelLineFromWrappedLines (int line) => wrappedModelLines.Count > 0
  357. ? wrappedModelLines [Math.Min (line, wrappedModelLines.Count - 1)].ModelLine
  358. : 0;
  359. public int GetModelColFromWrappedLines (int line, int col)
  360. {
  361. if (wrappedModelLines?.Count == 0) {
  362. return 0;
  363. }
  364. var modelLine = GetModelLineFromWrappedLines (line);
  365. var firstLine = wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  366. int modelCol = 0;
  367. for (int i = firstLine; i <= line; i++) {
  368. var wLine = wrappedModelLines [i];
  369. if (i < line) {
  370. modelCol += wLine.ColWidth;
  371. } else {
  372. modelCol += col;
  373. }
  374. }
  375. return modelCol;
  376. }
  377. List<Rune> GetCurrentLine (int row) => Model.GetLine (row);
  378. public void AddLine (int row, int col)
  379. {
  380. var modelRow = GetModelLineFromWrappedLines (row);
  381. var modelCol = GetModelColFromWrappedLines (row, col);
  382. var line = GetCurrentLine (modelRow);
  383. var restCount = line.Count - modelCol;
  384. var rest = line.GetRange (modelCol, restCount);
  385. line.RemoveRange (modelCol, restCount);
  386. Model.AddLine (modelRow + 1, rest);
  387. isWrapModelRefreshing = true;
  388. WrapModel (frameWidth, out _, out _, out _, out _, modelRow + 1, 0);
  389. isWrapModelRefreshing = false;
  390. }
  391. public bool Insert (int row, int col, Rune rune)
  392. {
  393. var line = GetCurrentLine (GetModelLineFromWrappedLines (row));
  394. line.Insert (GetModelColFromWrappedLines (row, col), rune);
  395. if (line.Count > frameWidth) {
  396. return true;
  397. } else {
  398. return false;
  399. }
  400. }
  401. public bool RemoveAt (int row, int col)
  402. {
  403. var modelRow = GetModelLineFromWrappedLines (row);
  404. var line = GetCurrentLine (modelRow);
  405. var modelCol = GetModelColFromWrappedLines (row, col);
  406. if (modelCol >= line.Count) {
  407. Model.RemoveLine (modelRow);
  408. RemoveAt (row, 0);
  409. return false;
  410. }
  411. line.RemoveAt (modelCol);
  412. if (line.Count > frameWidth || (row + 1 < wrappedModelLines.Count
  413. && wrappedModelLines [row + 1].ModelLine == modelRow)) {
  414. return true;
  415. }
  416. return false;
  417. }
  418. public bool RemoveLine (int row, int col, out bool lineRemoved, bool forward = true)
  419. {
  420. lineRemoved = false;
  421. var modelRow = GetModelLineFromWrappedLines (row);
  422. var line = GetCurrentLine (modelRow);
  423. var modelCol = GetModelColFromWrappedLines (row, col);
  424. if (modelCol == 0 && line.Count == 0) {
  425. Model.RemoveLine (modelRow);
  426. return false;
  427. } else if (modelCol < line.Count) {
  428. if (forward) {
  429. line.RemoveAt (modelCol);
  430. return true;
  431. } else if (modelCol - 1 > -1) {
  432. line.RemoveAt (modelCol - 1);
  433. return true;
  434. }
  435. }
  436. lineRemoved = true;
  437. if (forward) {
  438. if (modelRow + 1 == Model.Count) {
  439. return false;
  440. }
  441. var nextLine = Model.GetLine (modelRow + 1);
  442. line.AddRange (nextLine);
  443. Model.RemoveLine (modelRow + 1);
  444. if (line.Count > frameWidth) {
  445. return true;
  446. }
  447. } else {
  448. if (modelRow == 0) {
  449. return false;
  450. }
  451. var prevLine = Model.GetLine (modelRow - 1);
  452. prevLine.AddRange (line);
  453. Model.RemoveLine (modelRow);
  454. if (prevLine.Count > frameWidth) {
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. public void UpdateModel (TextModel model, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  461. int row, int col, int startRow, int startCol)
  462. {
  463. isWrapModelRefreshing = true;
  464. Model = model;
  465. WrapModel (frameWidth, out nRow, out nCol, out nStartRow, out nStartCol, row, col, startRow, startCol);
  466. isWrapModelRefreshing = false;
  467. }
  468. }
  469. /// <summary>
  470. /// Multi-line text editing <see cref="View"/>
  471. /// </summary>
  472. /// <remarks>
  473. /// <para>
  474. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  475. /// with it with the standard Emacs commands for movement or the arrow
  476. /// keys.
  477. /// </para>
  478. /// <list type="table">
  479. /// <listheader>
  480. /// <term>Shortcut</term>
  481. /// <description>Action performed</description>
  482. /// </listheader>
  483. /// <item>
  484. /// <term>Left cursor, Control-b</term>
  485. /// <description>
  486. /// Moves the editing point left.
  487. /// </description>
  488. /// </item>
  489. /// <item>
  490. /// <term>Right cursor, Control-f</term>
  491. /// <description>
  492. /// Moves the editing point right.
  493. /// </description>
  494. /// </item>
  495. /// <item>
  496. /// <term>Alt-b</term>
  497. /// <description>
  498. /// Moves one word back.
  499. /// </description>
  500. /// </item>
  501. /// <item>
  502. /// <term>Alt-f</term>
  503. /// <description>
  504. /// Moves one word forward.
  505. /// </description>
  506. /// </item>
  507. /// <item>
  508. /// <term>Up cursor, Control-p</term>
  509. /// <description>
  510. /// Moves the editing point one line up.
  511. /// </description>
  512. /// </item>
  513. /// <item>
  514. /// <term>Down cursor, Control-n</term>
  515. /// <description>
  516. /// Moves the editing point one line down
  517. /// </description>
  518. /// </item>
  519. /// <item>
  520. /// <term>Home key, Control-a</term>
  521. /// <description>
  522. /// Moves the cursor to the beginning of the line.
  523. /// </description>
  524. /// </item>
  525. /// <item>
  526. /// <term>End key, Control-e</term>
  527. /// <description>
  528. /// Moves the cursor to the end of the line.
  529. /// </description>
  530. /// </item>
  531. /// <item>
  532. /// <term>Control-Home</term>
  533. /// <description>
  534. /// Scrolls to the first line and moves the cursor there.
  535. /// </description>
  536. /// </item>
  537. /// <item>
  538. /// <term>Control-End</term>
  539. /// <description>
  540. /// Scrolls to the last line and moves the cursor there.
  541. /// </description>
  542. /// </item>
  543. /// <item>
  544. /// <term>Delete, Control-d</term>
  545. /// <description>
  546. /// Deletes the character in front of the cursor.
  547. /// </description>
  548. /// </item>
  549. /// <item>
  550. /// <term>Backspace</term>
  551. /// <description>
  552. /// Deletes the character behind the cursor.
  553. /// </description>
  554. /// </item>
  555. /// <item>
  556. /// <term>Control-k</term>
  557. /// <description>
  558. /// Deletes the text until the end of the line and replaces the kill buffer
  559. /// with the deleted text. You can paste this text in a different place by
  560. /// using Control-y.
  561. /// </description>
  562. /// </item>
  563. /// <item>
  564. /// <term>Control-y</term>
  565. /// <description>
  566. /// Pastes the content of the kill ring into the current position.
  567. /// </description>
  568. /// </item>
  569. /// <item>
  570. /// <term>Alt-d</term>
  571. /// <description>
  572. /// Deletes the word above the cursor and adds it to the kill ring. You
  573. /// can paste the contents of the kill ring with Control-y.
  574. /// </description>
  575. /// </item>
  576. /// <item>
  577. /// <term>Control-q</term>
  578. /// <description>
  579. /// Quotes the next input character, to prevent the normal processing of
  580. /// key handling to take place.
  581. /// </description>
  582. /// </item>
  583. /// </list>
  584. /// </remarks>
  585. public class TextView : View {
  586. TextModel model = new TextModel ();
  587. int topRow;
  588. int leftColumn;
  589. int currentRow;
  590. int currentColumn;
  591. int selectionStartColumn, selectionStartRow;
  592. bool selecting;
  593. //bool used;
  594. bool wordWrap;
  595. WordWrapManager wrapManager;
  596. /// <summary>
  597. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  598. /// </summary>
  599. public event Action TextChanged;
  600. #if false
  601. /// <summary>
  602. /// Changed event, raised when the text has clicked.
  603. /// </summary>
  604. /// <remarks>
  605. /// Client code can hook up to this event, it is
  606. /// raised when the text in the entry changes.
  607. /// </remarks>
  608. public Action Changed;
  609. #endif
  610. /// <summary>
  611. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  612. /// </summary>
  613. /// <remarks>
  614. /// </remarks>
  615. public TextView (Rect frame) : base (frame)
  616. {
  617. CanFocus = true;
  618. }
  619. /// <summary>
  620. /// Initializes a <see cref="TextView"/> on the specified area,
  621. /// with dimensions controlled with the X, Y, Width and Height properties.
  622. /// </summary>
  623. public TextView () : base ()
  624. {
  625. CanFocus = true;
  626. }
  627. void ResetPosition ()
  628. {
  629. topRow = leftColumn = currentRow = currentColumn = 0;
  630. selecting = false;
  631. shiftSelecting = false;
  632. ResetCursorVisibility ();
  633. }
  634. /// <summary>
  635. /// Sets or gets the text in the <see cref="TextView"/>.
  636. /// </summary>
  637. /// <remarks>
  638. /// </remarks>
  639. public override ustring Text {
  640. get {
  641. if (wordWrap) {
  642. return wrapManager.Model.ToString ();
  643. } else {
  644. return model.ToString ();
  645. }
  646. }
  647. set {
  648. ResetPosition ();
  649. model.LoadString (value);
  650. if (wordWrap) {
  651. wrapManager = new WordWrapManager (model);
  652. model = wrapManager.WrapModel (Frame.Width - 2, out _, out _, out _, out _);
  653. }
  654. TextChanged?.Invoke ();
  655. SetNeedsDisplay ();
  656. }
  657. }
  658. ///<inheritdoc/>
  659. public override Rect Frame {
  660. get => base.Frame;
  661. set {
  662. base.Frame = value;
  663. WrapTextModel ();
  664. Adjust ();
  665. }
  666. }
  667. void WrapTextModel ()
  668. {
  669. if (wordWrap && wrapManager != null) {
  670. model = wrapManager.WrapModel (Frame.Width - 2,
  671. out int nRow, out int nCol,
  672. out int nStartRow, out int nStartCol,
  673. currentRow, currentColumn,
  674. selectionStartRow, selectionStartColumn);
  675. currentRow = nRow;
  676. currentColumn = nCol;
  677. selectionStartRow = nStartRow;
  678. selectionStartColumn = nStartCol;
  679. SetNeedsDisplay ();
  680. }
  681. }
  682. /// <summary>
  683. /// Gets or sets the top row.
  684. /// </summary>
  685. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  686. /// <summary>
  687. /// Gets or sets the left column.
  688. /// </summary>
  689. public int LeftColumn { get => leftColumn; set => leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0); }
  690. /// <summary>
  691. /// Gets the maximum visible length line.
  692. /// </summary>
  693. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height);
  694. /// <summary>
  695. /// Gets the number of lines.
  696. /// </summary>
  697. public int Lines => model.Count;
  698. /// <summary>
  699. /// Allows word wrap the to fit the available container width.
  700. /// </summary>
  701. public bool WordWrap {
  702. get => wordWrap;
  703. set {
  704. if (value == wordWrap) {
  705. return;
  706. }
  707. wordWrap = value;
  708. ResetPosition ();
  709. if (wordWrap) {
  710. wrapManager = new WordWrapManager (model);
  711. model = wrapManager.WrapModel (Math.Max (Frame.Width - 2, 0), out _, out _, out _, out _);
  712. } else if (!wordWrap && wrapManager != null) {
  713. model = wrapManager.Model;
  714. }
  715. SetNeedsDisplay ();
  716. }
  717. }
  718. /// <summary>
  719. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  720. /// This is only needed with the keyboard navigation.
  721. /// </summary>
  722. public int BottomOffset { get; set; }
  723. /// <summary>
  724. /// The right offset needed to use a vertical scrollbar or for another reason.
  725. /// This is only needed with the keyboard navigation.
  726. /// </summary>
  727. public int RightOffset { get; set; }
  728. CursorVisibility savedCursorVisibility = CursorVisibility.Default;
  729. void SaveCursorVisibility ()
  730. {
  731. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  732. savedCursorVisibility = desiredCursorVisibility;
  733. DesiredCursorVisibility = CursorVisibility.Invisible;
  734. }
  735. }
  736. void ResetCursorVisibility ()
  737. {
  738. if (savedCursorVisibility != desiredCursorVisibility) {
  739. DesiredCursorVisibility = savedCursorVisibility;
  740. savedCursorVisibility = CursorVisibility.Default;
  741. } else {
  742. DesiredCursorVisibility = CursorVisibility.Underline;
  743. }
  744. }
  745. /// <summary>
  746. /// Loads the contents of the file into the <see cref="TextView"/>.
  747. /// </summary>
  748. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  749. /// <param name="path">Path to the file to load.</param>
  750. public bool LoadFile (string path)
  751. {
  752. if (path == null)
  753. throw new ArgumentNullException (nameof (path));
  754. ResetPosition ();
  755. var res = model.LoadFile (path);
  756. SetNeedsDisplay ();
  757. return res;
  758. }
  759. /// <summary>
  760. /// Loads the contents of the stream into the <see cref="TextView"/>.
  761. /// </summary>
  762. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  763. /// <param name="stream">Stream to load the contents from.</param>
  764. public void LoadStream (Stream stream)
  765. {
  766. if (stream == null)
  767. throw new ArgumentNullException (nameof (stream));
  768. ResetPosition ();
  769. model.LoadStream (stream);
  770. SetNeedsDisplay ();
  771. }
  772. /// <summary>
  773. /// Closes the contents of the stream into the <see cref="TextView"/>.
  774. /// </summary>
  775. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  776. public bool CloseFile ()
  777. {
  778. ResetPosition ();
  779. var res = model.CloseFile ();
  780. SetNeedsDisplay ();
  781. return res;
  782. }
  783. /// <summary>
  784. /// Gets the current cursor row.
  785. /// </summary>
  786. public int CurrentRow => currentRow;
  787. /// <summary>
  788. /// Gets the cursor column.
  789. /// </summary>
  790. /// <value>The cursor column.</value>
  791. public int CurrentColumn => currentColumn;
  792. /// <summary>
  793. /// Positions the cursor on the current row and column
  794. /// </summary>
  795. public override void PositionCursor ()
  796. {
  797. if (selecting) {
  798. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  799. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  800. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  801. }
  802. var line = model.GetLine (currentRow);
  803. var retreat = 0;
  804. var col = 0;
  805. if (line.Count > 0) {
  806. retreat = Math.Max (SpecialRune (line [Math.Min (Math.Max (currentColumn - leftColumn - 1, 0), line.Count - 1)])
  807. ? 1 : 0, 0);
  808. for (int idx = leftColumn < 0 ? 0 : leftColumn; idx < line.Count; idx++) {
  809. if (idx == currentColumn)
  810. break;
  811. var cols = Rune.ColumnWidth (line [idx]);
  812. col += cols - 1;
  813. }
  814. }
  815. var ccol = currentColumn - leftColumn - retreat + col;
  816. if (leftColumn <= currentColumn && ccol < Frame.Width
  817. && topRow <= currentRow && currentRow - topRow < Frame.Height) {
  818. ResetCursorVisibility ();
  819. Move (ccol, currentRow - topRow);
  820. } else {
  821. SaveCursorVisibility ();
  822. }
  823. }
  824. void ClearRegion (int left, int top, int right, int bottom)
  825. {
  826. for (int row = top; row < bottom; row++) {
  827. Move (left, row);
  828. for (int col = left; col < right; col++)
  829. AddRune (col, row, ' ');
  830. }
  831. }
  832. void ColorNormal ()
  833. {
  834. Driver.SetAttribute (ColorScheme.Normal);
  835. }
  836. void ColorSelection ()
  837. {
  838. Driver.SetAttribute (ColorScheme.Focus);
  839. }
  840. bool isReadOnly = false;
  841. /// <summary>
  842. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  843. /// </summary>
  844. /// <value>Boolean value(Default false)</value>
  845. public bool ReadOnly {
  846. get => isReadOnly;
  847. set {
  848. isReadOnly = value;
  849. }
  850. }
  851. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  852. /// <summary>
  853. /// Get / Set the wished cursor when the field is focused
  854. /// </summary>
  855. public CursorVisibility DesiredCursorVisibility {
  856. get => desiredCursorVisibility;
  857. set {
  858. if (desiredCursorVisibility != value && HasFocus) {
  859. Application.Driver.SetCursorVisibility (value);
  860. }
  861. desiredCursorVisibility = value;
  862. }
  863. }
  864. ///<inheritdoc/>
  865. public override bool OnEnter (View view)
  866. {
  867. //TODO: Improve it by handling read only mode of the text field
  868. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  869. return base.OnEnter (view);
  870. }
  871. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  872. void GetEncodedRegionBounds (out long start, out long end)
  873. {
  874. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  875. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  876. if (selection > point) {
  877. start = point;
  878. end = selection;
  879. } else {
  880. start = selection;
  881. end = point;
  882. }
  883. }
  884. bool PointInSelection (int col, int row)
  885. {
  886. long start, end;
  887. GetEncodedRegionBounds (out start, out end);
  888. var q = ((long)(uint)row << 32) | (uint)col;
  889. return q >= start && q <= end - 1;
  890. }
  891. //
  892. // Returns a ustring with the text in the selected
  893. // region.
  894. //
  895. ustring GetRegion ()
  896. {
  897. long start, end;
  898. GetEncodedRegionBounds (out start, out end);
  899. if (start == end) {
  900. return ustring.Empty;
  901. }
  902. int startRow = (int)(start >> 32);
  903. var maxrow = ((int)(end >> 32));
  904. int startCol = (int)(start & 0xffffffff);
  905. var endCol = (int)(end & 0xffffffff);
  906. var line = model.GetLine (startRow);
  907. if (startRow == maxrow)
  908. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  909. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  910. for (int row = startRow + 1; row < maxrow; row++) {
  911. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  912. }
  913. line = model.GetLine (maxrow);
  914. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  915. return res;
  916. }
  917. //
  918. // Clears the contents of the selected region
  919. //
  920. void ClearRegion ()
  921. {
  922. long start, end;
  923. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  924. GetEncodedRegionBounds (out start, out end);
  925. int startRow = (int)(start >> 32);
  926. var maxrow = ((int)(end >> 32));
  927. int startCol = (int)(start & 0xffffffff);
  928. var endCol = (int)(end & 0xffffffff);
  929. var line = model.GetLine (startRow);
  930. if (startRow == maxrow) {
  931. line.RemoveRange (startCol, endCol - startCol);
  932. currentColumn = startCol;
  933. if (wordWrap) {
  934. SetNeedsDisplay ();
  935. } else {
  936. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  937. }
  938. return;
  939. }
  940. line.RemoveRange (startCol, line.Count - startCol);
  941. var line2 = model.GetLine (maxrow);
  942. line.AddRange (line2.Skip (endCol));
  943. for (int row = startRow + 1; row <= maxrow; row++) {
  944. model.RemoveLine (startRow + 1);
  945. }
  946. if (currentEncoded == end) {
  947. currentRow -= maxrow - (startRow);
  948. }
  949. currentColumn = startCol;
  950. SetNeedsDisplay ();
  951. }
  952. /// <summary>
  953. /// Restore from original model.
  954. /// </summary>
  955. void SetWrapModel ()
  956. {
  957. if (wordWrap) {
  958. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  959. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  960. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  961. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  962. model = wrapManager.Model;
  963. }
  964. }
  965. /// <summary>
  966. /// Update the original model.
  967. /// </summary>
  968. void UpdateWrapModel ()
  969. {
  970. if (wordWrap) {
  971. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  972. out int nStartRow, out int nStartCol,
  973. currentRow, currentColumn,
  974. selectionStartRow, selectionStartColumn);
  975. currentRow = nRow;
  976. currentColumn = nCol;
  977. selectionStartRow = nStartRow;
  978. selectionStartColumn = nStartCol;
  979. wrapNeeded = true;
  980. }
  981. }
  982. ///<inheritdoc/>
  983. public override void Redraw (Rect bounds)
  984. {
  985. ColorNormal ();
  986. int bottom = bounds.Bottom;
  987. int right = bounds.Right + 1;
  988. for (int row = bounds.Top; row < bottom; row++) {
  989. int textLine = topRow + row;
  990. if (textLine >= model.Count) {
  991. ColorNormal ();
  992. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  993. continue;
  994. }
  995. var line = model.GetLine (textLine);
  996. int lineRuneCount = line.Count;
  997. if (line.Count < bounds.Left) {
  998. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  999. continue;
  1000. }
  1001. Move (bounds.Left, row);
  1002. var col = 0;
  1003. for (int idx = bounds.Left; idx < right; idx++) {
  1004. var lineCol = leftColumn + idx;
  1005. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  1006. var cols = Rune.ColumnWidth (rune);
  1007. if (lineCol < line.Count && selecting && PointInSelection (idx + leftColumn, row + topRow)) {
  1008. ColorSelection ();
  1009. } else {
  1010. ColorNormal ();
  1011. }
  1012. if (!SpecialRune (rune)) {
  1013. AddRune (col, row, rune);
  1014. }
  1015. col = TextModel.SetCol (col, bounds.Right, cols);
  1016. }
  1017. }
  1018. PositionCursor ();
  1019. }
  1020. bool SpecialRune (Rune rune)
  1021. {
  1022. switch (rune) {
  1023. case (uint)Key.Enter:
  1024. case 0xd:
  1025. return true;
  1026. default:
  1027. return false;
  1028. }
  1029. }
  1030. ///<inheritdoc/>
  1031. public override bool CanFocus {
  1032. get => base.CanFocus;
  1033. set { base.CanFocus = value; }
  1034. }
  1035. void SetClipboard (ustring text)
  1036. {
  1037. if (!text.IsEmpty) {
  1038. Clipboard.Contents = text;
  1039. }
  1040. }
  1041. void AppendClipboard (ustring text)
  1042. {
  1043. Clipboard.Contents += text;
  1044. }
  1045. void Insert (Rune rune)
  1046. {
  1047. var line = GetCurrentLine ();
  1048. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1049. if (wordWrap) {
  1050. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1051. if (wrapNeeded) {
  1052. SetNeedsDisplay ();
  1053. }
  1054. }
  1055. var prow = currentRow - topRow;
  1056. if (!wrapNeeded) {
  1057. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  1058. }
  1059. }
  1060. ustring StringFromRunes (List<Rune> runes)
  1061. {
  1062. if (runes == null)
  1063. throw new ArgumentNullException (nameof (runes));
  1064. int size = 0;
  1065. foreach (var rune in runes) {
  1066. size += Utf8.RuneLen (rune);
  1067. }
  1068. var encoded = new byte [size];
  1069. int offset = 0;
  1070. foreach (var rune in runes) {
  1071. offset += Utf8.EncodeRune (rune, encoded, offset);
  1072. }
  1073. return ustring.Make (encoded);
  1074. }
  1075. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  1076. void InsertText (ustring text)
  1077. {
  1078. if (ustring.IsNullOrEmpty (text)) {
  1079. return;
  1080. }
  1081. var lines = TextModel.StringToRunes (text);
  1082. if (lines.Count == 0) {
  1083. return;
  1084. }
  1085. var line = GetCurrentLine ();
  1086. // Optimize single line
  1087. if (lines.Count == 1) {
  1088. line.InsertRange (currentColumn, lines [0]);
  1089. currentColumn += lines [0].Count;
  1090. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  1091. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  1092. }
  1093. if (wordWrap) {
  1094. SetNeedsDisplay ();
  1095. } else {
  1096. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  1097. }
  1098. return;
  1099. }
  1100. List<Rune> rest = null;
  1101. int lastp = 0;
  1102. if (model.Count > 0 && currentColumn > 0) {
  1103. // Keep a copy of the rest of the line
  1104. var restCount = line.Count - currentColumn;
  1105. rest = line.GetRange (currentColumn, restCount);
  1106. line.RemoveRange (currentColumn, restCount);
  1107. }
  1108. // First line is inserted at the current location, the rest is appended
  1109. line.InsertRange (currentColumn, lines [0]);
  1110. //model.AddLine (currentRow, lines [0]);
  1111. for (int i = 1; i < lines.Count; i++) {
  1112. model.AddLine (currentRow + i, lines [i]);
  1113. }
  1114. if (rest != null) {
  1115. var last = model.GetLine (currentRow + lines.Count - 1);
  1116. lastp = last.Count;
  1117. last.InsertRange (last.Count, rest);
  1118. }
  1119. // Now adjust column and row positions
  1120. currentRow += lines.Count - 1;
  1121. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  1122. Adjust ();
  1123. }
  1124. // The column we are tracking, or -1 if we are not tracking any column
  1125. int columnTrack = -1;
  1126. // Tries to snap the cursor to the tracking column
  1127. void TrackColumn ()
  1128. {
  1129. // Now track the column
  1130. var line = GetCurrentLine ();
  1131. if (line.Count < columnTrack)
  1132. currentColumn = line.Count;
  1133. else if (columnTrack != -1)
  1134. currentColumn = columnTrack;
  1135. else if (currentColumn > line.Count)
  1136. currentColumn = line.Count;
  1137. Adjust ();
  1138. }
  1139. void Adjust ()
  1140. {
  1141. var offB = OffSetBackground ();
  1142. var line = GetCurrentLine ();
  1143. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  1144. if (!wordWrap && currentColumn < leftColumn) {
  1145. leftColumn = currentColumn;
  1146. need = true;
  1147. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width ||
  1148. TextModel.DisplaySize (line, leftColumn, currentColumn).size + RightOffset >= Frame.Width + offB.width)) {
  1149. leftColumn = Math.Max (TextModel.CalculateLeftColumn (line, leftColumn,
  1150. currentColumn + RightOffset, Frame.Width - 1 + offB.width, currentColumn), 0);
  1151. need = true;
  1152. }
  1153. if (currentRow < topRow) {
  1154. topRow = currentRow;
  1155. need = true;
  1156. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  1157. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  1158. need = true;
  1159. }
  1160. if (need) {
  1161. if (wrapNeeded) {
  1162. WrapTextModel ();
  1163. wrapNeeded = false;
  1164. }
  1165. SetNeedsDisplay ();
  1166. } else {
  1167. PositionCursor ();
  1168. }
  1169. }
  1170. (int width, int height) OffSetBackground ()
  1171. {
  1172. int w = 0;
  1173. int h = 0;
  1174. if (SuperView?.Frame.Right - Frame.Right < 0) {
  1175. w = SuperView.Frame.Right - Frame.Right - 1;
  1176. }
  1177. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  1178. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  1179. }
  1180. return (w, h);
  1181. }
  1182. /// <summary>
  1183. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  1184. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  1185. /// </summary>
  1186. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  1187. /// if the value is negative it will be reset to zero</param>
  1188. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  1189. public void ScrollTo (int idx, bool isRow = true)
  1190. {
  1191. if (idx < 0) {
  1192. idx = 0;
  1193. }
  1194. if (isRow) {
  1195. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  1196. } else if (!wordWrap) {
  1197. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset);
  1198. leftColumn = Math.Max (idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  1199. }
  1200. SetNeedsDisplay ();
  1201. }
  1202. bool lastWasKill;
  1203. bool wrapNeeded;
  1204. bool shiftSelecting;
  1205. ///<inheritdoc/>
  1206. public override bool ProcessKey (KeyEvent kb)
  1207. {
  1208. int restCount;
  1209. List<Rune> rest;
  1210. bool lineRemoved = false;
  1211. // Handle some state here - whether the last command was a kill
  1212. // operation and the column tracking (up/down)
  1213. switch (kb.Key) {
  1214. case Key.N | Key.CtrlMask:
  1215. case Key.CursorDown:
  1216. case Key.P | Key.CtrlMask:
  1217. case Key.CursorUp:
  1218. lastWasKill = false;
  1219. break;
  1220. case Key.K | Key.CtrlMask:
  1221. break;
  1222. default:
  1223. lastWasKill = false;
  1224. columnTrack = -1;
  1225. break;
  1226. }
  1227. // Dispatch the command.
  1228. switch (kb.Key) {
  1229. case Key.PageDown:
  1230. case Key.V | Key.CtrlMask:
  1231. case Key.PageDown | Key.ShiftMask:
  1232. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1233. StartSelecting ();
  1234. } else if (shiftSelecting && selecting) {
  1235. StopSelecting ();
  1236. }
  1237. int nPageDnShift = Frame.Height - 1;
  1238. if (currentRow < model.Count) {
  1239. if (columnTrack == -1)
  1240. columnTrack = currentColumn;
  1241. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  1242. if (topRow < currentRow - nPageDnShift) {
  1243. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  1244. SetNeedsDisplay ();
  1245. }
  1246. TrackColumn ();
  1247. PositionCursor ();
  1248. }
  1249. break;
  1250. case Key.PageUp:
  1251. case ((int)'V' + Key.AltMask):
  1252. case Key.PageUp | Key.ShiftMask:
  1253. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1254. StartSelecting ();
  1255. } else if (shiftSelecting && selecting) {
  1256. StopSelecting ();
  1257. }
  1258. int nPageUpShift = Frame.Height - 1;
  1259. if (currentRow > 0) {
  1260. if (columnTrack == -1)
  1261. columnTrack = currentColumn;
  1262. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  1263. if (currentRow < topRow) {
  1264. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  1265. SetNeedsDisplay ();
  1266. }
  1267. TrackColumn ();
  1268. PositionCursor ();
  1269. }
  1270. break;
  1271. case Key.N | Key.CtrlMask:
  1272. case Key.CursorDown:
  1273. case Key.CursorDown | Key.ShiftMask:
  1274. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1275. StartSelecting ();
  1276. } else if (shiftSelecting && selecting) {
  1277. StopSelecting ();
  1278. }
  1279. MoveDown ();
  1280. break;
  1281. case Key.P | Key.CtrlMask:
  1282. case Key.CursorUp:
  1283. case Key.CursorUp | Key.ShiftMask:
  1284. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1285. StartSelecting ();
  1286. } else if (shiftSelecting && selecting) {
  1287. StopSelecting ();
  1288. }
  1289. MoveUp ();
  1290. break;
  1291. case Key.F | Key.CtrlMask:
  1292. case Key.CursorRight:
  1293. case Key.CursorRight | Key.ShiftMask:
  1294. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1295. StartSelecting ();
  1296. } else if (shiftSelecting && selecting) {
  1297. StopSelecting ();
  1298. }
  1299. var currentLine = GetCurrentLine ();
  1300. if (currentColumn < currentLine.Count) {
  1301. currentColumn++;
  1302. } else {
  1303. if (currentRow + 1 < model.Count) {
  1304. currentRow++;
  1305. currentColumn = 0;
  1306. if (currentRow >= topRow + Frame.Height) {
  1307. topRow++;
  1308. SetNeedsDisplay ();
  1309. }
  1310. }
  1311. }
  1312. Adjust ();
  1313. break;
  1314. case Key.B | Key.CtrlMask:
  1315. case Key.CursorLeft:
  1316. case Key.CursorLeft | Key.ShiftMask:
  1317. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1318. StartSelecting ();
  1319. } else if (shiftSelecting && selecting) {
  1320. StopSelecting ();
  1321. }
  1322. if (currentColumn > 0) {
  1323. currentColumn--;
  1324. } else {
  1325. if (currentRow > 0) {
  1326. currentRow--;
  1327. if (currentRow < topRow) {
  1328. topRow--;
  1329. SetNeedsDisplay ();
  1330. }
  1331. currentLine = GetCurrentLine ();
  1332. currentColumn = currentLine.Count;
  1333. }
  1334. }
  1335. Adjust ();
  1336. break;
  1337. case Key.Delete:
  1338. case Key.Backspace:
  1339. if (isReadOnly)
  1340. break;
  1341. if (selecting) {
  1342. Cut ();
  1343. return true;
  1344. }
  1345. if (currentColumn > 0) {
  1346. // Delete backwards
  1347. currentLine = GetCurrentLine ();
  1348. currentLine.RemoveAt (currentColumn - 1);
  1349. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn - 1)) {
  1350. wrapNeeded = true;
  1351. }
  1352. currentColumn--;
  1353. if (currentColumn < leftColumn) {
  1354. leftColumn--;
  1355. SetNeedsDisplay ();
  1356. } else
  1357. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  1358. } else {
  1359. // Merges the current line with the previous one.
  1360. if (currentRow == 0)
  1361. return true;
  1362. var prowIdx = currentRow - 1;
  1363. var prevRow = model.GetLine (prowIdx);
  1364. var prevCount = prevRow.Count;
  1365. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  1366. model.RemoveLine (currentRow);
  1367. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out lineRemoved, false)) {
  1368. wrapNeeded = true;
  1369. }
  1370. currentRow--;
  1371. if (wrapNeeded && !lineRemoved) {
  1372. currentColumn = Math.Max (prevCount - 1, 0);
  1373. } else {
  1374. currentColumn = prevCount;
  1375. }
  1376. Adjust ();
  1377. }
  1378. break;
  1379. // Home, C-A
  1380. case Key.Home:
  1381. case Key.Home | Key.ShiftMask:
  1382. case Key.A | Key.CtrlMask:
  1383. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1384. StartSelecting ();
  1385. } else if (shiftSelecting && selecting) {
  1386. StopSelecting ();
  1387. }
  1388. currentColumn = 0;
  1389. Adjust ();
  1390. break;
  1391. case Key.DeleteChar:
  1392. case Key.D | Key.CtrlMask: // Delete
  1393. if (isReadOnly)
  1394. break;
  1395. if (selecting) {
  1396. Cut ();
  1397. return true;
  1398. }
  1399. currentLine = GetCurrentLine ();
  1400. if (currentColumn == currentLine.Count) {
  1401. if (currentRow + 1 == model.Count)
  1402. break;
  1403. var nextLine = model.GetLine (currentRow + 1);
  1404. currentLine.AddRange (nextLine);
  1405. model.RemoveLine (currentRow + 1);
  1406. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out _)) {
  1407. wrapNeeded = true;
  1408. }
  1409. var sr = currentRow - topRow;
  1410. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  1411. } else {
  1412. currentLine.RemoveAt (currentColumn);
  1413. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn)) {
  1414. wrapNeeded = true;
  1415. }
  1416. var r = currentRow - topRow;
  1417. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  1418. }
  1419. break;
  1420. case Key.End:
  1421. case Key.End | Key.ShiftMask:
  1422. case Key.E | Key.CtrlMask: // End
  1423. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1424. StartSelecting ();
  1425. } else if (shiftSelecting && selecting) {
  1426. StopSelecting ();
  1427. }
  1428. currentLine = GetCurrentLine ();
  1429. currentColumn = currentLine.Count;
  1430. int pcol = leftColumn;
  1431. Adjust ();
  1432. break;
  1433. case Key.K | Key.CtrlMask: // kill-to-end
  1434. if (isReadOnly)
  1435. break;
  1436. var cRow = currentRow;
  1437. SetWrapModel ();
  1438. currentLine = GetCurrentLine ();
  1439. var setLastWasKill = true;
  1440. if (currentLine.Count == 0) {
  1441. model.RemoveLine (currentRow);
  1442. if (model.Count > 0 || lastWasKill) {
  1443. var val = ustring.Make ((Rune)'\n');
  1444. if (lastWasKill) {
  1445. AppendClipboard (val);
  1446. } else {
  1447. SetClipboard (val);
  1448. }
  1449. }
  1450. if (model.Count == 0) {
  1451. // Prevents from adding line feeds if there is no more lines.
  1452. setLastWasKill = false;
  1453. }
  1454. if (currentRow > 0) {
  1455. currentRow--;
  1456. }
  1457. } else {
  1458. restCount = currentLine.Count - currentColumn;
  1459. rest = currentLine.GetRange (currentColumn, restCount);
  1460. var val = ustring.Empty;
  1461. if (currentColumn == 0 && lastWasKill && currentLine.Count > 0) {
  1462. val = ustring.Make ((Rune)'\n');
  1463. }
  1464. val += StringFromRunes (rest);
  1465. if (lastWasKill) {
  1466. AppendClipboard (val);
  1467. } else {
  1468. SetClipboard (val);
  1469. }
  1470. if (currentColumn == 0) {
  1471. model.RemoveLine (currentRow);
  1472. if (currentRow > 0) {
  1473. currentRow--;
  1474. }
  1475. } else {
  1476. currentLine.RemoveRange (currentColumn, restCount);
  1477. }
  1478. if (model.Count == 0) {
  1479. // Prevents from adding line feeds if there is no more lines.
  1480. setLastWasKill = false;
  1481. }
  1482. }
  1483. UpdateWrapModel ();
  1484. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  1485. lastWasKill = setLastWasKill;
  1486. break;
  1487. case Key.Y | Key.CtrlMask: // Control-y, yank
  1488. if (isReadOnly)
  1489. break;
  1490. Paste ();
  1491. return true;
  1492. case Key.Space | Key.CtrlMask:
  1493. selecting = !selecting;
  1494. selectionStartColumn = currentColumn;
  1495. selectionStartRow = currentRow;
  1496. break;
  1497. case ((int)'C' + Key.AltMask):
  1498. case Key.C | Key.CtrlMask:
  1499. Copy ();
  1500. return true;
  1501. case ((int)'W' + Key.AltMask):
  1502. case Key.W | Key.CtrlMask:
  1503. case Key.X | Key.CtrlMask:
  1504. Cut ();
  1505. return true;
  1506. case Key.CtrlMask | Key.CursorLeft:
  1507. case Key.CtrlMask | Key.CursorLeft | Key.ShiftMask:
  1508. case (Key)((int)'B' + Key.AltMask):
  1509. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1510. StartSelecting ();
  1511. } else if (shiftSelecting && selecting) {
  1512. StopSelecting ();
  1513. }
  1514. var newPos = WordBackward (currentColumn, currentRow);
  1515. if (newPos.HasValue) {
  1516. currentColumn = newPos.Value.col;
  1517. currentRow = newPos.Value.row;
  1518. }
  1519. Adjust ();
  1520. break;
  1521. case Key.CtrlMask | Key.CursorRight:
  1522. case Key.CtrlMask | Key.CursorRight | Key.ShiftMask:
  1523. case (Key)((int)'F' + Key.AltMask):
  1524. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1525. StartSelecting ();
  1526. } else if (shiftSelecting && selecting) {
  1527. StopSelecting ();
  1528. }
  1529. newPos = WordForward (currentColumn, currentRow);
  1530. if (newPos.HasValue) {
  1531. currentColumn = newPos.Value.col;
  1532. currentRow = newPos.Value.row;
  1533. }
  1534. Adjust ();
  1535. break;
  1536. case Key.Enter:
  1537. if (isReadOnly)
  1538. break;
  1539. currentLine = GetCurrentLine ();
  1540. restCount = currentLine.Count - currentColumn;
  1541. rest = currentLine.GetRange (currentColumn, restCount);
  1542. currentLine.RemoveRange (currentColumn, restCount);
  1543. model.AddLine (currentRow + 1, rest);
  1544. if (wordWrap) {
  1545. wrapManager.AddLine (currentRow, currentColumn);
  1546. wrapNeeded = true;
  1547. }
  1548. currentRow++;
  1549. bool fullNeedsDisplay = false;
  1550. if (currentRow >= topRow + Frame.Height) {
  1551. topRow++;
  1552. fullNeedsDisplay = true;
  1553. }
  1554. currentColumn = 0;
  1555. if (!wordWrap && currentColumn < leftColumn) {
  1556. fullNeedsDisplay = true;
  1557. leftColumn = 0;
  1558. }
  1559. if (fullNeedsDisplay)
  1560. SetNeedsDisplay ();
  1561. else
  1562. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  1563. break;
  1564. case Key.CtrlMask | Key.End:
  1565. case Key.CtrlMask | Key.End | Key.ShiftMask:
  1566. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1567. StartSelecting ();
  1568. } else if (shiftSelecting && selecting) {
  1569. StopSelecting ();
  1570. }
  1571. MoveEnd ();
  1572. break;
  1573. case Key.CtrlMask | Key.Home:
  1574. case Key.CtrlMask | Key.Home | Key.ShiftMask:
  1575. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1576. StartSelecting ();
  1577. } else if (shiftSelecting && selecting) {
  1578. StopSelecting ();
  1579. }
  1580. MoveHome ();
  1581. break;
  1582. default:
  1583. // Ignore control characters and other special keys
  1584. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  1585. return false;
  1586. //So that special keys like tab can be processed
  1587. if (isReadOnly)
  1588. return true;
  1589. if (selecting) {
  1590. Cut ();
  1591. }
  1592. Insert ((uint)kb.Key);
  1593. currentColumn++;
  1594. if (currentColumn >= leftColumn + Frame.Width) {
  1595. leftColumn++;
  1596. SetNeedsDisplay ();
  1597. }
  1598. break;
  1599. }
  1600. DoNeededAction ();
  1601. return true;
  1602. }
  1603. ///<inheritdoc/>
  1604. public override bool OnKeyUp (KeyEvent kb)
  1605. {
  1606. switch (kb.Key) {
  1607. case Key.Space | Key.CtrlMask:
  1608. return true;
  1609. }
  1610. return false;
  1611. }
  1612. void DoNeededAction ()
  1613. {
  1614. if (NeedDisplay.IsEmpty) {
  1615. PositionCursor ();
  1616. } else {
  1617. Adjust ();
  1618. }
  1619. }
  1620. /// <summary>
  1621. /// Copy the selected text to the clipboard contents.
  1622. /// </summary>
  1623. public void Copy ()
  1624. {
  1625. SetWrapModel ();
  1626. SetClipboard (GetRegion ());
  1627. UpdateWrapModel ();
  1628. DoNeededAction ();
  1629. }
  1630. /// <summary>
  1631. /// Cut the selected text to the clipboard contents.
  1632. /// </summary>
  1633. public void Cut ()
  1634. {
  1635. SetWrapModel ();
  1636. SetClipboard (GetRegion ());
  1637. if (!isReadOnly) {
  1638. ClearRegion ();
  1639. }
  1640. UpdateWrapModel ();
  1641. selecting = false;
  1642. DoNeededAction ();
  1643. }
  1644. /// <summary>
  1645. /// Paste the clipboard contents into the current selected position.
  1646. /// </summary>
  1647. public void Paste ()
  1648. {
  1649. if (isReadOnly) {
  1650. return;
  1651. }
  1652. SetWrapModel ();
  1653. if (selecting) {
  1654. ClearRegion ();
  1655. }
  1656. InsertText (Clipboard.Contents);
  1657. UpdateWrapModel ();
  1658. selecting = false;
  1659. DoNeededAction ();
  1660. }
  1661. void StartSelecting ()
  1662. {
  1663. if (shiftSelecting && selecting) {
  1664. return;
  1665. }
  1666. shiftSelecting = true;
  1667. selecting = true;
  1668. selectionStartColumn = currentColumn;
  1669. selectionStartRow = currentRow;
  1670. }
  1671. void StopSelecting ()
  1672. {
  1673. shiftSelecting = false;
  1674. selecting = false;
  1675. }
  1676. void MoveUp ()
  1677. {
  1678. if (currentRow > 0) {
  1679. if (columnTrack == -1) {
  1680. columnTrack = currentColumn;
  1681. }
  1682. currentRow--;
  1683. if (currentRow < topRow) {
  1684. topRow--;
  1685. SetNeedsDisplay ();
  1686. }
  1687. TrackColumn ();
  1688. PositionCursor ();
  1689. }
  1690. }
  1691. void MoveDown ()
  1692. {
  1693. if (currentRow + 1 < model.Count) {
  1694. if (columnTrack == -1) {
  1695. columnTrack = currentColumn;
  1696. }
  1697. currentRow++;
  1698. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  1699. topRow++;
  1700. SetNeedsDisplay ();
  1701. }
  1702. TrackColumn ();
  1703. PositionCursor ();
  1704. } else if (currentRow > Frame.Height) {
  1705. Adjust ();
  1706. }
  1707. }
  1708. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  1709. {
  1710. if (col < 0 || row < 0)
  1711. yield break;
  1712. if (row >= model.Count)
  1713. yield break;
  1714. var line = GetCurrentLine ();
  1715. if (col >= line.Count)
  1716. yield break;
  1717. while (row < model.Count) {
  1718. for (int c = col; c < line.Count; c++) {
  1719. yield return (c, row, line [c]);
  1720. }
  1721. col = 0;
  1722. row++;
  1723. line = GetCurrentLine ();
  1724. }
  1725. }
  1726. Rune RuneAt (int col, int row)
  1727. {
  1728. var line = model.GetLine (row);
  1729. return line [col > line.Count - 1 ? line.Count - 1 : col];
  1730. }
  1731. /// <summary>
  1732. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  1733. /// </summary>
  1734. public void MoveEnd ()
  1735. {
  1736. currentRow = model.Count - 1;
  1737. var line = GetCurrentLine ();
  1738. currentColumn = line.Count;
  1739. TrackColumn ();
  1740. PositionCursor ();
  1741. }
  1742. /// <summary>
  1743. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  1744. /// </summary>
  1745. public void MoveHome ()
  1746. {
  1747. currentRow = 0;
  1748. currentColumn = 0;
  1749. TrackColumn ();
  1750. PositionCursor ();
  1751. }
  1752. bool MoveNext (ref int col, ref int row, out Rune rune)
  1753. {
  1754. var line = model.GetLine (row);
  1755. if (col + 1 < line.Count) {
  1756. col++;
  1757. rune = line [col];
  1758. return true;
  1759. }
  1760. while (row + 1 < model.Count) {
  1761. col = 0;
  1762. row++;
  1763. line = model.GetLine (row);
  1764. if (line.Count > 0) {
  1765. rune = line [0];
  1766. return true;
  1767. }
  1768. }
  1769. rune = 0;
  1770. return false;
  1771. }
  1772. bool MovePrev (ref int col, ref int row, out Rune rune)
  1773. {
  1774. var line = model.GetLine (row);
  1775. if (col > 0) {
  1776. col--;
  1777. rune = line [col];
  1778. return true;
  1779. }
  1780. if (row == 0) {
  1781. rune = 0;
  1782. return false;
  1783. }
  1784. while (row > 0) {
  1785. row--;
  1786. line = model.GetLine (row);
  1787. col = line.Count - 1;
  1788. if (col >= 0) {
  1789. rune = line [col];
  1790. return true;
  1791. }
  1792. }
  1793. rune = 0;
  1794. return false;
  1795. }
  1796. (int col, int row)? WordForward (int fromCol, int fromRow)
  1797. {
  1798. var col = fromCol;
  1799. var row = fromRow;
  1800. try {
  1801. var rune = RuneAt (col, row);
  1802. var srow = row;
  1803. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1804. while (MoveNext (ref col, ref row, out rune)) {
  1805. if (Rune.IsLetterOrDigit (rune))
  1806. break;
  1807. }
  1808. if (row != fromRow && Rune.IsLetterOrDigit (rune)) {
  1809. return (col, row);
  1810. }
  1811. while (MoveNext (ref col, ref row, out rune)) {
  1812. if (!Rune.IsLetterOrDigit (rune))
  1813. break;
  1814. }
  1815. } else {
  1816. while (MoveNext (ref col, ref row, out rune)) {
  1817. if (!Rune.IsLetterOrDigit (rune))
  1818. break;
  1819. }
  1820. }
  1821. if (fromCol != col || fromRow != row)
  1822. return (col + 1, row);
  1823. return null;
  1824. } catch (Exception) {
  1825. return null;
  1826. }
  1827. }
  1828. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1829. {
  1830. if (fromRow == 0 && fromCol == 0)
  1831. return null;
  1832. var col = Math.Max (fromCol - 1, 0);
  1833. var row = fromRow;
  1834. try {
  1835. var rune = RuneAt (col, row);
  1836. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1837. while (MovePrev (ref col, ref row, out rune)) {
  1838. if (Rune.IsLetterOrDigit (rune))
  1839. break;
  1840. }
  1841. int lastValidCol = -1;
  1842. while (MovePrev (ref col, ref row, out rune)) {
  1843. if (col == 0 && Rune.IsLetterOrDigit (rune)) {
  1844. return (col, row);
  1845. } else if (col == 0 && !Rune.IsLetterOrDigit (rune) && lastValidCol > -1) {
  1846. col = lastValidCol;
  1847. return (col, row);
  1848. }
  1849. if (!Rune.IsLetterOrDigit (rune)) {
  1850. break;
  1851. }
  1852. lastValidCol = Rune.IsLetterOrDigit (rune) ? col : -1;
  1853. }
  1854. } else {
  1855. while (MovePrev (ref col, ref row, out rune)) {
  1856. if (!Rune.IsLetterOrDigit (rune))
  1857. break;
  1858. }
  1859. }
  1860. if (fromCol != col && fromRow == row) {
  1861. return (col == 0 ? col : col + 1, row);
  1862. } else if (fromCol != col && fromRow != row) {
  1863. return (col + 1, row);
  1864. }
  1865. return null;
  1866. } catch (Exception) {
  1867. return null;
  1868. }
  1869. }
  1870. ///<inheritdoc/>
  1871. public override bool MouseEvent (MouseEvent ev)
  1872. {
  1873. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  1874. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  1875. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  1876. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  1877. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)) {
  1878. return false;
  1879. }
  1880. if (!CanFocus) {
  1881. return true;
  1882. }
  1883. if (!HasFocus) {
  1884. SetFocus ();
  1885. }
  1886. if (ev.Flags == MouseFlags.Button1Clicked) {
  1887. if (shiftSelecting) {
  1888. shiftSelecting = false;
  1889. selecting = false;
  1890. }
  1891. ProcessMouseClick (ev, out _);
  1892. PositionCursor ();
  1893. lastWasKill = false;
  1894. columnTrack = currentColumn;
  1895. } else if (ev.Flags == MouseFlags.WheeledDown) {
  1896. lastWasKill = false;
  1897. columnTrack = currentColumn;
  1898. ScrollTo (topRow + 1);
  1899. } else if (ev.Flags == MouseFlags.WheeledUp) {
  1900. lastWasKill = false;
  1901. columnTrack = currentColumn;
  1902. ScrollTo (topRow - 1);
  1903. } else if (ev.Flags == MouseFlags.WheeledRight) {
  1904. lastWasKill = false;
  1905. columnTrack = currentColumn;
  1906. ScrollTo (leftColumn + 1, false);
  1907. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  1908. lastWasKill = false;
  1909. columnTrack = currentColumn;
  1910. ScrollTo (leftColumn - 1, false);
  1911. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  1912. ProcessMouseClick (ev, out List<Rune> line);
  1913. PositionCursor ();
  1914. if (model.Count > 0 && shiftSelecting && selecting) {
  1915. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  1916. && model.Count + BottomOffset > topRow + currentRow) {
  1917. ScrollTo (topRow + Frame.Height);
  1918. } else if (topRow > 0 && currentRow <= topRow) {
  1919. ScrollTo (topRow - Frame.Height);
  1920. } else if (ev.Y >= Frame.Height) {
  1921. ScrollTo (model.Count + BottomOffset);
  1922. } else if (ev.Y < 0 && topRow > 0) {
  1923. ScrollTo (0);
  1924. }
  1925. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  1926. && line.Count + RightOffset > leftColumn + currentColumn) {
  1927. ScrollTo (leftColumn + Frame.Width, false);
  1928. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  1929. ScrollTo (leftColumn - Frame.Width, false);
  1930. } else if (ev.X >= Frame.Width) {
  1931. ScrollTo (line.Count + RightOffset, false);
  1932. } else if (ev.X < 0 && leftColumn > 0) {
  1933. ScrollTo (0, false);
  1934. }
  1935. }
  1936. lastWasKill = false;
  1937. columnTrack = currentColumn;
  1938. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  1939. if (!shiftSelecting) {
  1940. StartSelecting ();
  1941. }
  1942. ProcessMouseClick (ev, out _);
  1943. PositionCursor ();
  1944. lastWasKill = false;
  1945. columnTrack = currentColumn;
  1946. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  1947. if (shiftSelecting) {
  1948. shiftSelecting = false;
  1949. selecting = false;
  1950. }
  1951. ProcessMouseClick (ev, out _);
  1952. PositionCursor ();
  1953. if (!selecting) {
  1954. StartSelecting ();
  1955. }
  1956. lastWasKill = false;
  1957. columnTrack = currentColumn;
  1958. if (Application.mouseGrabView == null) {
  1959. Application.GrabMouse (this);
  1960. }
  1961. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  1962. Application.UngrabMouse ();
  1963. }
  1964. return true;
  1965. }
  1966. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  1967. {
  1968. List<Rune> r = null;
  1969. if (model.Count > 0) {
  1970. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  1971. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  1972. currentRow = maxCursorPositionableLine + topRow;
  1973. } else {
  1974. currentRow = Math.Max (ev.Y + topRow, 0);
  1975. }
  1976. r = GetCurrentLine ();
  1977. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0));
  1978. if (idx - leftColumn >= r.Count + RightOffset) {
  1979. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  1980. } else {
  1981. currentColumn = idx + leftColumn;
  1982. }
  1983. }
  1984. line = r;
  1985. }
  1986. ///<inheritdoc/>
  1987. public override bool OnLeave (View view)
  1988. {
  1989. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  1990. Application.UngrabMouse ();
  1991. }
  1992. return base.OnLeave (view);
  1993. }
  1994. }
  1995. }