NetDriver.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. }
  135. public override Attribute MakeAttribute (Color fore, Color back)
  136. {
  137. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  138. }
  139. int redrawColor = -1;
  140. void SetColor (int color)
  141. {
  142. redrawColor = color;
  143. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  144. .OfType<ConsoleColor> ()
  145. .Select (s => (int)s);
  146. if (values.Contains (color & 0xffff)) {
  147. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  148. }
  149. if (values.Contains ((color >> 16) & 0xffff)) {
  150. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  151. }
  152. }
  153. public override void UpdateScreen ()
  154. {
  155. int rows = Rows;
  156. int cols = Cols;
  157. Console.CursorTop = 0;
  158. Console.CursorLeft = 0;
  159. for (int row = 0; row < rows; row++) {
  160. dirtyLine [row] = false;
  161. for (int col = 0; col < cols; col++) {
  162. contents [row, col, 2] = 0;
  163. var color = contents [row, col, 1];
  164. if (color != redrawColor)
  165. SetColor (color);
  166. Console.Write ((char)contents [row, col, 0]);
  167. }
  168. }
  169. }
  170. public override void Refresh ()
  171. {
  172. int rows = Rows;
  173. int cols = Cols;
  174. var savedRow = Console.CursorTop;
  175. var savedCol = Console.CursorLeft;
  176. for (int row = 0; row < rows; row++) {
  177. if (!dirtyLine [row])
  178. continue;
  179. dirtyLine [row] = false;
  180. for (int col = 0; col < cols; col++) {
  181. if (contents [row, col, 2] != 1)
  182. continue;
  183. Console.CursorTop = row;
  184. Console.CursorLeft = col;
  185. for (; col < cols && contents [row, col, 2] == 1; col++) {
  186. var color = contents [row, col, 1];
  187. if (color != redrawColor)
  188. SetColor (color);
  189. Console.Write ((char)contents [row, col, 0]);
  190. contents [row, col, 2] = 0;
  191. }
  192. }
  193. }
  194. Console.CursorTop = savedRow;
  195. Console.CursorLeft = savedCol;
  196. }
  197. public override void UpdateCursor ()
  198. {
  199. //
  200. }
  201. public override void StartReportingMouseMoves ()
  202. {
  203. }
  204. public override void StopReportingMouseMoves ()
  205. {
  206. }
  207. public override void Suspend ()
  208. {
  209. }
  210. int currentAttribute;
  211. public override void SetAttribute (Attribute c)
  212. {
  213. currentAttribute = c.value;
  214. }
  215. Key MapKey (ConsoleKeyInfo keyInfo)
  216. {
  217. switch (keyInfo.Key) {
  218. case ConsoleKey.Escape:
  219. return Key.Esc;
  220. case ConsoleKey.Tab:
  221. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  222. case ConsoleKey.Home:
  223. return Key.Home;
  224. case ConsoleKey.End:
  225. return Key.End;
  226. case ConsoleKey.LeftArrow:
  227. return Key.CursorLeft;
  228. case ConsoleKey.RightArrow:
  229. return Key.CursorRight;
  230. case ConsoleKey.UpArrow:
  231. return Key.CursorUp;
  232. case ConsoleKey.DownArrow:
  233. return Key.CursorDown;
  234. case ConsoleKey.PageUp:
  235. return Key.PageUp;
  236. case ConsoleKey.PageDown:
  237. return Key.PageDown;
  238. case ConsoleKey.Enter:
  239. return Key.Enter;
  240. case ConsoleKey.Spacebar:
  241. return Key.Space;
  242. case ConsoleKey.Backspace:
  243. return Key.Backspace;
  244. case ConsoleKey.Delete:
  245. return Key.Delete;
  246. case ConsoleKey.Oem1:
  247. case ConsoleKey.Oem2:
  248. case ConsoleKey.Oem3:
  249. case ConsoleKey.Oem4:
  250. case ConsoleKey.Oem5:
  251. case ConsoleKey.Oem6:
  252. case ConsoleKey.Oem7:
  253. case ConsoleKey.Oem8:
  254. case ConsoleKey.Oem102:
  255. case ConsoleKey.OemPeriod:
  256. case ConsoleKey.OemComma:
  257. case ConsoleKey.OemPlus:
  258. case ConsoleKey.OemMinus:
  259. return (Key)((uint)keyInfo.KeyChar);
  260. }
  261. var key = keyInfo.Key;
  262. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  263. var delta = key - ConsoleKey.A;
  264. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  265. return (Key)((uint)Key.A + delta);
  266. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  267. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  268. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  269. return (Key)((uint)Key.A + delta);
  270. else
  271. return (Key)((uint)'a' + delta);
  272. }
  273. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  274. var delta = key - ConsoleKey.D0;
  275. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  276. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  277. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  278. return (Key)((uint)keyInfo.KeyChar);
  279. return (Key)((uint)Key.D0 + delta);
  280. }
  281. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  282. var delta = key - ConsoleKey.F1;
  283. return (Key)((int)Key.F1 + delta);
  284. }
  285. return (Key)(0xffffffff);
  286. }
  287. KeyModifiers keyModifiers = new KeyModifiers ();
  288. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  289. {
  290. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  291. (mainLoop.Driver as NetMainLoop).KeyPressed = delegate (ConsoleKeyInfo consoleKey) {
  292. var map = MapKey (consoleKey);
  293. if (map == (Key)0xffffffff)
  294. return;
  295. keyHandler (new KeyEvent (map, keyModifiers));
  296. keyUpHandler (new KeyEvent (map, keyModifiers));
  297. };
  298. }
  299. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  300. {
  301. throw new NotImplementedException ();
  302. }
  303. public override void SetColors (short foregroundColorId, short backgroundColorId)
  304. {
  305. throw new NotImplementedException ();
  306. }
  307. public override void CookMouse ()
  308. {
  309. }
  310. public override void UncookMouse ()
  311. {
  312. }
  313. //
  314. // These are for the .NET driver, but running natively on Windows, wont run
  315. // on the Mono emulation
  316. //
  317. }
  318. /// <summary>
  319. /// Mainloop intended to be used with the .NET System.Console API, and can
  320. /// be used on Windows and Unix, it is cross platform but lacks things like
  321. /// file descriptor monitoring.
  322. /// </summary>
  323. /// <remarks>
  324. /// This implementation is used for both NetDriver and FakeDriver.
  325. /// </remarks>
  326. public class NetMainLoop : IMainLoopDriver {
  327. AutoResetEvent keyReady = new AutoResetEvent (false);
  328. AutoResetEvent waitForProbe = new AutoResetEvent (false);
  329. ConsoleKeyInfo? keyResult = null;
  330. MainLoop mainLoop;
  331. Func<ConsoleKeyInfo> consoleKeyReaderFn = null;
  332. /// <summary>
  333. /// Invoked when a Key is pressed.
  334. /// </summary>
  335. public Action<ConsoleKeyInfo> KeyPressed;
  336. /// <summary>
  337. /// Initializes the class.
  338. /// </summary>
  339. /// <remarks>
  340. /// Passing a consoleKeyReaderfn is provided to support unit test sceanrios.
  341. /// </remarks>
  342. /// <param name="consoleKeyReaderFn">The method to be called to get a key from the console.</param>
  343. public NetMainLoop (Func<ConsoleKeyInfo> consoleKeyReaderFn = null)
  344. {
  345. if (consoleKeyReaderFn == null) {
  346. throw new ArgumentNullException ("key reader function must be provided.");
  347. }
  348. this.consoleKeyReaderFn = consoleKeyReaderFn;
  349. }
  350. void WindowsKeyReader ()
  351. {
  352. while (true) {
  353. waitForProbe.WaitOne ();
  354. keyResult = consoleKeyReaderFn();
  355. keyReady.Set ();
  356. }
  357. }
  358. void IMainLoopDriver.Setup (MainLoop mainLoop)
  359. {
  360. this.mainLoop = mainLoop;
  361. Thread readThread = new Thread (WindowsKeyReader);
  362. readThread.Start ();
  363. }
  364. void IMainLoopDriver.Wakeup ()
  365. {
  366. }
  367. bool IMainLoopDriver.EventsPending (bool wait)
  368. {
  369. long now = DateTime.UtcNow.Ticks;
  370. int waitTimeout;
  371. if (mainLoop.timeouts.Count > 0) {
  372. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  373. if (waitTimeout < 0)
  374. return true;
  375. } else
  376. waitTimeout = -1;
  377. if (!wait)
  378. waitTimeout = 0;
  379. keyResult = null;
  380. waitForProbe.Set ();
  381. keyReady.WaitOne (waitTimeout);
  382. return keyResult.HasValue;
  383. }
  384. void IMainLoopDriver.MainIteration ()
  385. {
  386. if (keyResult.HasValue) {
  387. KeyPressed?.Invoke (keyResult.Value);
  388. keyResult = null;
  389. }
  390. }
  391. }
  392. }