Geen omschrijving
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LongTextArea.cs 128KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using UnityEngine;
  7. using UnityEditor;
  8. [assembly: InternalsVisibleTo("Unity.Burst.Editor.Tests")]
  9. namespace Unity.Burst.Editor
  10. {
  11. internal class LongTextArea
  12. {
  13. internal const float naturalEnhancedPad = 20f;
  14. private const int kMaxFragment = 2048;
  15. internal struct Fragment
  16. {
  17. public int lineCount;
  18. public string text;
  19. }
  20. public enum Direction
  21. {
  22. Left,
  23. Right,
  24. Up,
  25. Down
  26. }
  27. internal struct Branch
  28. {
  29. public BurstDisassembler.AsmEdge Edge;
  30. public Rect StartHorizontal;
  31. public Rect VerticalLine;
  32. public Rect EndHorizontal;
  33. public Rect UpperLine;
  34. public Rect LowerLine;
  35. public float UpperAngle;
  36. public float LowerAngle;
  37. public Branch(BurstDisassembler.AsmEdge edge, Rect startHorizontal, Rect verticalLine, Rect endHorizontal, Rect upperLine, Rect lowerLine, float angle1, float angle2)
  38. {
  39. Edge = edge;
  40. StartHorizontal = startHorizontal;
  41. VerticalLine = verticalLine;
  42. EndHorizontal = endHorizontal;
  43. UpperLine = upperLine;
  44. LowerLine = lowerLine;
  45. UpperAngle = angle1;
  46. LowerAngle = angle2;
  47. }
  48. }
  49. internal float fontHeight = 0.0f;
  50. internal float fontWidth = 0.0f;
  51. public string GetText => m_Text;
  52. private string m_Text = "";
  53. private int _mTextLines = 0;
  54. private List<Fragment> m_Fragments = null;
  55. private bool invalidated = true;
  56. internal Vector2 finalAreaSize;
  57. private static readonly Texture2D backgroundTexture = Texture2D.whiteTexture;
  58. private static readonly GUIStyle textureStyle = new GUIStyle { normal = new GUIStyleState { background = backgroundTexture } };
  59. internal float horizontalPad = 50.0f;
  60. internal int[] lineDepth = null;
  61. internal bool[] _folded = null;
  62. internal int[] blockLine = null;
  63. private List<Fragment>[] _blocksFragments = null;
  64. private Fragment[] _blocksFragmentsStart = null;
  65. private Fragment GetFragmentStart(int blockIdx)
  66. {
  67. AddFoldedString(blockIdx);
  68. return _blocksFragmentsStart[blockIdx];
  69. }
  70. // Need two separate caches for start of blocks fragments, as we possibly differentiate between
  71. // rendered line and copied.
  72. private Fragment[] _blocksFragmentsStartPlain = null;
  73. private Fragment GetFragmentStartPlain(int blockIdx)
  74. {
  75. AddFoldedStringColorless(blockIdx);
  76. return _blocksFragmentsStartPlain[blockIdx];
  77. }
  78. // Used for searching when text is colored:
  79. internal List<Fragment>[] blocksFragmentsPlain = null;
  80. internal List<Fragment> GetPlainFragments(int blockIdx)
  81. {
  82. blocksFragmentsPlain[blockIdx] ??= RecomputeFragmentsFromBlock(blockIdx, false);
  83. return blocksFragmentsPlain[blockIdx];
  84. }
  85. private BurstDisassembler _disassembler;
  86. private int _selectBlockStart = -1;
  87. private float _selectStartY = -1f;
  88. private int _selectBlockEnd = -1;
  89. private float _selectEndY = -1f;
  90. private float _renderStartY = 0.0f;
  91. private int _renderBlockStart = -1;
  92. internal int _renderBlockEnd = -1;
  93. private int _initialLineCount = -1;
  94. private bool _mouseDown = false;
  95. private bool _mouseOutsideBounds = true;
  96. internal Vector2 selectPos = Vector2.zero;
  97. internal Vector2 selectDragPos = Vector2.zero;
  98. public bool HasSelection { get; private set; }
  99. private Color _selectionColor;
  100. private readonly Color _selectionColorDarkmode = new Color(0f, .6f, .9f, .5f);
  101. private readonly Color _selectionColorLightmode = new Color(0f, 0f, .9f, .2f);
  102. private readonly Color _lineHighlightColor = new Color(.56f, .56f, .56f, 0.2f);
  103. private readonly Color[] _regsColourWheel =
  104. {
  105. new Color(0f, 0f, .9f, .2f),
  106. new Color(0f, .9f, 0f, .2f),
  107. new Color(.9f, 0f, 0f, .2f)
  108. };
  109. private Color _hoverBoxColor;
  110. private Color _hoverTextColor;
  111. private readonly Color _hoverBoxColorDarkMode = new Color(.33f, .33f, .33f);
  112. private readonly Color _hoverBoxColorLightMode = new Color(.88f, .88f, .88f);
  113. // Current active hit should just be selection color
  114. private readonly Color _searchHitColor = new Color(.5f, .2f, .2f, .5f);
  115. private SearchCriteria _prevCriteria;
  116. internal int _activeSearchHitIdx = -1;
  117. internal readonly Dictionary<int, List<(int startIdx, int endIdx, int nr)>> searchHits = new Dictionary<int, List<(int startIdx, int endIdx, int nr)>>();
  118. private int _nrSearchHits = 0;
  119. public int NrSearchHits => _nrSearchHits;
  120. public int ActiveSearchNr => _activeSearchHitIdx;
  121. private readonly Color[] _colourWheel = new Color[]
  122. {Color.blue, Color.cyan, Color.green, Color.magenta, Color.red, Color.yellow, Color.white, Color.black};
  123. internal (int idx, int length) textSelectionIdx = (0, 0);
  124. private bool _textSelectionIdxValid = true;
  125. internal (int blockIdx, int textIdx) enhancedTextSelectionIdxStart = (0, 0);
  126. internal (int blockIdx, int textIdx) enhancedTextSelectionIdxEnd = (0, 0);
  127. internal bool CopyColorTags { get; private set; } = true;
  128. private bool _oldShowBranchMarkers = false;
  129. internal const int regLineThickness = 2;
  130. private const int highlightLineThickness = 3;
  131. private float _verticalPad = 0;
  132. internal Branch hoveredBranch;
  133. private BurstDisassembler.AsmEdge _prevHoveredEdge;
  134. private string _jobName;
  135. // Have this field, as NextHit needs the actual horizontal padding
  136. // in order to have correct horizontal scroll.
  137. private float _actualHorizontalPad = 0;
  138. internal int MaxLineDepth;
  139. /// <returns>
  140. /// (idx in regards to whole <see cref="str"/> , where color tags are removed from this line, idx from this line with color tags removed)
  141. /// </returns>
  142. internal readonly Func<string, int, (int total, int relative)> GetEndIndexOfColoredLine = BurstStringSearch.GetEndIndexOfColoredLine;
  143. internal readonly Func<string, int, (int total, int relative)> GetEndIndexOfPlainLine = BurstStringSearch.GetEndIndexOfPlainLine;
  144. internal bool IsTextSet(string jobName)
  145. {
  146. return _jobName == jobName;
  147. }
  148. public void SetText(string jobName, string textToRender, bool isDarkMode, BurstDisassembler disassembler, bool useDisassembler)
  149. {
  150. selectDragPos = Vector2.zero;
  151. StopSearching();
  152. StopSelection();
  153. ClearLinePress();
  154. _jobName = jobName;
  155. if (!useDisassembler)
  156. {
  157. m_Text = textToRender;
  158. _disassembler = null;
  159. m_Fragments = RecomputeFragments(m_Text);
  160. horizontalPad = 0.0f;
  161. }
  162. else
  163. {
  164. m_Fragments = null;
  165. SetDisassembler(disassembler);
  166. (_selectionColor, _hoverBoxColor, _hoverTextColor) = isDarkMode
  167. ? (_selectionColorDarkmode, _hoverBoxColorDarkMode, _hoverBoxColorLightMode)
  168. : (_selectionColorLightmode, _hoverBoxColorLightMode, _hoverBoxColorDarkMode);
  169. }
  170. invalidated = true;
  171. }
  172. public void ExpandAllBlocks()
  173. {
  174. StopSelection();
  175. ClearLinePress();
  176. int blockIdx = 0;
  177. foreach (var block in _disassembler.Blocks)
  178. {
  179. var changed = _folded[blockIdx];
  180. var blockLongEnoughForFold = block.Length > 1;
  181. _folded[blockIdx] = false;
  182. if (changed && blockLongEnoughForFold)
  183. {
  184. finalAreaSize.y += Math.Max(block.Length - 1, 1) * fontHeight;
  185. }
  186. blockIdx++;
  187. }
  188. }
  189. private void ClearLinePress()
  190. {
  191. _lineRegCache.Clear();
  192. _pressedLine = -1;
  193. }
  194. public void FocusCodeBlocks()
  195. {
  196. StopSelection();
  197. ClearLinePress();
  198. var blockIdx = 0;
  199. foreach (var block in _disassembler.Blocks)
  200. {
  201. bool changed = false;
  202. switch (block.Kind)
  203. {
  204. case BurstDisassembler.AsmBlockKind.None:
  205. case BurstDisassembler.AsmBlockKind.Directive:
  206. case BurstDisassembler.AsmBlockKind.Block:
  207. case BurstDisassembler.AsmBlockKind.Data:
  208. if (!_folded[blockIdx])
  209. {
  210. changed = true;
  211. }
  212. _folded[blockIdx] = true;
  213. break;
  214. case BurstDisassembler.AsmBlockKind.Code:
  215. if (_folded[blockIdx])
  216. {
  217. changed = true;
  218. }
  219. _folded[blockIdx] = false;
  220. break;
  221. }
  222. if (changed)
  223. {
  224. if (_folded[blockIdx])
  225. {
  226. finalAreaSize.y -= Math.Max(block.Length - 1, 1) * fontHeight;
  227. }
  228. else
  229. {
  230. finalAreaSize.y += Math.Max(block.Length - 1, 1) * fontHeight;
  231. }
  232. }
  233. blockIdx++;
  234. }
  235. }
  236. private void ComputeInitialLineCount()
  237. {
  238. var blockIdx = 0;
  239. _initialLineCount = 0;
  240. foreach (var block in _disassembler.Blocks)
  241. {
  242. switch (block.Kind)
  243. {
  244. case BurstDisassembler.AsmBlockKind.None:
  245. case BurstDisassembler.AsmBlockKind.Directive:
  246. case BurstDisassembler.AsmBlockKind.Block:
  247. case BurstDisassembler.AsmBlockKind.Data:
  248. _folded[blockIdx] = true;
  249. break;
  250. case BurstDisassembler.AsmBlockKind.Code:
  251. _folded[blockIdx] = false;
  252. break;
  253. }
  254. var blockLongEnoughForFold = block.Length > 1;
  255. _folded[blockIdx] = _folded[blockIdx] && blockLongEnoughForFold;
  256. _initialLineCount += _folded[blockIdx] ? 1 : block.Length;
  257. blockIdx++;
  258. }
  259. }
  260. public void SetDisassembler(BurstDisassembler disassembler)
  261. {
  262. _disassembler = disassembler;
  263. if (disassembler == null)
  264. {
  265. return;
  266. }
  267. var numBlocks = _disassembler.Blocks.Count;
  268. var numLinesFromBlock = new int[numBlocks];
  269. lineDepth = new int[numBlocks];
  270. _folded = new bool[numBlocks];
  271. blockLine = new int[numBlocks];
  272. _blocksFragments = new List<Fragment>[numBlocks];
  273. _blocksFragmentsStart = new Fragment[numBlocks];
  274. _blocksFragmentsStartPlain = new Fragment[numBlocks];
  275. blocksFragmentsPlain = new List<Fragment>[numBlocks];
  276. ComputeInitialLineCount();
  277. // Count edges
  278. var edgeCount = 0;
  279. StringBuilder sb = new StringBuilder();
  280. for (int i = 0; i < numBlocks; i++)
  281. {
  282. sb.Append(_disassembler.GetOrRenderBlockToTextUncached(i, false));
  283. var block = _disassembler.Blocks[i];
  284. if (block.Edges != null)
  285. {
  286. foreach (var edge in block.Edges)
  287. {
  288. if (edge.Kind == BurstDisassembler.AsmEdgeKind.OutBound)
  289. {
  290. edgeCount++;
  291. }
  292. }
  293. }
  294. }
  295. m_Text = sb.ToString();
  296. var edgeArray = new BurstDisassembler.AsmEdge[edgeCount];
  297. var edgeIndex = 0;
  298. foreach (var block in _disassembler.Blocks)
  299. {
  300. if (block.Edges != null)
  301. {
  302. foreach (var edge in block.Edges)
  303. {
  304. if (edge.Kind == BurstDisassembler.AsmEdgeKind.OutBound)
  305. {
  306. edgeArray[edgeIndex++] = edge;
  307. }
  308. }
  309. }
  310. }
  311. Array.Sort(edgeArray, (a, b) =>
  312. {
  313. var src1BlockIdx = a.OriginRef.BlockIndex;
  314. var src1Line = _disassembler.Blocks[src1BlockIdx].LineIndex;
  315. src1Line += a.OriginRef.LineIndex;
  316. var dst1BlockIdx = a.LineRef.BlockIndex;
  317. var dst1Line = _disassembler.Blocks[dst1BlockIdx].LineIndex;
  318. dst1Line += a.LineRef.LineIndex;
  319. var Len1 = Math.Abs(src1Line - dst1Line);
  320. var src2BlockIdx = b.OriginRef.BlockIndex;
  321. var src2Line = _disassembler.Blocks[src2BlockIdx].LineIndex;
  322. src2Line += b.OriginRef.LineIndex;
  323. var dst2BlockIdx = b.LineRef.BlockIndex;
  324. var dst2Line = _disassembler.Blocks[dst2BlockIdx].LineIndex;
  325. dst2Line += b.LineRef.LineIndex;
  326. var Len2 = Math.Abs(src2Line - dst2Line);
  327. return Len1 - Len2;
  328. });
  329. // Iterate through the blocks to precompute the widths for branches
  330. var maxLine = 0;
  331. foreach (var edge in edgeArray)
  332. {
  333. if (edge.Kind != BurstDisassembler.AsmEdgeKind.OutBound) continue;
  334. var s = edge.OriginRef.BlockIndex;
  335. var e = edge.LineRef.BlockIndex;
  336. if (e == s + 1)
  337. {
  338. continue; // don't render if its pointing to next line
  339. }
  340. var m = 0;
  341. var l = s;
  342. var le = e;
  343. if (e < s)
  344. {
  345. l = e;
  346. le = s;
  347. }
  348. for (; l <= le; l++)
  349. {
  350. numLinesFromBlock[l]++;
  351. if (m < numLinesFromBlock[l])
  352. {
  353. m = numLinesFromBlock[l];
  354. }
  355. if (maxLine < m)
  356. {
  357. maxLine = m;
  358. }
  359. }
  360. lineDepth[s] = m;
  361. }
  362. MaxLineDepth = maxLine;
  363. horizontalPad = naturalEnhancedPad + maxLine * 10;
  364. }
  365. // Changing the font size doesn't update the text field, so added this to force a recalculation
  366. public void Invalidate()
  367. {
  368. // Assumed to only happen on altering font size (or similar actions not leading to altered number of
  369. // assembly lines in view).
  370. // Hence we only have to clear the cached rects for highlighting, and not the actual line number _linePressed,
  371. // as that will stay constant.
  372. _lineRegCache.Clear();
  373. invalidated = true;
  374. }
  375. private struct HoverBox
  376. {
  377. public Rect box;
  378. public string info;
  379. /// <summary>
  380. /// Indicates start and end column of hovered token.
  381. /// </summary>
  382. public (int start, int end) columnRange;
  383. public int lineNumber;
  384. public bool valid;
  385. }
  386. private HoverBox hover;
  387. public void Interact(Rect workingArea, EventType eventT)
  388. {
  389. if (_disassembler == null)
  390. {
  391. return;
  392. }
  393. var pos = GetMousePosForHover();
  394. if (!workingArea.Contains(pos))
  395. {
  396. // Mouse position outside of assembly view
  397. return;
  398. }
  399. // lineNumber (absolute)
  400. var lineNumber = GetLineNumber(pos);
  401. // Mouse just pressed this line.
  402. if (eventT == EventType.MouseDown)
  403. {
  404. var lineStr = GetLineString(_disassembler.Lines[lineNumber]);
  405. var lineLen = (lineStr.Length) * fontWidth;
  406. var blockIdx = 0;
  407. var len = _disassembler.Blocks.Count;
  408. for (; blockIdx < len-1; blockIdx++)
  409. {
  410. if (_disassembler.Blocks[blockIdx+1].LineIndex > lineNumber)
  411. {
  412. break;
  413. }
  414. }
  415. if (_folded[blockIdx])
  416. {
  417. lineLen += 4*fontWidth;
  418. }
  419. if (pos.x < _actualHorizontalPad || pos.x > _actualHorizontalPad + lineLen)
  420. {
  421. _pressedLine = -1;
  422. }
  423. else
  424. {
  425. _pressedLine = lineNumber;
  426. }
  427. }
  428. var column = Mathf.FloorToInt((pos.x - horizontalPad) / fontWidth);
  429. var sameToken = hover.lineNumber == lineNumber &&
  430. BurstMath.WithinRange(hover.columnRange.start, hover.columnRange.end, column);
  431. if (hover.valid && (sameToken || hover.box.Contains(pos)))
  432. {
  433. // Use the cached info text.
  434. return;
  435. }
  436. // Cached instruction info text is not valid. So try query new.
  437. hover.valid = false;
  438. if (column < 0 || lineNumber < 0 || lineNumber >= _disassembler.Lines.Count)
  439. {
  440. return;
  441. }
  442. int tokIdx;
  443. try
  444. {
  445. // block 0 is queried as the absolut line number is given to the function.
  446. // This will give us the correct assembly token, as the function queries
  447. // assembly line based on offset from block start => line lineNumber is queried.
  448. tokIdx = _disassembler.GetTokenIndexFromColumn(0, lineNumber, column, out _);
  449. }
  450. catch (ArgumentOutOfRangeException)
  451. {
  452. return;
  453. }
  454. if (tokIdx < 0)
  455. {
  456. return;
  457. }
  458. // Found match
  459. var token = _disassembler.GetToken(tokIdx);
  460. var tokenString = _disassembler.GetTokenAsText(token);
  461. if (token.Kind != BurstDisassembler.AsmTokenKind.Instruction &&
  462. token.Kind != BurstDisassembler.AsmTokenKind.BranchInstruction &&
  463. token.Kind != BurstDisassembler.AsmTokenKind.CallInstruction &&
  464. token.Kind != BurstDisassembler.AsmTokenKind.FunctionBegin &&
  465. token.Kind != BurstDisassembler.AsmTokenKind.FunctionEnd &&
  466. token.Kind != BurstDisassembler.AsmTokenKind.JumpInstruction &&
  467. token.Kind != BurstDisassembler.AsmTokenKind.ReturnInstruction &&
  468. token.Kind != BurstDisassembler.AsmTokenKind.InstructionSIMD)
  469. {
  470. return;
  471. }
  472. if (_disassembler.GetInstructionInformation(tokenString, out var info))
  473. {
  474. hover.valid = true;
  475. // Don't know the actual size needed yet.
  476. hover.box = new Rect(pos, Vector2.zero);
  477. hover.info = info;
  478. hover.lineNumber = lineNumber;
  479. // Find column range of instruction:
  480. var line = _disassembler.Lines[lineNumber];
  481. var idx = line.ColumnIndex + (tokIdx - line.TokenIndex - 1);
  482. var colStart = _disassembler.ColumnIndices[idx];
  483. var colEnd = colStart + token.Length - 1;
  484. hover.columnRange = (colStart, colEnd);
  485. }
  486. }
  487. /// Not clipped, so use only if you know the line will be within the UI element
  488. private static void DrawLine(Vector2 start, Vector2 end, int width)
  489. {
  490. var matrix = GUI.matrix;
  491. Vector2 distance = end - start;
  492. float angle = Mathf.Rad2Deg * Mathf.Atan(distance.y / distance.x);
  493. if (distance.x < 0)
  494. {
  495. angle += 180;
  496. }
  497. int width2 = (int)Mathf.Ceil(width / 2);
  498. Rect pos = new Rect(start.x, start.y - width2, distance.magnitude, width);
  499. GUIUtility.RotateAroundPivot(angle, start);
  500. GUI.DrawTexture(pos, backgroundTexture);
  501. GUI.matrix = matrix; // restore initial matrix to avoid floating point inaccuracies with RotateAroundPivot(...)
  502. }
  503. private void DrawLine(Rect line, float angle)
  504. {
  505. var matrix = GUI.matrix;
  506. GUIUtility.RotateAroundPivot(angle, new Vector2(line.x, line.center.y));
  507. GUI.DrawTexture(line, backgroundTexture);
  508. GUI.matrix = matrix; // restore initial matrix to avoid floating point inaccuracies with RotateAroundPivot(...)
  509. }
  510. private void DrawHover(GUIStyle style, Rect workingArea)
  511. {
  512. if (!hover.valid)
  513. {
  514. return;
  515. }
  516. if (hover.box.size == Vector2.zero)
  517. {
  518. // Hover size has not been initialized yet.
  519. var sizex = (hover.info.Length + 1.5f) * fontWidth;
  520. var sizey = 2f * fontHeight;
  521. var posx = hover.box.x + 10;
  522. var posy = hover.box.y;
  523. if (posx + sizex > workingArea.width)
  524. {
  525. // Box exceeds rightmost bound so cramp it in
  526. var availableSpace = workingArea.xMax - posx;
  527. var possiblyCharacters = Mathf.FloorToInt(availableSpace / fontWidth);
  528. var neededLines = hover.info.Length / possiblyCharacters + 2; // +2 to ensure enough lines for the label
  529. var availableSpacey = workingArea.yMax - posy;
  530. var possibleLines = Mathf.FloorToInt(availableSpacey / fontHeight);
  531. var tmp = neededLines - possibleLines;
  532. if (tmp > 0)
  533. {
  534. posy -= tmp * fontHeight;
  535. }
  536. sizey = neededLines * fontHeight + fontHeight;
  537. sizex = availableSpace;
  538. }
  539. hover.box.size = new Vector2(sizex, sizey);
  540. hover.box.position = new Vector2(posx, posy);
  541. }
  542. var col = GUI.color;
  543. GUI.color = _hoverBoxColor;
  544. var pos = hover.box.position;
  545. var size = hover.box.size;
  546. GUI.Box(hover.box, "", textureStyle);
  547. GUI.color = _hoverTextColor;
  548. var hoverStyle = style;
  549. hoverStyle.wordWrap = true;
  550. GUI.Label(
  551. new Rect(pos.x + fontWidth * 0.5f,
  552. pos.y + fontHeight * 0.5f,
  553. size.x - fontWidth/2f,
  554. size.y - fontHeight),
  555. hover.info, hoverStyle);
  556. GUI.color = col;
  557. }
  558. private void MakeBranchThin(ref Branch branch)
  559. {
  560. int lineThickness = regLineThickness;
  561. branch.StartHorizontal.height = lineThickness;
  562. branch.VerticalLine.width = lineThickness;
  563. branch.EndHorizontal.height = lineThickness;
  564. branch.UpperLine.height = lineThickness;
  565. branch.LowerLine.height = lineThickness;
  566. // Adjusting position for arrow tip for thicker lines.
  567. branch.UpperLine.y += (highlightLineThickness - regLineThickness);
  568. branch.UpperLine.position -= new Vector2(.5f, .5f);
  569. branch.LowerLine.position -= new Vector2(.5f, -.5f);
  570. // Make end part of arrow expand upwards.
  571. branch.EndHorizontal.y += (highlightLineThickness - regLineThickness);
  572. }
  573. /// <summary>
  574. /// Use this for hover, as there is a slight visual mis-balance
  575. /// between cursor position and visual cursor.
  576. /// </summary>
  577. private Vector2 GetMousePosForHover()
  578. {
  579. Vector2 mousePos = Event.current.mousePosition;
  580. mousePos.y -= 0.5f;
  581. mousePos.x += 0.5f;
  582. return mousePos;
  583. }
  584. /// <summary>
  585. /// Calculate the position and size of an edge, and return it as a branch.
  586. /// </summary>
  587. /// <param name="edge"> The edge to base branch on. </param>
  588. /// <param name="x"> Start x position of branch. </param>
  589. /// <param name="y1"> Start y position of branch. </param>
  590. /// <param name="y2"> End y position of branch. </param>
  591. /// <param name="w"> Depth of branch. </param>
  592. private Branch CalculateBranch(BurstDisassembler.AsmEdge edge, float x, float y1, float y2, int w)
  593. {
  594. bool isEdgeHovered = edge.Equals(_prevHoveredEdge);
  595. int lineThickness = isEdgeHovered
  596. ? highlightLineThickness
  597. : regLineThickness;
  598. // Calculate rectangles for branch arrows:
  599. var start = new Vector2(x, y1 + _verticalPad);
  600. var end = start + new Vector2(-(w * 10), 0);
  601. var branchStartPos = new Rect(end.x - lineThickness / 2, start.y - 1, start.x - end.x + lineThickness / 2, lineThickness);
  602. start = end;
  603. end = start + new Vector2(0, y2 - y1);
  604. var branchVerticalPartPos = end.y < start.y
  605. ? new Rect(start.x - 1, end.y, lineThickness, start.y - end.y)
  606. : new Rect(start.x - 1, start.y, lineThickness, end.y - start.y);
  607. start = end;
  608. end = start + new Vector2(w * 10, 0);
  609. var branchEndPos = new Rect(start.x - lineThickness / 2, start.y - 1, end.x - start.x, lineThickness);
  610. // Calculate rectangles for arrow tip.
  611. Vector2 lowerArrowTipStart = end;
  612. Vector2 upperArrowtipStart = end;
  613. // Moving the arrow tips closer together.
  614. upperArrowtipStart += new Vector2(0, 0.5f);
  615. lowerArrowTipStart -= new Vector2(0, 0.5f);
  616. // Upper arrow tip.
  617. var upperArrowTipEnd = upperArrowtipStart + new Vector2(-5, -5);
  618. var upperLine = new Rect(upperArrowtipStart.x, upperArrowtipStart.y - (int)Mathf.Ceil(lineThickness / 2), (upperArrowTipEnd - upperArrowtipStart).magnitude, lineThickness);
  619. // Lower arrow tip.
  620. var lowerArrowtipEnd = lowerArrowTipStart + new Vector2(-5, 5);
  621. var lowerLine = new Rect(lowerArrowTipStart.x, lowerArrowTipStart.y - (int)Mathf.Ceil(lineThickness / 2), (lowerArrowtipEnd - lowerArrowTipStart).magnitude, lineThickness);
  622. if (isEdgeHovered)
  623. {
  624. // Adjusting position for arrow tip for thicker lines.
  625. upperArrowtipStart.y -= (highlightLineThickness - regLineThickness);
  626. upperArrowTipEnd.y -= (highlightLineThickness - regLineThickness);
  627. upperLine.y -= (highlightLineThickness - regLineThickness);
  628. upperLine.position += new Vector2(.5f, .5f);
  629. lowerLine.position += new Vector2(.5f, -.5f);
  630. // Make end part of arrow expand upwards.
  631. branchEndPos.y -= (highlightLineThickness - regLineThickness);
  632. }
  633. var branch = new Branch(edge, branchStartPos, branchVerticalPartPos, branchEndPos, upperLine, lowerLine,
  634. BurstMath.CalculateAngle(upperArrowtipStart, upperArrowTipEnd), BurstMath.CalculateAngle(lowerArrowTipStart, lowerArrowtipEnd));
  635. // Handling whether mouse is hovering over edge.
  636. Vector2 mousePos = GetMousePosForHover();
  637. // Rotate mousePos so it seems like lower arrow tip is not rotated.
  638. Vector2 lowerArrowTipPivot = lowerArrowTipStart;
  639. lowerArrowTipPivot.y -= (int)Mathf.Ceil(lineThickness / 2);
  640. Vector2 angledMouseLower = BurstMath.AnglePoint(BurstMath.CalculateAngle(lowerArrowTipPivot, lowerArrowtipEnd), mousePos, new Vector2(lowerLine.x, lowerLine.center.y));
  641. angledMouseLower.y -= (int)Mathf.Ceil(lineThickness / 2);
  642. Vector2 upperArrowTipPivot = upperArrowtipStart;
  643. upperArrowTipPivot.y += (int)Mathf.Ceil(lineThickness / 2);
  644. Vector2 angleMouseUpper = BurstMath.AnglePoint(BurstMath.CalculateAngle(upperArrowTipPivot, upperArrowTipEnd) - 360, mousePos, new Vector2(upperLine.x, upperLine.center.y));
  645. angleMouseUpper.y += (int)Mathf.Ceil(lineThickness / 2);
  646. if (BurstMath.AdjustedContains(branchStartPos, mousePos) || BurstMath.AdjustedContains(branchVerticalPartPos, mousePos) || BurstMath.AdjustedContains(branchEndPos, mousePos)
  647. || BurstMath.AdjustedContains(lowerLine, angledMouseLower) || BurstMath.AdjustedContains(upperLine, angleMouseUpper))
  648. {
  649. // Handling whether another branch was already made thick is done in DrawBranch(...).
  650. if (!hoveredBranch.Edge.Equals(default(BurstDisassembler.AsmEdge)) && hoveredBranch.Edge.Equals(_prevHoveredEdge))
  651. {
  652. return branch;
  653. }
  654. hoveredBranch = branch;
  655. }
  656. return branch;
  657. }
  658. /// <summary>
  659. /// Draws a branch as a jump-able set of boxes.
  660. /// </summary>
  661. /// <param name="branch"> The branch to draw. </param>
  662. /// <param name="w"> Depth of the branch. </param>
  663. /// <param name="colourWheel"> Array of possible colors for branches. </param>
  664. /// <param name="workingArea"> Current view in inspector. </param>
  665. private void DrawBranch(Branch branch, int w, Rect workingArea)
  666. {
  667. bool isBranchHovered = branch.Edge.Equals(hoveredBranch.Edge);
  668. Vector2 scrollPos = workingArea.position;
  669. int lineThickness = isBranchHovered
  670. ? highlightLineThickness
  671. : regLineThickness;
  672. GUI.color = _colourWheel[w % _colourWheel.Length];
  673. // Check if hovered but not made thick yet:
  674. if (isBranchHovered && !branch.Edge.Equals(_prevHoveredEdge))
  675. {
  676. // alter thickness as edge is hovered over.
  677. branch.StartHorizontal.height = highlightLineThickness;
  678. branch.VerticalLine.width = highlightLineThickness;
  679. branch.EndHorizontal.height = highlightLineThickness;
  680. branch.UpperLine.height = highlightLineThickness;
  681. branch.LowerLine.height = highlightLineThickness;
  682. // Adjusting position for arrow tip for thicker lines.
  683. branch.UpperLine.y -= (highlightLineThickness - regLineThickness);
  684. branch.UpperLine.position += new Vector2(.5f, .5f);
  685. branch.LowerLine.position += new Vector2(.5f, -.5f);
  686. // Make end part of arrow expand upwards.
  687. branch.EndHorizontal.y -= (highlightLineThickness - regLineThickness);
  688. }
  689. else if (branch.EndHorizontal.height == highlightLineThickness && !isBranchHovered)
  690. {
  691. // the branch was previously hovered, but is now hidden behind
  692. // another branch, that is the one being visually hovered.
  693. MakeBranchThin(ref branch);
  694. }
  695. // Render actual arrows:
  696. GUI.Box(branch.StartHorizontal, "", textureStyle);
  697. GUI.Box(branch.VerticalLine, "", textureStyle);
  698. float yy = branch.EndHorizontal.y - scrollPos.y;
  699. if (yy >= 0 && yy < workingArea.height)
  700. {
  701. GUI.Box(branch.EndHorizontal, "", textureStyle);
  702. DrawLine(branch.UpperLine, branch.UpperAngle);
  703. DrawLine(branch.LowerLine, branch.LowerAngle);
  704. }
  705. // Use below instead of buttons, to make the currently hovered edge the jump-able,
  706. // and not the edge rendered first i.e. when two edges overlap.
  707. if (Event.current.type == EventType.MouseDown && isBranchHovered)
  708. {
  709. Vector2 mousePos = GetMousePosForHover();
  710. // Rotate mousePos so it seems like lower arrow tip is not rotated.
  711. Vector2 lowerLineEnd = branch.LowerLine.position;
  712. lowerLineEnd.y += (int)Mathf.Ceil(lineThickness / 2);
  713. lowerLineEnd += new Vector2(-5, 5);
  714. Vector2 angledMouseLower = BurstMath.AnglePoint(BurstMath.CalculateAngle(branch.LowerLine.position, lowerLineEnd),
  715. mousePos, new Vector2(branch.LowerLine.x, branch.LowerLine.center.y));
  716. angledMouseLower.y -= (int)Mathf.Ceil(lineThickness / 2);
  717. // Rotate mousePos so it seems like upper arrow tip isn't rotated.
  718. Vector2 upperArrowTipPivot = branch.UpperLine.position;
  719. upperArrowTipPivot.y += 2 * (int)Mathf.Ceil(lineThickness / 2);
  720. Vector2 upperLineEnd = branch.UpperLine.position;
  721. upperLineEnd.y += (int)Mathf.Ceil(lineThickness / 2);
  722. upperLineEnd += new Vector2(-5, -5);
  723. Vector2 angleMouseUpper = BurstMath.AnglePoint(BurstMath.CalculateAngle(upperArrowTipPivot, upperLineEnd) - 360,
  724. Event.current.mousePosition, new Vector2(branch.UpperLine.x, branch.UpperLine.center.y));
  725. angleMouseUpper.y += (int)Mathf.Ceil(lineThickness / 2);
  726. // Se if a jump should be made and jump.
  727. if (BurstMath.AdjustedContains(branch.StartHorizontal, mousePos))
  728. {
  729. // make end arrow be at mouse cursor.
  730. var target = branch.EndHorizontal;
  731. target.y += branch.StartHorizontal.y < branch.EndHorizontal.y
  732. ? (workingArea.yMax - mousePos.y)
  733. : (workingArea.yMin - mousePos.y + highlightLineThickness / 2f);
  734. GUI.ScrollTo(target);
  735. Event.current.Use();
  736. }
  737. else if (BurstMath.AdjustedContains(branch.EndHorizontal, mousePos) || BurstMath.AdjustedContains(branch.LowerLine, angledMouseLower)
  738. || BurstMath.AdjustedContains(branch.UpperLine, angleMouseUpper) || BurstMath.AdjustedContains(branch.VerticalLine, mousePos))
  739. {
  740. var target = branch.StartHorizontal;
  741. target.y += branch.StartHorizontal.y < branch.EndHorizontal.y
  742. ? workingArea.yMin - mousePos.y + highlightLineThickness / 2
  743. : workingArea.yMax - mousePos.y;
  744. GUI.ScrollTo(target);
  745. Event.current.Use();
  746. }
  747. }
  748. }
  749. private bool DrawFold(float x, float y, bool state, BurstDisassembler.AsmBlockKind kind)
  750. {
  751. var currentBg = GUI.backgroundColor;
  752. switch (kind)
  753. {
  754. case BurstDisassembler.AsmBlockKind.None:
  755. case BurstDisassembler.AsmBlockKind.Directive:
  756. case BurstDisassembler.AsmBlockKind.Block:
  757. GUI.backgroundColor = Color.grey;
  758. break;
  759. case BurstDisassembler.AsmBlockKind.Code:
  760. GUI.backgroundColor = Color.green;
  761. break;
  762. case BurstDisassembler.AsmBlockKind.Data:
  763. GUI.backgroundColor = Color.magenta;
  764. break;
  765. }
  766. var pressed = false;
  767. if (state)
  768. {
  769. pressed = GUI.Button(new Rect(x - fontWidth, y, fontWidth, fontHeight), "+");
  770. }
  771. else
  772. {
  773. pressed = GUI.Button(new Rect(x - fontWidth, y, fontWidth, fontHeight), "-");
  774. }
  775. GUI.backgroundColor = currentBg;
  776. return pressed;
  777. }
  778. internal void Layout(GUIStyle style, float hPad)
  779. {
  780. var oldFontHeight = fontHeight;
  781. var oldFontWidth = fontWidth;
  782. #if UNITY_2023_1_OR_NEWER
  783. var cacheWidth0 = style.CalcSize(new GUIContent("W"));
  784. var cacheWidth1 = style.CalcSize(new GUIContent("WW"));
  785. var cacheHeight0 = style.CalcSize(new GUIContent("\n"));
  786. var cacheHeight1 = style.CalcSize(new GUIContent("\n\n"));
  787. fontHeight = cacheHeight1.y - cacheHeight0.y;
  788. fontWidth = cacheWidth1.x - cacheWidth0.x;
  789. #else
  790. var cacheSize0 = style.CalcSize(new GUIContent("W\n"));
  791. var cacheSize1 = style.CalcSize(new GUIContent("WW\n\n"));
  792. fontHeight = cacheSize1.y - cacheSize0.y;
  793. fontWidth = cacheSize1.x - cacheSize0.x;
  794. #endif
  795. _verticalPad = fontHeight * 0.5f;
  796. // oldFontWidth == 0 means we picked the first target after opening inspector.
  797. var diffX = oldFontWidth != 0 ? fontWidth / oldFontWidth : 0.0f;
  798. if (HasSelection && (oldFontWidth != fontWidth || oldFontHeight != fontHeight))
  799. {
  800. float diffY = fontHeight / oldFontHeight;
  801. // We only have to take padding into account for x-axis, as it's the only one with it.
  802. selectPos = new Vector2(((selectPos.x - hPad) * diffX) + hPad, diffY * selectPos.y);
  803. selectDragPos = new Vector2(((selectDragPos.x - hPad) * diffX) + hPad, diffY * selectDragPos.y);
  804. }
  805. invalidated = false;
  806. var oldFinalAreaSizeX = finalAreaSize.x;
  807. finalAreaSize = new Vector2(0.0f, 0.0f);
  808. if (_disassembler == null)
  809. {
  810. LayoutPlain(style);
  811. }
  812. else
  813. {
  814. finalAreaSize.y = _initialLineCount * fontHeight;
  815. finalAreaSize.x = oldFinalAreaSizeX * diffX;
  816. }
  817. }
  818. /// <summary>
  819. /// Find accumulated fragment number the block start at.
  820. /// </summary>
  821. /// <param name="start">Block index to start search at. Should match <see cref="acc"/>.</param>
  822. /// <param name="acc">Accumulated fragment number that block <see cref="start"/> start at.</param>
  823. internal int GetFragNrFromBlockIdx(int blockIdx, int start, int acc, ref float positionY)
  824. {
  825. int fragNr = acc;
  826. for (int b = start; b < blockIdx; b++)
  827. {
  828. if (_folded[b])
  829. {
  830. fragNr += GetPlainFragments(b).Count;
  831. positionY += fontHeight;
  832. }
  833. else
  834. {
  835. foreach (var frag in GetPlainFragments(b))
  836. {
  837. fragNr++;
  838. positionY += frag.lineCount * fontHeight;
  839. }
  840. }
  841. }
  842. return fragNr;
  843. }
  844. internal bool SearchText(SearchCriteria searchCriteria, Regex regx, ref Rect workingArea, bool stopFirstMatch = false, bool focusTop = false) =>
  845. _disassembler == null
  846. ? SearchTextPlain(searchCriteria, regx, ref workingArea, stopFirstMatch, focusTop)
  847. : SearchTextEnhanced(searchCriteria, regx, ref workingArea, stopFirstMatch, focusTop);
  848. /// <summary>
  849. /// Searches <see cref="m_Text"/> for every match, and saves each match in <see cref="searchHits"/>.
  850. /// </summary>
  851. /// <param name="criteria">Search options.</param>
  852. /// <param name="regx">Used if <see cref="criteria"/> specifies a regex search.</param>
  853. /// <param name="workingArea">Inspector View.</param>
  854. /// <param name="stopFirstMatch">Whether search should stop at first match.</param>
  855. /// <param name="focusTop">Whether match focus should be at the top of view.</param>
  856. private bool SearchTextEnhanced(SearchCriteria criteria, Regex regx, ref Rect workingArea, bool stopFirstMatch = false, bool focusTop = false)
  857. {
  858. searchHits.Clear();
  859. _nrSearchHits = 0;
  860. _activeSearchHitIdx = -1;
  861. var matches = stopFirstMatch
  862. ? new List<(int, int)> { BurstStringSearch.FindMatch(m_Text, criteria, regx, 0) }
  863. : BurstStringSearch.FindAllMatches(m_Text, criteria, regx);
  864. var renderStartY = workingArea.y;
  865. bool doRepaint = false;
  866. float positionY = 0f;
  867. int accFragNr = 0;
  868. int accBlockNr = 0;
  869. int accIdx;
  870. foreach (var (idx, len) in matches)
  871. {
  872. if (len <= 0)
  873. {
  874. continue;
  875. }
  876. int idxEnd = idx + len;
  877. // Find block + fragment match starts in:
  878. var blockStartInfo = _disassembler.GetBlockIdxFromTextIdx(idx, accBlockNr);
  879. // search hit within a folded block => unfold block.
  880. if (_folded[blockStartInfo.idx]) FoldUnfoldBlock(blockStartInfo.idx);
  881. // Finds the accumulated fragment number of the first fragment in block
  882. accFragNr = GetFragNrFromBlockIdx(blockStartInfo.idx, accBlockNr, accFragNr, ref positionY);
  883. int fragNrStart;
  884. float fragPositionY;
  885. // Finds actual accumulated fragment we just reached and it's index
  886. (fragNrStart, accIdx, fragPositionY) = GetFragNrFromEnhancedTextIdx(idx, blockStartInfo.idx, accFragNr, blockStartInfo.l, positionY);
  887. var frag1Text = GetPlainFragments(blockStartInfo.idx)[fragNrStart - accFragNr].text;
  888. // Make idx relative to fragment:
  889. int idxStartInFrag1 = idx - accIdx;
  890. int idxEndInFrag1 = Math.Min(idxStartInFrag1 + len, frag1Text.Length);
  891. // positionY should be stationed at top of fragment we have hit in.
  892. // Need to push it down to the specific line the hit is in. But keep this in a temporary variable so as to not fuck up the property of positionY!!!
  893. int exactLineNr = BurstStringSearch.FindLineNr(frag1Text, idxStartInFrag1);
  894. float exactPositionY = fragPositionY + exactLineNr * fontHeight;
  895. // Find block + fragment match ends in:
  896. var blockEndInfo = _disassembler.GetBlockIdxFromTextIdx(idxEnd, blockStartInfo.idx);
  897. // Finds the accumulated fragment number of match's last fragment
  898. accFragNr = GetFragNrFromBlockIdx(blockEndInfo.idx, blockStartInfo.idx, accFragNr, ref positionY);
  899. int fragNrEnd;
  900. // Finds the actual accumulated fragment number of match last fragment
  901. (fragNrEnd, accIdx, _) = GetFragNrFromEnhancedTextIdx(idxEnd, blockEndInfo.idx, accFragNr, blockEndInfo.l, positionY);
  902. accBlockNr = blockEndInfo.idx;
  903. if (!searchHits.ContainsKey(fragNrStart)) searchHits.Add(fragNrStart, new List<(int startIdx, int endIdx, int nr)>());
  904. searchHits[fragNrStart].Add((idxStartInFrag1, idxEndInFrag1, _nrSearchHits));
  905. if (fragNrStart < fragNrEnd)
  906. {
  907. // match span multiple fragments
  908. fragNrStart++; // Already captured this fragment
  909. // For every fragment in-between first and last we capture the whole fragment
  910. for (; fragNrStart < fragNrEnd; fragNrStart++)
  911. {
  912. if (!searchHits.ContainsKey(fragNrStart)) searchHits.Add(fragNrStart, new List<(int startIdx, int endIdx, int nr)>());
  913. searchHits[fragNrStart].Add((0, int.MaxValue, _nrSearchHits)); // Max value to indicate it's the entire fragment
  914. }
  915. int idxStartInFragN = accIdx;
  916. int idxEndInFragN = idxEnd - idxStartInFragN;
  917. if (!searchHits.ContainsKey(fragNrStart)) searchHits.Add(fragNrStart, new List<(int startIdx, int endIdx, int nr)>());
  918. searchHits[fragNrStart].Add((0, idxEndInFragN, _nrSearchHits));
  919. }
  920. if (_activeSearchHitIdx < 0 && exactPositionY >= renderStartY)
  921. {
  922. _activeSearchHitIdx = _nrSearchHits;
  923. doRepaint = SetScrollOnView(ref workingArea, frag1Text, exactLineNr, idxStartInFrag1, exactPositionY);
  924. }
  925. _nrSearchHits++;
  926. }
  927. return doRepaint;
  928. }
  929. private bool SetScrollOnView(ref Rect workingArea, string text, int lineNr, int matchIdx, float goToPosY)
  930. {
  931. // Find x position of search word:
  932. var startOfLine = lineNr > 0 ? GetEndIndexOfPlainLine(text, lineNr - 1).total + 1 : 0;
  933. float goToPosX = (matchIdx - startOfLine) * fontWidth + _actualHorizontalPad;
  934. // Set x position of view if search outside:
  935. bool leftOfView = workingArea.xMin > goToPosX;
  936. bool rightOfView = goToPosX > workingArea.xMax;
  937. workingArea.x = leftOfView
  938. ? goToPosX - 5 * fontWidth
  939. : rightOfView
  940. ? goToPosX - workingArea.width + 5 * fontWidth
  941. : workingArea.x;
  942. // Set y position of view if search outside:
  943. bool aboveView = workingArea.yMin > goToPosY;
  944. bool belowView = goToPosY > workingArea.yMax;
  945. workingArea.y = aboveView
  946. ? goToPosY - 5 * fontHeight
  947. : belowView
  948. ? goToPosY - workingArea.height + 5*fontHeight
  949. : workingArea.y;
  950. return aboveView || belowView || leftOfView || rightOfView;
  951. }
  952. /// <remarks>Works on non-colored text.</remarks>
  953. /// <param name="goal">Index we want fragment number from.</param>
  954. /// <param name="blockNrStart">Block to start search in.</param>
  955. /// <param name="fragNrStart">Accumulated fragment number of <see cref="blockNrStart"/>.</param>
  956. /// <param name="start">Start index of <see cref="blockNrStart"/>.</param>
  957. /// <returns>(accumulated fragment number, total index for returning fragment number)</returns>
  958. internal (int fragNr, int idx, float positionY) GetFragNrFromEnhancedTextIdx(int goal, int blockNrStart, int fragNrStart, int start, float positionY)
  959. {
  960. bool goThroughfrags(int goal, int blockIdx, ref int start, ref int f, ref float positionY)
  961. {
  962. var frags = GetPlainFragments(blockIdx);
  963. for (int i = 0; i < frags.Count; i++)
  964. {
  965. Fragment frag = frags[i];
  966. int len = frag.text.Length;
  967. if (start + len >= goal)
  968. {
  969. return true;
  970. }
  971. start += len + 1; // +1 because of newline
  972. f++;
  973. positionY += frag.lineCount * fontHeight;
  974. }
  975. return false;
  976. }
  977. int f = fragNrStart;
  978. for (int b = blockNrStart; b < blocksFragmentsPlain.Length; b++)
  979. {
  980. if (goThroughfrags(goal, b, ref start, ref f, ref positionY)) break;
  981. }
  982. return (f, start, positionY);
  983. }
  984. /// <returns>(accumulated fragment number, total index for returning fragment number)</returns>
  985. private (int fragNr, int idx) GetFragNrFromPlainTextIdx(int goal, int fragNrStart, int start, ref float positionY)
  986. {
  987. int i = fragNrStart;
  988. for (; i < m_Fragments.Count; i++)
  989. {
  990. Fragment frag = m_Fragments[i];
  991. int len = frag.text.Length;
  992. if (start + len >= goal)
  993. {
  994. break;
  995. }
  996. start += len + 1; // +1 because of newline
  997. positionY += frag.lineCount * fontHeight;
  998. }
  999. return (i, start);
  1000. }
  1001. private bool SearchTextPlain(SearchCriteria criteria, Regex regx, ref Rect workingArea, bool stopFirstMatch = false, bool focusTop = false)
  1002. {
  1003. _nrSearchHits = 0;
  1004. searchHits.Clear();
  1005. _activeSearchHitIdx = -1;
  1006. var matches = stopFirstMatch
  1007. ? new List<(int, int)> { BurstStringSearch.FindMatch(m_Text, criteria, regx, 0) }
  1008. : BurstStringSearch.FindAllMatches(m_Text, criteria, regx);
  1009. bool doRepaint = false;
  1010. float positionY = 0f;
  1011. int accFragNr = 0;
  1012. int accFragIdx = 0;
  1013. var renderStartY = workingArea.y;
  1014. foreach (var (idx, len) in matches)
  1015. {
  1016. if (len <= 0)
  1017. {
  1018. continue;
  1019. }
  1020. int idxEnd = idx + len;
  1021. // Find fragment match start in:
  1022. (accFragNr, accFragIdx) = GetFragNrFromPlainTextIdx(idx, accFragNr, accFragIdx, ref positionY);
  1023. int fragNrStart = accFragNr;
  1024. string frag1Text = m_Fragments[fragNrStart].text;
  1025. // Get relative index in fragment:
  1026. int idxStartInFrag1 = idx - accFragIdx;
  1027. int idxEndInFrag1 = Math.Min(idxStartInFrag1 + len, frag1Text.Length);
  1028. int exactLineNr = BurstStringSearch.FindLineNr(frag1Text, idxStartInFrag1);
  1029. float exactPositionY = positionY + exactLineNr * fontHeight;
  1030. // Find fragment match end in:
  1031. (accFragNr, accFragIdx) = GetFragNrFromPlainTextIdx(idxEnd, accFragNr, accFragIdx, ref positionY);
  1032. int fragNrEnd = accFragNr;
  1033. if (!searchHits.ContainsKey(fragNrStart)) searchHits.Add(fragNrStart, new List<(int startIdx, int endIdx, int nr)>());
  1034. searchHits[fragNrStart].Add((idxStartInFrag1, idxEndInFrag1, _nrSearchHits));
  1035. if (fragNrStart < fragNrEnd)
  1036. {
  1037. // They must directly follow each other
  1038. int fragNr = fragNrStart + 1;
  1039. for (; fragNr < fragNrEnd; fragNr++)
  1040. {
  1041. if (!searchHits.ContainsKey(fragNr)) searchHits.Add(fragNr, new List<(int startIdx, int endIdx, int nr)>());
  1042. searchHits[fragNr].Add((0, m_Fragments[fragNr].text.Length, _nrSearchHits));
  1043. }
  1044. int idxStartInFrag2 = idxEnd - accFragIdx;
  1045. int idxEndInFrag2 = idxEnd - accFragIdx;
  1046. if (!searchHits.ContainsKey(fragNr)) searchHits.Add(fragNr, new List<(int startIdx, int endIdx, int nr)>());
  1047. searchHits[fragNr].Add((idxStartInFrag2, idxEndInFrag2, _nrSearchHits));
  1048. }
  1049. if (_activeSearchHitIdx < 0 && exactPositionY >= renderStartY)
  1050. {
  1051. _activeSearchHitIdx = _nrSearchHits;
  1052. doRepaint = SetScrollOnView(ref workingArea, frag1Text, exactLineNr, idxStartInFrag1, exactPositionY);
  1053. }
  1054. _nrSearchHits++;
  1055. }
  1056. return doRepaint;
  1057. }
  1058. private void LayoutPlain(GUIStyle style)
  1059. {
  1060. foreach (var frag in m_Fragments)
  1061. {
  1062. // Calculate the size as we have hidden control codes in the string
  1063. var size = style.CalcSize(new GUIContent(frag.text));
  1064. finalAreaSize.x = Math.Max(finalAreaSize.x, size.x);
  1065. finalAreaSize.y += frag.lineCount * fontHeight;
  1066. }
  1067. }
  1068. private void AddFoldedStringColorless(int blockIdx)
  1069. {
  1070. if (_blocksFragmentsStartPlain[blockIdx].lineCount != 0) return;
  1071. string text = null;
  1072. if (!_disassembler.IsColored)
  1073. {
  1074. _blocksFragments[blockIdx] ??= RecomputeFragmentsFromBlock(blockIdx);
  1075. text = _blocksFragments[blockIdx][0].text;
  1076. }
  1077. else
  1078. {
  1079. text = GetPlainFragments(blockIdx)[0].text;
  1080. }
  1081. var endOfFirstLineIdx = text.IndexOf('\n');
  1082. if (endOfFirstLineIdx == -1) endOfFirstLineIdx = text.Length;
  1083. _blocksFragmentsStartPlain[blockIdx] = new Fragment() { lineCount = 1, text = text.Substring(0, endOfFirstLineIdx) + " ..." };
  1084. }
  1085. private void AddFoldedString(int blockIdx)
  1086. {
  1087. if (_blocksFragmentsStart[blockIdx].lineCount != 0) return;
  1088. // precomputing every block to avoid having runtime check at every access later on
  1089. _blocksFragments[blockIdx] ??= RecomputeFragmentsFromBlock(blockIdx);
  1090. // precompute string to present for folded block.
  1091. var text = _blocksFragments[blockIdx][0].text;
  1092. var endOfFirstLineIdx = text.IndexOf('\n');
  1093. if (endOfFirstLineIdx == -1) endOfFirstLineIdx = text.Length;
  1094. _blocksFragmentsStart[blockIdx] = new Fragment() { lineCount = 1, text = text.Substring(0, endOfFirstLineIdx) + " ..." };
  1095. }
  1096. internal void LayoutEnhanced(GUIStyle style, Rect workingArea, bool showBranchMarkers)
  1097. {
  1098. Vector2 scrollPos = workingArea.position;
  1099. if (showBranchMarkers != _oldShowBranchMarkers)
  1100. {
  1101. // need to alter selection according to padding on x-axis.
  1102. if (showBranchMarkers)
  1103. {
  1104. selectPos.x += (horizontalPad - naturalEnhancedPad);
  1105. selectDragPos.x += (horizontalPad - naturalEnhancedPad);
  1106. }
  1107. else
  1108. {
  1109. selectPos.x -= (horizontalPad - naturalEnhancedPad);
  1110. selectDragPos.x -= (horizontalPad - naturalEnhancedPad);
  1111. }
  1112. // register cache needs to be cleared:
  1113. _lineRegCache.Clear();
  1114. }
  1115. _oldShowBranchMarkers = showBranchMarkers;
  1116. // Also computes the first and last blocks to render this time and ensures
  1117. float positionY = 0.0f;
  1118. int lNum = 0;
  1119. _renderBlockStart = -1;
  1120. _renderBlockEnd = -1;
  1121. _selectBlockStart = -1;
  1122. _selectStartY = -1f;
  1123. _selectBlockEnd = -1;
  1124. _selectEndY = -1f;
  1125. for (int idx = 0; idx<_disassembler.Blocks.Count; idx++)
  1126. {
  1127. var block = _disassembler.Blocks[idx];
  1128. var blockHeight = block.Length * fontHeight;
  1129. var lHeight = block.Length;
  1130. if (_folded[idx])
  1131. {
  1132. blockHeight = fontHeight;
  1133. lHeight = 1;
  1134. }
  1135. blockLine[idx] = lNum;
  1136. if (_selectBlockStart == -1 && selectPos.y - blockHeight <= positionY)
  1137. {
  1138. _selectBlockStart = idx;
  1139. _selectStartY = positionY;
  1140. }
  1141. if (_selectBlockEnd == -1 && (selectDragPos.y - blockHeight <= positionY || idx == _disassembler.Blocks.Count - 1))
  1142. {
  1143. _selectBlockEnd = idx;
  1144. _selectEndY = positionY;
  1145. }
  1146. // Whole block is above view, or block starts below view.
  1147. // If at last block and _renderBlockStart == -1, we must have had all block above our scrollPos.
  1148. // Happens when Scroll view is at bottom and fontSize is decreased. As this forces the scroll view upwards,
  1149. // we simply set the last block as the one being rendered (avoids an indexOutOfBounds exception).
  1150. if (((positionY - scrollPos.y + blockHeight) < 0 || (positionY - scrollPos.y) > workingArea.size.y)
  1151. && !(idx == _disassembler.Blocks.Count - 1 && _renderBlockStart == -1))
  1152. {
  1153. positionY += blockHeight;
  1154. lNum += lHeight;
  1155. continue;
  1156. }
  1157. if (_renderBlockStart == -1)
  1158. {
  1159. _renderBlockStart = idx;
  1160. _renderStartY = positionY;
  1161. }
  1162. _renderBlockEnd = idx;
  1163. if (_blocksFragments[idx] == null)
  1164. {
  1165. AddFoldedString(idx);
  1166. foreach (var fragment in _blocksFragments[idx])
  1167. {
  1168. style.CalcMinMaxWidth(new GUIContent(fragment.text), out _, out var maxWidth);
  1169. if (finalAreaSize.x < maxWidth)
  1170. {
  1171. finalAreaSize.x = maxWidth;
  1172. }
  1173. }
  1174. }
  1175. positionY += blockHeight;
  1176. lNum += lHeight;
  1177. }
  1178. // selection is below last line of assembly.
  1179. if (_selectBlockStart == -1)
  1180. {
  1181. _selectBlockStart = _disassembler.Blocks.Count - 1;
  1182. }
  1183. }
  1184. internal string GetStartingColorTag(int blockIdx, int textIdx)
  1185. {
  1186. if (!CopyColorTags || !(_disassembler?.IsColored ?? false)) return "";
  1187. const int colorTagLength = 15;
  1188. var text = _folded[blockIdx]
  1189. ? GetFragmentStart(blockIdx).text// _blocksFragmentsStart[blockIdx].text
  1190. : _disassembler.GetOrRenderBlockToText(blockIdx);
  1191. var colorTagIdx = text.LastIndexOf("<color=", textIdx);
  1192. if (colorTagIdx == -1) return "";
  1193. // Checking that found tas is actually for this idx
  1194. return text.IndexOf("</color>", colorTagIdx, textIdx - colorTagIdx) == -1
  1195. ? text.Substring(colorTagIdx, colorTagLength)
  1196. : "";
  1197. }
  1198. internal string GetEndingColorTag(int blockIdx, int textIdx)
  1199. {
  1200. if (!CopyColorTags || !(_disassembler?.IsColored ?? false)) return "";
  1201. var text = _folded[blockIdx]
  1202. ? GetFragmentStart(blockIdx).text// _blocksFragmentsStart[blockIdx].text
  1203. : _disassembler.GetOrRenderBlockToText(blockIdx);
  1204. var endColorTagIdx = text.IndexOf("</color>", textIdx);
  1205. if (endColorTagIdx == -1) return "";
  1206. // Check that tag actually belongs for thid idx
  1207. return text.IndexOf("<color=", textIdx, endColorTagIdx - textIdx) == -1
  1208. ? "</color>"
  1209. : "";
  1210. }
  1211. internal void ChangeCopyMode()
  1212. {
  1213. CopyColorTags = !CopyColorTags;
  1214. // Need to update text selection fields as it should now ignore/use color tags
  1215. _textSelectionIdxValid = false;
  1216. UpdateEnhancedSelectTextIdx(_oldShowBranchMarkers ? horizontalPad : naturalEnhancedPad);
  1217. }
  1218. internal void DoSelectionCopy()
  1219. {
  1220. // textIdxE = -1 to indicate we want till the end of the block of text.
  1221. string GetStringFromBlock(int blockIdx, int textIdxS, int textIdxE = -1)
  1222. {
  1223. string text;
  1224. if (_folded[blockIdx])
  1225. {
  1226. text = (CopyColorTags
  1227. ? GetFragmentStart(blockIdx).text
  1228. : GetFragmentStartPlain(blockIdx).text)
  1229. + '\n';
  1230. return textIdxE == -1
  1231. ? text.Substring(textIdxS, text.Length - textIdxS)
  1232. : text.Substring(textIdxS, textIdxE - textIdxS);
  1233. }
  1234. if (CopyColorTags)
  1235. {
  1236. text = _disassembler.GetOrRenderBlockToText(blockIdx);
  1237. if (textIdxE == -1) textIdxE = text.Length;
  1238. }
  1239. else
  1240. {
  1241. text = m_Text;
  1242. // Transform textIdxS and textIdxE to absolute index into m_Text
  1243. var (blockStart, blockEnd) = _disassembler.BlockIdxs[blockIdx];
  1244. textIdxS += blockStart;
  1245. if (textIdxE == -1) textIdxE = blockEnd + 1; // +1 to take newline as well
  1246. else textIdxE += blockStart;
  1247. }
  1248. return text.Substring(textIdxS, textIdxE - textIdxS);
  1249. }
  1250. if (!HasSelection) return;
  1251. var sb = new StringBuilder();
  1252. if (_disassembler != null && enhancedTextSelectionIdxStart != enhancedTextSelectionIdxEnd)
  1253. {
  1254. if (enhancedTextSelectionIdxStart.blockIdx < enhancedTextSelectionIdxEnd.blockIdx)
  1255. {
  1256. // Multiple block selection
  1257. var blockIdx = enhancedTextSelectionIdxStart.blockIdx;
  1258. sb.Append(
  1259. GetStartingColorTag(enhancedTextSelectionIdxStart.blockIdx, enhancedTextSelectionIdxStart.textIdx) +
  1260. GetStringFromBlock(blockIdx++, enhancedTextSelectionIdxStart.textIdx));
  1261. for (; blockIdx < enhancedTextSelectionIdxEnd.blockIdx; blockIdx++)
  1262. {
  1263. sb.Append(GetStringFromBlock(blockIdx, 0));
  1264. }
  1265. sb.Append(
  1266. GetStringFromBlock(blockIdx, 0, enhancedTextSelectionIdxEnd.textIdx) +
  1267. GetEndingColorTag(enhancedTextSelectionIdxEnd.blockIdx, enhancedTextSelectionIdxEnd.textIdx));
  1268. }
  1269. else
  1270. {
  1271. // Single block selection
  1272. sb.Append(
  1273. GetStartingColorTag(enhancedTextSelectionIdxStart.blockIdx, enhancedTextSelectionIdxStart.textIdx) +
  1274. GetStringFromBlock(
  1275. enhancedTextSelectionIdxStart.blockIdx,
  1276. enhancedTextSelectionIdxStart.textIdx,
  1277. enhancedTextSelectionIdxEnd.textIdx) +
  1278. GetEndingColorTag(enhancedTextSelectionIdxEnd.blockIdx, enhancedTextSelectionIdxEnd.textIdx));
  1279. }
  1280. }
  1281. else
  1282. {
  1283. sb.Append(m_Text.Substring(textSelectionIdx.idx, textSelectionIdx.length));
  1284. }
  1285. EditorGUIUtility.systemCopyBuffer = sb.ToString();
  1286. }
  1287. internal void SelectAll()
  1288. {
  1289. HasSelection = true;
  1290. selectPos = Vector2.zero;
  1291. selectDragPos = finalAreaSize;
  1292. if (_disassembler != null)
  1293. {
  1294. enhancedTextSelectionIdxStart = (0, 0);
  1295. var blockIdx = _disassembler.Blocks.Count - 1;
  1296. enhancedTextSelectionIdxEnd.blockIdx = blockIdx;
  1297. // Make sure selection works on appropriate text:
  1298. enhancedTextSelectionIdxEnd.textIdx = _folded[blockIdx]
  1299. ? CopyColorTags
  1300. ? GetFragmentStart(blockIdx).text.Length
  1301. : GetFragmentStartPlain(blockIdx).text.Length
  1302. : CopyColorTags
  1303. ? _disassembler.GetOrRenderBlockToText(blockIdx).Length
  1304. : _disassembler.BlockIdxs[blockIdx].endIdx - _disassembler.BlockIdxs[blockIdx].startIdx;
  1305. _selectBlockStart = 0;
  1306. _selectBlockEnd = blockIdx;
  1307. _selectEndY = finalAreaSize.y -
  1308. (_folded[blockIdx] ? fontHeight : _disassembler.Blocks[blockIdx].Length * fontHeight);
  1309. }
  1310. else
  1311. {
  1312. textSelectionIdx = (0, m_Text.Length);
  1313. }
  1314. _textSelectionIdxValid = true;
  1315. }
  1316. private void ScrollDownToSelection(Rect workingArea)
  1317. {
  1318. if (!workingArea.Contains(selectDragPos + new Vector2(fontWidth, fontHeight / 2)))
  1319. {
  1320. GUI.ScrollTo(new Rect(selectDragPos + new Vector2(fontWidth, fontHeight), Vector2.zero));
  1321. }
  1322. _textSelectionIdxValid = false;
  1323. }
  1324. private void ScrollUpToSelection(Rect workingArea)
  1325. {
  1326. if (!workingArea.Contains(selectDragPos - new Vector2(0, fontHeight / 2)))
  1327. {
  1328. GUI.ScrollTo(new Rect(selectDragPos - new Vector2(0, fontHeight), Vector2.zero));
  1329. }
  1330. _textSelectionIdxValid = false;
  1331. }
  1332. internal void MoveSelectionLeft(Rect workingArea, bool showBranchMarkers)
  1333. {
  1334. HasSelection = true;
  1335. if (_disassembler != null)
  1336. {
  1337. float hPad = showBranchMarkers ? horizontalPad : naturalEnhancedPad;
  1338. string text;
  1339. int prevLineIdx = Mathf.FloorToInt((selectDragPos.y - _selectEndY) / fontHeight) - 1;
  1340. if (selectDragPos.x < hPad + fontWidth)
  1341. {
  1342. if (prevLineIdx < 0 && _selectBlockEnd == 0)
  1343. {
  1344. // we are at the beginning of the text.
  1345. return;
  1346. }
  1347. if (prevLineIdx < 0 && _selectBlockEnd > 0)
  1348. {
  1349. // get text from previous block, and do calculations for that.
  1350. _selectBlockEnd--;
  1351. _selectEndY -= _folded[_selectBlockEnd]
  1352. ? fontHeight
  1353. : _disassembler.Blocks[_selectBlockEnd].Length * fontHeight;
  1354. (text, prevLineIdx) = !_folded[_selectBlockEnd]
  1355. ? (_disassembler.GetOrRenderBlockToText(_selectBlockEnd), _disassembler.Blocks[_selectBlockEnd].Length - 1)
  1356. : (GetFragmentStart(_selectBlockEnd).text + '\n', 0);
  1357. }
  1358. else
  1359. {
  1360. text = _folded[_selectBlockEnd]
  1361. ? GetFragmentStart(_selectBlockEnd).text + '\n'
  1362. : _disassembler.GetOrRenderBlockToText(_selectBlockEnd);
  1363. }
  1364. var charsInLine = GetEndIndexOfColoredLine(text, prevLineIdx).relative;
  1365. selectDragPos.x = charsInLine * fontWidth + hPad + fontWidth / 2;
  1366. selectDragPos.y -= fontHeight;
  1367. }
  1368. else
  1369. {
  1370. // simply move selection left.
  1371. text = _folded[_selectBlockEnd]
  1372. ? GetFragmentStart(_selectBlockEnd).text + '\n'
  1373. : _disassembler.GetOrRenderBlockToText(_selectBlockEnd);
  1374. var charsInLine = GetEndIndexOfColoredLine(text, prevLineIdx + 1).relative;
  1375. if (selectDragPos.x > charsInLine * fontWidth + hPad)
  1376. selectDragPos.x = hPad + charsInLine * fontWidth + fontWidth / 2;
  1377. selectDragPos.x -= fontWidth;
  1378. }
  1379. }
  1380. else
  1381. {
  1382. int prevLineIdx = Mathf.FloorToInt((selectDragPos.y) / fontHeight) - 1;
  1383. if (selectDragPos.x < fontWidth)
  1384. {
  1385. if (prevLineIdx < 0)
  1386. {
  1387. // we are at beginning of the text
  1388. return;
  1389. }
  1390. int charsInLine = GetEndIndexOfPlainLine(m_Text, prevLineIdx).relative;
  1391. selectDragPos.x = charsInLine * fontWidth + fontWidth / 2;
  1392. selectDragPos.y -= fontHeight;
  1393. }
  1394. else
  1395. {
  1396. // simply move selection left.
  1397. int charsInLine = GetEndIndexOfPlainLine(m_Text, prevLineIdx+1).relative;
  1398. if (selectDragPos.x > charsInLine * fontWidth)
  1399. {
  1400. selectDragPos.x = charsInLine * fontWidth + fontWidth / 2;
  1401. }
  1402. selectDragPos.x -= fontWidth;
  1403. }
  1404. }
  1405. // check if we moved outside of view and scroll if true.
  1406. ScrollUpToSelection(workingArea);
  1407. }
  1408. internal void MoveSelectionRight(Rect workingArea, bool showBranchMarkers)
  1409. {
  1410. HasSelection = true;
  1411. if (_disassembler != null)
  1412. {
  1413. var hPad = showBranchMarkers ? horizontalPad : naturalEnhancedPad;
  1414. var text = _folded[_selectBlockEnd]
  1415. ? GetFragmentStart(_selectBlockEnd).text + '\n'
  1416. : _disassembler.GetOrRenderBlockToText(_selectBlockEnd);
  1417. var thisLine = Mathf.FloorToInt((selectDragPos.y - _selectEndY) / fontHeight);
  1418. var charsInLine = GetEndIndexOfColoredLine(text, thisLine).relative;
  1419. if (selectDragPos.x >= hPad + charsInLine * fontWidth)
  1420. {
  1421. // move down a line:
  1422. thisLine++;
  1423. int lineCount = _folded[_selectBlockEnd] ? 1 : _disassembler.Blocks[_selectBlockEnd].Length;
  1424. if (thisLine > lineCount && _selectBlockEnd == _disassembler.Blocks.Count - 1)
  1425. {
  1426. // We are at the end of the text
  1427. return;
  1428. }
  1429. if (thisLine > lineCount)
  1430. {
  1431. // selected into next block.
  1432. _selectBlockEnd++;
  1433. _selectEndY += _folded[_selectBlockEnd - 1]
  1434. ? fontHeight
  1435. : _disassembler.Blocks[_selectBlockEnd - 1].Length * fontHeight;
  1436. }
  1437. selectDragPos.x = hPad + fontWidth/2;
  1438. selectDragPos.y += fontHeight;
  1439. }
  1440. else
  1441. {
  1442. // simply move selection right.
  1443. if (selectDragPos.x < hPad)
  1444. {
  1445. selectDragPos.x = hPad + fontWidth / 2;
  1446. }
  1447. selectDragPos.x += fontWidth;
  1448. }
  1449. }
  1450. else
  1451. {
  1452. int thisLine = Mathf.FloorToInt((selectDragPos.y) / fontHeight);
  1453. int charsInLine = GetEndIndexOfColoredLine(m_Text, thisLine).relative;
  1454. if (selectDragPos.x >= charsInLine*fontWidth)
  1455. {
  1456. thisLine++;
  1457. if (thisLine >= _mTextLines)
  1458. {
  1459. // we are at end of the text
  1460. return;
  1461. }
  1462. selectDragPos.x = 0f;
  1463. selectDragPos.y += fontHeight;
  1464. }
  1465. else
  1466. {
  1467. // simply move selection right.
  1468. selectDragPos.x += fontWidth;
  1469. }
  1470. }
  1471. // check if we moved outside of view and scroll if true.
  1472. ScrollDownToSelection(workingArea);
  1473. }
  1474. internal void MoveSelectionUp(Rect workingArea, bool showBranchMarkers)
  1475. {
  1476. HasSelection = true;
  1477. if (_disassembler != null)
  1478. {
  1479. int thisLine = Mathf.FloorToInt((selectDragPos.y - _selectEndY) / fontHeight);
  1480. // At the first line
  1481. if (thisLine == 0 && _selectBlockEnd == 0) return;
  1482. if (thisLine == 0)
  1483. {
  1484. // We are moving on to a block above
  1485. _selectBlockEnd--;
  1486. _selectEndY -= _folded[_selectBlockEnd]
  1487. ? fontHeight
  1488. : _disassembler.Blocks[_selectBlockEnd].Length * fontHeight;
  1489. }
  1490. }
  1491. else
  1492. {
  1493. int thisLine = Mathf.FloorToInt((selectDragPos.y) / fontHeight) - 1;
  1494. if (thisLine < 0) return;
  1495. }
  1496. selectDragPos.y -= fontHeight;
  1497. // check if we moved outside of view and scroll if true.
  1498. ScrollUpToSelection(workingArea);
  1499. }
  1500. internal void MoveSelectionDown(Rect workingArea, bool showBranchMarkers)
  1501. {
  1502. HasSelection = true;
  1503. if (_disassembler != null)
  1504. {
  1505. int thisLine = Mathf.FloorToInt((selectDragPos.y - _selectEndY) / fontHeight) + 1;
  1506. int lineCount = _folded[_selectBlockEnd] ? 0 : _disassembler.Blocks[_selectBlockEnd].Length - 1;
  1507. if (thisLine > lineCount)
  1508. {
  1509. // At the last line
  1510. if (_selectBlockEnd == _disassembler.Blocks.Count - 1) { return; }
  1511. // Moved into next block
  1512. _selectBlockEnd++;
  1513. _selectEndY += _folded[_selectBlockEnd - 1]
  1514. ? fontHeight
  1515. : _disassembler.Blocks[_selectBlockEnd - 1].Length * fontHeight;
  1516. }
  1517. }
  1518. else
  1519. {
  1520. int thisLine = Mathf.FloorToInt(selectDragPos.y / fontHeight) + 1;
  1521. if (thisLine > _mTextLines) return;
  1522. }
  1523. selectDragPos.y += fontHeight;
  1524. // check if we moved outside of view and scroll if true.
  1525. ScrollDownToSelection(workingArea);
  1526. }
  1527. internal bool MouseOutsideView(Rect workingArea, Vector2 mousePos, int controlID)
  1528. {
  1529. if (!workingArea.Contains(mousePos))
  1530. {
  1531. if (GUIUtility.hotControl == controlID && Event.current.rawType == EventType.MouseUp)
  1532. {
  1533. _mouseDown = false;
  1534. }
  1535. _mouseOutsideBounds = true;
  1536. return true;
  1537. }
  1538. _mouseOutsideBounds = false;
  1539. return false;
  1540. }
  1541. private Vector2 MouseClickAndClamp(bool showBranchMarkers, Vector2 mousePos)
  1542. {
  1543. HasSelection = true;
  1544. if (_disassembler != null)
  1545. {
  1546. float hPad = showBranchMarkers ? horizontalPad : naturalEnhancedPad;
  1547. // Make sure we cannot set cursor in the horizontal padding:
  1548. if (mousePos.x < hPad) mousePos.x = hPad;
  1549. }
  1550. return mousePos;
  1551. }
  1552. private int GetLineNumber(Vector2 mousePos)
  1553. {
  1554. var lineNumber = Mathf.FloorToInt(mousePos.y / fontHeight);
  1555. var len = _disassembler.Blocks.Count;
  1556. for (var idx = 0; idx < len; idx++)
  1557. {
  1558. var block = _disassembler.Blocks[idx];
  1559. if (lineNumber <= block.LineIndex)
  1560. {
  1561. break;
  1562. }
  1563. if (_folded[idx])
  1564. {
  1565. lineNumber += block.Length - 1;
  1566. }
  1567. }
  1568. return lineNumber;
  1569. }
  1570. internal void MouseClicked(bool showBranchMarkers, bool withShift, Vector2 mousePos, int controlID)
  1571. {
  1572. if (_mouseOutsideBounds || mousePos.y > finalAreaSize.y) { return; }
  1573. GUIUtility.hotControl = controlID;
  1574. // FocusControl is to take keyboard focus away from the TreeView.
  1575. GUI.FocusControl("long text");
  1576. if (withShift)
  1577. {
  1578. mousePos = MouseClickAndClamp(showBranchMarkers, mousePos);
  1579. selectDragPos = mousePos;
  1580. _textSelectionIdxValid = false;
  1581. }
  1582. else
  1583. {
  1584. selectDragPos = mousePos;
  1585. StopSelection();
  1586. }
  1587. _mouseDown = true;
  1588. }
  1589. internal void DragMouse(Vector2 mousePos, bool showBranchMarkers)
  1590. {
  1591. if (!_mouseDown || mousePos.y > finalAreaSize.y) { return; }
  1592. mousePos = MouseClickAndClamp(showBranchMarkers, mousePos);
  1593. selectDragPos = mousePos;
  1594. _textSelectionIdxValid = false;
  1595. }
  1596. internal void MouseReleased()
  1597. {
  1598. GUIUtility.hotControl = 0;
  1599. _mouseDown = false;
  1600. }
  1601. internal void DoScroll(Rect workingArea, float mouseRelMoveY)
  1602. {
  1603. if (!_mouseDown) { return; }
  1604. var movingDown = mouseRelMoveY > 0;
  1605. var room = Mathf.Max(0, movingDown
  1606. ? finalAreaSize.y - workingArea.yMax
  1607. : workingArea.yMin);
  1608. // naturalEnhancedPad magic number taken from unity engine (GUI.cs under EndScrollView).
  1609. var dist = Mathf.Min(Mathf.Abs(mouseRelMoveY * naturalEnhancedPad), room);
  1610. selectDragPos.y += movingDown ? dist : -dist;
  1611. _textSelectionIdxValid = false;
  1612. }
  1613. public void MoveView(Direction dir, Rect workingArea)
  1614. {
  1615. switch (dir)
  1616. {
  1617. case Direction.Left:
  1618. GUI.ScrollTo(new Rect(workingArea.xMin - 2*fontWidth, workingArea.y, 0, 0));
  1619. break;
  1620. case Direction.Right:
  1621. GUI.ScrollTo(new Rect(workingArea.xMax + 2*fontWidth, workingArea.y, 0, 0));
  1622. break;
  1623. case Direction.Up:
  1624. GUI.ScrollTo(new Rect(workingArea.x, workingArea.yMin - 2*fontWidth, 0, 0));
  1625. break;
  1626. case Direction.Down:
  1627. GUI.ScrollTo(new Rect(workingArea.x, workingArea.yMax + 2*fontWidth, 0, 0));
  1628. break;
  1629. }
  1630. }
  1631. public void StopSelection()
  1632. {
  1633. selectPos = selectDragPos;
  1634. textSelectionIdx = (0, 0);
  1635. _textSelectionIdxValid = true;
  1636. HasSelection = false;
  1637. }
  1638. /// <summary>
  1639. /// Renders a blue box relative to text at (positionX, positionY) from start idx to end idx.
  1640. /// </summary>
  1641. private void RenderLineSelection(float positionX, float positionY, int start, int end, bool IsSelection = true)
  1642. {
  1643. const int alignmentPad = 2;
  1644. var oldColor = GUI.color;
  1645. GUI.color = IsSelection ? _selectionColor : _searchHitColor;
  1646. GUI.Box(new Rect(positionX + alignmentPad + start*fontWidth, positionY, (end - start)*fontWidth, fontHeight), "", textureStyle);
  1647. GUI.color = oldColor;
  1648. }
  1649. internal struct FragmentSelectionInfo
  1650. {
  1651. public float startY;
  1652. public float lastY;
  1653. public float botY;
  1654. public int startLineEndIdxRel;
  1655. public int startLine;
  1656. public int lastLine;
  1657. public int charsIn;
  1658. public int charsInDrag;
  1659. }
  1660. internal FragmentSelectionInfo PrepareInfoForSelection(float positionX, float positionY, float fragHeight, Fragment frag, Func<string, int, (int total, int relative)> GetEndIndexOfLine)
  1661. {
  1662. const float distanceFromBorder = 0.001f;
  1663. var text = frag.text;
  1664. var top = selectPos;
  1665. var bot = selectDragPos;
  1666. if (selectPos.y > selectDragPos.y)
  1667. {
  1668. top = selectDragPos;
  1669. bot = selectPos;
  1670. }
  1671. // fixing so we only look at things within this current fragment.
  1672. var start = top.y < positionY ? new Vector2(positionX, positionY) : top;
  1673. // `y = ... - adjustBottomSlightly` so it is within current fragments outer "border".
  1674. var last = bot.y < positionY + fragHeight ? bot : new Vector2(finalAreaSize.x, positionY + fragHeight - distanceFromBorder);
  1675. // Make sure this cannot go beyond number of lines in fragment (zero indexed).
  1676. var startLine = Math.Min(Mathf.FloorToInt((start.y - positionY) / fontHeight), frag.lineCount-1);
  1677. var lastLine = Math.Min(Mathf.FloorToInt((last.y - positionY) / fontHeight), frag.lineCount-1);
  1678. if (startLine == lastLine && start.x > last.x)
  1679. (start, last) = (last, start);
  1680. // Used for making sure charsIn and charsInDrag does not exceed line length.
  1681. var (_, startLineEndIdxRel) = GetEndIndexOfLine(text, startLine);
  1682. var (_, lastLineEndIdxRel) = GetEndIndexOfLine(text, lastLine);
  1683. // Each fragment does not end on a newline, so we need to add one to idx.
  1684. if (startLine == frag.lineCount - 1) startLineEndIdxRel++;
  1685. if (lastLine == frag.lineCount - 1) lastLineEndIdxRel++;
  1686. var charsIn = Math.Min(Mathf.FloorToInt((start.x - positionX) / fontWidth), startLineEndIdxRel);
  1687. var charsInDrag = Math.Min(Mathf.FloorToInt((last.x - positionX) / fontWidth), lastLineEndIdxRel);
  1688. charsIn = charsIn < 0 ? 0 : charsIn;
  1689. charsInDrag = charsInDrag < 0 ? 0 : charsInDrag;
  1690. return new FragmentSelectionInfo() {startY = start.y, lastY = last.y, botY = bot.y,
  1691. startLineEndIdxRel = startLineEndIdxRel, startLine = startLine, lastLine = lastLine,
  1692. charsIn = charsIn, charsInDrag = charsInDrag};
  1693. }
  1694. private void SelectText(float positionX, float positionY, float fragHeight, Fragment frag, Func<string, int, (int total, int relative)> GetEndIndexOfLine)
  1695. {
  1696. if (!HasSelection || !(BurstMath.WithinRange(selectPos.y, selectDragPos.y, positionY) ||
  1697. BurstMath.WithinRange(selectPos.y, selectDragPos.y, positionY + fragHeight)
  1698. || BurstMath.WithinRange(positionY, positionY + fragHeight, selectPos.y)))
  1699. {
  1700. return;
  1701. }
  1702. var inf = PrepareInfoForSelection(positionX, positionY, fragHeight, frag, GetEndIndexOfLine);
  1703. var text = frag.text;
  1704. if (BurstMath.RoundDownToNearest(inf.lastY, fontHeight) > BurstMath.RoundDownToNearest(inf.startY, fontHeight))
  1705. {
  1706. // Multi line selection in this text.
  1707. int lineEndIdx = inf.startLineEndIdxRel;
  1708. if (inf.startY != positionY)
  1709. {
  1710. // Selection started in this fragment.
  1711. RenderLineSelection(positionX, positionY + (inf.startLine * fontHeight), inf.charsIn, lineEndIdx + 1);
  1712. inf.startLine++;
  1713. }
  1714. for (; inf.startLine < inf.lastLine; inf.startLine++)
  1715. {
  1716. lineEndIdx = GetEndIndexOfLine(text, inf.startLine).relative;
  1717. RenderLineSelection(positionX, positionY + (inf.startLine * fontHeight), 0, lineEndIdx + 1);
  1718. }
  1719. if (positionY + fragHeight < inf.botY)
  1720. {
  1721. // select going into next fragment
  1722. inf.charsInDrag++;
  1723. }
  1724. RenderLineSelection(positionX, positionY + (inf.startLine * fontHeight), 0, inf.charsInDrag);
  1725. }
  1726. else
  1727. {
  1728. // Single line selection in this text segment.
  1729. int startIdx = inf.charsIn;
  1730. int endIdx = inf.charsInDrag;
  1731. if (inf.startY == positionY)
  1732. {
  1733. // Selection started in text segment above.
  1734. startIdx = 0;
  1735. }
  1736. if (positionY + fragHeight < inf.botY)
  1737. {
  1738. // Selection going into next text segment.
  1739. endIdx = inf.startLineEndIdxRel + 1;
  1740. }
  1741. RenderLineSelection(positionX, positionY + (inf.startLine * fontHeight), startIdx, endIdx);
  1742. }
  1743. }
  1744. /// <summary>
  1745. /// Updates _textSelectionIdx based on the position of _selectPos and _selectDragPos.
  1746. /// </summary>
  1747. /// <param name="GetEndIndexOfLine"> either GetEndIndexOfPlainLine or GetEndIndexOfColoredLine</param>
  1748. private void UpdateSelectTextIdx(Func<string, int, (int total, int relative)> GetEndIndexOfLine)
  1749. {
  1750. if (!_textSelectionIdxValid && HasSelection)
  1751. {
  1752. var start = selectPos;
  1753. var last = selectDragPos;
  1754. if (last.y < start.y)
  1755. {
  1756. start = selectDragPos;
  1757. last = selectPos;
  1758. }
  1759. int startLine = Mathf.FloorToInt(start.y / fontHeight);
  1760. int lastLine = Mathf.FloorToInt(last.y / fontHeight);
  1761. if (startLine == lastLine && start.x > last.x)
  1762. {
  1763. (start, last) = (last, start);
  1764. }
  1765. var (startLineEndIdxTotal, startLineEndIdxRel) = GetEndIndexOfLine(m_Text, startLine);
  1766. var (lastLineEndIdxTotal, lastLineEndIdxRel) = GetEndIndexOfLine(m_Text, lastLine);
  1767. int charsIn = Math.Min(Mathf.FloorToInt(start.x / fontWidth), startLineEndIdxRel);
  1768. int charsInDrag = Math.Min(Mathf.FloorToInt(last.x / fontWidth), lastLineEndIdxRel);
  1769. charsIn = charsIn < 0 ? 0 : charsIn;
  1770. charsInDrag = charsInDrag < 0 ? 0 : charsInDrag;
  1771. int selectStartIdx = startLineEndIdxTotal - (startLineEndIdxRel - charsIn);
  1772. textSelectionIdx = (selectStartIdx, lastLineEndIdxTotal - (lastLineEndIdxRel - charsInDrag) - selectStartIdx);
  1773. _textSelectionIdxValid = true;
  1774. }
  1775. }
  1776. public void NextSearchHit(bool shift, Rect workingArea)
  1777. {
  1778. if (_nrSearchHits <= 0) return;
  1779. // If shift is held down: Go backwards through active search
  1780. _activeSearchHitIdx = shift
  1781. ? (Math.Max(_activeSearchHitIdx, 0) - 1 + _nrSearchHits) % _nrSearchHits
  1782. : (_activeSearchHitIdx + 1) % _nrSearchHits;
  1783. // Find fragment number of _activeSearchHit
  1784. var fragIdx = 0;
  1785. int prevFragLastHitNr = -1;
  1786. var activeSearchIdx = _activeSearchHitIdx;
  1787. foreach (var key in searchHits.Keys)
  1788. {
  1789. var hits = searchHits[key];
  1790. var nrHits = hits.Count;
  1791. var hitsLastNr = hits[nrHits - 1].nr;
  1792. // If last hit continues into this fragment we subtracted too much
  1793. if (hits[0].nr == prevFragLastHitNr) { activeSearchIdx++; }
  1794. if (hitsLastNr >= _activeSearchHitIdx)
  1795. {
  1796. fragIdx = key;
  1797. break;
  1798. }
  1799. activeSearchIdx -= nrHits;
  1800. prevFragLastHitNr = hitsLastNr;
  1801. }
  1802. var hit = searchHits[fragIdx][activeSearchIdx];
  1803. // Find y position of _activeSearchHit.
  1804. int exactLineNumber;
  1805. string text;
  1806. var positionY = 0f;
  1807. if (_disassembler == null)
  1808. {
  1809. int i = 0;
  1810. for (; i < fragIdx; i++)
  1811. {
  1812. positionY += m_Fragments[i].lineCount * fontHeight;
  1813. }
  1814. text = m_Fragments[i].text;
  1815. exactLineNumber = BurstStringSearch.FindLineNr(text, hit.startIdx);
  1816. positionY += exactLineNumber * fontHeight;
  1817. }
  1818. else
  1819. {
  1820. int blockIdx = 0;
  1821. int innerFragIdx = 0;
  1822. int tmpFragIdx = 0;
  1823. for (; tmpFragIdx < fragIdx; blockIdx++)
  1824. {
  1825. var frags = GetPlainFragments(blockIdx);
  1826. if (_folded[blockIdx])
  1827. {
  1828. positionY += fontHeight;
  1829. tmpFragIdx += frags.Count;
  1830. }
  1831. else
  1832. {
  1833. for (innerFragIdx = 0; ; innerFragIdx++, tmpFragIdx++)
  1834. {
  1835. if (innerFragIdx >= frags.Count)
  1836. {
  1837. innerFragIdx = 0;
  1838. break;
  1839. }
  1840. if (tmpFragIdx >= fragIdx) break;
  1841. positionY += frags[innerFragIdx].lineCount * fontHeight;
  1842. }
  1843. }
  1844. if (innerFragIdx != 0) break;
  1845. }
  1846. text = GetPlainFragments(blockIdx)[innerFragIdx].text;
  1847. exactLineNumber = BurstStringSearch.FindLineNr(text, hit.startIdx);
  1848. positionY += exactLineNumber * fontHeight;
  1849. }
  1850. int startOfLine = exactLineNumber > 0 ? GetEndIndexOfPlainLine(text, exactLineNumber-1).total + 1 : 0;
  1851. int hitLength = hit.endIdx - hit.startIdx;
  1852. float positionX = hit.startIdx - startOfLine;
  1853. if (positionX * fontWidth > workingArea.x) positionX += hitLength + 3 * fontWidth;
  1854. else positionX -= 3 * fontWidth;
  1855. GUI.ScrollTo(new Rect(positionX * fontWidth + _actualHorizontalPad, positionY < workingArea.yMin ? positionY - 5 * fontHeight : positionY + 5 * fontHeight, 0, 0));
  1856. }
  1857. public void StopSearching()
  1858. {
  1859. _nrSearchHits = 0;
  1860. searchHits.Clear();
  1861. _activeSearchHitIdx = -1;
  1862. _prevCriteria.filter = String.Empty;
  1863. }
  1864. private void RenderMultipleLinesSelection(string text, float positionX, float positionY, int startIdx, int endIdx, bool IsSelection = true)
  1865. {
  1866. int lineStart = BurstStringSearch.FindLineNr(text, startIdx);
  1867. int lineEnd = BurstStringSearch.FindLineNr(text, endIdx);
  1868. // Make idx relative to line
  1869. int startOfLine = lineStart == 0 ? 0 : GetEndIndexOfPlainLine(text, lineStart-1).total + 1;
  1870. startIdx = startIdx - startOfLine;
  1871. startOfLine = lineEnd == 0 ? 0 : GetEndIndexOfPlainLine(text, lineEnd-1).total + 1;
  1872. endIdx = endIdx - startOfLine;
  1873. positionY += (lineStart * fontHeight);
  1874. if (lineStart == lineEnd)
  1875. {
  1876. RenderLineSelection(positionX, positionY, startIdx, endIdx, IsSelection);
  1877. }
  1878. else
  1879. {
  1880. int endOfLine = GetEndIndexOfPlainLine(text, lineStart).relative;
  1881. RenderLineSelection(positionX, positionY, startIdx, endOfLine, IsSelection);
  1882. lineStart++;
  1883. positionY += fontHeight;
  1884. for (; lineStart < lineEnd; lineStart++)
  1885. {
  1886. endOfLine = GetEndIndexOfPlainLine(text, lineStart).relative;
  1887. RenderLineSelection(positionX, positionY, 0, endOfLine, IsSelection);
  1888. positionY += fontHeight;
  1889. }
  1890. RenderLineSelection(positionX, positionY, 0, endIdx, IsSelection);
  1891. }
  1892. }
  1893. private void RenderPlainOldFragments(GUIStyle style, Rect workingArea, bool doSearch)
  1894. {
  1895. Vector2 scrollPos = workingArea.position;
  1896. float positionY = 0.0f;
  1897. for (int i = 0; i < m_Fragments.Count; i++)
  1898. {
  1899. // if fragment is below view
  1900. if ((positionY - scrollPos.y) > workingArea.size.y) break;
  1901. var fragment = m_Fragments[i];
  1902. float fragHeight = fragment.lineCount * fontHeight;
  1903. // if whole fragment is above view
  1904. if ((positionY - scrollPos.y + fragHeight) < 0)
  1905. {
  1906. positionY += fragHeight;
  1907. continue;
  1908. }
  1909. if (doSearch && searchHits.TryGetValue(i, out var lst))
  1910. {
  1911. foreach (var (startI, endI, nr) in lst)
  1912. {
  1913. bool isActive = nr == _activeSearchHitIdx;
  1914. RenderMultipleLinesSelection(fragment.text, horizontalPad, positionY, startI, endI, isActive);
  1915. }
  1916. }
  1917. // we append \n here, as we want it for the selection but not the rendering.
  1918. SelectText(horizontalPad, positionY, fragHeight, fragment, GetEndIndexOfPlainLine);
  1919. GUI.Label(new Rect(horizontalPad, positionY, finalAreaSize.x, fragHeight + fontHeight*0.5f), fragment.text, style);
  1920. positionY += fragHeight;
  1921. }
  1922. UpdateSelectTextIdx(GetEndIndexOfPlainLine);
  1923. }
  1924. /// <returns>Whether the GUI should be forced to repaint during this frame.</returns>
  1925. public bool Render(GUIStyle style, Rect workingArea, bool showBranchMarkers, bool doSearch, SearchCriteria searchCriteria, Regex regx)
  1926. {
  1927. _actualHorizontalPad = showBranchMarkers ? horizontalPad : naturalEnhancedPad;
  1928. style.richText = true;
  1929. if (invalidated)
  1930. {
  1931. Layout(style, _actualHorizontalPad);
  1932. }
  1933. if (_disassembler != null)
  1934. {
  1935. // We always need to call this as its sets up the correct horizontal bar and block rendering
  1936. LayoutEnhanced(style, workingArea, showBranchMarkers);
  1937. }
  1938. if (Event.current.type == EventType.Layout)
  1939. {
  1940. // working area will be valid only during repaint, for the layout event we don't draw the labels
  1941. // Add correct size Rect to GUILayoutUtillity.topLevel for retrieval with next GetRect(.) call.
  1942. GUILayoutUtility.GetRect(finalAreaSize.x + (showBranchMarkers ? horizontalPad : 20.0f), finalAreaSize.y);
  1943. return false;
  1944. }
  1945. var newSearch = doSearch && (searchCriteria.filter != "" && !searchCriteria.Equals(_prevCriteria));
  1946. _prevCriteria = searchCriteria;
  1947. var doRepaint = false;
  1948. if (newSearch)
  1949. {
  1950. doRepaint = SearchText(searchCriteria, regx, ref workingArea);
  1951. if (doRepaint)
  1952. {
  1953. // Search found at least one match, so move to the first
  1954. GUI.ScrollTo(workingArea);
  1955. }
  1956. }
  1957. if (_disassembler == null)
  1958. {
  1959. RenderPlainOldFragments(style, workingArea, doSearch);
  1960. }
  1961. else
  1962. {
  1963. RenderEnhanced(style, workingArea, showBranchMarkers, _actualHorizontalPad, doSearch);
  1964. RenderRegisterHighlight(workingArea, _actualHorizontalPad);
  1965. RenderLineHighlight(_actualHorizontalPad);
  1966. }
  1967. DrawHover(style, workingArea);
  1968. return doRepaint;
  1969. }
  1970. internal int GetLinesBlockIdx(int pressedLine)
  1971. {
  1972. // Find block that was pressed:
  1973. var b = _renderBlockStart;
  1974. var numBlocks = _blocksFragments.Length;
  1975. for (; b <= _renderBlockEnd && b < numBlocks-1; b++)
  1976. {
  1977. var block = _disassembler.Blocks[b];
  1978. if (block.LineIndex <= pressedLine && block.LineIndex + block.Length > pressedLine)
  1979. {
  1980. break;
  1981. }
  1982. }
  1983. return b;
  1984. }
  1985. internal Rect GetLineHighlight(ref LineRegRectsCache cache, float hPad, int pressedLine)
  1986. {
  1987. // Find block that was pressed:
  1988. var b = GetLinesBlockIdx(pressedLine);
  1989. if (cache.IsLineHighlightCached(pressedLine, _folded[b]))
  1990. {
  1991. // Same old line
  1992. return cache.lineHighlight;
  1993. }
  1994. var pressedLineRel = pressedLine - _disassembler.Blocks[b].LineIndex;
  1995. var positionY =
  1996. _renderStartY + (blockLine[b] - blockLine[_renderBlockStart] + pressedLineRel) * fontHeight;
  1997. const float lineHeight = 2f;
  1998. // Cannot use tokens in disassembler, as it's not updated with the proper output created by
  1999. // RenderLine(.).
  2000. var line = _disassembler.Lines[pressedLine];
  2001. var lineStr = _folded[b] ? GetFragmentStartPlain(b).text : GetLineString(line);
  2002. var xEnd = lineStr.Length * fontWidth;
  2003. var xStart = hPad;
  2004. var yPos = positionY + fontHeight;
  2005. var rect = new Rect(xStart, yPos, xEnd, lineHeight);
  2006. cache.UpdateLineHighlight(pressedLine, rect, _folded[b]);
  2007. return rect;
  2008. }
  2009. private void RenderLineHighlight(float hPad)
  2010. {
  2011. if (_pressedLine == -1)
  2012. {
  2013. return;
  2014. }
  2015. var firstRenderedLine = _disassembler.Blocks[_renderBlockStart].LineIndex;
  2016. var tmp = _disassembler.Blocks[_renderBlockEnd];
  2017. var lastRenderedLine = tmp.LineIndex + tmp.Length;
  2018. if (!BurstMath.WithinRange(firstRenderedLine, lastRenderedLine, _pressedLine))
  2019. {
  2020. return;
  2021. }
  2022. var col = GUI.color;
  2023. GUI.color = _lineHighlightColor;
  2024. GUI.Box(GetLineHighlight(ref _lineRegCache, hPad, _pressedLine), "", textureStyle);
  2025. GUI.color = col;
  2026. }
  2027. internal LineRegRectsCache _lineRegCache;
  2028. internal int _pressedLine = -1;
  2029. private void RenderRegisterHighlight(Rect workingArea, float hPad)
  2030. {
  2031. if (_pressedLine == -1)
  2032. {
  2033. return;
  2034. }
  2035. if (_disassembler.LineUsesRegs(_pressedLine, out var usedRegs) && _disassembler.Lines[_pressedLine].Kind != BurstDisassembler.AsmLineKind.Directive)
  2036. {
  2037. var oldColor = GUI.color;
  2038. var regRects = GetRegisterRects(hPad, ref _lineRegCache, _pressedLine, usedRegs);
  2039. var i = 0;
  2040. foreach (var rects in regRects)
  2041. {
  2042. GUI.color = _regsColourWheel[i % _regsColourWheel.Length];
  2043. foreach (var rect in rects)
  2044. {
  2045. if (!workingArea.Contains(rect.position))
  2046. {
  2047. continue;
  2048. }
  2049. GUI.Box(rect, "", textureStyle);
  2050. }
  2051. i++;
  2052. }
  2053. GUI.color = oldColor;
  2054. }
  2055. else if (_pressedLine != _lineRegCache.chosenLine)
  2056. {
  2057. // We need to clear the cache, as we pressed somewhere new.
  2058. // Alternatively we only need to do this if a fold changed, or the view changed!
  2059. _lineRegCache.Clear();
  2060. }
  2061. }
  2062. internal string GetLineString(BurstDisassembler.AsmLine line)
  2063. {
  2064. _disassembler._output.Clear();
  2065. _disassembler.RenderLine(ref line, false);
  2066. var str = _disassembler._output.ToString();
  2067. _disassembler._output.Length = 0;
  2068. return str;
  2069. }
  2070. private (int start, int end) FindBlockIdx(int startBlock, int firstLine, int lastLine)
  2071. {
  2072. var blockIdx = startBlock;
  2073. for (; blockIdx > 0; blockIdx--)
  2074. {
  2075. if (blockLine[blockIdx] <= firstLine)
  2076. {
  2077. break;
  2078. }
  2079. }
  2080. var blockIdxEnd = _renderBlockEnd;
  2081. for (; blockIdxEnd < _blocksFragments.Length - 1; blockIdxEnd++)
  2082. {
  2083. var bLen = _folded[blockIdxEnd]
  2084. ? 1
  2085. : _disassembler.Blocks[blockIdxEnd].Length;
  2086. if (blockLine[blockIdxEnd] + bLen >= lastLine)
  2087. {
  2088. break;
  2089. }
  2090. }
  2091. return (blockIdx, blockIdxEnd);
  2092. }
  2093. /// <summary>
  2094. /// Finds all usages of <see cref="regs"/> within view, and returns a list of <see cref="Rect"/>
  2095. /// presenting these usages.
  2096. /// </summary>
  2097. /// <param name="hPad">Horizontal padding in text area.</param>
  2098. /// <param name="cache">Cache handling saving register rects.</param>
  2099. /// <param name="pressedLine">The currently selected line.</param>
  2100. /// <param name="regs">Registers to match against.</param>
  2101. /// <remarks>
  2102. /// This will return representation of ALL matching registers within <see cref="workingArea"/>.
  2103. ///
  2104. /// Depends on:
  2105. /// <list type="bullet">
  2106. /// <item>
  2107. /// <see cref="_burstDisassember"/>.
  2108. /// </item>
  2109. /// <item>
  2110. /// <see cref="LayoutEnhanced"/> been called at least once before this.
  2111. /// </item>
  2112. /// </list>
  2113. /// </remarks>
  2114. internal List<Rect>[] GetRegisterRects(float hPad, ref LineRegRectsCache cache, int pressedLine, List<string> regs)
  2115. {
  2116. const int extraLines = 5;
  2117. const float horizontalAlignmentPad = 2f;
  2118. var firstLine = Math.Max(blockLine[_renderBlockStart] - extraLines, 0);
  2119. var lastLine = blockLine[_renderBlockEnd] + (_folded[_renderBlockEnd]
  2120. ? 1
  2121. : _disassembler.Blocks[_renderBlockEnd].Length-1) + extraLines;
  2122. var (blockIdx, blockIdxEnd) = FindBlockIdx(_renderBlockStart, firstLine, lastLine);
  2123. var positionY = Math.Max(_renderStartY - (extraLines * fontHeight), 0);
  2124. // Convert lineIdx to absolut indexes. Needed for _disassembler.Lines[...]
  2125. for (var i = 0; i < blockIdxEnd; i++)
  2126. {
  2127. if (_folded[i])
  2128. {
  2129. var len = _disassembler.Blocks[i].Length - 1;
  2130. if (i < blockIdx) { firstLine += len; }
  2131. lastLine += len;
  2132. }
  2133. }
  2134. // Make sure LastLine does not exceed number of lines
  2135. lastLine = Math.Min(lastLine, _disassembler.Lines.Count - 1);
  2136. if (cache.IsRegisterCachedOrClear(pressedLine, firstLine, lastLine))
  2137. {
  2138. return cache.rects;
  2139. }
  2140. // Clean up regs, so e.g. "rcx" and "ecx" only counts as one:
  2141. regs = _disassembler.CleanRegs(regs);
  2142. var currentLine = firstLine;
  2143. var lineInBlock = firstLine - _disassembler.Blocks[blockIdx].LineIndex;
  2144. var rects = cache.rects;
  2145. if (rects == null)
  2146. {
  2147. rects = new List<Rect>[regs.Count];
  2148. for (var i = 0; i < regs.Count; i++)
  2149. {
  2150. rects[i] = new List<Rect>();
  2151. }
  2152. }
  2153. while (blockIdx < _blocksFragments.Length && currentLine <= lastLine)
  2154. {
  2155. var lineNotCached = !cache.LinesRegsCached(currentLine);
  2156. var line = _disassembler.Lines[currentLine];
  2157. if (lineNotCached && line.Kind != BurstDisassembler.AsmLineKind.Directive)
  2158. {
  2159. // Loop body
  2160. var lineStart = _disassembler.Tokens[line.TokenIndex].AlignedPosition;
  2161. var i = 0;
  2162. foreach (var reg in regs)
  2163. {
  2164. var regUsedNr = _disassembler.LineUsedReg(currentLine, reg);
  2165. if (regUsedNr > 0)
  2166. {
  2167. var tmpIdx = 0;
  2168. for (var r = 0; r < regUsedNr; r++)
  2169. {
  2170. // Find position and width/height of reg:
  2171. var height = fontHeight;
  2172. var width = reg.Length * fontWidth;
  2173. var y = positionY;
  2174. var tokenRegIdx = _disassembler.GetRegisterTokenIndex(line, reg, tmpIdx);
  2175. if (tokenRegIdx == -1)
  2176. {
  2177. throw new Exception($"Could not find token index of \"{reg}\" on line {currentLine}.");
  2178. }
  2179. var regIdx = _disassembler.Tokens[tokenRegIdx].AlignedPosition - lineStart;
  2180. var regPos = regIdx * fontWidth;
  2181. var x = hPad + regPos + horizontalAlignmentPad;
  2182. rects[i].Add(new Rect(x, y, width, height));
  2183. tmpIdx = tokenRegIdx + 1;
  2184. }
  2185. }
  2186. i++;
  2187. }
  2188. }
  2189. // Loop end statements
  2190. if (lineInBlock >= _disassembler.Blocks[blockIdx].Length)
  2191. {
  2192. // Moved into next block
  2193. blockIdx++;
  2194. lineInBlock = 0;
  2195. }
  2196. if (_folded[blockIdx])
  2197. {
  2198. currentLine += _disassembler.Blocks[blockIdx].Length;
  2199. blockIdx++;
  2200. lineInBlock = 0;
  2201. }
  2202. else
  2203. {
  2204. currentLine++;
  2205. lineInBlock++;
  2206. }
  2207. positionY += fontHeight;
  2208. }
  2209. cache.UpdateRegisters(firstLine, lastLine, pressedLine, rects);
  2210. return cache.rects;
  2211. }
  2212. internal struct LineRegRectsCache
  2213. {
  2214. [Flags]
  2215. private enum CachedItem
  2216. {
  2217. None = 0,
  2218. Line = 1,
  2219. Registers = 2
  2220. }
  2221. private CachedItem _isCached;
  2222. private bool _folded;
  2223. /// <summary>
  2224. /// First line we have cached up till.
  2225. /// </summary>
  2226. public int startLine;
  2227. /// <summary>
  2228. /// Last line we have cached down till.
  2229. /// </summary>
  2230. public int endLine;
  2231. /// <summary>
  2232. /// Line we have in focus.
  2233. /// </summary>
  2234. public int chosenLine;
  2235. public Rect lineHighlight;
  2236. /// <summary>
  2237. /// Cached rects. Each row represent one register, and each column is a rect for that register.
  2238. /// </summary>
  2239. public List<Rect>[] rects;
  2240. public bool LinesRegsCached(int pressedLine)
  2241. {
  2242. return (_isCached & CachedItem.Registers) > 0 && BurstMath.WithinRange(startLine, endLine, pressedLine);
  2243. }
  2244. public bool IsRegisterCachedOrClear(int pressedLine, int firstLine, int lastLine)
  2245. {
  2246. var isCached = false;
  2247. if (!IsRegistersCached(pressedLine))
  2248. {
  2249. // New line was pressed!
  2250. Clear();
  2251. }
  2252. else if (!ShouldUpdateCache(firstLine, lastLine))
  2253. {
  2254. isCached = true;
  2255. }
  2256. return isCached;
  2257. }
  2258. public bool IsLineHighlightCached(int linePressed, bool folded) =>
  2259. folded == _folded && (_isCached & CachedItem.Line) > 0 && linePressed == chosenLine;
  2260. public bool IsRegistersCached(int linePressed) => (_isCached & CachedItem.Registers) > 0 && linePressed == chosenLine;
  2261. private bool ShouldUpdateCache(int viewLineStart, int viewLineEnd) => viewLineStart < startLine || viewLineEnd > endLine;
  2262. public void UpdateRegisters(int firstLine, int lastLine, int pressedLine, List<Rect>[] RegRects)
  2263. {
  2264. if (chosenLine != pressedLine && (_isCached & CachedItem.Line) > 0)
  2265. {
  2266. _isCached ^= CachedItem.Line;
  2267. }
  2268. startLine = Math.Min(firstLine, startLine);
  2269. endLine = Math.Max(lastLine, endLine);
  2270. chosenLine = pressedLine;
  2271. rects = RegRects;
  2272. _isCached |= CachedItem.Registers;
  2273. }
  2274. public void UpdateLineHighlight(int pressedLine, Rect rect, bool folded)
  2275. {
  2276. _isCached |= CachedItem.Line;
  2277. if (chosenLine != pressedLine && (_isCached & CachedItem.Registers) > 0)
  2278. {
  2279. // line just changed so register cache is no longer valid.
  2280. _isCached ^= CachedItem.Registers;
  2281. }
  2282. lineHighlight = rect;
  2283. chosenLine = pressedLine;
  2284. _folded = folded;
  2285. }
  2286. public void Clear()
  2287. {
  2288. rects = null;
  2289. chosenLine = -1;
  2290. startLine = int.MaxValue;
  2291. endLine = -1;
  2292. _isCached = CachedItem.None;
  2293. }
  2294. }
  2295. private void TestSelUnderscore(GUIStyle style, Vector2 scrollPos, Rect workingArea)
  2296. {
  2297. var current = GUI.color;
  2298. // Selection
  2299. GUI.color = Color.blue;
  2300. GUI.Box(
  2301. new Rect(horizontalPad + style.padding.left + fontWidth * 8, style.padding.top + fontHeight * 19,
  2302. 3 * fontWidth, 1 * fontHeight), "", textureStyle);
  2303. // Underscored
  2304. Vector2 start = new Vector2(horizontalPad + style.padding.left + fontWidth * 8,
  2305. style.padding.top + fontHeight * 20 - 2);
  2306. Vector2 end = start + new Vector2((3 + 22) * fontWidth, 0 * fontHeight);
  2307. GUI.color = Color.red;
  2308. DrawLine(start, end, 2);
  2309. GUI.color = current;
  2310. }
  2311. internal void RenderBranches(Rect workingArea)
  2312. {
  2313. var color = GUI.color;
  2314. List<Branch> branches = new List<Branch>();
  2315. hoveredBranch = default;
  2316. for (int idx = 0;idx<_disassembler.Blocks.Count; idx++)
  2317. {
  2318. var block = _disassembler.Blocks[idx];
  2319. if (block.Edges != null)
  2320. {
  2321. foreach (var edge in block.Edges)
  2322. {
  2323. if (edge.Kind == BurstDisassembler.AsmEdgeKind.OutBound)
  2324. {
  2325. var srcLine = blockLine[idx];
  2326. if (!_folded[idx])
  2327. {
  2328. srcLine += edge.OriginRef.LineIndex;
  2329. }
  2330. var dstBlockIdx = edge.LineRef.BlockIndex;
  2331. var dstLine = blockLine[dstBlockIdx];
  2332. if (!_folded[dstBlockIdx])
  2333. {
  2334. dstLine += edge.LineRef.LineIndex;
  2335. }
  2336. int arrowMinY = srcLine;
  2337. int arrowMaxY = dstLine;
  2338. if (srcLine > dstLine)
  2339. {
  2340. (arrowMinY, arrowMaxY) = (dstLine, srcLine);
  2341. }
  2342. if ((dstBlockIdx == idx + 1 && edge.LineRef.LineIndex == 0) // pointing to next line
  2343. || !(workingArea.yMin <= arrowMaxY * fontHeight && // Arrow not inside view.
  2344. workingArea.yMax >= arrowMinY * fontHeight))
  2345. {
  2346. continue;
  2347. }
  2348. branches.Add(CalculateBranch(edge, horizontalPad - (4 + fontWidth), srcLine * fontHeight,
  2349. dstLine * fontHeight, lineDepth[idx]));
  2350. }
  2351. }
  2352. }
  2353. }
  2354. // Drawing branches while making sure the hovered is rendered at top.
  2355. foreach (var branch in branches)
  2356. {
  2357. if (!branch.Edge.Equals(hoveredBranch.Edge))
  2358. {
  2359. DrawBranch(branch, lineDepth[branch.Edge.OriginRef.BlockIndex], workingArea);
  2360. }
  2361. }
  2362. if (!hoveredBranch.Edge.Equals(default(BurstDisassembler.AsmEdge)))
  2363. {
  2364. DrawBranch(hoveredBranch, lineDepth[hoveredBranch.Edge.OriginRef.BlockIndex], workingArea);
  2365. }
  2366. _prevHoveredEdge = hoveredBranch.Edge;
  2367. GUI.color = color;
  2368. }
  2369. internal int BumpSelectionXByColorTag(string text, int lineIdxTotal, int charsIn)
  2370. {
  2371. bool lastWasStart = true;
  2372. int colorTagStart = text.IndexOf("<color=", lineIdxTotal);
  2373. while (colorTagStart != -1 && colorTagStart - lineIdxTotal < charsIn)
  2374. {
  2375. int colorTagEnd = text.IndexOf('>', colorTagStart + 1);
  2376. // +1 as the index calculation is zero based.
  2377. charsIn += colorTagEnd - colorTagStart + 1;
  2378. if (lastWasStart)
  2379. {
  2380. colorTagStart = text.IndexOf("</color>", colorTagEnd + 1);
  2381. lastWasStart = false;
  2382. }
  2383. else
  2384. {
  2385. colorTagStart = text.IndexOf("<color=", colorTagEnd + 1);
  2386. lastWasStart = true;
  2387. }
  2388. }
  2389. return charsIn;
  2390. }
  2391. internal void UpdateEnhancedSelectTextIdx(float hPad)
  2392. {
  2393. if (_textSelectionIdxValid || !HasSelection) return;
  2394. int blockIdxStart = _selectBlockStart;
  2395. int blockIdxEnd = _selectBlockEnd;
  2396. float blockStartPosY = _selectStartY;
  2397. float blockEndPosY = _selectEndY;
  2398. var start = selectPos;
  2399. var last = selectDragPos;
  2400. if (last.y < start.y)
  2401. {
  2402. // we selected upwards.
  2403. (start, last) = (last, start);
  2404. (blockIdxStart, blockIdxEnd, blockStartPosY, blockEndPosY) = (blockIdxEnd, blockIdxStart, blockEndPosY, blockStartPosY);
  2405. }
  2406. // Math.Min to make sure line number does not exceed number of line in block (zero indexed).
  2407. var blockStartline = Math.Min(Mathf.FloorToInt((start.y - blockStartPosY) / fontHeight),
  2408. _folded[blockIdxStart]
  2409. ? 0
  2410. : _disassembler.Blocks[blockIdxStart].Length-1);
  2411. var blockEndLine = Math.Min(Mathf.FloorToInt((last.y - blockEndPosY) / fontHeight),
  2412. _folded[blockIdxEnd]
  2413. ? 0
  2414. : _disassembler.Blocks[blockIdxEnd].Length-1);
  2415. if (blockStartline == blockEndLine && blockIdxStart == blockIdxEnd && start.x > last.x)
  2416. {
  2417. // _selectDragPos was above and behind _selectPos on same line.
  2418. (start, last) = (last, start);
  2419. }
  2420. var text = _folded[blockIdxStart]
  2421. ? CopyColorTags
  2422. ? GetFragmentStart(blockIdxStart).text + '\n'
  2423. : GetFragmentStartPlain(blockIdxStart).text + '\n'
  2424. : CopyColorTags
  2425. ? _disassembler.GetOrRenderBlockToText(blockIdxStart)
  2426. : _disassembler.GetOrRenderBlockToTextUncached(blockIdxStart, false);
  2427. var (startLineEndIdxTotal, startLineEndIdxRel) = GetEndIndexOfColoredLine(text, blockStartline);
  2428. int startOfLineIdx = startLineEndIdxTotal - startLineEndIdxRel;
  2429. int charsIn = Math.Min(Mathf.FloorToInt((start.x - hPad) / fontWidth), startLineEndIdxRel);
  2430. charsIn = charsIn < 0 ? 0 : charsIn;
  2431. // Adjust charsIn so it takes color tags into considerations.
  2432. charsIn = BumpSelectionXByColorTag(text, startOfLineIdx, charsIn + 1) - 1; // +1 -1 to not bump charsIn when selecting char just after color tag.
  2433. enhancedTextSelectionIdxStart = (blockIdxStart, startOfLineIdx + charsIn);
  2434. if (blockIdxStart < blockIdxEnd)
  2435. {
  2436. text = _folded[blockIdxEnd]
  2437. ? CopyColorTags
  2438. ? GetFragmentStart(blockIdxEnd).text + '\n'
  2439. : GetFragmentStartPlain(blockIdxEnd).text + '\n'
  2440. : CopyColorTags
  2441. ? _disassembler.GetOrRenderBlockToText(blockIdxEnd)
  2442. : _disassembler.GetOrRenderBlockToTextUncached(blockIdxEnd, false);
  2443. }
  2444. var (lastLineEndIdxTotal, lastLineEndIdxRel) = GetEndIndexOfColoredLine(text, blockEndLine);
  2445. startOfLineIdx = lastLineEndIdxTotal - lastLineEndIdxRel;
  2446. int charsInDrag = Math.Min(Mathf.FloorToInt((last.x - hPad) / fontWidth), lastLineEndIdxRel);
  2447. charsInDrag = charsInDrag < 0 ? 0 : charsInDrag;
  2448. // Adjust charsInDrag so it takes color tags into considerations.
  2449. charsInDrag = BumpSelectionXByColorTag(text, startOfLineIdx, charsInDrag);
  2450. enhancedTextSelectionIdxEnd = (blockIdxEnd, startOfLineIdx + charsInDrag);
  2451. _textSelectionIdxValid = true;
  2452. }
  2453. /// <summary>
  2454. /// Updates selection based on whether <see cref="blockIdx"/> was folded or unfolded.
  2455. /// </summary>
  2456. /// <param name="hPad">horizontal padding.</param>
  2457. /// <param name="blockIdx">Block idx of folded/unfolded block.</param>
  2458. /// <param name="block">folded/unfolded block.</param>
  2459. /// <param name="positionY">Blocks y-position in textarea.</param>
  2460. private void UpdateSelectionByFolding(float hPad, int blockIdx, BurstDisassembler.AsmBlock block, float positionY)
  2461. {
  2462. // cursor start and end position of selection
  2463. var start = selectPos;
  2464. var end = selectDragPos;
  2465. // selection block start and end
  2466. var blockStart = _selectBlockStart;
  2467. var blockEnd = _selectBlockEnd;
  2468. // top y-coordinate of selections end block
  2469. var blockEndY = _selectEndY;
  2470. var rightWaySelect = true;
  2471. if (start.y > end.y)
  2472. {
  2473. (start, end) = (end, start);
  2474. (blockStart, blockEnd) = (blockEnd, blockStart);
  2475. blockEndY = _selectStartY;
  2476. rightWaySelect = false;
  2477. }
  2478. if (BurstMath.RoundDownToNearest(end.y, fontHeight) - BurstMath.RoundDownToNearest(start.y, fontHeight) < fontHeight
  2479. && end.x < start.x)
  2480. {
  2481. (start, end) = (end, start);
  2482. rightWaySelect = !rightWaySelect;
  2483. }
  2484. var changeY = _folded[blockIdx]
  2485. ? -Math.Max(block.Length - 1, 1) * fontHeight
  2486. : Math.Max(block.Length - 1, 1) * fontHeight;
  2487. var charsInLine = GetEndIndexOfColoredLine(
  2488. _folded[blockIdx]
  2489. ? GetFragmentStart(blockIdx).text + '\n'
  2490. : _disassembler.GetOrRenderBlockToText(blockIdx),
  2491. 0).relative;
  2492. var thisLineSelect = Mathf.FloorToInt((start.y - positionY) / fontHeight);
  2493. var thisLineDrag = Mathf.FloorToInt((end.y - positionY) / fontHeight);
  2494. var selectPosCharsIn = Mathf.FloorToInt((start.x - hPad) / fontWidth);
  2495. var selectDragPosCharsIn = Mathf.FloorToInt((end.x - hPad) / fontWidth);
  2496. if (blockStart < blockIdx)
  2497. {
  2498. if (blockEnd == blockIdx)
  2499. {
  2500. if (thisLineDrag > 0 || (end.x - hPad) / fontWidth > charsInLine)
  2501. {
  2502. /* selection starts above touched block but ends in the middle of it.
  2503. *
  2504. * b-1 _xxx b-1 _xxx
  2505. * b xxx_ => b xxx
  2506. * b+1 ____ b+1 ____
  2507. */
  2508. // Move selectDragPos onto end of this line.
  2509. end.y -= thisLineDrag * fontHeight;
  2510. end.x = charsInLine * fontWidth + hPad + fontWidth / 2;
  2511. }
  2512. }
  2513. else if (blockEnd > blockIdx)
  2514. {
  2515. /* selection starts above touched block and ends below it.
  2516. *
  2517. * b-1 _xxx
  2518. * b xxxx
  2519. * b+1 xx__
  2520. */
  2521. end.y += changeY;
  2522. blockEndY += changeY;
  2523. }
  2524. }
  2525. else if (blockStart == blockIdx)
  2526. {
  2527. if (blockEnd == blockIdx)
  2528. {
  2529. if (thisLineSelect > 0 || selectPosCharsIn > charsInLine)
  2530. {
  2531. /* selection starts and ends in the middle of the touched block
  2532. *
  2533. * b-1 ____ b-1 ____
  2534. * b _xx_ => b _
  2535. * b+1 ____ b+1 ____
  2536. */
  2537. // Make cursor go to the end of line
  2538. end.y -= thisLineDrag * fontHeight;
  2539. end.x = charsInLine * fontWidth + hPad + fontWidth / 2;
  2540. StopSelection();
  2541. }
  2542. else if (thisLineDrag > 0 || selectDragPosCharsIn > charsInLine)
  2543. {
  2544. /* selection starts at first line and ends within
  2545. *
  2546. * b-1 ____ b-1 ____
  2547. * b _xx_ => b x
  2548. * xxx_
  2549. * b+1 ____ b+1 ____
  2550. */
  2551. // Move selectDragPos onto end of this line.
  2552. end.y -= thisLineDrag * fontHeight;
  2553. end.x = charsInLine * fontWidth + hPad + fontWidth / 2;
  2554. }
  2555. }
  2556. else if (blockEnd > blockIdx)
  2557. {
  2558. // selection starts either in first line or middle of touched block and ends below it
  2559. end.y += changeY;
  2560. if (thisLineSelect > 0 || selectPosCharsIn > charsInLine)
  2561. {
  2562. /* selection starts in middle of touched block and ends below it
  2563. *
  2564. * b-1 ____ b-1 ____
  2565. * b ____ => b ___x
  2566. * x___
  2567. * b+1 xx__ b+1 xx__
  2568. */
  2569. // Move selectPos onto end of this line.
  2570. start.y -= thisLineSelect * fontHeight;
  2571. start.x = charsInLine * fontWidth + hPad + fontWidth / 2;
  2572. }
  2573. }
  2574. }
  2575. else
  2576. {
  2577. start.y += changeY;
  2578. end.y += changeY;
  2579. }
  2580. // Write back changes made during folding/unfolding
  2581. if (rightWaySelect)
  2582. {
  2583. selectPos = start;
  2584. selectDragPos = end;
  2585. _selectEndY = blockEndY;
  2586. }
  2587. else
  2588. {
  2589. selectPos = end;
  2590. selectDragPos = start;
  2591. _selectStartY = blockEndY;
  2592. }
  2593. if (!HasSelection) selectPos = selectDragPos;
  2594. else _textSelectionIdxValid = false;
  2595. }
  2596. private void FoldUnfoldBlock(int blockIdx)
  2597. {
  2598. var block = _disassembler.Blocks[blockIdx];
  2599. _folded[blockIdx] = !_folded[blockIdx];
  2600. if (_folded[blockIdx])
  2601. {
  2602. finalAreaSize.y -= Math.Max(block.Length - 1, 1) * fontHeight;
  2603. AddFoldedString(blockIdx);
  2604. }
  2605. else
  2606. {
  2607. finalAreaSize.y += Math.Max(block.Length - 1, 1) * fontHeight;
  2608. }
  2609. }
  2610. private void RenderEnhanced(GUIStyle style, Rect workingArea, bool showBranchMarkers, float hPad, bool doSearch)
  2611. {
  2612. //TestSelUnderscore();
  2613. if (showBranchMarkers)
  2614. {
  2615. RenderBranches(workingArea);
  2616. }
  2617. var positionY = _renderStartY;
  2618. var fragNr = 0;
  2619. for (var i = 0; i <= _renderBlockEnd; i++)
  2620. {
  2621. if (i < _renderBlockStart)
  2622. {
  2623. if (doSearch)
  2624. {
  2625. foreach (var frag in GetPlainFragments(i))
  2626. {
  2627. fragNr++;
  2628. }
  2629. }
  2630. continue;
  2631. }
  2632. var block = _disassembler.Blocks[i];
  2633. var blockLongEnoughForFold = block.Length > 1;
  2634. if (blockLongEnoughForFold)
  2635. {
  2636. var pressed = DrawFold(hPad - 2, positionY, _folded[i], block.Kind);
  2637. if (pressed)
  2638. {
  2639. FoldUnfoldBlock(i);
  2640. // Make sure cursor and selection is updated according to the changed folding.
  2641. UpdateSelectionByFolding(hPad, i, block, positionY);
  2642. }
  2643. }
  2644. if (doSearch)
  2645. {
  2646. var tmpPositionY = positionY;
  2647. for (var tmp = 0; tmp < GetPlainFragments(i).Count; fragNr++, tmp++)
  2648. {
  2649. if (searchHits.TryGetValue(fragNr, out var hits))
  2650. {
  2651. if (_folded[i]) FoldUnfoldBlock(i);
  2652. foreach (var (startIdx, endIdx, nr) in hits)
  2653. {
  2654. var isActive = nr == _activeSearchHitIdx;
  2655. var realEndIdx = endIdx;
  2656. if (endIdx == int.MaxValue)
  2657. {
  2658. var text = GetPlainFragments(i)[tmp].text;
  2659. realEndIdx = text.Length;
  2660. RenderMultipleLinesSelection(text, horizontalPad, tmpPositionY, startIdx,
  2661. realEndIdx, isActive);
  2662. }
  2663. else
  2664. {
  2665. RenderMultipleLinesSelection(
  2666. GetPlainFragments(i)[tmp].text,
  2667. horizontalPad,
  2668. tmpPositionY,
  2669. startIdx,
  2670. realEndIdx,
  2671. isActive);
  2672. }
  2673. }
  2674. }
  2675. tmpPositionY += GetPlainFragments(i)[tmp].lineCount * fontHeight;
  2676. }
  2677. }
  2678. if (!_folded[i] || !blockLongEnoughForFold)
  2679. {
  2680. for (var j = 0; j < _blocksFragments[i].Count; j++)
  2681. {
  2682. var fragment = _blocksFragments[i][j];
  2683. var fragLineCount = fragment.lineCount;
  2684. var fragHeight = fragLineCount * fontHeight;
  2685. SelectText(hPad, positionY, fragHeight, fragment,
  2686. _disassembler.IsColored
  2687. ? GetEndIndexOfColoredLine
  2688. : GetEndIndexOfPlainLine);
  2689. GUI.Label(new Rect(hPad, positionY, finalAreaSize.x, fragHeight + fontHeight*0.5f),
  2690. fragment.text, style);
  2691. positionY += fragHeight;
  2692. }
  2693. }
  2694. else
  2695. {
  2696. var frag = GetFragmentStart(i);
  2697. SelectText(hPad, positionY, fontHeight, frag,
  2698. _disassembler.IsColored
  2699. ? GetEndIndexOfColoredLine
  2700. : GetEndIndexOfPlainLine);
  2701. float fragHeight = fontHeight;
  2702. GUI.Label(new Rect(hPad, positionY, finalAreaSize.x, fragHeight*1.5f), frag.text, style);
  2703. positionY += fragHeight;
  2704. }
  2705. }
  2706. UpdateEnhancedSelectTextIdx(hPad);
  2707. }
  2708. private List<Fragment> RecomputeFragments(string text)
  2709. {
  2710. List<Fragment> result = new List<Fragment>();
  2711. string[] pieces = text.Split('\n');
  2712. _mTextLines = pieces.Length;
  2713. StringBuilder b = new StringBuilder();
  2714. int lineCount = 0;
  2715. for (int a = 0; a < pieces.Length; a++)
  2716. {
  2717. if (b.Length >= kMaxFragment)
  2718. {
  2719. b.Remove(b.Length - 1, 1);
  2720. AddFragment(b, lineCount, result);
  2721. lineCount = 0;
  2722. }
  2723. b.Append(pieces[a]);
  2724. b.Append('\n');
  2725. lineCount++;
  2726. }
  2727. if (b.Length > 0)
  2728. {
  2729. b.Remove(b.Length - 1, 1);
  2730. AddFragment(b, lineCount, result);
  2731. }
  2732. return result;
  2733. }
  2734. private List<Fragment> RecomputeFragmentsFromBlock(int blockIdx, bool colored)
  2735. {
  2736. var text = _disassembler.GetOrRenderBlockToTextUncached(blockIdx, colored).TrimEnd('\n');
  2737. return RecomputeFragments(text);
  2738. }
  2739. internal List<Fragment> RecomputeFragmentsFromBlock(int blockIdx)
  2740. {
  2741. var text = _disassembler.GetOrRenderBlockToText(blockIdx).TrimEnd('\n');
  2742. return RecomputeFragments(text);
  2743. }
  2744. private static void AddFragment(StringBuilder b, int lineCount, List<Fragment> result)
  2745. {
  2746. result.Add(new Fragment() { text = b.ToString(), lineCount = lineCount });
  2747. b.Length = 0;
  2748. }
  2749. }
  2750. }