TextView.cs 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755
  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. (Point startPointToFind, Point currentPointToFind, bool found) toFind;
  258. internal (Point current, bool found) FindNextText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  259. {
  260. if (text == null || lines.Count == 0) {
  261. gaveFullTurn = false;
  262. return (Point.Empty, false);
  263. }
  264. if (toFind.found) {
  265. toFind.currentPointToFind.X++;
  266. }
  267. var foundPos = GetFoundNextTextPoint (text, lines.Count, matchCase, matchWholeWord, toFind.currentPointToFind);
  268. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  269. foundPos = GetFoundNextTextPoint (text, toFind.startPointToFind.Y + 1, matchCase, matchWholeWord, Point.Empty);
  270. }
  271. gaveFullTurn = ApplyToFind (foundPos);
  272. return foundPos;
  273. }
  274. internal (Point current, bool found) FindPreviousText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  275. {
  276. if (text == null || lines.Count == 0) {
  277. gaveFullTurn = false;
  278. return (Point.Empty, false);
  279. }
  280. if (toFind.found) {
  281. toFind.currentPointToFind.X++;
  282. }
  283. var foundPos = GetFoundPreviousTextPoint (text, toFind.currentPointToFind.Y, matchCase, matchWholeWord, toFind.currentPointToFind);
  284. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  285. foundPos = GetFoundPreviousTextPoint (text, lines.Count - 1, matchCase, matchWholeWord,
  286. new Point (lines [lines.Count - 1].Count, lines.Count));
  287. }
  288. gaveFullTurn = ApplyToFind (foundPos);
  289. return foundPos;
  290. }
  291. internal (Point current, bool found) ReplaceAllText (ustring text, bool matchCase = false, bool matchWholeWord = false, ustring textToReplace = null)
  292. {
  293. bool found = false;
  294. Point pos = Point.Empty;
  295. for (int i = 0; i < lines.Count; i++) {
  296. var x = lines [i];
  297. var txt = ustring.Make (x).ToString ();
  298. if (!matchCase) {
  299. txt = txt.ToUpper ();
  300. }
  301. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  302. var col = txt.IndexOf (matchText);
  303. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  304. continue;
  305. }
  306. if (col > -1) {
  307. if (!found) {
  308. found = true;
  309. }
  310. pos = new Point (col, i);
  311. lines [i] = ReplaceText (x, textToReplace, matchText, col).ToRuneList ();
  312. i--;
  313. }
  314. }
  315. return (pos, found);
  316. }
  317. ustring ReplaceText (List<Rune> source, ustring textToReplace, string matchText, int col)
  318. {
  319. var origTxt = ustring.Make (source);
  320. (int _, int len) = TextModel.DisplaySize (source, 0, col, false);
  321. (var _, var len2) = TextModel.DisplaySize (source, col, col + matchText.Length, false);
  322. (var _, var len3) = TextModel.DisplaySize (source, col + matchText.Length, origTxt.RuneCount, false);
  323. return origTxt [0, len] +
  324. textToReplace.ToString () +
  325. origTxt [len + len2, len + len2 + len3];
  326. }
  327. bool ApplyToFind ((Point current, bool found) foundPos)
  328. {
  329. bool gaveFullTurn = false;
  330. if (foundPos.found) {
  331. toFind.currentPointToFind = foundPos.current;
  332. if (toFind.found && toFind.currentPointToFind == toFind.startPointToFind) {
  333. gaveFullTurn = true;
  334. }
  335. if (!toFind.found) {
  336. toFind.startPointToFind = toFind.currentPointToFind = foundPos.current;
  337. toFind.found = foundPos.found;
  338. }
  339. }
  340. return gaveFullTurn;
  341. }
  342. (Point current, bool found) GetFoundNextTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  343. {
  344. for (int i = start.Y; i < linesCount; i++) {
  345. var x = lines [i];
  346. var txt = ustring.Make (x).ToString ();
  347. if (!matchCase) {
  348. txt = txt.ToUpper ();
  349. }
  350. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  351. var col = txt.IndexOf (matchText, Math.Min (start.X, txt.Length));
  352. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  353. continue;
  354. }
  355. if (col > -1 && ((i == start.Y && col >= start.X)
  356. || i > start.Y)
  357. && txt.Contains (matchText)) {
  358. return (new Point (col, i), true);
  359. } else if (col == -1 && start.X > 0) {
  360. start.X = 0;
  361. }
  362. }
  363. return (Point.Empty, false);
  364. }
  365. (Point current, bool found) GetFoundPreviousTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  366. {
  367. for (int i = linesCount; i >= 0; i--) {
  368. var x = lines [i];
  369. var txt = ustring.Make (x).ToString ();
  370. if (!matchCase) {
  371. txt = txt.ToUpper ();
  372. }
  373. if (start.Y != i) {
  374. start.X = Math.Max (x.Count - 1, 0);
  375. }
  376. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  377. var col = txt.LastIndexOf (matchText, start.X);
  378. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  379. continue;
  380. }
  381. if (col > -1 && ((i == linesCount && col <= start.X)
  382. || i < start.Y)
  383. && txt.Contains (matchText)) {
  384. return (new Point (col, i), true);
  385. }
  386. }
  387. return (Point.Empty, false);
  388. }
  389. bool MatchWholeWord (string source, string matchText, int index = 0)
  390. {
  391. if (string.IsNullOrEmpty (source) || string.IsNullOrEmpty (matchText)) {
  392. return false;
  393. }
  394. var txt = matchText.Trim ();
  395. var start = index > 0 ? index - 1 : 0;
  396. var end = index + txt.Length;
  397. if ((start == 0 || Rune.IsWhiteSpace (source [start]))
  398. && (end == source.Length || Rune.IsWhiteSpace (source [end]))) {
  399. return true;
  400. }
  401. return false;
  402. }
  403. /// <summary>
  404. /// Redefine column and line tracking.
  405. /// </summary>
  406. /// <param name="point">Contains the column and line.</param>
  407. internal void ResetContinuousFind (Point point)
  408. {
  409. toFind.startPointToFind = toFind.currentPointToFind = point;
  410. toFind.found = false;
  411. }
  412. }
  413. class WordWrapManager {
  414. class WrappedLine {
  415. public int ModelLine;
  416. public int Row;
  417. public int RowIndex;
  418. public int ColWidth;
  419. }
  420. List<WrappedLine> wrappedModelLines = new List<WrappedLine> ();
  421. int frameWidth;
  422. bool isWrapModelRefreshing;
  423. public TextModel Model { get; private set; }
  424. public WordWrapManager (TextModel model)
  425. {
  426. Model = model;
  427. }
  428. public TextModel WrapModel (int width, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  429. int row = 0, int col = 0, int startRow = 0, int startCol = 0)
  430. {
  431. frameWidth = width;
  432. var modelRow = isWrapModelRefreshing ? row : GetModelLineFromWrappedLines (row);
  433. var modelCol = isWrapModelRefreshing ? col : GetModelColFromWrappedLines (row, col);
  434. var modelStartRow = isWrapModelRefreshing ? startRow : GetModelLineFromWrappedLines (startRow);
  435. var modelStartCol = isWrapModelRefreshing ? startCol : GetModelColFromWrappedLines (startRow, startCol);
  436. var wrappedModel = new TextModel ();
  437. int lines = 0;
  438. nRow = 0;
  439. nCol = 0;
  440. nStartRow = 0;
  441. nStartCol = 0;
  442. bool isRowAndColSetted = row == 0 && col == 0;
  443. bool isStartRowAndColSetted = startRow == 0 && startCol == 0;
  444. List<WrappedLine> wModelLines = new List<WrappedLine> ();
  445. for (int i = 0; i < Model.Count; i++) {
  446. var line = Model.GetLine (i);
  447. var wrappedLines = ToListRune (
  448. TextFormatter.Format (ustring.Make (line), width, TextAlignment.Left, true, true));
  449. int sumColWidth = 0;
  450. for (int j = 0; j < wrappedLines.Count; j++) {
  451. var wrapLine = wrappedLines [j];
  452. if (!isRowAndColSetted && modelRow == i) {
  453. if (nCol + wrapLine.Count <= modelCol) {
  454. nCol += wrapLine.Count;
  455. nRow = lines;
  456. if (nCol == modelCol) {
  457. nCol = wrapLine.Count;
  458. isRowAndColSetted = true;
  459. } else if (j == wrappedLines.Count - 1) {
  460. nCol = wrapLine.Count - j + modelCol - nCol;
  461. isRowAndColSetted = true;
  462. }
  463. } else {
  464. var offset = nCol + wrapLine.Count - modelCol;
  465. nCol = wrapLine.Count - offset;
  466. nRow = lines;
  467. isRowAndColSetted = true;
  468. }
  469. }
  470. if (!isStartRowAndColSetted && modelStartRow == i) {
  471. if (nStartCol + wrapLine.Count <= modelStartCol) {
  472. nStartCol += wrapLine.Count;
  473. nStartRow = lines;
  474. if (nStartCol == modelStartCol) {
  475. nStartCol = wrapLine.Count;
  476. isStartRowAndColSetted = true;
  477. } else if (j == wrappedLines.Count - 1) {
  478. nStartCol = wrapLine.Count - j + modelStartCol - nStartCol;
  479. isStartRowAndColSetted = true;
  480. }
  481. } else {
  482. var offset = nStartCol + wrapLine.Count - modelStartCol;
  483. nStartCol = wrapLine.Count - offset;
  484. nStartRow = lines;
  485. isStartRowAndColSetted = true;
  486. }
  487. }
  488. wrappedModel.AddLine (lines, wrapLine);
  489. sumColWidth += wrapLine.Count;
  490. var wrappedLine = new WrappedLine () {
  491. ModelLine = i,
  492. Row = lines,
  493. RowIndex = j,
  494. ColWidth = wrapLine.Count,
  495. };
  496. wModelLines.Add (wrappedLine);
  497. lines++;
  498. }
  499. }
  500. wrappedModelLines = wModelLines;
  501. return wrappedModel;
  502. }
  503. public List<List<Rune>> ToListRune (List<ustring> textList)
  504. {
  505. var runesList = new List<List<Rune>> ();
  506. foreach (var text in textList) {
  507. runesList.Add (text.ToRuneList ());
  508. }
  509. return runesList;
  510. }
  511. public int GetModelLineFromWrappedLines (int line) => wrappedModelLines.Count > 0
  512. ? wrappedModelLines [Math.Min (line, wrappedModelLines.Count - 1)].ModelLine
  513. : 0;
  514. public int GetModelColFromWrappedLines (int line, int col)
  515. {
  516. if (wrappedModelLines?.Count == 0) {
  517. return 0;
  518. }
  519. var modelLine = GetModelLineFromWrappedLines (line);
  520. var firstLine = wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  521. int modelCol = 0;
  522. for (int i = firstLine; i <= line; i++) {
  523. var wLine = wrappedModelLines [i];
  524. if (i < line) {
  525. modelCol += wLine.ColWidth;
  526. } else {
  527. modelCol += col;
  528. }
  529. }
  530. return modelCol;
  531. }
  532. List<Rune> GetCurrentLine (int row) => Model.GetLine (row);
  533. public void AddLine (int row, int col)
  534. {
  535. var modelRow = GetModelLineFromWrappedLines (row);
  536. var modelCol = GetModelColFromWrappedLines (row, col);
  537. var line = GetCurrentLine (modelRow);
  538. var restCount = line.Count - modelCol;
  539. var rest = line.GetRange (modelCol, restCount);
  540. line.RemoveRange (modelCol, restCount);
  541. Model.AddLine (modelRow + 1, rest);
  542. isWrapModelRefreshing = true;
  543. WrapModel (frameWidth, out _, out _, out _, out _, modelRow + 1, 0);
  544. isWrapModelRefreshing = false;
  545. }
  546. public bool Insert (int row, int col, Rune rune)
  547. {
  548. var line = GetCurrentLine (GetModelLineFromWrappedLines (row));
  549. line.Insert (GetModelColFromWrappedLines (row, col), rune);
  550. if (line.Count > frameWidth) {
  551. return true;
  552. } else {
  553. return false;
  554. }
  555. }
  556. public bool RemoveAt (int row, int col)
  557. {
  558. var modelRow = GetModelLineFromWrappedLines (row);
  559. var line = GetCurrentLine (modelRow);
  560. var modelCol = GetModelColFromWrappedLines (row, col);
  561. if (modelCol >= line.Count) {
  562. Model.RemoveLine (modelRow);
  563. RemoveAt (row, 0);
  564. return false;
  565. }
  566. line.RemoveAt (modelCol);
  567. if (line.Count > frameWidth || (row + 1 < wrappedModelLines.Count
  568. && wrappedModelLines [row + 1].ModelLine == modelRow)) {
  569. return true;
  570. }
  571. return false;
  572. }
  573. public bool RemoveLine (int row, int col, out bool lineRemoved, bool forward = true)
  574. {
  575. lineRemoved = false;
  576. var modelRow = GetModelLineFromWrappedLines (row);
  577. var line = GetCurrentLine (modelRow);
  578. var modelCol = GetModelColFromWrappedLines (row, col);
  579. if (modelCol == 0 && line.Count == 0) {
  580. Model.RemoveLine (modelRow);
  581. return false;
  582. } else if (modelCol < line.Count) {
  583. if (forward) {
  584. line.RemoveAt (modelCol);
  585. return true;
  586. } else if (modelCol - 1 > -1) {
  587. line.RemoveAt (modelCol - 1);
  588. return true;
  589. }
  590. }
  591. lineRemoved = true;
  592. if (forward) {
  593. if (modelRow + 1 == Model.Count) {
  594. return false;
  595. }
  596. var nextLine = Model.GetLine (modelRow + 1);
  597. line.AddRange (nextLine);
  598. Model.RemoveLine (modelRow + 1);
  599. if (line.Count > frameWidth) {
  600. return true;
  601. }
  602. } else {
  603. if (modelRow == 0) {
  604. return false;
  605. }
  606. var prevLine = Model.GetLine (modelRow - 1);
  607. prevLine.AddRange (line);
  608. Model.RemoveLine (modelRow);
  609. if (prevLine.Count > frameWidth) {
  610. return true;
  611. }
  612. }
  613. return false;
  614. }
  615. public void UpdateModel (TextModel model, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  616. int row, int col, int startRow, int startCol)
  617. {
  618. isWrapModelRefreshing = true;
  619. Model = model;
  620. WrapModel (frameWidth, out nRow, out nCol, out nStartRow, out nStartCol, row, col, startRow, startCol);
  621. isWrapModelRefreshing = false;
  622. }
  623. }
  624. /// <summary>
  625. /// Multi-line text editing <see cref="View"/>
  626. /// </summary>
  627. /// <remarks>
  628. /// <para>
  629. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  630. /// with it with the standard Emacs commands for movement or the arrow
  631. /// keys.
  632. /// </para>
  633. /// <list type="table">
  634. /// <listheader>
  635. /// <term>Shortcut</term>
  636. /// <description>Action performed</description>
  637. /// </listheader>
  638. /// <item>
  639. /// <term>Left cursor, Control-b</term>
  640. /// <description>
  641. /// Moves the editing point left.
  642. /// </description>
  643. /// </item>
  644. /// <item>
  645. /// <term>Right cursor, Control-f</term>
  646. /// <description>
  647. /// Moves the editing point right.
  648. /// </description>
  649. /// </item>
  650. /// <item>
  651. /// <term>Alt-b</term>
  652. /// <description>
  653. /// Moves one word back.
  654. /// </description>
  655. /// </item>
  656. /// <item>
  657. /// <term>Alt-f</term>
  658. /// <description>
  659. /// Moves one word forward.
  660. /// </description>
  661. /// </item>
  662. /// <item>
  663. /// <term>Up cursor, Control-p</term>
  664. /// <description>
  665. /// Moves the editing point one line up.
  666. /// </description>
  667. /// </item>
  668. /// <item>
  669. /// <term>Down cursor, Control-n</term>
  670. /// <description>
  671. /// Moves the editing point one line down
  672. /// </description>
  673. /// </item>
  674. /// <item>
  675. /// <term>Home key, Control-a</term>
  676. /// <description>
  677. /// Moves the cursor to the beginning of the line.
  678. /// </description>
  679. /// </item>
  680. /// <item>
  681. /// <term>End key, Control-e</term>
  682. /// <description>
  683. /// Moves the cursor to the end of the line.
  684. /// </description>
  685. /// </item>
  686. /// <item>
  687. /// <term>Control-Home</term>
  688. /// <description>
  689. /// Scrolls to the first line and moves the cursor there.
  690. /// </description>
  691. /// </item>
  692. /// <item>
  693. /// <term>Control-End</term>
  694. /// <description>
  695. /// Scrolls to the last line and moves the cursor there.
  696. /// </description>
  697. /// </item>
  698. /// <item>
  699. /// <term>Delete, Control-d</term>
  700. /// <description>
  701. /// Deletes the character in front of the cursor.
  702. /// </description>
  703. /// </item>
  704. /// <item>
  705. /// <term>Backspace</term>
  706. /// <description>
  707. /// Deletes the character behind the cursor.
  708. /// </description>
  709. /// </item>
  710. /// <item>
  711. /// <term>Control-k</term>
  712. /// <description>
  713. /// Deletes the text until the end of the line and replaces the kill buffer
  714. /// with the deleted text. You can paste this text in a different place by
  715. /// using Control-y.
  716. /// </description>
  717. /// </item>
  718. /// <item>
  719. /// <term>Control-y</term>
  720. /// <description>
  721. /// Pastes the content of the kill ring into the current position.
  722. /// </description>
  723. /// </item>
  724. /// <item>
  725. /// <term>Alt-d</term>
  726. /// <description>
  727. /// Deletes the word above the cursor and adds it to the kill ring. You
  728. /// can paste the contents of the kill ring with Control-y.
  729. /// </description>
  730. /// </item>
  731. /// <item>
  732. /// <term>Control-q</term>
  733. /// <description>
  734. /// Quotes the next input character, to prevent the normal processing of
  735. /// key handling to take place.
  736. /// </description>
  737. /// </item>
  738. /// </list>
  739. /// </remarks>
  740. public class TextView : View {
  741. TextModel model = new TextModel ();
  742. int topRow;
  743. int leftColumn;
  744. int currentRow;
  745. int currentColumn;
  746. int selectionStartColumn, selectionStartRow;
  747. bool selecting;
  748. bool wordWrap;
  749. WordWrapManager wrapManager;
  750. bool continuousFind;
  751. /// <summary>
  752. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  753. /// </summary>
  754. public event Action TextChanged;
  755. #if false
  756. /// <summary>
  757. /// Changed event, raised when the text has clicked.
  758. /// </summary>
  759. /// <remarks>
  760. /// Client code can hook up to this event, it is
  761. /// raised when the text in the entry changes.
  762. /// </remarks>
  763. public Action Changed;
  764. #endif
  765. /// <summary>
  766. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  767. /// </summary>
  768. /// <remarks>
  769. /// </remarks>
  770. public TextView (Rect frame) : base (frame)
  771. {
  772. Initialize ();
  773. }
  774. /// <summary>
  775. /// Initializes a <see cref="TextView"/> on the specified area,
  776. /// with dimensions controlled with the X, Y, Width and Height properties.
  777. /// </summary>
  778. public TextView () : base ()
  779. {
  780. Initialize ();
  781. }
  782. void Initialize ()
  783. {
  784. CanFocus = true;
  785. Used = true;
  786. }
  787. /// <summary>
  788. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  789. /// so new input should be appended at the cursor position, rather than clearing the entry
  790. /// </summary>
  791. public bool Used { get; set; }
  792. void ResetPosition ()
  793. {
  794. topRow = leftColumn = currentRow = currentColumn = 0;
  795. selecting = false;
  796. shiftSelecting = false;
  797. ResetCursorVisibility ();
  798. }
  799. /// <summary>
  800. /// Sets or gets the text in the <see cref="TextView"/>.
  801. /// </summary>
  802. /// <remarks>
  803. /// </remarks>
  804. public override ustring Text {
  805. get {
  806. if (wordWrap) {
  807. return wrapManager.Model.ToString ();
  808. } else {
  809. return model.ToString ();
  810. }
  811. }
  812. set {
  813. ResetPosition ();
  814. model.LoadString (value);
  815. if (wordWrap) {
  816. wrapManager = new WordWrapManager (model);
  817. model = wrapManager.WrapModel (Frame.Width - 2, out _, out _, out _, out _);
  818. }
  819. TextChanged?.Invoke ();
  820. SetNeedsDisplay ();
  821. }
  822. }
  823. ///<inheritdoc/>
  824. public override Rect Frame {
  825. get => base.Frame;
  826. set {
  827. base.Frame = value;
  828. WrapTextModel ();
  829. Adjust ();
  830. }
  831. }
  832. void WrapTextModel ()
  833. {
  834. if (wordWrap && wrapManager != null) {
  835. model = wrapManager.WrapModel (Frame.Width - 2,
  836. out int nRow, out int nCol,
  837. out int nStartRow, out int nStartCol,
  838. currentRow, currentColumn,
  839. selectionStartRow, selectionStartColumn);
  840. currentRow = nRow;
  841. currentColumn = nCol;
  842. selectionStartRow = nStartRow;
  843. selectionStartColumn = nStartCol;
  844. SetNeedsDisplay ();
  845. }
  846. }
  847. /// <summary>
  848. /// Gets or sets the top row.
  849. /// </summary>
  850. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  851. /// <summary>
  852. /// Gets or sets the left column.
  853. /// </summary>
  854. public int LeftColumn { get => leftColumn; set => leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0); }
  855. /// <summary>
  856. /// Gets the maximum visible length line.
  857. /// </summary>
  858. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height);
  859. /// <summary>
  860. /// Gets the number of lines.
  861. /// </summary>
  862. public int Lines => model.Count;
  863. /// <summary>
  864. /// Sets or gets the current cursor position.
  865. /// </summary>
  866. public Point CursorPosition {
  867. get => new Point (currentColumn, currentRow);
  868. set {
  869. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  870. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  871. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  872. ? Math.Max (model.Count - 1, 0) : value.Y;
  873. SetNeedsDisplay ();
  874. Adjust ();
  875. }
  876. }
  877. /// <summary>
  878. /// Start column position of the selected text.
  879. /// </summary>
  880. public int SelectionStartColumn {
  881. get => selectionStartColumn;
  882. set {
  883. var line = model.GetLine (currentRow);
  884. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  885. selecting = true;
  886. SetNeedsDisplay ();
  887. Adjust ();
  888. }
  889. }
  890. /// <summary>
  891. /// Start row position of the selected text.
  892. /// </summary>
  893. public int SelectionStartRow {
  894. get => selectionStartRow;
  895. set {
  896. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  897. ? Math.Max (model.Count - 1, 0) : value;
  898. selecting = true;
  899. SetNeedsDisplay ();
  900. Adjust ();
  901. }
  902. }
  903. /// <summary>
  904. /// The selected text.
  905. /// </summary>
  906. public ustring SelectedText {
  907. get {
  908. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  909. return ustring.Empty;
  910. }
  911. SetWrapModel ();
  912. var sel = GetRegion ();
  913. UpdateWrapModel ();
  914. Adjust ();
  915. return sel;
  916. }
  917. }
  918. /// <summary>
  919. /// Length of the selected text.
  920. /// </summary>
  921. public int SelectedLength => GetSelectedLength ();
  922. /// <summary>
  923. /// Get or sets the selecting.
  924. /// </summary>
  925. public bool Selecting {
  926. get => selecting;
  927. set => selecting = value;
  928. }
  929. /// <summary>
  930. /// Allows word wrap the to fit the available container width.
  931. /// </summary>
  932. public bool WordWrap {
  933. get => wordWrap;
  934. set {
  935. if (value == wordWrap) {
  936. return;
  937. }
  938. wordWrap = value;
  939. ResetPosition ();
  940. if (wordWrap) {
  941. wrapManager = new WordWrapManager (model);
  942. model = wrapManager.WrapModel (Math.Max (Frame.Width - 2, 0), out _, out _, out _, out _);
  943. } else if (!wordWrap && wrapManager != null) {
  944. model = wrapManager.Model;
  945. }
  946. SetNeedsDisplay ();
  947. }
  948. }
  949. /// <summary>
  950. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  951. /// This is only needed with the keyboard navigation.
  952. /// </summary>
  953. public int BottomOffset { get; set; }
  954. /// <summary>
  955. /// The right offset needed to use a vertical scrollbar or for another reason.
  956. /// This is only needed with the keyboard navigation.
  957. /// </summary>
  958. public int RightOffset { get; set; }
  959. int GetSelectedLength ()
  960. {
  961. return SelectedText.Length;
  962. }
  963. CursorVisibility savedCursorVisibility = CursorVisibility.Default;
  964. void SaveCursorVisibility ()
  965. {
  966. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  967. savedCursorVisibility = desiredCursorVisibility;
  968. DesiredCursorVisibility = CursorVisibility.Invisible;
  969. }
  970. }
  971. void ResetCursorVisibility ()
  972. {
  973. if (savedCursorVisibility != desiredCursorVisibility) {
  974. DesiredCursorVisibility = savedCursorVisibility;
  975. savedCursorVisibility = CursorVisibility.Default;
  976. } else {
  977. DesiredCursorVisibility = CursorVisibility.Underline;
  978. }
  979. }
  980. /// <summary>
  981. /// Loads the contents of the file into the <see cref="TextView"/>.
  982. /// </summary>
  983. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  984. /// <param name="path">Path to the file to load.</param>
  985. public bool LoadFile (string path)
  986. {
  987. if (path == null)
  988. throw new ArgumentNullException (nameof (path));
  989. ResetPosition ();
  990. var res = model.LoadFile (path);
  991. SetNeedsDisplay ();
  992. return res;
  993. }
  994. /// <summary>
  995. /// Loads the contents of the stream into the <see cref="TextView"/>.
  996. /// </summary>
  997. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  998. /// <param name="stream">Stream to load the contents from.</param>
  999. public void LoadStream (Stream stream)
  1000. {
  1001. if (stream == null)
  1002. throw new ArgumentNullException (nameof (stream));
  1003. ResetPosition ();
  1004. model.LoadStream (stream);
  1005. SetNeedsDisplay ();
  1006. }
  1007. /// <summary>
  1008. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1009. /// </summary>
  1010. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1011. public bool CloseFile ()
  1012. {
  1013. ResetPosition ();
  1014. var res = model.CloseFile ();
  1015. SetNeedsDisplay ();
  1016. return res;
  1017. }
  1018. /// <summary>
  1019. /// Gets the current cursor row.
  1020. /// </summary>
  1021. public int CurrentRow => currentRow;
  1022. /// <summary>
  1023. /// Gets the cursor column.
  1024. /// </summary>
  1025. /// <value>The cursor column.</value>
  1026. public int CurrentColumn => currentColumn;
  1027. /// <summary>
  1028. /// Positions the cursor on the current row and column
  1029. /// </summary>
  1030. public override void PositionCursor ()
  1031. {
  1032. if (selecting) {
  1033. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1034. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1035. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1036. }
  1037. var line = model.GetLine (currentRow);
  1038. var retreat = 0;
  1039. var col = 0;
  1040. if (line.Count > 0) {
  1041. retreat = Math.Max (SpecialRune (line [Math.Min (Math.Max (currentColumn - leftColumn - 1, 0), line.Count - 1)])
  1042. ? 1 : 0, 0);
  1043. for (int idx = leftColumn < 0 ? 0 : leftColumn; idx < line.Count; idx++) {
  1044. if (idx == currentColumn)
  1045. break;
  1046. var cols = Rune.ColumnWidth (line [idx]);
  1047. col += cols - 1;
  1048. }
  1049. }
  1050. var ccol = currentColumn - leftColumn + retreat + col;
  1051. if (leftColumn <= currentColumn && ccol < Frame.Width
  1052. && topRow <= currentRow && currentRow - topRow < Frame.Height) {
  1053. ResetCursorVisibility ();
  1054. Move (ccol, currentRow - topRow);
  1055. } else {
  1056. SaveCursorVisibility ();
  1057. }
  1058. }
  1059. void ClearRegion (int left, int top, int right, int bottom)
  1060. {
  1061. for (int row = top; row < bottom; row++) {
  1062. Move (left, row);
  1063. for (int col = left; col < right; col++)
  1064. AddRune (col, row, ' ');
  1065. }
  1066. }
  1067. void ColorNormal ()
  1068. {
  1069. Driver.SetAttribute (ColorScheme.Normal);
  1070. }
  1071. void ColorSelection ()
  1072. {
  1073. Driver.SetAttribute (ColorScheme.Focus);
  1074. }
  1075. void ColorUsed ()
  1076. {
  1077. Driver.SetAttribute (ColorScheme.HotFocus);
  1078. }
  1079. bool isReadOnly = false;
  1080. /// <summary>
  1081. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1082. /// </summary>
  1083. /// <value>Boolean value(Default false)</value>
  1084. public bool ReadOnly {
  1085. get => isReadOnly;
  1086. set {
  1087. isReadOnly = value;
  1088. }
  1089. }
  1090. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1091. /// <summary>
  1092. /// Get / Set the wished cursor when the field is focused
  1093. /// </summary>
  1094. public CursorVisibility DesiredCursorVisibility {
  1095. get => desiredCursorVisibility;
  1096. set {
  1097. if (desiredCursorVisibility != value && HasFocus) {
  1098. Application.Driver.SetCursorVisibility (value);
  1099. }
  1100. desiredCursorVisibility = value;
  1101. }
  1102. }
  1103. ///<inheritdoc/>
  1104. public override bool OnEnter (View view)
  1105. {
  1106. //TODO: Improve it by handling read only mode of the text field
  1107. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1108. return base.OnEnter (view);
  1109. }
  1110. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1111. void GetEncodedRegionBounds (out long start, out long end)
  1112. {
  1113. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1114. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1115. if (selection > point) {
  1116. start = point;
  1117. end = selection;
  1118. } else {
  1119. start = selection;
  1120. end = point;
  1121. }
  1122. }
  1123. bool PointInSelection (int col, int row)
  1124. {
  1125. long start, end;
  1126. GetEncodedRegionBounds (out start, out end);
  1127. var q = ((long)(uint)row << 32) | (uint)col;
  1128. return q >= start && q <= end - 1;
  1129. }
  1130. //
  1131. // Returns a ustring with the text in the selected
  1132. // region.
  1133. //
  1134. ustring GetRegion ()
  1135. {
  1136. long start, end;
  1137. GetEncodedRegionBounds (out start, out end);
  1138. if (start == end) {
  1139. return ustring.Empty;
  1140. }
  1141. int startRow = (int)(start >> 32);
  1142. var maxrow = ((int)(end >> 32));
  1143. int startCol = (int)(start & 0xffffffff);
  1144. var endCol = (int)(end & 0xffffffff);
  1145. var line = model.GetLine (startRow);
  1146. if (startRow == maxrow)
  1147. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1148. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1149. for (int row = startRow + 1; row < maxrow; row++) {
  1150. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  1151. }
  1152. line = model.GetLine (maxrow);
  1153. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  1154. return res;
  1155. }
  1156. //
  1157. // Clears the contents of the selected region
  1158. //
  1159. void ClearRegion ()
  1160. {
  1161. long start, end;
  1162. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1163. GetEncodedRegionBounds (out start, out end);
  1164. int startRow = (int)(start >> 32);
  1165. var maxrow = ((int)(end >> 32));
  1166. int startCol = (int)(start & 0xffffffff);
  1167. var endCol = (int)(end & 0xffffffff);
  1168. var line = model.GetLine (startRow);
  1169. if (startRow == maxrow) {
  1170. line.RemoveRange (startCol, endCol - startCol);
  1171. currentColumn = startCol;
  1172. if (wordWrap) {
  1173. SetNeedsDisplay ();
  1174. } else {
  1175. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1176. }
  1177. return;
  1178. }
  1179. line.RemoveRange (startCol, line.Count - startCol);
  1180. var line2 = model.GetLine (maxrow);
  1181. line.AddRange (line2.Skip (endCol));
  1182. for (int row = startRow + 1; row <= maxrow; row++) {
  1183. model.RemoveLine (startRow + 1);
  1184. }
  1185. if (currentEncoded == end) {
  1186. currentRow -= maxrow - (startRow);
  1187. }
  1188. currentColumn = startCol;
  1189. SetNeedsDisplay ();
  1190. }
  1191. /// <summary>
  1192. /// Select all text.
  1193. /// </summary>
  1194. public void SelectAll ()
  1195. {
  1196. if (model.Count == 0) {
  1197. return;
  1198. }
  1199. StartSelecting ();
  1200. selectionStartColumn = 0;
  1201. selectionStartRow = 0;
  1202. currentColumn = model.GetLine (model.Count - 1).Count;
  1203. currentRow = model.Count - 1;
  1204. SetNeedsDisplay ();
  1205. }
  1206. /// <summary>
  1207. /// Find the next text based on the match case with the option to replace it.
  1208. /// </summary>
  1209. /// <param name="textToFind">The text to find.</param>
  1210. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1211. /// <param name="matchCase">The match case setting.</param>
  1212. /// <param name="matchWholeWord">The match whole word setting.</param>
  1213. /// <param name="textToReplace">The text to replace.</param>
  1214. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1215. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1216. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1217. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1218. {
  1219. if (model.Count == 0) {
  1220. gaveFullTurn = false;
  1221. return false;
  1222. }
  1223. SetWrapModel ();
  1224. ResetContinuousFind ();
  1225. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1226. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1227. }
  1228. /// <summary>
  1229. /// Find the previous text based on the match case with the option to replace it.
  1230. /// </summary>
  1231. /// <param name="textToFind">The text to find.</param>
  1232. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1233. /// <param name="matchCase">The match case setting.</param>
  1234. /// <param name="matchWholeWord">The match whole word setting.</param>
  1235. /// <param name="textToReplace">The text to replace.</param>
  1236. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1237. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1238. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1239. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1240. {
  1241. if (model.Count == 0) {
  1242. gaveFullTurn = false;
  1243. return false;
  1244. }
  1245. SetWrapModel ();
  1246. ResetContinuousFind ();
  1247. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1248. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1249. }
  1250. /// <summary>
  1251. /// Reset the flag to stop continuous find.
  1252. /// </summary>
  1253. public void FindTextChanged ()
  1254. {
  1255. continuousFind = false;
  1256. }
  1257. /// <summary>
  1258. /// Replaces all the text based on the match case.
  1259. /// </summary>
  1260. /// <param name="textToFind">The text to find.</param>
  1261. /// <param name="matchCase">The match case setting.</param>
  1262. /// <param name="matchWholeWord">The match whole word setting.</param>
  1263. /// <param name="textToReplace">The text to replace.</param>
  1264. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1265. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1266. ustring textToReplace = null)
  1267. {
  1268. if (isReadOnly || model.Count == 0) {
  1269. return false;
  1270. }
  1271. SetWrapModel ();
  1272. ResetContinuousFind ();
  1273. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1274. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1275. }
  1276. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1277. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1278. {
  1279. if (foundPos.found) {
  1280. StartSelecting ();
  1281. selectionStartColumn = foundPos.current.X;
  1282. selectionStartRow = foundPos.current.Y;
  1283. if (!replaceAll) {
  1284. currentColumn = selectionStartColumn + text.RuneCount;
  1285. } else {
  1286. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1287. }
  1288. currentRow = foundPos.current.Y;
  1289. if (!isReadOnly && replace) {
  1290. Adjust ();
  1291. ClearSelectedRegion ();
  1292. InsertText (textToReplace);
  1293. StartSelecting ();
  1294. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1295. } else {
  1296. UpdateWrapModel ();
  1297. SetNeedsDisplay ();
  1298. Adjust ();
  1299. }
  1300. continuousFind = true;
  1301. return foundPos.found;
  1302. }
  1303. UpdateWrapModel ();
  1304. continuousFind = false;
  1305. return foundPos.found;
  1306. }
  1307. void ResetContinuousFind ()
  1308. {
  1309. if (!continuousFind) {
  1310. var col = selecting ? selectionStartColumn : currentColumn;
  1311. var row = selecting ? selectionStartRow : currentRow;
  1312. model.ResetContinuousFind (new Point (col, row));
  1313. }
  1314. }
  1315. /// <summary>
  1316. /// Restore from original model.
  1317. /// </summary>
  1318. void SetWrapModel ()
  1319. {
  1320. if (wordWrap) {
  1321. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  1322. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  1323. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  1324. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  1325. model = wrapManager.Model;
  1326. }
  1327. }
  1328. /// <summary>
  1329. /// Update the original model.
  1330. /// </summary>
  1331. void UpdateWrapModel ()
  1332. {
  1333. if (wordWrap) {
  1334. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  1335. out int nStartRow, out int nStartCol,
  1336. currentRow, currentColumn,
  1337. selectionStartRow, selectionStartColumn);
  1338. currentRow = nRow;
  1339. currentColumn = nCol;
  1340. selectionStartRow = nStartRow;
  1341. selectionStartColumn = nStartCol;
  1342. wrapNeeded = true;
  1343. }
  1344. }
  1345. ///<inheritdoc/>
  1346. public override void Redraw (Rect bounds)
  1347. {
  1348. ColorNormal ();
  1349. int bottom = bounds.Bottom;
  1350. int right = bounds.Right;
  1351. for (int row = bounds.Top; row < bottom; row++) {
  1352. int textLine = topRow + row;
  1353. if (textLine >= model.Count) {
  1354. ColorNormal ();
  1355. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  1356. continue;
  1357. }
  1358. var line = model.GetLine (textLine);
  1359. int lineRuneCount = line.Count;
  1360. if (line.Count < bounds.Left) {
  1361. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  1362. continue;
  1363. }
  1364. Move (bounds.Left, row);
  1365. var col = 0;
  1366. for (int idx = bounds.Left; idx < right; idx++) {
  1367. var lineCol = leftColumn + idx;
  1368. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  1369. var cols = Rune.ColumnWidth (rune);
  1370. if (lineCol < line.Count && selecting && PointInSelection (idx + leftColumn, row + topRow)) {
  1371. ColorSelection ();
  1372. } else if (lineCol == currentColumn && textLine == currentRow && !selecting && !Used
  1373. && HasFocus && lineCol < lineRuneCount) {
  1374. ColorUsed ();
  1375. } else {
  1376. ColorNormal ();
  1377. }
  1378. if (!SpecialRune (rune)) {
  1379. AddRune (col, row, rune);
  1380. } else {
  1381. col++;
  1382. }
  1383. col = TextModel.SetCol (col, bounds.Right, cols);
  1384. if (idx + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idx + 1]) > right) {
  1385. break;
  1386. } else if (idx == lineRuneCount - 1) {
  1387. ColorNormal ();
  1388. for (int i = col; i < right; i++) {
  1389. Driver.AddRune (' ');
  1390. }
  1391. }
  1392. }
  1393. }
  1394. PositionCursor ();
  1395. }
  1396. bool SpecialRune (Rune rune)
  1397. {
  1398. switch (rune) {
  1399. case (uint)Key.Enter:
  1400. case 0xd:
  1401. return true;
  1402. default:
  1403. return false;
  1404. }
  1405. }
  1406. ///<inheritdoc/>
  1407. public override bool CanFocus {
  1408. get => base.CanFocus;
  1409. set { base.CanFocus = value; }
  1410. }
  1411. void SetClipboard (ustring text)
  1412. {
  1413. if (!text.IsEmpty) {
  1414. Clipboard.Contents = text;
  1415. }
  1416. }
  1417. void AppendClipboard (ustring text)
  1418. {
  1419. Clipboard.Contents += text;
  1420. }
  1421. void Insert (Rune rune)
  1422. {
  1423. var line = GetCurrentLine ();
  1424. if (Used) {
  1425. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1426. } else {
  1427. if (currentColumn < line.Count) {
  1428. line.RemoveAt (currentColumn);
  1429. }
  1430. line.Insert (Math.Min (currentColumn, line.Count), rune);
  1431. }
  1432. if (wordWrap) {
  1433. if (Used) {
  1434. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1435. } else {
  1436. wrapNeeded = wrapManager.RemoveAt (currentRow, currentColumn);
  1437. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  1438. }
  1439. if (wrapNeeded) {
  1440. SetNeedsDisplay ();
  1441. }
  1442. }
  1443. var prow = currentRow - topRow;
  1444. if (!wrapNeeded) {
  1445. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  1446. }
  1447. }
  1448. ustring StringFromRunes (List<Rune> runes)
  1449. {
  1450. if (runes == null)
  1451. throw new ArgumentNullException (nameof (runes));
  1452. int size = 0;
  1453. foreach (var rune in runes) {
  1454. size += Utf8.RuneLen (rune);
  1455. }
  1456. var encoded = new byte [size];
  1457. int offset = 0;
  1458. foreach (var rune in runes) {
  1459. offset += Utf8.EncodeRune (rune, encoded, offset);
  1460. }
  1461. return ustring.Make (encoded);
  1462. }
  1463. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  1464. void InsertText (ustring text)
  1465. {
  1466. if (ustring.IsNullOrEmpty (text)) {
  1467. return;
  1468. }
  1469. var lines = TextModel.StringToRunes (text);
  1470. if (lines.Count == 0) {
  1471. return;
  1472. }
  1473. var line = GetCurrentLine ();
  1474. // Optimize single line
  1475. if (lines.Count == 1) {
  1476. line.InsertRange (currentColumn, lines [0]);
  1477. currentColumn += lines [0].Count;
  1478. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  1479. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  1480. }
  1481. if (wordWrap) {
  1482. SetNeedsDisplay ();
  1483. } else {
  1484. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  1485. }
  1486. return;
  1487. }
  1488. List<Rune> rest = null;
  1489. int lastp = 0;
  1490. if (model.Count > 0 && currentColumn > 0) {
  1491. // Keep a copy of the rest of the line
  1492. var restCount = line.Count - currentColumn;
  1493. rest = line.GetRange (currentColumn, restCount);
  1494. line.RemoveRange (currentColumn, restCount);
  1495. }
  1496. // First line is inserted at the current location, the rest is appended
  1497. line.InsertRange (currentColumn, lines [0]);
  1498. //model.AddLine (currentRow, lines [0]);
  1499. for (int i = 1; i < lines.Count; i++) {
  1500. model.AddLine (currentRow + i, lines [i]);
  1501. }
  1502. if (rest != null) {
  1503. var last = model.GetLine (currentRow + lines.Count - 1);
  1504. lastp = last.Count;
  1505. last.InsertRange (last.Count, rest);
  1506. }
  1507. // Now adjust column and row positions
  1508. currentRow += lines.Count - 1;
  1509. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  1510. Adjust ();
  1511. }
  1512. // The column we are tracking, or -1 if we are not tracking any column
  1513. int columnTrack = -1;
  1514. // Tries to snap the cursor to the tracking column
  1515. void TrackColumn ()
  1516. {
  1517. // Now track the column
  1518. var line = GetCurrentLine ();
  1519. if (line.Count < columnTrack)
  1520. currentColumn = line.Count;
  1521. else if (columnTrack != -1)
  1522. currentColumn = columnTrack;
  1523. else if (currentColumn > line.Count)
  1524. currentColumn = line.Count;
  1525. Adjust ();
  1526. }
  1527. void Adjust ()
  1528. {
  1529. var offB = OffSetBackground ();
  1530. var line = GetCurrentLine ();
  1531. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  1532. if (!wordWrap && currentColumn < leftColumn) {
  1533. leftColumn = currentColumn;
  1534. need = true;
  1535. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width ||
  1536. TextModel.DisplaySize (line, leftColumn, currentColumn).size + RightOffset >= Frame.Width + offB.width)) {
  1537. leftColumn = Math.Max (TextModel.CalculateLeftColumn (line, leftColumn,
  1538. currentColumn + RightOffset, Frame.Width - 1 + offB.width, currentColumn), 0);
  1539. need = true;
  1540. }
  1541. if (currentRow < topRow) {
  1542. topRow = currentRow;
  1543. need = true;
  1544. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  1545. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  1546. need = true;
  1547. }
  1548. if (need) {
  1549. if (wrapNeeded) {
  1550. WrapTextModel ();
  1551. wrapNeeded = false;
  1552. }
  1553. SetNeedsDisplay ();
  1554. } else {
  1555. PositionCursor ();
  1556. }
  1557. }
  1558. (int width, int height) OffSetBackground ()
  1559. {
  1560. int w = 0;
  1561. int h = 0;
  1562. if (SuperView?.Frame.Right - Frame.Right < 0) {
  1563. w = SuperView.Frame.Right - Frame.Right - 1;
  1564. }
  1565. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  1566. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  1567. }
  1568. return (w, h);
  1569. }
  1570. /// <summary>
  1571. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  1572. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  1573. /// </summary>
  1574. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  1575. /// if the value is negative it will be reset to zero</param>
  1576. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  1577. public void ScrollTo (int idx, bool isRow = true)
  1578. {
  1579. if (idx < 0) {
  1580. idx = 0;
  1581. }
  1582. if (isRow) {
  1583. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  1584. } else if (!wordWrap) {
  1585. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset);
  1586. leftColumn = Math.Max (idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  1587. }
  1588. SetNeedsDisplay ();
  1589. }
  1590. bool lastWasKill;
  1591. bool wrapNeeded;
  1592. bool shiftSelecting;
  1593. ///<inheritdoc/>
  1594. public override bool ProcessKey (KeyEvent kb)
  1595. {
  1596. int restCount;
  1597. List<Rune> rest;
  1598. bool lineRemoved = false;
  1599. // Handle some state here - whether the last command was a kill
  1600. // operation and the column tracking (up/down)
  1601. switch (kb.Key) {
  1602. case Key.N | Key.CtrlMask:
  1603. case Key.CursorDown:
  1604. case Key.P | Key.CtrlMask:
  1605. case Key.CursorUp:
  1606. lastWasKill = false;
  1607. continuousFind = false;
  1608. break;
  1609. case Key.K | Key.CtrlMask:
  1610. break;
  1611. case Key.F | Key.CtrlMask:
  1612. case Key.B | Key.CtrlMask:
  1613. case (Key)((int)'B' + Key.AltMask):
  1614. case Key.A | Key.CtrlMask:
  1615. case Key.E | Key.CtrlMask:
  1616. case Key.CursorRight:
  1617. case Key.CursorLeft:
  1618. case Key.CursorRight | Key.CtrlMask:
  1619. case Key.CursorLeft | Key.CtrlMask:
  1620. case Key.CursorRight | Key.ShiftMask:
  1621. case Key.CursorLeft | Key.ShiftMask:
  1622. case Key.CursorRight | Key.CtrlMask | Key.ShiftMask:
  1623. case Key.CursorLeft | Key.CtrlMask | Key.ShiftMask:
  1624. case Key.Home:
  1625. case Key.Home | Key.CtrlMask:
  1626. case Key.Home | Key.ShiftMask:
  1627. case Key.Home | Key.CtrlMask | Key.ShiftMask:
  1628. case Key.End:
  1629. case Key.End | Key.CtrlMask:
  1630. case Key.End | Key.ShiftMask:
  1631. case Key.End | Key.CtrlMask | Key.ShiftMask:
  1632. lastWasKill = false;
  1633. columnTrack = -1;
  1634. continuousFind = false;
  1635. break;
  1636. default:
  1637. lastWasKill = false;
  1638. columnTrack = -1;
  1639. break;
  1640. }
  1641. // Dispatch the command.
  1642. switch (kb.Key) {
  1643. case Key.PageDown:
  1644. case Key.V | Key.CtrlMask:
  1645. case Key.PageDown | Key.ShiftMask:
  1646. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1647. StartSelecting ();
  1648. } else if (shiftSelecting && selecting) {
  1649. StopSelecting ();
  1650. }
  1651. int nPageDnShift = Frame.Height - 1;
  1652. if (currentRow < model.Count) {
  1653. if (columnTrack == -1)
  1654. columnTrack = currentColumn;
  1655. currentRow = (currentRow + nPageDnShift) > model.Count
  1656. ? model.Count > 0 ? model.Count - 1 : 0
  1657. : currentRow + nPageDnShift;
  1658. if (topRow < currentRow - nPageDnShift) {
  1659. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  1660. SetNeedsDisplay ();
  1661. }
  1662. TrackColumn ();
  1663. PositionCursor ();
  1664. }
  1665. break;
  1666. case Key.PageUp:
  1667. case ((int)'V' + Key.AltMask):
  1668. case Key.PageUp | Key.ShiftMask:
  1669. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1670. StartSelecting ();
  1671. } else if (shiftSelecting && selecting) {
  1672. StopSelecting ();
  1673. }
  1674. int nPageUpShift = Frame.Height - 1;
  1675. if (currentRow > 0) {
  1676. if (columnTrack == -1)
  1677. columnTrack = currentColumn;
  1678. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  1679. if (currentRow < topRow) {
  1680. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  1681. SetNeedsDisplay ();
  1682. }
  1683. TrackColumn ();
  1684. PositionCursor ();
  1685. }
  1686. break;
  1687. case Key.N | Key.CtrlMask:
  1688. case Key.CursorDown:
  1689. case Key.CursorDown | Key.ShiftMask:
  1690. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1691. StartSelecting ();
  1692. } else if (shiftSelecting && selecting) {
  1693. StopSelecting ();
  1694. }
  1695. MoveDown ();
  1696. break;
  1697. case Key.P | Key.CtrlMask:
  1698. case Key.CursorUp:
  1699. case Key.CursorUp | Key.ShiftMask:
  1700. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1701. StartSelecting ();
  1702. } else if (shiftSelecting && selecting) {
  1703. StopSelecting ();
  1704. }
  1705. MoveUp ();
  1706. break;
  1707. case Key.F | Key.CtrlMask:
  1708. case Key.CursorRight:
  1709. case Key.CursorRight | Key.ShiftMask:
  1710. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1711. StartSelecting ();
  1712. } else if (shiftSelecting && selecting) {
  1713. StopSelecting ();
  1714. }
  1715. var currentLine = GetCurrentLine ();
  1716. if (currentColumn < currentLine.Count) {
  1717. currentColumn++;
  1718. } else {
  1719. if (currentRow + 1 < model.Count) {
  1720. currentRow++;
  1721. currentColumn = 0;
  1722. if (currentRow >= topRow + Frame.Height) {
  1723. topRow++;
  1724. SetNeedsDisplay ();
  1725. }
  1726. }
  1727. }
  1728. Adjust ();
  1729. break;
  1730. case Key.B | Key.CtrlMask:
  1731. case Key.CursorLeft:
  1732. case Key.CursorLeft | Key.ShiftMask:
  1733. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1734. StartSelecting ();
  1735. } else if (shiftSelecting && selecting) {
  1736. StopSelecting ();
  1737. }
  1738. if (currentColumn > 0) {
  1739. currentColumn--;
  1740. } else {
  1741. if (currentRow > 0) {
  1742. currentRow--;
  1743. if (currentRow < topRow) {
  1744. topRow--;
  1745. SetNeedsDisplay ();
  1746. }
  1747. currentLine = GetCurrentLine ();
  1748. currentColumn = currentLine.Count;
  1749. }
  1750. }
  1751. Adjust ();
  1752. break;
  1753. case Key.Delete:
  1754. case Key.Backspace:
  1755. if (isReadOnly)
  1756. break;
  1757. if (selecting) {
  1758. ClearSelectedRegion ();
  1759. return true;
  1760. }
  1761. if (currentColumn > 0) {
  1762. // Delete backwards
  1763. currentLine = GetCurrentLine ();
  1764. currentLine.RemoveAt (currentColumn - 1);
  1765. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn - 1)) {
  1766. wrapNeeded = true;
  1767. }
  1768. currentColumn--;
  1769. if (currentColumn < leftColumn) {
  1770. leftColumn--;
  1771. SetNeedsDisplay ();
  1772. } else
  1773. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  1774. } else {
  1775. // Merges the current line with the previous one.
  1776. if (currentRow == 0)
  1777. return true;
  1778. var prowIdx = currentRow - 1;
  1779. var prevRow = model.GetLine (prowIdx);
  1780. var prevCount = prevRow.Count;
  1781. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  1782. model.RemoveLine (currentRow);
  1783. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out lineRemoved, false)) {
  1784. wrapNeeded = true;
  1785. }
  1786. currentRow--;
  1787. if (wrapNeeded && !lineRemoved) {
  1788. currentColumn = Math.Max (prevCount - 1, 0);
  1789. } else {
  1790. currentColumn = prevCount;
  1791. }
  1792. Adjust ();
  1793. }
  1794. break;
  1795. // Home, C-A
  1796. case Key.Home:
  1797. case Key.Home | Key.ShiftMask:
  1798. case Key.A | Key.CtrlMask:
  1799. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1800. StartSelecting ();
  1801. } else if (shiftSelecting && selecting) {
  1802. StopSelecting ();
  1803. }
  1804. currentColumn = 0;
  1805. Adjust ();
  1806. break;
  1807. case Key.DeleteChar:
  1808. case Key.D | Key.CtrlMask: // Delete
  1809. if (isReadOnly)
  1810. break;
  1811. if (selecting) {
  1812. ClearSelectedRegion ();
  1813. return true;
  1814. }
  1815. currentLine = GetCurrentLine ();
  1816. if (currentColumn == currentLine.Count) {
  1817. if (currentRow + 1 == model.Count)
  1818. break;
  1819. var nextLine = model.GetLine (currentRow + 1);
  1820. currentLine.AddRange (nextLine);
  1821. model.RemoveLine (currentRow + 1);
  1822. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out _)) {
  1823. wrapNeeded = true;
  1824. }
  1825. var sr = currentRow - topRow;
  1826. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  1827. } else {
  1828. currentLine.RemoveAt (currentColumn);
  1829. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn)) {
  1830. wrapNeeded = true;
  1831. }
  1832. var r = currentRow - topRow;
  1833. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  1834. }
  1835. break;
  1836. case Key.End:
  1837. case Key.End | Key.ShiftMask:
  1838. case Key.E | Key.CtrlMask: // End
  1839. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1840. StartSelecting ();
  1841. } else if (shiftSelecting && selecting) {
  1842. StopSelecting ();
  1843. }
  1844. currentLine = GetCurrentLine ();
  1845. currentColumn = currentLine.Count;
  1846. int pcol = leftColumn;
  1847. Adjust ();
  1848. break;
  1849. case Key.K | Key.CtrlMask: // kill-to-end
  1850. if (isReadOnly)
  1851. break;
  1852. var cRow = currentRow;
  1853. SetWrapModel ();
  1854. currentLine = GetCurrentLine ();
  1855. var setLastWasKill = true;
  1856. if (currentLine.Count == 0) {
  1857. model.RemoveLine (currentRow);
  1858. if (model.Count > 0 || lastWasKill) {
  1859. var val = ustring.Make ((Rune)'\n');
  1860. if (lastWasKill) {
  1861. AppendClipboard (val);
  1862. } else {
  1863. SetClipboard (val);
  1864. }
  1865. }
  1866. if (model.Count == 0) {
  1867. // Prevents from adding line feeds if there is no more lines.
  1868. setLastWasKill = false;
  1869. }
  1870. if (currentRow > 0) {
  1871. currentRow--;
  1872. }
  1873. } else {
  1874. restCount = currentLine.Count - currentColumn;
  1875. rest = currentLine.GetRange (currentColumn, restCount);
  1876. var val = ustring.Empty;
  1877. if (currentColumn == 0 && lastWasKill && currentLine.Count > 0) {
  1878. val = ustring.Make ((Rune)'\n');
  1879. }
  1880. val += StringFromRunes (rest);
  1881. if (lastWasKill) {
  1882. AppendClipboard (val);
  1883. } else {
  1884. SetClipboard (val);
  1885. }
  1886. if (currentColumn == 0) {
  1887. model.RemoveLine (currentRow);
  1888. if (currentRow > 0) {
  1889. currentRow--;
  1890. }
  1891. } else {
  1892. currentLine.RemoveRange (currentColumn, restCount);
  1893. }
  1894. if (model.Count == 0) {
  1895. // Prevents from adding line feeds if there is no more lines.
  1896. setLastWasKill = false;
  1897. }
  1898. }
  1899. UpdateWrapModel ();
  1900. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  1901. lastWasKill = setLastWasKill;
  1902. break;
  1903. case Key.Y | Key.CtrlMask: // Control-y, yank
  1904. if (isReadOnly)
  1905. break;
  1906. Paste ();
  1907. return true;
  1908. case Key.Space | Key.CtrlMask:
  1909. selecting = !selecting;
  1910. selectionStartColumn = currentColumn;
  1911. selectionStartRow = currentRow;
  1912. break;
  1913. case ((int)'C' + Key.AltMask):
  1914. case Key.C | Key.CtrlMask:
  1915. Copy ();
  1916. return true;
  1917. case ((int)'W' + Key.AltMask):
  1918. case Key.W | Key.CtrlMask:
  1919. case Key.X | Key.CtrlMask:
  1920. Cut ();
  1921. return true;
  1922. case Key.CtrlMask | Key.CursorLeft:
  1923. case Key.CtrlMask | Key.CursorLeft | Key.ShiftMask:
  1924. case (Key)((int)'B' + Key.AltMask):
  1925. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1926. StartSelecting ();
  1927. } else if (shiftSelecting && selecting) {
  1928. StopSelecting ();
  1929. }
  1930. var newPos = WordBackward (currentColumn, currentRow);
  1931. if (newPos.HasValue) {
  1932. currentColumn = newPos.Value.col;
  1933. currentRow = newPos.Value.row;
  1934. }
  1935. Adjust ();
  1936. break;
  1937. case Key.CtrlMask | Key.CursorRight:
  1938. case Key.CtrlMask | Key.CursorRight | Key.ShiftMask:
  1939. case (Key)((int)'F' + Key.AltMask):
  1940. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1941. StartSelecting ();
  1942. } else if (shiftSelecting && selecting) {
  1943. StopSelecting ();
  1944. }
  1945. newPos = WordForward (currentColumn, currentRow);
  1946. if (newPos.HasValue) {
  1947. currentColumn = newPos.Value.col;
  1948. currentRow = newPos.Value.row;
  1949. }
  1950. Adjust ();
  1951. break;
  1952. case Key.Enter:
  1953. if (isReadOnly)
  1954. break;
  1955. currentLine = GetCurrentLine ();
  1956. restCount = currentLine.Count - currentColumn;
  1957. rest = currentLine.GetRange (currentColumn, restCount);
  1958. currentLine.RemoveRange (currentColumn, restCount);
  1959. model.AddLine (currentRow + 1, rest);
  1960. if (wordWrap) {
  1961. wrapManager.AddLine (currentRow, currentColumn);
  1962. wrapNeeded = true;
  1963. }
  1964. currentRow++;
  1965. bool fullNeedsDisplay = false;
  1966. if (currentRow >= topRow + Frame.Height) {
  1967. topRow++;
  1968. fullNeedsDisplay = true;
  1969. }
  1970. currentColumn = 0;
  1971. if (!wordWrap && currentColumn < leftColumn) {
  1972. fullNeedsDisplay = true;
  1973. leftColumn = 0;
  1974. }
  1975. if (fullNeedsDisplay)
  1976. SetNeedsDisplay ();
  1977. else
  1978. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  1979. break;
  1980. case Key.CtrlMask | Key.End:
  1981. case Key.CtrlMask | Key.End | Key.ShiftMask:
  1982. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1983. StartSelecting ();
  1984. } else if (shiftSelecting && selecting) {
  1985. StopSelecting ();
  1986. }
  1987. MoveEnd ();
  1988. break;
  1989. case Key.CtrlMask | Key.Home:
  1990. case Key.CtrlMask | Key.Home | Key.ShiftMask:
  1991. if (kb.Key.HasFlag (Key.ShiftMask)) {
  1992. StartSelecting ();
  1993. } else if (shiftSelecting && selecting) {
  1994. StopSelecting ();
  1995. }
  1996. MoveHome ();
  1997. break;
  1998. case Key.T | Key.CtrlMask:
  1999. SelectAll ();
  2000. break;
  2001. case Key.InsertChar:
  2002. Used = !Used;
  2003. SetNeedsDisplay ();
  2004. break;
  2005. default:
  2006. // Ignore control characters and other special keys
  2007. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2008. return false;
  2009. //So that special keys like tab can be processed
  2010. if (isReadOnly)
  2011. return true;
  2012. if (selecting) {
  2013. ClearSelectedRegion ();
  2014. }
  2015. if (Used) {
  2016. Insert ((uint)kb.Key);
  2017. currentColumn++;
  2018. if (currentColumn >= leftColumn + Frame.Width) {
  2019. leftColumn++;
  2020. SetNeedsDisplay ();
  2021. }
  2022. } else {
  2023. Insert ((uint)kb.Key);
  2024. currentColumn++;
  2025. }
  2026. break;
  2027. }
  2028. DoNeededAction ();
  2029. return true;
  2030. }
  2031. ///<inheritdoc/>
  2032. public override bool OnKeyUp (KeyEvent kb)
  2033. {
  2034. switch (kb.Key) {
  2035. case Key.Space | Key.CtrlMask:
  2036. return true;
  2037. }
  2038. return false;
  2039. }
  2040. void DoNeededAction ()
  2041. {
  2042. if (NeedDisplay.IsEmpty) {
  2043. PositionCursor ();
  2044. } else {
  2045. Adjust ();
  2046. }
  2047. }
  2048. /// <summary>
  2049. /// Copy the selected text to the clipboard contents.
  2050. /// </summary>
  2051. public void Copy ()
  2052. {
  2053. SetWrapModel ();
  2054. SetClipboard (GetRegion ());
  2055. UpdateWrapModel ();
  2056. DoNeededAction ();
  2057. }
  2058. /// <summary>
  2059. /// Cut the selected text to the clipboard contents.
  2060. /// </summary>
  2061. public void Cut ()
  2062. {
  2063. SetWrapModel ();
  2064. SetClipboard (GetRegion ());
  2065. if (!isReadOnly) {
  2066. ClearRegion ();
  2067. }
  2068. UpdateWrapModel ();
  2069. selecting = false;
  2070. DoNeededAction ();
  2071. }
  2072. /// <summary>
  2073. /// Paste the clipboard contents into the current selected position.
  2074. /// </summary>
  2075. public void Paste ()
  2076. {
  2077. if (isReadOnly) {
  2078. return;
  2079. }
  2080. SetWrapModel ();
  2081. if (selecting) {
  2082. ClearRegion ();
  2083. }
  2084. InsertText (Clipboard.Contents);
  2085. UpdateWrapModel ();
  2086. selecting = false;
  2087. DoNeededAction ();
  2088. }
  2089. void StartSelecting ()
  2090. {
  2091. if (shiftSelecting && selecting) {
  2092. return;
  2093. }
  2094. shiftSelecting = true;
  2095. selecting = true;
  2096. selectionStartColumn = currentColumn;
  2097. selectionStartRow = currentRow;
  2098. }
  2099. void StopSelecting ()
  2100. {
  2101. shiftSelecting = false;
  2102. selecting = false;
  2103. }
  2104. void ClearSelectedRegion ()
  2105. {
  2106. SetWrapModel ();
  2107. if (!isReadOnly) {
  2108. ClearRegion ();
  2109. }
  2110. UpdateWrapModel ();
  2111. selecting = false;
  2112. DoNeededAction ();
  2113. }
  2114. void MoveUp ()
  2115. {
  2116. if (currentRow > 0) {
  2117. if (columnTrack == -1) {
  2118. columnTrack = currentColumn;
  2119. }
  2120. currentRow--;
  2121. if (currentRow < topRow) {
  2122. topRow--;
  2123. SetNeedsDisplay ();
  2124. }
  2125. TrackColumn ();
  2126. PositionCursor ();
  2127. }
  2128. }
  2129. void MoveDown ()
  2130. {
  2131. if (currentRow + 1 < model.Count) {
  2132. if (columnTrack == -1) {
  2133. columnTrack = currentColumn;
  2134. }
  2135. currentRow++;
  2136. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  2137. topRow++;
  2138. SetNeedsDisplay ();
  2139. }
  2140. TrackColumn ();
  2141. PositionCursor ();
  2142. } else if (currentRow > Frame.Height) {
  2143. Adjust ();
  2144. }
  2145. }
  2146. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  2147. {
  2148. if (col < 0 || row < 0)
  2149. yield break;
  2150. if (row >= model.Count)
  2151. yield break;
  2152. var line = GetCurrentLine ();
  2153. if (col >= line.Count)
  2154. yield break;
  2155. while (row < model.Count) {
  2156. for (int c = col; c < line.Count; c++) {
  2157. yield return (c, row, line [c]);
  2158. }
  2159. col = 0;
  2160. row++;
  2161. line = GetCurrentLine ();
  2162. }
  2163. }
  2164. Rune RuneAt (int col, int row)
  2165. {
  2166. var line = model.GetLine (row);
  2167. if (line.Count > 0) {
  2168. return line [col > line.Count - 1 ? line.Count - 1 : col];
  2169. } else {
  2170. return 0;
  2171. }
  2172. }
  2173. /// <summary>
  2174. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  2175. /// </summary>
  2176. public void MoveEnd ()
  2177. {
  2178. currentRow = model.Count - 1;
  2179. var line = GetCurrentLine ();
  2180. currentColumn = line.Count;
  2181. TrackColumn ();
  2182. PositionCursor ();
  2183. }
  2184. /// <summary>
  2185. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  2186. /// </summary>
  2187. public void MoveHome ()
  2188. {
  2189. currentRow = 0;
  2190. currentColumn = 0;
  2191. TrackColumn ();
  2192. PositionCursor ();
  2193. }
  2194. bool MoveNext (ref int col, ref int row, out Rune rune)
  2195. {
  2196. var line = model.GetLine (row);
  2197. if (col + 1 < line.Count) {
  2198. col++;
  2199. rune = line [col];
  2200. if (col + 1 == line.Count) {
  2201. col++;
  2202. }
  2203. return true;
  2204. }
  2205. while (row + 1 < model.Count) {
  2206. col = 0;
  2207. row++;
  2208. line = model.GetLine (row);
  2209. if (line.Count > 0) {
  2210. rune = line [0];
  2211. return true;
  2212. }
  2213. }
  2214. rune = 0;
  2215. return false;
  2216. }
  2217. bool MovePrev (ref int col, ref int row, out Rune rune)
  2218. {
  2219. var line = model.GetLine (row);
  2220. if (col > 0) {
  2221. col--;
  2222. rune = line [col];
  2223. return true;
  2224. }
  2225. if (row == 0) {
  2226. rune = 0;
  2227. return false;
  2228. }
  2229. while (row > 0) {
  2230. row--;
  2231. line = model.GetLine (row);
  2232. col = line.Count - 1;
  2233. if (col >= 0) {
  2234. rune = line [col];
  2235. return true;
  2236. }
  2237. }
  2238. rune = 0;
  2239. return false;
  2240. }
  2241. (int col, int row)? WordForward (int fromCol, int fromRow)
  2242. {
  2243. var col = fromCol;
  2244. var row = fromRow;
  2245. try {
  2246. var rune = RuneAt (col, row);
  2247. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  2248. {
  2249. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  2250. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  2251. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  2252. return;
  2253. }
  2254. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  2255. return;
  2256. }
  2257. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  2258. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  2259. break;
  2260. }
  2261. } else {
  2262. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  2263. return;
  2264. }
  2265. var line = model.GetLine (fromRow);
  2266. if ((nRow != fromRow && fromCol < line.Count)
  2267. || (nRow == fromRow && nCol == line.Count - 1)) {
  2268. nCol = line.Count;
  2269. nRow = fromRow;
  2270. return;
  2271. } else if (nRow != fromRow && fromCol == line.Count) {
  2272. line = model.GetLine (nRow);
  2273. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  2274. return;
  2275. }
  2276. }
  2277. ProcMoveNext (ref nCol, ref nRow, nRune);
  2278. }
  2279. }
  2280. ProcMoveNext (ref col, ref row, rune);
  2281. if (fromCol != col || fromRow != row)
  2282. return (col, row);
  2283. return null;
  2284. } catch (Exception) {
  2285. return null;
  2286. }
  2287. }
  2288. (int col, int row)? WordBackward (int fromCol, int fromRow)
  2289. {
  2290. if (fromRow == 0 && fromCol == 0)
  2291. return null;
  2292. var col = Math.Max (fromCol - 1, 0);
  2293. var row = fromRow;
  2294. try {
  2295. var rune = RuneAt (col, row);
  2296. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  2297. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  2298. {
  2299. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  2300. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  2301. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  2302. lastValidCol = nCol;
  2303. break;
  2304. }
  2305. }
  2306. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  2307. return;
  2308. }
  2309. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  2310. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  2311. break;
  2312. lastValidCol = nCol;
  2313. }
  2314. if (lastValidCol > -1) {
  2315. nCol = lastValidCol;
  2316. }
  2317. } else {
  2318. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  2319. return;
  2320. }
  2321. var line = model.GetLine (nRow);
  2322. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  2323. return;
  2324. }
  2325. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  2326. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  2327. nCol = lastValidCol;
  2328. return;
  2329. }
  2330. if (fromRow != nRow) {
  2331. nCol = line.Count;
  2332. return;
  2333. }
  2334. ProcMovePrev (ref nCol, ref nRow, nRune);
  2335. }
  2336. }
  2337. ProcMovePrev (ref col, ref row, rune);
  2338. if (fromCol != col || fromRow != row)
  2339. return (col, row);
  2340. return null;
  2341. } catch (Exception) {
  2342. return null;
  2343. }
  2344. }
  2345. ///<inheritdoc/>
  2346. public override bool MouseEvent (MouseEvent ev)
  2347. {
  2348. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  2349. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  2350. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  2351. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  2352. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  2353. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  2354. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)) {
  2355. return false;
  2356. }
  2357. if (!CanFocus) {
  2358. return true;
  2359. }
  2360. if (!HasFocus) {
  2361. SetFocus ();
  2362. }
  2363. continuousFind = false;
  2364. if (ev.Flags == MouseFlags.Button1Clicked) {
  2365. if (shiftSelecting) {
  2366. shiftSelecting = false;
  2367. selecting = false;
  2368. }
  2369. ProcessMouseClick (ev, out _);
  2370. PositionCursor ();
  2371. lastWasKill = false;
  2372. columnTrack = currentColumn;
  2373. } else if (ev.Flags == MouseFlags.WheeledDown) {
  2374. lastWasKill = false;
  2375. columnTrack = currentColumn;
  2376. ScrollTo (topRow + 1);
  2377. } else if (ev.Flags == MouseFlags.WheeledUp) {
  2378. lastWasKill = false;
  2379. columnTrack = currentColumn;
  2380. ScrollTo (topRow - 1);
  2381. } else if (ev.Flags == MouseFlags.WheeledRight) {
  2382. lastWasKill = false;
  2383. columnTrack = currentColumn;
  2384. ScrollTo (leftColumn + 1, false);
  2385. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  2386. lastWasKill = false;
  2387. columnTrack = currentColumn;
  2388. ScrollTo (leftColumn - 1, false);
  2389. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  2390. ProcessMouseClick (ev, out List<Rune> line);
  2391. PositionCursor ();
  2392. if (model.Count > 0 && shiftSelecting && selecting) {
  2393. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  2394. && model.Count + BottomOffset > topRow + currentRow) {
  2395. ScrollTo (topRow + Frame.Height);
  2396. } else if (topRow > 0 && currentRow <= topRow) {
  2397. ScrollTo (topRow - Frame.Height);
  2398. } else if (ev.Y >= Frame.Height) {
  2399. ScrollTo (model.Count + BottomOffset);
  2400. } else if (ev.Y < 0 && topRow > 0) {
  2401. ScrollTo (0);
  2402. }
  2403. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  2404. && line.Count + RightOffset > leftColumn + currentColumn) {
  2405. ScrollTo (leftColumn + Frame.Width, false);
  2406. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  2407. ScrollTo (leftColumn - Frame.Width, false);
  2408. } else if (ev.X >= Frame.Width) {
  2409. ScrollTo (line.Count + RightOffset, false);
  2410. } else if (ev.X < 0 && leftColumn > 0) {
  2411. ScrollTo (0, false);
  2412. }
  2413. }
  2414. lastWasKill = false;
  2415. columnTrack = currentColumn;
  2416. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  2417. if (!shiftSelecting) {
  2418. StartSelecting ();
  2419. }
  2420. ProcessMouseClick (ev, out _);
  2421. PositionCursor ();
  2422. lastWasKill = false;
  2423. columnTrack = currentColumn;
  2424. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  2425. if (shiftSelecting) {
  2426. shiftSelecting = false;
  2427. selecting = false;
  2428. }
  2429. ProcessMouseClick (ev, out _);
  2430. PositionCursor ();
  2431. if (!selecting) {
  2432. StartSelecting ();
  2433. }
  2434. lastWasKill = false;
  2435. columnTrack = currentColumn;
  2436. if (Application.mouseGrabView == null) {
  2437. Application.GrabMouse (this);
  2438. }
  2439. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  2440. Application.UngrabMouse ();
  2441. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  2442. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  2443. if (!selecting) {
  2444. StartSelecting ();
  2445. }
  2446. } else if (selecting) {
  2447. StopSelecting ();
  2448. }
  2449. ProcessMouseClick (ev, out List<Rune> line);
  2450. (int col, int row)? newPos = null;
  2451. if (currentColumn > 0 && line [currentColumn - 1] != ' ') {
  2452. newPos = WordBackward (currentColumn, currentRow);
  2453. if (newPos.HasValue) {
  2454. currentColumn = newPos.Value.col;
  2455. currentRow = newPos.Value.row;
  2456. }
  2457. }
  2458. if (!selecting) {
  2459. StartSelecting ();
  2460. }
  2461. if (currentRow < selectionStartRow || currentRow == selectionStartRow && currentColumn < selectionStartColumn) {
  2462. if (currentColumn > 0 && line [currentColumn - 1] != ' ') {
  2463. newPos = WordBackward (currentColumn, currentRow);
  2464. }
  2465. } else {
  2466. newPos = WordForward (currentColumn, currentRow);
  2467. }
  2468. if (newPos != null && newPos.HasValue) {
  2469. currentColumn = newPos.Value.col;
  2470. currentRow = newPos.Value.row;
  2471. }
  2472. PositionCursor ();
  2473. lastWasKill = false;
  2474. columnTrack = currentColumn;
  2475. }
  2476. return true;
  2477. }
  2478. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  2479. {
  2480. List<Rune> r = null;
  2481. if (model.Count > 0) {
  2482. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  2483. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  2484. currentRow = maxCursorPositionableLine + topRow;
  2485. } else {
  2486. currentRow = Math.Max (ev.Y + topRow, 0);
  2487. }
  2488. r = GetCurrentLine ();
  2489. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0));
  2490. if (idx - leftColumn >= r.Count + RightOffset) {
  2491. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  2492. } else {
  2493. currentColumn = idx + leftColumn;
  2494. }
  2495. }
  2496. line = r;
  2497. }
  2498. ///<inheritdoc/>
  2499. public override bool OnLeave (View view)
  2500. {
  2501. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  2502. Application.UngrabMouse ();
  2503. }
  2504. return base.OnLeave (view);
  2505. }
  2506. }
  2507. }