NetDriver.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. //
  2. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using NStack;
  12. namespace Terminal.Gui {
  13. internal class NetDriver : ConsoleDriver {
  14. int cols, rows;
  15. public override int Cols => cols;
  16. public override int Rows => rows;
  17. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  18. int [,,] contents;
  19. bool [] dirtyLine;
  20. void UpdateOffscreen ()
  21. {
  22. int cols = Cols;
  23. int rows = Rows;
  24. contents = new int [rows, cols, 3];
  25. for (int r = 0; r < rows; r++) {
  26. for (int c = 0; c < cols; c++) {
  27. contents [r, c, 0] = ' ';
  28. contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
  29. contents [r, c, 2] = 0;
  30. }
  31. }
  32. dirtyLine = new bool [rows];
  33. for (int row = 0; row < rows; row++)
  34. dirtyLine [row] = true;
  35. }
  36. static bool sync = false;
  37. public NetDriver ()
  38. {
  39. cols = Console.WindowWidth;
  40. rows = Console.WindowHeight - 1;
  41. UpdateOffscreen ();
  42. }
  43. bool needMove;
  44. // Current row, and current col, tracked by Move/AddCh only
  45. int ccol, crow;
  46. public override void Move (int col, int row)
  47. {
  48. ccol = col;
  49. crow = row;
  50. if (Clip.Contains (col, row)) {
  51. Console.CursorTop = row;
  52. Console.CursorLeft = col;
  53. needMove = false;
  54. } else {
  55. Console.CursorTop = Clip.Y;
  56. Console.CursorLeft = Clip.X;
  57. needMove = true;
  58. }
  59. }
  60. public override void AddRune (Rune rune)
  61. {
  62. rune = MakePrintable (rune);
  63. if (Clip.Contains (ccol, crow)) {
  64. if (needMove) {
  65. //Console.CursorLeft = ccol;
  66. //Console.CursorTop = crow;
  67. needMove = false;
  68. }
  69. contents [crow, ccol, 0] = (int)(uint)rune;
  70. contents [crow, ccol, 1] = currentAttribute;
  71. contents [crow, ccol, 2] = 1;
  72. dirtyLine [crow] = true;
  73. } else
  74. needMove = true;
  75. ccol++;
  76. //if (ccol == Cols) {
  77. // ccol = 0;
  78. // if (crow + 1 < Rows)
  79. // crow++;
  80. //}
  81. if (sync)
  82. UpdateScreen ();
  83. }
  84. public override void AddStr (ustring str)
  85. {
  86. foreach (var rune in str)
  87. AddRune (rune);
  88. }
  89. public override void End ()
  90. {
  91. Console.ResetColor ();
  92. Console.Clear ();
  93. }
  94. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  95. {
  96. // Encode the colors into the int value.
  97. return new Attribute () { value = ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff) };
  98. }
  99. public override void Init (Action terminalResized)
  100. {
  101. Colors.TopLevel = new ColorScheme ();
  102. Colors.Base = new ColorScheme ();
  103. Colors.Dialog = new ColorScheme ();
  104. Colors.Menu = new ColorScheme ();
  105. Colors.Error = new ColorScheme ();
  106. Clip = new Rect (0, 0, Cols, Rows);
  107. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  108. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  109. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  110. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  111. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  112. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  113. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  114. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  115. // Focused,
  116. // Selected, Hot: Yellow on Black
  117. // Selected, text: white on black
  118. // Unselected, hot: yellow on cyan
  119. // unselected, text: same as unfocused
  120. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  121. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  122. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  123. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  124. Colors.Menu.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Cyan);
  125. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  126. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  127. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  128. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  129. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  130. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  131. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  132. Colors.Error.HotFocus = Colors.Error.HotNormal;
  133. Console.Clear ();
  134. HLine = '\u2500';
  135. VLine = '\u2502';
  136. Stipple = '\u2592';
  137. Diamond = '\u25c6';
  138. ULCorner = '\u250C';
  139. LLCorner = '\u2514';
  140. URCorner = '\u2510';
  141. LRCorner = '\u2518';
  142. LeftTee = '\u251c';
  143. RightTee = '\u2524';
  144. TopTee = '\u22a4';
  145. BottomTee = '\u22a5';
  146. Checked = '\u221a';
  147. UnChecked = ' ';
  148. Selected = '\u25cf';
  149. UnSelected = '\u25cc';
  150. RightArrow = '\u25ba';
  151. LeftArrow = '\u25c4';
  152. UpArrow = '\u25b2';
  153. DownArrow = '\u25bc';
  154. LeftDefaultIndicator = '\u25e6';
  155. RightDefaultIndicator = '\u25e6';
  156. LeftBracket = '[';
  157. RightBracket = ']';
  158. OnMeterSegment = '\u258c';
  159. OffMeterSegement = ' ';
  160. }
  161. public override Attribute MakeAttribute (Color fore, Color back)
  162. {
  163. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  164. }
  165. int redrawColor = -1;
  166. void SetColor (int color)
  167. {
  168. redrawColor = color;
  169. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  170. .OfType<ConsoleColor> ()
  171. .Select (s => (int)s);
  172. if (values.Contains (color & 0xffff)) {
  173. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  174. }
  175. if (values.Contains ((color >> 16) & 0xffff)) {
  176. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  177. }
  178. }
  179. public override void UpdateScreen ()
  180. {
  181. int rows = Rows;
  182. int cols = Cols;
  183. Console.CursorTop = 0;
  184. Console.CursorLeft = 0;
  185. for (int row = 0; row < rows; row++) {
  186. dirtyLine [row] = false;
  187. for (int col = 0; col < cols; col++) {
  188. contents [row, col, 2] = 0;
  189. var color = contents [row, col, 1];
  190. if (color != redrawColor)
  191. SetColor (color);
  192. Console.Write ((char)contents [row, col, 0]);
  193. }
  194. }
  195. }
  196. public override void Refresh ()
  197. {
  198. int rows = Rows;
  199. int cols = Cols;
  200. var savedRow = Console.CursorTop;
  201. var savedCol = Console.CursorLeft;
  202. for (int row = 0; row < rows; row++) {
  203. if (!dirtyLine [row])
  204. continue;
  205. dirtyLine [row] = false;
  206. for (int col = 0; col < cols; col++) {
  207. if (contents [row, col, 2] != 1)
  208. continue;
  209. Console.CursorTop = row;
  210. Console.CursorLeft = col;
  211. for (; col < cols && contents [row, col, 2] == 1; col++) {
  212. var color = contents [row, col, 1];
  213. if (color != redrawColor)
  214. SetColor (color);
  215. Console.Write ((char)contents [row, col, 0]);
  216. contents [row, col, 2] = 0;
  217. }
  218. }
  219. }
  220. Console.CursorTop = savedRow;
  221. Console.CursorLeft = savedCol;
  222. }
  223. public override void UpdateCursor ()
  224. {
  225. //
  226. }
  227. public override void StartReportingMouseMoves ()
  228. {
  229. }
  230. public override void StopReportingMouseMoves ()
  231. {
  232. }
  233. public override void Suspend ()
  234. {
  235. }
  236. int currentAttribute;
  237. public override void SetAttribute (Attribute c)
  238. {
  239. currentAttribute = c.value;
  240. }
  241. Key MapKey (ConsoleKeyInfo keyInfo)
  242. {
  243. switch (keyInfo.Key) {
  244. case ConsoleKey.Escape:
  245. return Key.Esc;
  246. case ConsoleKey.Tab:
  247. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  248. case ConsoleKey.Home:
  249. return Key.Home;
  250. case ConsoleKey.End:
  251. return Key.End;
  252. case ConsoleKey.LeftArrow:
  253. return Key.CursorLeft;
  254. case ConsoleKey.RightArrow:
  255. return Key.CursorRight;
  256. case ConsoleKey.UpArrow:
  257. return Key.CursorUp;
  258. case ConsoleKey.DownArrow:
  259. return Key.CursorDown;
  260. case ConsoleKey.PageUp:
  261. return Key.PageUp;
  262. case ConsoleKey.PageDown:
  263. return Key.PageDown;
  264. case ConsoleKey.Enter:
  265. return Key.Enter;
  266. case ConsoleKey.Spacebar:
  267. return Key.Space;
  268. case ConsoleKey.Backspace:
  269. return Key.Backspace;
  270. case ConsoleKey.Delete:
  271. return Key.Delete;
  272. case ConsoleKey.Oem1:
  273. case ConsoleKey.Oem2:
  274. case ConsoleKey.Oem3:
  275. case ConsoleKey.Oem4:
  276. case ConsoleKey.Oem5:
  277. case ConsoleKey.Oem6:
  278. case ConsoleKey.Oem7:
  279. case ConsoleKey.Oem8:
  280. case ConsoleKey.Oem102:
  281. case ConsoleKey.OemPeriod:
  282. case ConsoleKey.OemComma:
  283. case ConsoleKey.OemPlus:
  284. case ConsoleKey.OemMinus:
  285. return (Key)((uint)keyInfo.KeyChar);
  286. }
  287. var key = keyInfo.Key;
  288. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  289. var delta = key - ConsoleKey.A;
  290. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  291. return (Key)((uint)Key.ControlA + delta);
  292. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  293. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  294. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  295. return (Key)((uint)'A' + delta);
  296. else
  297. return (Key)((uint)'a' + delta);
  298. }
  299. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  300. var delta = key - ConsoleKey.D0;
  301. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  302. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  303. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  304. return (Key)((uint)keyInfo.KeyChar);
  305. return (Key)((uint)'0' + delta);
  306. }
  307. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  308. var delta = key - ConsoleKey.F1;
  309. return (Key)((int)Key.F1 + delta);
  310. }
  311. return (Key)(0xffffffff);
  312. }
  313. KeyModifiers keyModifiers = new KeyModifiers ();
  314. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  315. {
  316. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  317. (mainLoop.Driver as NetMainLoop).KeyPressed = delegate (ConsoleKeyInfo consoleKey) {
  318. var map = MapKey (consoleKey);
  319. if (map == (Key)0xffffffff)
  320. return;
  321. keyHandler (new KeyEvent (map, keyModifiers));
  322. keyUpHandler (new KeyEvent (map, keyModifiers));
  323. };
  324. }
  325. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  326. {
  327. throw new NotImplementedException ();
  328. }
  329. public override void SetColors (short foregroundColorId, short backgroundColorId)
  330. {
  331. throw new NotImplementedException ();
  332. }
  333. public override void CookMouse ()
  334. {
  335. }
  336. public override void UncookMouse ()
  337. {
  338. }
  339. //
  340. // These are for the .NET driver, but running natively on Windows, wont run
  341. // on the Mono emulation
  342. //
  343. }
  344. /// <summary>
  345. /// Mainloop intended to be used with the .NET System.Console API, and can
  346. /// be used on Windows and Unix, it is cross platform but lacks things like
  347. /// file descriptor monitoring.
  348. /// </summary>
  349. /// <remarks>
  350. /// This implementation is used for both NetDriver and FakeDriver.
  351. /// </remarks>
  352. public class NetMainLoop : IMainLoopDriver {
  353. AutoResetEvent keyReady = new AutoResetEvent (false);
  354. AutoResetEvent waitForProbe = new AutoResetEvent (false);
  355. ConsoleKeyInfo? keyResult = null;
  356. MainLoop mainLoop;
  357. Func<ConsoleKeyInfo> consoleKeyReaderFn = null;
  358. /// <summary>
  359. /// Invoked when a Key is pressed.
  360. /// </summary>
  361. public Action<ConsoleKeyInfo> KeyPressed;
  362. /// <summary>
  363. /// Initializes the class.
  364. /// </summary>
  365. /// <remarks>
  366. /// Passing a consoleKeyReaderfn is provided to support unit test sceanrios.
  367. /// </remarks>
  368. /// <param name="consoleKeyReaderFn">The method to be called to get a key from the console.</param>
  369. public NetMainLoop (Func<ConsoleKeyInfo> consoleKeyReaderFn = null)
  370. {
  371. if (consoleKeyReaderFn == null) {
  372. throw new ArgumentNullException ("key reader function must be provided.");
  373. }
  374. this.consoleKeyReaderFn = consoleKeyReaderFn;
  375. }
  376. void WindowsKeyReader ()
  377. {
  378. while (true) {
  379. waitForProbe.WaitOne ();
  380. keyResult = consoleKeyReaderFn();
  381. keyReady.Set ();
  382. }
  383. }
  384. void IMainLoopDriver.Setup (MainLoop mainLoop)
  385. {
  386. this.mainLoop = mainLoop;
  387. Thread readThread = new Thread (WindowsKeyReader);
  388. readThread.Start ();
  389. }
  390. void IMainLoopDriver.Wakeup ()
  391. {
  392. }
  393. bool IMainLoopDriver.EventsPending (bool wait)
  394. {
  395. long now = DateTime.UtcNow.Ticks;
  396. int waitTimeout;
  397. if (mainLoop.timeouts.Count > 0) {
  398. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  399. if (waitTimeout < 0)
  400. return true;
  401. } else
  402. waitTimeout = -1;
  403. if (!wait)
  404. waitTimeout = 0;
  405. keyResult = null;
  406. waitForProbe.Set ();
  407. keyReady.WaitOne (waitTimeout);
  408. return keyResult.HasValue;
  409. }
  410. void IMainLoopDriver.MainIteration ()
  411. {
  412. if (keyResult.HasValue) {
  413. KeyPressed?.Invoke (keyResult.Value);
  414. keyResult = null;
  415. }
  416. }
  417. }
  418. }