ConsoleProvider.bf 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. #pragma warning disable 168
  2. using Beefy.geom;
  3. using System;
  4. using Beefy.widgets;
  5. using System.Security.Cryptography;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Threading;
  9. namespace IDE.util;
  10. #if BF_PLATFORM_WINDOWS
  11. class ConsoleProvider
  12. {
  13. public enum UpdateState
  14. {
  15. None,
  16. Dirty
  17. }
  18. public struct Cell
  19. {
  20. public char16 mChar;
  21. public uint16 mAttributes;
  22. }
  23. public virtual int Width => 0;
  24. public virtual int Height => 0;
  25. public virtual int BufferHeight => 0;
  26. public virtual bool Attached => false;
  27. public virtual bool Connected => Attached;
  28. public virtual int ScrollTop => 0;
  29. public virtual bool CursorVisible => true;
  30. public virtual float CursorHeight => 1.0f;
  31. public virtual (int32 col, int32 row) CursorPos
  32. {
  33. get
  34. {
  35. return default;
  36. }
  37. set
  38. {
  39. }
  40. }
  41. public virtual Cell GetCell(int col, int row)
  42. {
  43. return default;
  44. }
  45. public Cell GetCell(int idx)
  46. {
  47. int width = Math.Max(Width, 1);
  48. int scrollTop = ScrollTop;
  49. return GetCell(idx % width, idx / width - scrollTop);
  50. }
  51. public virtual void Resize(int cols, int rows, bool resizeContent)
  52. {
  53. }
  54. public virtual void ScrollTo(int row)
  55. {
  56. }
  57. public virtual void Attach()
  58. {
  59. }
  60. public virtual void Detach()
  61. {
  62. }
  63. public virtual void MouseDown(int col, int row, int btnState, int btnCount, KeyFlags keyFlags)
  64. {
  65. }
  66. public virtual void MouseMove(int col, int row, int btnState, KeyFlags keyFlags)
  67. {
  68. }
  69. public virtual void MouseUp(int col, int row, int btnState, KeyFlags keyFlags)
  70. {
  71. }
  72. public virtual void MouseWheel(int col, int row, int dy)
  73. {
  74. }
  75. public virtual void KeyDown(KeyCode keyCode, KeyFlags keyFlags)
  76. {
  77. }
  78. public virtual void KeyUp(KeyCode keyCode)
  79. {
  80. }
  81. public virtual void SendInput(StringView str)
  82. {
  83. }
  84. public virtual UpdateState Update(bool paused) => .None;
  85. public virtual uint32 GetColor(int i) => 0xFF000000;
  86. }
  87. class WinNativeConsoleProvider : ConsoleProvider
  88. {
  89. [CRepr]
  90. struct CONSOLE_SCREEN_BUFFER_INFOEX
  91. {
  92. public uint32 mSize;
  93. public int16 mWidth;
  94. public int16 mHeight;
  95. public uint16 mCursorX;
  96. public uint16 mCursorY;
  97. public uint16 wAttributes;
  98. public RECT mWindowRect;
  99. public POINT mMaximumWindowSize;
  100. public uint16 mPopupAttributes;
  101. public Windows.IntBool mFullscreenSupported;
  102. public uint32[16] mColorTable;
  103. public this()
  104. {
  105. this = default;
  106. mSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
  107. }
  108. }
  109. [CRepr]
  110. struct POINT : this(int16 x, int16 y)
  111. {
  112. }
  113. [CRepr]
  114. struct RECT : this(int16 left, int16 top, int16 right, int16 bottom)
  115. {
  116. [Inline]
  117. public int16 Width => right - left;
  118. [Inline]
  119. public int16 Height => bottom - top;
  120. }
  121. [CRepr]
  122. struct CHAR_INFO
  123. {
  124. public char16 mChar;
  125. public uint16 mAttributes;
  126. }
  127. [CRepr]
  128. struct CONSOLE_FONT_INFO
  129. {
  130. public uint32 mNumFont;
  131. public POINT mSize;
  132. }
  133. [CRepr]
  134. struct CONSOLE_CURSOR_INFO
  135. {
  136. public uint32 mSize;
  137. public uint32 mVisible;
  138. }
  139. [CRepr]
  140. struct CONSOLE_SELECTION_INFO
  141. {
  142. public uint32 mFlags;
  143. public POINT mSelectionAnchor;
  144. public RECT mSelection;
  145. }
  146. [CRepr]
  147. struct KEY_EVENT_RECORD
  148. {
  149. public int32 mKeyDown;
  150. public uint16 mRepeatCount;
  151. public uint16 mVirtualKeyCode;
  152. public uint16 mVirtualScanCode;
  153. public char16 mChar;
  154. public uint32 mControlKeyState;
  155. }
  156. [CRepr]
  157. struct MOUSE_EVENT_RECORD
  158. {
  159. public POINT mMousePosition;
  160. public uint32 mButtonState;
  161. public uint32 mControlKeyState;
  162. public uint32 mEventFlags;
  163. }
  164. [CRepr]
  165. struct INPUT_RECORD
  166. {
  167. public uint16 mEventType;
  168. public INPUT_RECORD_DATA mEventData;
  169. }
  170. [Union]
  171. struct INPUT_RECORD_DATA
  172. {
  173. public KEY_EVENT_RECORD mKeyEvent;
  174. public MOUSE_EVENT_RECORD mMouseEvent;
  175. }
  176. class ScreenInfo
  177. {
  178. public CONSOLE_SCREEN_BUFFER_INFOEX mInfo;
  179. public CONSOLE_CURSOR_INFO mCursorInfo;
  180. public CONSOLE_SELECTION_INFO mSelectionInfo;
  181. public int32 mScrollTop;
  182. public CHAR_INFO* mCharInfo;
  183. public CHAR_INFO* mFullCharInfo;
  184. public uint32[16] mColorTable = .(0xFF000000, );
  185. public int32 WindowWidth => mInfo.mWindowRect.Width;
  186. public int32 WindowHeight => mInfo.mWindowRect.Height;
  187. public ~this()
  188. {
  189. delete mCharInfo;
  190. delete mFullCharInfo;
  191. }
  192. public int GetHashCode()
  193. {
  194. MD5 md5 = scope .();
  195. md5.Update(.((.)&mInfo, sizeof(CONSOLE_SCREEN_BUFFER_INFOEX)));
  196. md5.Update(.((.)&mSelectionInfo, sizeof(CONSOLE_SELECTION_INFO)));
  197. md5.Update(.((.)&mCursorInfo, sizeof(CONSOLE_CURSOR_INFO)));
  198. if (mCharInfo != null)
  199. md5.Update(.((.)mCharInfo, (int32)mInfo.mWindowRect.Width * mInfo.mWindowRect.Height * sizeof(CHAR_INFO)));
  200. var hash = md5.Finish();
  201. return hash.GetHashCode();
  202. }
  203. }
  204. #if BF_PLATFORM_WINDOWS
  205. [CLink, CallingConvention(.Stdcall)]
  206. public static extern Windows.IntBool AllocConsole();
  207. [CLink, CallingConvention(.Stdcall)]
  208. public static extern void SetConsoleTitleW(char16* title);
  209. [CLink, CallingConvention(.Stdcall)]
  210. public static extern Windows.IntBool AttachConsole(int processId);
  211. [CLink, CallingConvention(.Stdcall)]
  212. public static extern void FreeConsole();
  213. [CLink, CallingConvention(.Stdcall)]
  214. public static extern Windows.IntBool GetConsoleScreenBufferInfoEx(Windows.Handle handle, ref CONSOLE_SCREEN_BUFFER_INFOEX info);
  215. [CLink, CallingConvention(.Stdcall)]
  216. public static extern Windows.IntBool SetConsoleScreenBufferInfoEx(Windows.Handle handle, ref CONSOLE_SCREEN_BUFFER_INFOEX info);
  217. [CLink]
  218. public static extern Windows.IntBool ReadConsoleOutputW(Windows.Handle handle, void* buffer, POINT bufferSize, POINT bufferCoord, ref RECT readRegion);
  219. [CLink]
  220. public static extern Windows.IntBool SetConsoleScreenBufferSize(Windows.Handle handle, POINT bufferSize);
  221. [CLink]
  222. public static extern Windows.IntBool SetConsoleWindowInfo(Windows.Handle handle, Windows.IntBool absolute, in RECT window);
  223. [CLink]
  224. public static extern Windows.HWnd GetConsoleWindow();
  225. [CLink]
  226. public static extern Windows.IntBool GetCurrentConsoleFont(Windows.Handle handle, Windows.IntBool maxWindow, out CONSOLE_FONT_INFO fontInfo);
  227. [CLink]
  228. public static extern Windows.IntBool GetConsoleCursorInfo(Windows.Handle handle, out CONSOLE_CURSOR_INFO cursorInfo);
  229. [CLink]
  230. public static extern Windows.IntBool GetConsoleSelectionInfo(out CONSOLE_SELECTION_INFO selectionInfo);
  231. [CLink]
  232. public static extern Windows.IntBool WriteConsoleInputW(Windows.Handle handle, INPUT_RECORD* eventsPtr, int32 eventCount, out int32 numEventsWritten);
  233. [CLink]
  234. public static extern Windows.IntBool ReadConsoleInputW(Windows.Handle handle, INPUT_RECORD* eventsPtr, int32 eventCount, out int32 numEventsRead);
  235. [CLink]
  236. public static extern Windows.IntBool SetConsoleCursorPosition(Windows.Handle handle, POINT pos);
  237. [CLink]
  238. public static extern Windows.IntBool FillConsoleOutputCharacterW(Windows.Handle handle, char16 char, int32 length, POINT writeCoord, out int32 numCharsWritten);
  239. [CLink]
  240. public static extern Windows.IntBool FillConsoleOutputAttribute(Windows.Handle handle, uint16 attribute, int32 length, POINT writeCoord, out int32 numCharsWritten);
  241. #endif
  242. ScreenInfo mScreenInfo ~ delete _;
  243. public bool mDirty;
  244. bool mHasConsole;
  245. SpawnedProcess mCmdSpawn ~ delete _;
  246. SpawnedProcess mExecSpawn ~ delete _;
  247. public int mLastDrawnHashCode;
  248. public bool mHideNativeConsole = true;
  249. static uint8[256*5] sKeyCharMap = .(0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 0, 0, 0, 0, 0,
  250. 0, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 0, 0, 0, 0, 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 42, 43, 0, 45, 46, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 61, 44, 45, 46, 47,
  252. 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91, 92, 93, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  253. 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, 33, 64, 35, 36, 37, 94, 38, 42, 40, 0, 0, 0, 0, 0, 0,
  254. 0, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 0, 45, 46, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 43, 60, 95, 62, 63,
  256. 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 125, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  257. 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 0, 0, 0, 0, 0,
  258. 0, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 0, 0, 0, 0, 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 42, 43, 0, 45, 46, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 61, 44, 45, 46, 47,
  260. 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91, 92, 93, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  261. 0, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, 33, 64, 35, 36, 37, 94, 38, 42, 40, 0, 0, 0, 0, 0, 0,
  262. 0, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 0, 45, 46, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 43, 60, 95, 62, 63,
  264. 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 125, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  266. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  269. public override int Width => (mScreenInfo != null) ? (mScreenInfo.mInfo.mWindowRect.Width) : 0;
  270. public override int Height => (mScreenInfo != null) ? (mScreenInfo.mInfo.mWindowRect.Height) : 0;
  271. public override int BufferHeight
  272. {
  273. get
  274. {
  275. #if BF_PLATFORM_WINDOWS
  276. var outHandle = Console.[Friend]GetStdHandle(Console.STD_OUTPUT_HANDLE);
  277. CONSOLE_SCREEN_BUFFER_INFOEX info = default;
  278. info.mSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
  279. if (GetConsoleScreenBufferInfoEx(outHandle, ref info))
  280. return info.mHeight;
  281. #endif
  282. if (mScreenInfo != null)
  283. return mScreenInfo.mInfo.mHeight;
  284. return 0;
  285. }
  286. }
  287. public override bool Attached => mHasConsole;
  288. public override int ScrollTop => (mScreenInfo != null) ? mScreenInfo.mScrollTop : 0;
  289. public override bool CursorVisible => (mScreenInfo != null) ? (mScreenInfo.mCursorInfo.mVisible != 0) : true;
  290. public override float CursorHeight => (mScreenInfo != null) ? (mScreenInfo.mCursorInfo.mSize / 100.0f) : 0.15f;
  291. public ~this()
  292. {
  293. mCmdSpawn?.Kill();
  294. mExecSpawn?.Kill();
  295. }
  296. public override (int32 col, int32 row) CursorPos
  297. {
  298. get
  299. {
  300. if (mScreenInfo != null)
  301. return (mScreenInfo.mInfo.mCursorX, mScreenInfo.mInfo.mCursorY);
  302. return default;
  303. }
  304. }
  305. public override Cell GetCell(int col, int row)
  306. {
  307. if (mScreenInfo == null)
  308. return default;
  309. if ((row < 0) || (row >= mScreenInfo.mInfo.mWindowRect.Height))
  310. {
  311. GetFullScreenInfo(mScreenInfo);
  312. }
  313. if (mScreenInfo.mFullCharInfo != null)
  314. {
  315. int bufRow = row + mScreenInfo.mScrollTop;
  316. int idx = bufRow * mScreenInfo.mInfo.mWidth + col;
  317. int maxIdx = (int)mScreenInfo.mInfo.mWidth * mScreenInfo.mInfo.mHeight;
  318. if ((idx < 0) || (idx >= maxIdx))
  319. return default;
  320. var info = mScreenInfo.mFullCharInfo[idx];
  321. return .() { mChar = info.mChar, mAttributes = info.mAttributes };
  322. }
  323. int idx = row * mScreenInfo.mInfo.mWindowRect.Width + col;
  324. int maxIdx = (int)mScreenInfo.mInfo.mWindowRect.Width * mScreenInfo.mInfo.mWindowRect.Height;
  325. if ((idx < 0) || (idx >= maxIdx))
  326. return default;
  327. var info = mScreenInfo.mCharInfo[idx];
  328. return .() { mChar = info.mChar, mAttributes = info.mAttributes };
  329. }
  330. public bool GetScreenInfo(ScreenInfo screenInfo)
  331. {
  332. var outHandle = Console.[Friend]GetStdHandle(Console.STD_OUTPUT_HANDLE);
  333. CONSOLE_SCREEN_BUFFER_INFOEX info = default;
  334. info.mSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
  335. #if BF_PLATFORM_WINDOWS
  336. if (!GetConsoleScreenBufferInfoEx(outHandle, ref info))
  337. return false;
  338. #endif
  339. info.mWindowRect.right++;
  340. info.mWindowRect.bottom++;
  341. screenInfo.mInfo = info;
  342. screenInfo.mScrollTop = info.mWindowRect.top;
  343. //mScrollableWidget.VertScrollTo(screenInfo.mInfo.mWindowRect.top * mCellHeight);
  344. //int width = info.mWindowRect.Width;
  345. //int height = info.mWindowRect.Height;
  346. POINT bufferSize = .(info.mWindowRect.Width, info.mWindowRect.Height);
  347. screenInfo.mCharInfo = new .[(int32)info.mWindowRect.Width * info.mWindowRect.Height]*;
  348. RECT readRegion = .(screenInfo.mInfo.mWindowRect.left, (.)screenInfo.mScrollTop, screenInfo.mInfo.mWindowRect.right, (.)(screenInfo.mScrollTop + screenInfo.mInfo.mWindowRect.Height - 1));
  349. #if BF_PLATFORM_WINDOWS
  350. ReadConsoleOutputW(outHandle, screenInfo.mCharInfo, bufferSize, POINT(0, 0), ref readRegion);
  351. GetConsoleCursorInfo(outHandle, out screenInfo.mCursorInfo);
  352. GetConsoleSelectionInfo(out screenInfo.mSelectionInfo);
  353. #endif
  354. for (int i < 16)
  355. {
  356. screenInfo.mColorTable[i] = 0xFF000000 |
  357. ((screenInfo.mInfo.mColorTable[i] >> 16) & 0x0000FF) |
  358. ((screenInfo.mInfo.mColorTable[i] ) & 0x00FF00) |
  359. ((screenInfo.mInfo.mColorTable[i] << 16) & 0xFF0000);
  360. }
  361. return true;
  362. }
  363. public bool GetFullScreenInfo(ScreenInfo screenInfo)
  364. {
  365. if (screenInfo.mFullCharInfo != null)
  366. return true;
  367. if (screenInfo.mCharInfo == null)
  368. {
  369. if (!GetScreenInfo(screenInfo))
  370. return false;
  371. }
  372. DeleteAndNullify!(screenInfo.mCharInfo);
  373. var outHandle = Console.[Friend]GetStdHandle(Console.STD_OUTPUT_HANDLE);
  374. POINT bufferSize = .(screenInfo.mInfo.mWidth, screenInfo.mInfo.mHeight);
  375. screenInfo.mFullCharInfo = new .[(int32)screenInfo.mInfo.mWidth * screenInfo.mInfo.mHeight]*;
  376. RECT readRegion = .(0, 0, screenInfo.mInfo.mWidth, screenInfo.mInfo.mHeight);
  377. #if BF_PLATFORM_WINDOWS
  378. ReadConsoleOutputW(outHandle, screenInfo.mFullCharInfo, bufferSize, POINT(0, 0), ref readRegion);
  379. #endif
  380. return true;
  381. }
  382. public bool UpdateScreenInfo(ScreenInfo screenInfo)
  383. {
  384. if (screenInfo.mFullCharInfo == null)
  385. {
  386. if (!GetFullScreenInfo(screenInfo))
  387. return false;
  388. }
  389. Internal.MemCpy(screenInfo.mCharInfo,
  390. screenInfo.mFullCharInfo + screenInfo.mScrollTop * screenInfo.mInfo.mWidth,
  391. screenInfo.mInfo.mWindowRect.Width * screenInfo.mInfo.mWindowRect.Height * sizeof(CHAR_INFO));
  392. return true;
  393. }
  394. public override void ScrollTo(int row)
  395. {
  396. if (mScreenInfo == null)
  397. return;
  398. if (mScreenInfo.mScrollTop == row)
  399. return;
  400. GetFullScreenInfo(mScreenInfo);
  401. mScreenInfo.mScrollTop = (.)row;
  402. int windowHeight = mScreenInfo.mInfo.mWindowRect.Height;
  403. mScreenInfo.mInfo.mWindowRect.top = (.)mScreenInfo.mScrollTop;
  404. mScreenInfo.mInfo.mWindowRect.bottom = (.)(mScreenInfo.mScrollTop + windowHeight);
  405. }
  406. public override void Resize(int cols, int rows, bool resizeContent)
  407. {
  408. if (resizeContent)
  409. {
  410. if (mScreenInfo != null)
  411. {
  412. GetFullScreenInfo(mScreenInfo);
  413. mScreenInfo.mInfo.mWindowRect.right = (.)(mScreenInfo.mInfo.mWindowRect.left + cols);
  414. mScreenInfo.mInfo.mWindowRect.bottom = (.)(mScreenInfo.mInfo.mWindowRect.top + rows);
  415. }
  416. }
  417. if (!mHasConsole)
  418. return;
  419. var outHandle = Console.[Friend]GetStdHandle(Console.STD_OUTPUT_HANDLE);
  420. CONSOLE_SCREEN_BUFFER_INFOEX info = default;
  421. info.mSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
  422. #if BF_PLATFORM_WINDOWS
  423. GetConsoleScreenBufferInfoEx(outHandle, ref info);
  424. #endif
  425. info.mWindowRect.right = (.)(info.mWindowRect.left + cols);
  426. info.mWindowRect.bottom = (.)(info.mWindowRect.top + rows);
  427. //SetConsoleScreenBufferInfoEx(outHandle, ref info);
  428. //SetConsoleScreenBufferSize(outHandle, .((.)cols, (.)rows));
  429. //SetConsoleWindowInfo(outHandle, true, info.mWindowRect);
  430. #if BF_PLATFORM_WINDOWS
  431. GetCurrentConsoleFont(outHandle, false, var fontInfo);
  432. var window = GetConsoleWindow();
  433. uint32 style = (.)Windows.GetWindowLong(window, Windows.GWL_STYLE);
  434. uint32 styleEx = (.)Windows.GetWindowLong(window, Windows.GWL_EXSTYLE);
  435. Windows.Rect rect = .(0, 0, (.)(cols * fontInfo.mSize.x), (.)(rows * fontInfo.mSize.y));
  436. Windows.AdjustWindowRectEx(ref rect, style, false, styleEx);
  437. Windows.SetWindowPos(window, default, 0, 0, rect.Width, rect.Height,
  438. 0x10 /* SWP_NOACTIVATE */
  439. //0x90 /* SWP_HIDEWINDOW | SWP_NOACTIVATE */
  440. );
  441. #endif
  442. }
  443. public override void Attach()
  444. {
  445. if (mHasConsole)
  446. return;
  447. mHasConsole = true;
  448. #if BF_PLATFORM_WINDOWS
  449. //AllocConsole();
  450. /*ProcessStartInfo procInfo = scope ProcessStartInfo();
  451. procInfo.UseShellExecute = false;
  452. procInfo.SetFileName(scope $"{gApp.mInstallDir}/BeefCon_d.exe");
  453. procInfo.SetArguments(scope $"{Process.CurrentId}");
  454. String resultStr = scope String();
  455. mCmdSpawn = new SpawnedProcess();
  456. mCmdSpawn.Start(procInfo);
  457. Thread.Sleep(2000);
  458. var processId = mCmdSpawn.ProcessId;
  459. if (processId > 0)
  460. AttachConsole(processId);
  461. else*/
  462. AllocConsole();
  463. var window = GetConsoleWindow();
  464. if ((mHideNativeConsole) && (window != default))
  465. {
  466. Windows.SetWindowPos(window, default, 0, 0, 0, 0, 0x290 /* SWP_NOACTIVATE | SWP_NOREPOSITION | SWP_HIDEWINDOW */);
  467. #if !BEEFCON
  468. gApp.mMainWindow.SetForeground();
  469. #endif
  470. }
  471. //ResizeComponents();
  472. #endif
  473. }
  474. public override void Detach()
  475. {
  476. if (!mHasConsole)
  477. return;
  478. if (mScreenInfo != null)
  479. GetFullScreenInfo(mScreenInfo);
  480. mHasConsole = false;
  481. #if BF_PLATFORM_WINDOWS
  482. FreeConsole();
  483. #endif
  484. //gApp.mMainWindow.SetForeground();
  485. mCmdSpawn?.Kill();
  486. DeleteAndNullify!(mCmdSpawn);
  487. mExecSpawn?.Kill();
  488. DeleteAndNullify!(mExecSpawn);
  489. }
  490. public uint32 GetControlKeyState(KeyFlags keyFlags)
  491. {
  492. uint16 controlKeyState = 0;
  493. if (keyFlags.HasFlag(.Alt))
  494. controlKeyState |= 1;
  495. if (keyFlags.HasFlag(.Ctrl))
  496. controlKeyState |= 4;
  497. if (keyFlags.HasFlag(.Shift))
  498. controlKeyState |= 0x10;
  499. if (keyFlags.HasFlag(.CapsLock))
  500. controlKeyState |= 0x80;
  501. return controlKeyState;
  502. }
  503. public override void MouseDown(int col, int row, int btnState, int btnCount, KeyFlags keyFlags)
  504. {
  505. var inHandle = Console.[Friend]GetStdHandle(Console.STD_INPUT_HANDLE);
  506. INPUT_RECORD input = default;
  507. input.mEventType = 2 /*MOUSE_EVENT */;
  508. input.mEventData.mMouseEvent.mButtonState = (.)btnState;
  509. if (btnCount > 1)
  510. input.mEventData.mMouseEvent.mEventFlags |= 2;
  511. input.mEventData.mMouseEvent.mMousePosition = .((.)col, (.)row);
  512. input.mEventData.mMouseEvent.mControlKeyState = GetControlKeyState(keyFlags);
  513. WriteConsoleInputW(inHandle, &input, 1, var numEVentsWritten);
  514. }
  515. public override void MouseMove(int col, int row, int btnState, KeyFlags keyFlags)
  516. {
  517. var inHandle = Console.[Friend]GetStdHandle(Console.STD_INPUT_HANDLE);
  518. INPUT_RECORD input = default;
  519. input.mEventType = 2 /*MOUSE_EVENT */;
  520. input.mEventData.mMouseEvent.mEventFlags |= 1; /* MOUSE_MOVED */
  521. input.mEventData.mMouseEvent.mButtonState = (.)btnState;
  522. input.mEventData.mMouseEvent.mMousePosition = .((.)col, (.)row);
  523. input.mEventData.mMouseEvent.mControlKeyState = GetControlKeyState(keyFlags);
  524. WriteConsoleInputW(inHandle, &input, 1, var numEVentsWritten);
  525. }
  526. public override void MouseUp(int col, int row, int btnState, KeyFlags keyFlags)
  527. {
  528. var inHandle = Console.[Friend]GetStdHandle(Console.STD_INPUT_HANDLE);
  529. INPUT_RECORD input = default;
  530. input.mEventType = 2 /*MOUSE_EVENT */;
  531. input.mEventData.mMouseEvent.mButtonState = (.)btnState;
  532. input.mEventData.mMouseEvent.mMousePosition = .((.)col, (.)row);
  533. input.mEventData.mMouseEvent.mControlKeyState = GetControlKeyState(keyFlags);
  534. WriteConsoleInputW(inHandle, &input, 1, var numEVentsWritten);
  535. }
  536. public override void MouseWheel(int col, int row, int dy)
  537. {
  538. var window = GetConsoleWindow();
  539. Windows.SendMessageW(window, 0x0007, 0, 0); // WM_SETFOCUS
  540. //Windows.SendMessageW(window, 0x0006, 0, 0); // WM_ACTIVATE
  541. float x = col;
  542. float y = row;
  543. Windows.SendMessageW(window, 0x0200 /*WM_MOUSEMOVE*/, 0, (int)x | ((int)y << 16));
  544. Windows.SendMessageW(window, 0x020A /*WM_MOUSEWHEEL*/, (int32)(120 * dy) << 16, (int)x | ((int)y << 16));
  545. }
  546. public override void KeyDown(KeyCode keyCode, KeyFlags keyFlags)
  547. {
  548. var inHandle = Console.[Friend]GetStdHandle(Console.STD_INPUT_HANDLE);
  549. INPUT_RECORD input = default;
  550. /*if (keyEvent.mKeyCode == .F1)
  551. {
  552. Debug.WriteLine("Key Events:");
  553. while (true)
  554. {
  555. ReadConsoleInputW(inHandle, &input, 1, var numEventsRead);
  556. if (input.mEventType == 1)
  557. {
  558. if (input.mEventData.mKeyEvent.mChar != 0)
  559. {
  560. int keyMod = default;
  561. if ((input.mEventData.mKeyEvent.mControlKeyState & 8) != 0) // Ctrl
  562. {
  563. keyMod |= 4;
  564. }
  565. else
  566. {
  567. if ((input.mEventData.mKeyEvent.mControlKeyState & 0x10) != 0) // Shift
  568. keyMod |= 1;
  569. if ((input.mEventData.mKeyEvent.mControlKeyState & 0x80) != 0) // Caps Lock
  570. keyMod |= 2;
  571. }
  572. /*if ((input.mEventData.mKeyEvent.mControlKeyState & 2) != 0) // Alt
  573. flags |= .Alt;*/
  574. Debug.WriteLine($"{input.mEventData.mKeyEvent.mVirtualKeyCode} {keyMod} : {(int)input.mEventData.mKeyEvent.mChar} {input.mEventData.mKeyEvent.mChar}");
  575. uint16 keyState = ((uint16)keyMod << 8) + (uint16)input.mEventData.mKeyEvent.mVirtualKeyCode;
  576. sKeyCharMap[keyState] = (uint8)input.mEventData.mKeyEvent.mChar;
  577. }
  578. if (input.mEventData.mKeyEvent.mChar == '?')
  579. {
  580. for (int i < sKeyCharMap.Count)
  581. {
  582. if (i % 64 == 0)
  583. Debug.WriteLine();
  584. Debug.Write($"{sKeyCharMap[i]}, ");
  585. }
  586. Debug.WriteLine();
  587. }
  588. }
  589. else if (input.mEventType == 2)
  590. {
  591. }
  592. }
  593. return;
  594. }*/
  595. input.mEventType = 1 /*KEY_EVENT */;
  596. input.mEventData.mKeyEvent.mKeyDown = 1;
  597. input.mEventData.mKeyEvent.mRepeatCount = 1;
  598. input.mEventData.mKeyEvent.mVirtualKeyCode = (.)keyCode;
  599. //input.mEventData.mKeyEvent.mVirtualScanCode = 61;
  600. int keyMod = 0;
  601. if (keyFlags.HasFlag(.Ctrl))
  602. {
  603. keyMod |= 4;
  604. }
  605. else
  606. {
  607. if (keyFlags.HasFlag(.Shift))
  608. keyMod |= 1;
  609. if (keyFlags.HasFlag(.CapsLock))
  610. keyMod |= 2;
  611. }
  612. input.mEventData.mKeyEvent.mControlKeyState = GetControlKeyState(keyFlags);
  613. input.mEventData.mKeyEvent.mChar = (.)sKeyCharMap[(keyMod << 8) | (int)keyCode];
  614. WriteConsoleInputW(inHandle, &input, 1, var numEventsWritten);
  615. }
  616. public override void KeyUp(KeyCode keyCode)
  617. {
  618. var inHandle = Console.[Friend]GetStdHandle(Console.STD_INPUT_HANDLE);
  619. INPUT_RECORD input = default;
  620. input.mEventType = 1 /*KEY_EVENT */;
  621. input.mEventData.mKeyEvent.mVirtualKeyCode = (.)keyCode;
  622. WriteConsoleInputW(inHandle, &input, 1, var numEventsWritten);
  623. }
  624. public override void SendInput(StringView str)
  625. {
  626. var inHandle = Console.[Friend]GetStdHandle(Console.STD_INPUT_HANDLE);
  627. for (var c in str.DecodedChars)
  628. {
  629. INPUT_RECORD input = default;
  630. input.mEventType = 1 /*KEY_EVENT */;
  631. input.mEventData.mKeyEvent.mKeyDown = 1;
  632. input.mEventData.mKeyEvent.mRepeatCount = 1;
  633. input.mEventData.mKeyEvent.mChar = (.)c;
  634. WriteConsoleInputW(inHandle, &input, 1, var numEVentsWritten);
  635. }
  636. }
  637. public override UpdateState Update(bool paused)
  638. {
  639. if (paused)
  640. return .None;
  641. ScreenInfo newScreenInfo = new .();
  642. if (GetScreenInfo(newScreenInfo))
  643. {
  644. delete mScreenInfo;
  645. mScreenInfo = newScreenInfo;
  646. }
  647. else
  648. {
  649. Detach();
  650. delete newScreenInfo;
  651. }
  652. int hashCode = (mScreenInfo?.GetHashCode()).GetValueOrDefault();
  653. if (hashCode != mLastDrawnHashCode)
  654. {
  655. mLastDrawnHashCode = hashCode;
  656. mDirty = true;
  657. }
  658. if (mDirty)
  659. {
  660. mDirty = false;
  661. return .Dirty;
  662. }
  663. return .None;
  664. }
  665. public override uint32 GetColor(int i)
  666. {
  667. return (mScreenInfo != null) ? mScreenInfo.mColorTable[i] : 0xFF000000;
  668. }
  669. public static void ClearConsole()
  670. {
  671. var outHandle = Console.[Friend]GetStdHandle(Console.STD_OUTPUT_HANDLE);
  672. POINT coordScreen = default; // home for the cursor
  673. int32 cCharsWritten;
  674. CONSOLE_SCREEN_BUFFER_INFOEX csbi = default;
  675. csbi.mSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
  676. // Get the number of character cells in the current buffer.
  677. if (!GetConsoleScreenBufferInfoEx(outHandle, ref csbi))
  678. {
  679. return;
  680. }
  681. let dwConSize = (int32)csbi.mWidth * csbi.mHeight;
  682. // Fill the entire screen with blanks.
  683. if (!FillConsoleOutputCharacterW(outHandle, // Handle to console screen buffer
  684. ' ', // Character to write to the buffer
  685. dwConSize, // Number of cells to write
  686. coordScreen, // Coordinates of first cell
  687. out cCharsWritten)) // Receive number of characters written
  688. {
  689. return;
  690. }
  691. // Get the current text attribute.
  692. if (!GetConsoleScreenBufferInfoEx(outHandle, ref csbi))
  693. {
  694. return;
  695. }
  696. // Set the buffer's attributes accordingly.
  697. if (!FillConsoleOutputAttribute(outHandle, // Handle to console screen buffer
  698. csbi.wAttributes, // Character attributes to use
  699. dwConSize, // Number of cells to set attribute
  700. coordScreen, // Coordinates of first cell
  701. out cCharsWritten)) // Receive number of characters written
  702. {
  703. return;
  704. }
  705. // Put the cursor at its home coordinates.
  706. SetConsoleCursorPosition(outHandle, coordScreen);
  707. }
  708. public void Clear()
  709. {
  710. ClearConsole();
  711. }
  712. }
  713. class BeefConConsoleProvider : ConsoleProvider
  714. {
  715. public enum Message
  716. {
  717. None,
  718. GetData,
  719. Resize,
  720. Data,
  721. InputString,
  722. KeyDown,
  723. KeyUp,
  724. MouseDown,
  725. MouseMove,
  726. MouseUp,
  727. MouseWheel,
  728. ScrollTo,
  729. Update,
  730. Attached
  731. }
  732. public class Pipe
  733. {
  734. public NamedPipe mSendPipe = new .() ~ delete _;
  735. public NamedPipe mRecvPipe = new .() ~ delete _;
  736. public MemoryStream mRecvStream = new .() ~ delete _;
  737. public MemoryStream mSendStream = new .() ~ delete _;
  738. public MemoryStream Stream => mSendStream;
  739. public bool mFailed;
  740. public bool mConnected;
  741. public Thread mThread ~ delete _;
  742. public Monitor mDataMonitor = new .() ~ delete _;
  743. public WaitEvent mDataEvent = new .() ~ delete _;
  744. public int mPendingReadClear;
  745. public bool mExiting;
  746. public this()
  747. {
  748. }
  749. public ~this()
  750. {
  751. mExiting = true;
  752. using (mDataMonitor.Enter())
  753. {
  754. mSendPipe.Close();
  755. mRecvPipe.Close();
  756. }
  757. if (mThread != null)
  758. {
  759. mThread.Join();
  760. }
  761. }
  762. void ThreadProc()
  763. {
  764. while (!mExiting)
  765. {
  766. uint8[4096] data = ?;
  767. using (mDataMonitor.Enter())
  768. {
  769. if (mExiting)
  770. return;
  771. }
  772. switch (mRecvPipe.TryRead(.(&data, 4096), -1))
  773. {
  774. case .Ok(int len):
  775. if (len == 0)
  776. {
  777. mFailed = true;
  778. return;
  779. }
  780. mConnected = true;
  781. using (mDataMonitor.Enter())
  782. {
  783. mRecvStream.TryWrite(.(&data, len));
  784. mDataEvent.Set(true);
  785. }
  786. case .Err(let err):
  787. if ((err == .PipeListening) && (!mConnected))
  788. {
  789. Thread.Sleep(20);
  790. break;
  791. }
  792. mFailed = true;
  793. return;
  794. }
  795. }
  796. }
  797. void StartThread()
  798. {
  799. mThread = new Thread(new => ThreadProc);
  800. mThread.Start(false);
  801. }
  802. public Result<void> Connect(int processId, int conId)
  803. {
  804. if (mSendPipe.Open(".", scope $"BEEFCON_{processId}_{conId}_A", .None) case .Err)
  805. return .Err;
  806. if (mRecvPipe.Open(".", scope $"BEEFCON_{processId}_{conId}_B", .None) case .Err)
  807. return .Err;
  808. StartThread();
  809. mConnected = true;
  810. return .Ok;
  811. }
  812. public Result<void> Listen(int processId, int conId)
  813. {
  814. if (mRecvPipe.Create(".", scope $"BEEFCON_{processId}_{conId}_A", .None) case .Err)
  815. return .Err;
  816. if (mSendPipe.Create(".", scope $"BEEFCON_{processId}_{conId}_B", .None) case .Err)
  817. return .Err;
  818. StartThread();
  819. return .Ok;
  820. }
  821. public void StartMessage(Message message)
  822. {
  823. Debug.Assert(Stream.Length == 0);
  824. mSendStream.Write(message);
  825. }
  826. public void EndMessage()
  827. {
  828. defer mSendStream.Clear();
  829. if (!mConnected)
  830. return;
  831. if (mSendPipe.Write((int32)mSendStream.Length) case .Err)
  832. {
  833. mFailed = true;
  834. return;
  835. }
  836. Span<uint8> span = .(mSendStream.Memory.Ptr, mSendStream.Length);
  837. while (span.Length > 0)
  838. {
  839. switch (mSendPipe.TryWrite(span))
  840. {
  841. case .Ok(int len):
  842. span.RemoveFromStart(len);
  843. case .Err:
  844. mFailed = true;
  845. return;
  846. }
  847. }
  848. }
  849. Result<Span<uint8>> DoReadMessage()
  850. {
  851. using (mDataMonitor.Enter())
  852. {
  853. if (mPendingReadClear > 0)
  854. {
  855. mRecvStream.Memory.RemoveRange(0, mPendingReadClear);
  856. mRecvStream.Position = mRecvStream.Position - mPendingReadClear;
  857. mPendingReadClear = 0;
  858. }
  859. if (mRecvStream.Length < 4)
  860. return .Err;
  861. int wantTotalLen = *(int32*)mRecvStream.Memory.Ptr + 4;
  862. if (mRecvStream.Length < wantTotalLen)
  863. return .Err;
  864. mPendingReadClear = wantTotalLen;
  865. return .Ok(.(mRecvStream.Memory.Ptr + 4, wantTotalLen - 4));
  866. }
  867. }
  868. public Result<Span<uint8>> ReadMessage(int timeoutMS)
  869. {
  870. if (timeoutMS != 0)
  871. mDataEvent.WaitFor(timeoutMS);
  872. using (mDataMonitor.Enter())
  873. {
  874. var result = DoReadMessage();
  875. if (result case .Err)
  876. mDataEvent.Reset();
  877. return result;
  878. }
  879. }
  880. }
  881. public static int sConId = 0;
  882. public SpawnedProcess mBeefConProcess ~ delete _;
  883. public int mConId = ++sConId;
  884. public String mWorkingDir = new .() ~ delete _;
  885. public String mBeefConExePath ~ delete _;
  886. public String mTerminalExe ~ delete _;
  887. public Pipe mPipe = new .() ~ delete _;
  888. public int mProcessId = Process.CurrentId;
  889. public bool mAttached;
  890. public int32 mResizedWidth;
  891. public int32 mResizedHeight;
  892. public int32 mWidth;
  893. public int32 mHeight;
  894. public int32 mBufferHeight;
  895. public int32 mScrollTop;
  896. public bool mCursorVisible;
  897. public float mCursorHeight;
  898. public Cell* mCells ~ delete _;
  899. public (int32 col, int32 row) mCursorPos;
  900. public uint32[16] mColors;
  901. public int mLastDrawnHashCode;
  902. public bool mDirty;
  903. public int32 mFailDelay;
  904. public override bool Connected => mPipe.mConnected && !mPipe.mFailed;
  905. public override int Width => mWidth;
  906. public override int Height => mHeight;
  907. public override int BufferHeight => mBufferHeight;
  908. public override bool Attached => mAttached;
  909. public override int ScrollTop => mScrollTop;
  910. public override bool CursorVisible => mCursorVisible;
  911. public override float CursorHeight => mCursorHeight;
  912. public override (int32 col, int32 row) CursorPos
  913. {
  914. get
  915. {
  916. return mCursorPos;
  917. }
  918. set
  919. {
  920. mCursorPos = value;
  921. }
  922. }
  923. public override Cell GetCell(int col, int row)
  924. {
  925. if (mCells == null)
  926. return default;
  927. return mCells[row * mWidth + col];
  928. }
  929. public override uint32 GetColor(int i)
  930. {
  931. return mColors[i];
  932. }
  933. public override void Attach()
  934. {
  935. if (mAttached)
  936. return;
  937. if (mBeefConProcess != null)
  938. {
  939. mBeefConProcess.Kill();
  940. DeleteAndNullify!(mBeefConProcess);
  941. }
  942. if (mBeefConExePath != null)
  943. {
  944. ProcessStartInfo procInfo = scope ProcessStartInfo();
  945. procInfo.UseShellExecute = false;
  946. procInfo.SetFileName(mBeefConExePath);
  947. procInfo.SetWorkingDirectory(mWorkingDir);
  948. procInfo.SetArguments(scope $"{Process.CurrentId} {sConId} {mTerminalExe}");
  949. String resultStr = scope String();
  950. mBeefConProcess = new SpawnedProcess();
  951. mBeefConProcess.Start(procInfo).IgnoreError();
  952. }
  953. mDirty = true;
  954. mAttached = true;
  955. }
  956. public override void Detach()
  957. {
  958. if (!mAttached)
  959. return;
  960. mWidth = 0;
  961. mHeight = 0;
  962. mAttached = false;
  963. DeleteAndNullify!(mPipe);
  964. mPipe = new .();
  965. if (mBeefConProcess != null)
  966. {
  967. delete mBeefConProcess;
  968. mBeefConProcess = null;
  969. }
  970. }
  971. static mixin GET<T>(var ptr)
  972. {
  973. *((T*)(ptr += sizeof(T)) - 1)
  974. }
  975. public override UpdateState Update(bool paused)
  976. {
  977. if (!mAttached)
  978. return .None;
  979. if (mPipe.mFailed)
  980. {
  981. if (mFailDelay == 0)
  982. {
  983. mFailDelay = 120;
  984. return .None;
  985. }
  986. else
  987. {
  988. if (--mFailDelay == 0)
  989. {
  990. Detach();
  991. Attach();
  992. }
  993. return .None;
  994. }
  995. }
  996. if (!mPipe.mConnected)
  997. {
  998. if (mPipe.Connect((mBeefConProcess != null) ? mProcessId : 123, mConId) case .Err)
  999. return .None;
  1000. Resize(mResizedWidth, mResizedHeight, false);
  1001. }
  1002. if (!paused)
  1003. {
  1004. mPipe.StartMessage(.Update);
  1005. mPipe.Stream.Write(paused);
  1006. mPipe.EndMessage();
  1007. }
  1008. mPipe.StartMessage(.GetData);
  1009. mPipe.EndMessage();
  1010. MessageLoop: while (true)
  1011. {
  1012. switch (mPipe.ReadMessage(0))
  1013. {
  1014. case .Ok(let msg):
  1015. uint8* ptr = msg.Ptr + 1;
  1016. switch (*(Message*)msg.Ptr)
  1017. {
  1018. case .Data:
  1019. mWidth = GET!<int32>(ptr);
  1020. mHeight = GET!<int32>(ptr);
  1021. mBufferHeight = GET!<int32>(ptr);
  1022. mScrollTop = GET!<int32>(ptr);
  1023. mCursorVisible = GET!<bool>(ptr);
  1024. mCursorHeight = GET!<float>(ptr);
  1025. mCursorPos = GET!<(int32 col, int32 row)>(ptr);
  1026. for (int i < 16)
  1027. {
  1028. uint32 color = GET!<uint32>(ptr);
  1029. mColors[i] = 0xFF000000 |
  1030. ((color >> 16) & 0x0000FF) |
  1031. ((color ) & 0x00FF00) |
  1032. ((color << 16) & 0xFF0000);
  1033. mColors[i] = color;
  1034. }
  1035. delete mCells;
  1036. mCells = new Cell[mWidth * mHeight]*;
  1037. for (int row < mHeight)
  1038. {
  1039. for (int col < mWidth)
  1040. {
  1041. mCells[row * mWidth + col] = GET!<Cell>(ptr);
  1042. }
  1043. }
  1044. int hashCode = MD5.Hash(msg).GetHashCode();
  1045. if (hashCode != mLastDrawnHashCode)
  1046. {
  1047. mLastDrawnHashCode = hashCode;
  1048. mDirty = true;
  1049. }
  1050. default:
  1051. }
  1052. case .Err:
  1053. break MessageLoop;
  1054. }
  1055. }
  1056. if (mDirty)
  1057. {
  1058. mDirty = false;
  1059. return .Dirty;
  1060. }
  1061. return .None;
  1062. }
  1063. public override void Resize(int cols, int rows, bool resizeContent)
  1064. {
  1065. mResizedWidth = (.)cols;
  1066. mResizedHeight = (.)rows;
  1067. mPipe.StartMessage(.Resize);
  1068. mPipe.Stream.Write((int32)cols);
  1069. mPipe.Stream.Write((int32)rows);
  1070. mPipe.Stream.Write(resizeContent);
  1071. mPipe.EndMessage();
  1072. }
  1073. public override void ScrollTo(int row)
  1074. {
  1075. if (row == mScrollTop)
  1076. return;
  1077. mScrollTop = (.)row;
  1078. mPipe.StartMessage(.ScrollTo);
  1079. mPipe.Stream.Write((int32)row);
  1080. mPipe.EndMessage();
  1081. }
  1082. public override void KeyDown(KeyCode keyCode, KeyFlags keyFlags)
  1083. {
  1084. mPipe.StartMessage(.KeyDown);
  1085. mPipe.Stream.Write(keyCode);
  1086. mPipe.Stream.Write(keyFlags);
  1087. mPipe.EndMessage();
  1088. }
  1089. public override void KeyUp(KeyCode keyCode)
  1090. {
  1091. mPipe.StartMessage(.KeyUp);
  1092. mPipe.Stream.Write(keyCode);
  1093. mPipe.EndMessage();
  1094. }
  1095. public override void SendInput(StringView str)
  1096. {
  1097. mPipe.StartMessage(.InputString);
  1098. mPipe.Stream.WriteStrSized32(str);
  1099. mPipe.EndMessage();
  1100. }
  1101. public override void MouseDown(int col, int row, int btnState, int btnCount, KeyFlags keyFlags)
  1102. {
  1103. mPipe.StartMessage(.MouseDown);
  1104. mPipe.Stream.Write((int32)col);
  1105. mPipe.Stream.Write((int32)row);
  1106. mPipe.Stream.Write((int32)btnState);
  1107. mPipe.Stream.Write((int32)btnCount);
  1108. mPipe.Stream.Write(keyFlags);
  1109. mPipe.EndMessage();
  1110. }
  1111. public override void MouseMove(int col, int row, int btnState, KeyFlags keyFlags)
  1112. {
  1113. mPipe.StartMessage(.MouseMove);
  1114. mPipe.Stream.Write((int32)col);
  1115. mPipe.Stream.Write((int32)row);
  1116. mPipe.Stream.Write((int32)btnState);
  1117. mPipe.Stream.Write(keyFlags);
  1118. mPipe.EndMessage();
  1119. }
  1120. public override void MouseUp(int col, int row, int btnState, KeyFlags keyFlags)
  1121. {
  1122. mPipe.StartMessage(.MouseUp);
  1123. mPipe.Stream.Write((int32)col);
  1124. mPipe.Stream.Write((int32)row);
  1125. mPipe.Stream.Write((int32)btnState);
  1126. mPipe.Stream.Write(keyFlags);
  1127. mPipe.EndMessage();
  1128. }
  1129. public override void MouseWheel(int col, int row, int dy)
  1130. {
  1131. mPipe.StartMessage(.MouseWheel);
  1132. mPipe.Stream.Write((int32)col);
  1133. mPipe.Stream.Write((int32)row);
  1134. mPipe.Stream.Write((int32)dy);
  1135. mPipe.EndMessage();
  1136. }
  1137. }
  1138. #endif