Driver.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  1. //
  2. // Driver.cs: Abstract and concrete interfaces to the console (curses or console)
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Runtime.InteropServices;
  10. using Mono.Terminal;
  11. using NStack;
  12. using Unix.Terminal;
  13. namespace Terminal.Gui {
  14. /// <summary>
  15. /// Basic colors that can be used to set the foreground and background colors in console applications. These can only be
  16. /// </summary>
  17. public enum Color {
  18. /// <summary>
  19. /// The black color.
  20. /// </summary>
  21. Black,
  22. /// <summary>
  23. /// The blue color.
  24. /// </summary>
  25. Blue,
  26. /// <summary>
  27. /// The green color.
  28. /// </summary>
  29. Green,
  30. /// <summary>
  31. /// The cyan color.
  32. /// </summary>
  33. Cyan,
  34. /// <summary>
  35. /// The red color.
  36. /// </summary>
  37. Red,
  38. /// <summary>
  39. /// The magenta color.
  40. /// </summary>
  41. Magenta,
  42. /// <summary>
  43. /// The brown color.
  44. /// </summary>
  45. Brown,
  46. /// <summary>
  47. /// The gray color.
  48. /// </summary>
  49. Gray,
  50. /// <summary>
  51. /// The dark gray color.
  52. /// </summary>
  53. DarkGray,
  54. /// <summary>
  55. /// The bright bBlue color.
  56. /// </summary>
  57. BrightBlue,
  58. /// <summary>
  59. /// The bright green color.
  60. /// </summary>
  61. BrightGreen,
  62. /// <summary>
  63. /// The brigh cyan color.
  64. /// </summary>
  65. BrighCyan,
  66. /// <summary>
  67. /// The bright red color.
  68. /// </summary>
  69. BrightRed,
  70. /// <summary>
  71. /// The bright magenta color.
  72. /// </summary>
  73. BrightMagenta,
  74. /// <summary>
  75. /// The bright yellow color.
  76. /// </summary>
  77. BrightYellow,
  78. /// <summary>
  79. /// The White color.
  80. /// </summary>
  81. White
  82. }
  83. /// <summary>
  84. /// Attributes are used as elements that contain both a foreground and a background or platform specific features
  85. /// </summary>
  86. /// <remarks>
  87. /// Attributes are needed to map colors to terminal capabilities that might lack colors, on color
  88. /// scenarios, they encode both the foreground and the background color and are used in the ColorScheme
  89. /// class to define color schemes that can be used in your application.
  90. /// </remarks>
  91. public struct Attribute {
  92. internal int value;
  93. /// <summary>
  94. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Attribute"/> struct.
  95. /// </summary>
  96. /// <param name="value">Value.</param>
  97. public Attribute (int value)
  98. {
  99. this.value = value;
  100. }
  101. public static implicit operator int (Attribute c) => c.value;
  102. public static implicit operator Attribute (int v) => new Attribute (v);
  103. }
  104. /// <summary>
  105. /// Color scheme definitions, they cover some common scenarios and are used
  106. /// typically in toplevel containers to set the scheme that is used by all the
  107. /// views contained inside.
  108. /// </summary>
  109. public class ColorScheme {
  110. /// <summary>
  111. /// The default color for text, when the view is not focused.
  112. /// </summary>
  113. public Attribute Normal;
  114. /// <summary>
  115. /// The color for text when the view has the focus.
  116. /// </summary>
  117. public Attribute Focus;
  118. /// <summary>
  119. /// The color for the hotkey when a view is not focused
  120. /// </summary>
  121. public Attribute HotNormal;
  122. /// <summary>
  123. /// The color for the hotkey when the view is focused.
  124. /// </summary>
  125. public Attribute HotFocus;
  126. }
  127. /// <summary>
  128. /// The default ColorSchemes for the application.
  129. /// </summary>
  130. public static class Colors {
  131. /// <summary>
  132. /// The base color scheme, for the default toplevel views.
  133. /// </summary>
  134. public static ColorScheme Base;
  135. /// <summary>
  136. /// The dialog color scheme, for standard popup dialog boxes
  137. /// </summary>
  138. public static ColorScheme Dialog;
  139. /// <summary>
  140. /// The menu bar color
  141. /// </summary>
  142. public static ColorScheme Menu;
  143. /// <summary>
  144. /// The color scheme for showing errors.
  145. /// </summary>
  146. public static ColorScheme Error;
  147. }
  148. /// <summary>
  149. /// Special characters that can be drawn with Driver.AddSpecial.
  150. /// </summary>
  151. public enum SpecialChar {
  152. /// <summary>
  153. /// Horizontal line character.
  154. /// </summary>
  155. HLine,
  156. /// <summary>
  157. /// Vertical line character.
  158. /// </summary>
  159. VLine,
  160. /// <summary>
  161. /// Stipple pattern
  162. /// </summary>
  163. Stipple,
  164. /// <summary>
  165. /// Diamond character
  166. /// </summary>
  167. Diamond,
  168. /// <summary>
  169. /// Upper left corner
  170. /// </summary>
  171. ULCorner,
  172. /// <summary>
  173. /// Lower left corner
  174. /// </summary>
  175. LLCorner,
  176. /// <summary>
  177. /// Upper right corner
  178. /// </summary>
  179. URCorner,
  180. /// <summary>
  181. /// Lower right corner
  182. /// </summary>
  183. LRCorner,
  184. /// <summary>
  185. /// Left tee
  186. /// </summary>
  187. LeftTee,
  188. /// <summary>
  189. /// Right tee
  190. /// </summary>
  191. RightTee,
  192. /// <summary>
  193. /// Top tee
  194. /// </summary>
  195. TopTee,
  196. /// <summary>
  197. /// The bottom tee.
  198. /// </summary>
  199. BottomTee,
  200. }
  201. /// <summary>
  202. /// ConsoleDriver is an abstract class that defines the requirements for a console driver. One implementation if the CursesDriver, and another one uses the .NET Console one.
  203. /// </summary>
  204. public abstract class ConsoleDriver {
  205. /// <summary>
  206. /// The current number of columns in the terminal.
  207. /// </summary>
  208. public abstract int Cols { get; }
  209. /// <summary>
  210. /// The current number of rows in the terminal.
  211. /// </summary>
  212. public abstract int Rows { get; }
  213. /// <summary>
  214. /// Initializes the driver
  215. /// </summary>
  216. /// <param name="terminalResized">Method to invoke when the terminal is resized.</param>
  217. public abstract void Init (Action terminalResized);
  218. /// <summary>
  219. /// Moves the cursor to the specified column and row.
  220. /// </summary>
  221. /// <param name="col">Column to move the cursor to.</param>
  222. /// <param name="row">Row to move the cursor to.</param>
  223. public abstract void Move (int col, int row);
  224. /// <summary>
  225. /// Adds the specified rune to the display at the current cursor position
  226. /// </summary>
  227. /// <param name="rune">Rune to add.</param>
  228. public abstract void AddRune (Rune rune);
  229. /// <summary>
  230. /// Adds the specified
  231. /// </summary>
  232. /// <param name="str">String.</param>
  233. public abstract void AddStr (ustring str);
  234. public abstract void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler);
  235. /// <summary>
  236. /// Updates the screen to reflect all the changes that have been done to the display buffer
  237. /// </summary>
  238. public abstract void Refresh ();
  239. /// <summary>
  240. /// Updates the location of the cursor position
  241. /// </summary>
  242. public abstract void UpdateCursor ();
  243. /// <summary>
  244. /// Ends the execution of the console driver.
  245. /// </summary>
  246. public abstract void End ();
  247. /// <summary>
  248. /// Redraws the physical screen with the contents that have been queued up via any of the printing commands.
  249. /// </summary>
  250. public abstract void UpdateScreen ();
  251. /// <summary>
  252. /// Selects the specified attribute as the attribute to use for future calls to AddRune, AddString.
  253. /// </summary>
  254. /// <param name="c">C.</param>
  255. public abstract void SetAttribute (Attribute c);
  256. // Set Colors from limit sets of colors
  257. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  258. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  259. // that independently with the R, G, B values.
  260. /// <summary>
  261. /// Advanced uses - set colors to any pre-set pairs, you would need to init_color
  262. /// that independently with the R, G, B values.
  263. /// </summary>
  264. /// <param name="foregroundColorId">Foreground color identifier.</param>
  265. /// <param name="backgroundColorId">Background color identifier.</param>
  266. public abstract void SetColors (short foregroundColorId, short backgroundColorId);
  267. /// <summary>
  268. /// Draws a frame on the specified region with the specified padding around the frame.
  269. /// </summary>
  270. /// <param name="region">Region where the frame will be drawn..</param>
  271. /// <param name="padding">Padding to add on the sides.</param>
  272. /// <param name="fill">If set to <c>true</c> it will clear the contents with the current color, otherwise the contents will be left untouched.</param>
  273. public virtual void DrawFrame (Rect region, int padding, bool fill)
  274. {
  275. int width = region.Width;
  276. int height = region.Height;
  277. int b;
  278. int fwidth = width - padding * 2;
  279. int fheight = height - 1 - padding;
  280. Move (region.X, region.Y);
  281. if (padding > 0) {
  282. for (int l = 0; l < padding; l++)
  283. for (b = 0; b < width; b++)
  284. AddRune (' ');
  285. }
  286. Move (region.X, region.Y + padding);
  287. for (int c = 0; c < padding; c++)
  288. AddRune (' ');
  289. AddRune (ULCorner);
  290. for (b = 0; b < fwidth - 2; b++)
  291. AddRune (HLine);
  292. AddRune (URCorner);
  293. for (int c = 0; c < padding; c++)
  294. AddRune (' ');
  295. for (b = 1 + padding; b < fheight; b++) {
  296. Move (region.X, region.Y + b);
  297. for (int c = 0; c < padding; c++)
  298. AddRune (' ');
  299. AddRune (VLine);
  300. if (fill) {
  301. for (int x = 1; x < fwidth - 1; x++)
  302. AddRune (' ');
  303. } else
  304. Move (region.X + fwidth - 1, region.Y + b);
  305. AddRune (VLine);
  306. for (int c = 0; c < padding; c++)
  307. AddRune (' ');
  308. }
  309. Move (region.X, region.Y + fheight);
  310. for (int c = 0; c < padding; c++)
  311. AddRune (' ');
  312. AddRune (LLCorner);
  313. for (b = 0; b < fwidth - 2; b++)
  314. AddRune (HLine);
  315. AddRune (LRCorner);
  316. for (int c = 0; c < padding; c++)
  317. AddRune (' ');
  318. if (padding > 0) {
  319. Move (region.X, region.Y + height - padding);
  320. for (int l = 0; l < padding; l++)
  321. for (b = 0; b < width; b++)
  322. AddRune (' ');
  323. }
  324. }
  325. /// <summary>
  326. /// Suspend the application, typically needs to save the state, suspend the app and upon return, reset the console driver.
  327. /// </summary>
  328. public abstract void Suspend ();
  329. Rect clip;
  330. /// <summary>
  331. /// Controls the current clipping region that AddRune/AddStr is subject to.
  332. /// </summary>
  333. /// <value>The clip.</value>
  334. public Rect Clip {
  335. get => clip;
  336. set => this.clip = value;
  337. }
  338. public abstract void StartReportingMouseMoves ();
  339. public abstract void StopReportingMouseMoves ();
  340. /// <summary>
  341. /// Disables the cooked event processing from the mouse driver. At startup, it is assumed mouse events are cooked.
  342. /// </summary>
  343. public abstract void UncookMouse ();
  344. /// <summary>
  345. /// Enables the cooked event processing from the mouse driver
  346. /// </summary>
  347. public abstract void CookMouse ();
  348. /// <summary>
  349. /// Horizontal line character.
  350. /// </summary>
  351. public Rune HLine;
  352. /// <summary>
  353. /// Vertical line character.
  354. /// </summary>
  355. public Rune VLine;
  356. /// <summary>
  357. /// Stipple pattern
  358. /// </summary>
  359. public Rune Stipple;
  360. /// <summary>
  361. /// Diamond character
  362. /// </summary>
  363. public Rune Diamond;
  364. /// <summary>
  365. /// Upper left corner
  366. /// </summary>
  367. public Rune ULCorner;
  368. /// <summary>
  369. /// Lower left corner
  370. /// </summary>
  371. public Rune LLCorner;
  372. /// <summary>
  373. /// Upper right corner
  374. /// </summary>
  375. public Rune URCorner;
  376. /// <summary>
  377. /// Lower right corner
  378. /// </summary>
  379. public Rune LRCorner;
  380. /// <summary>
  381. /// Left tee
  382. /// </summary>
  383. public Rune LeftTee;
  384. /// <summary>
  385. /// Right tee
  386. /// </summary>
  387. public Rune RightTee;
  388. /// <summary>
  389. /// Top tee
  390. /// </summary>
  391. public Rune TopTee;
  392. /// <summary>
  393. /// The bottom tee.
  394. /// </summary>
  395. public Rune BottomTee;
  396. }
  397. /// <summary>
  398. /// This is the Curses driver for the gui.cs/Terminal framework.
  399. /// </summary>
  400. internal class CursesDriver : ConsoleDriver {
  401. Action terminalResized;
  402. public override int Cols => Curses.Cols;
  403. public override int Rows => Curses.Lines;
  404. // Current row, and current col, tracked by Move/AddRune only
  405. int ccol, crow;
  406. bool needMove;
  407. public override void Move (int col, int row)
  408. {
  409. ccol = col;
  410. crow = row;
  411. if (Clip.Contains (col, row)) {
  412. Curses.move (row, col);
  413. needMove = false;
  414. } else {
  415. Curses.move (Clip.Y, Clip.X);
  416. needMove = true;
  417. }
  418. }
  419. static bool sync;
  420. public override void AddRune (Rune rune)
  421. {
  422. if (Clip.Contains (ccol, crow)) {
  423. if (needMove) {
  424. Curses.move (crow, ccol);
  425. needMove = false;
  426. }
  427. Curses.addch ((int)(uint)rune);
  428. } else
  429. needMove = true;
  430. if (sync)
  431. Application.Driver.Refresh ();
  432. ccol++;
  433. }
  434. public override void AddStr (ustring str)
  435. {
  436. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  437. foreach (var rune in str)
  438. AddRune (rune);
  439. }
  440. public override void Refresh () => Curses.refresh ();
  441. public override void UpdateCursor () => Curses.refresh ();
  442. public override void End () => Curses.endwin ();
  443. public override void UpdateScreen () => window.redrawwin ();
  444. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  445. public Curses.Window window;
  446. static short last_color_pair = 16;
  447. static Attribute MakeColor (short f, short b)
  448. {
  449. Curses.InitColorPair (++last_color_pair, f, b);
  450. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  451. }
  452. int [,] colorPairs = new int [16, 16];
  453. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  454. {
  455. int f = (short)foreground;
  456. int b = (short)background;
  457. var v = colorPairs [f, b];
  458. if ((v & 0x10000) == 0) {
  459. b = b & 0x7;
  460. bool bold = (f & 0x8) != 0;
  461. f = f & 0x7;
  462. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  463. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  464. }
  465. SetAttribute (v & 0xffff);
  466. }
  467. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  468. public override void SetColors (short foreColorId, short backgroundColorId)
  469. {
  470. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  471. if (!rawPairs.TryGetValue (key, out var v)) {
  472. v = MakeColor (foreColorId, backgroundColorId);
  473. rawPairs [key] = v;
  474. }
  475. SetAttribute (v);
  476. }
  477. static Key MapCursesKey (int cursesKey)
  478. {
  479. switch (cursesKey) {
  480. case Curses.KeyF1: return Key.F1;
  481. case Curses.KeyF2: return Key.F2;
  482. case Curses.KeyF3: return Key.F3;
  483. case Curses.KeyF4: return Key.F4;
  484. case Curses.KeyF5: return Key.F5;
  485. case Curses.KeyF6: return Key.F6;
  486. case Curses.KeyF7: return Key.F7;
  487. case Curses.KeyF8: return Key.F8;
  488. case Curses.KeyF9: return Key.F9;
  489. case Curses.KeyF10: return Key.F10;
  490. case Curses.KeyUp: return Key.CursorUp;
  491. case Curses.KeyDown: return Key.CursorDown;
  492. case Curses.KeyLeft: return Key.CursorLeft;
  493. case Curses.KeyRight: return Key.CursorRight;
  494. case Curses.KeyHome: return Key.Home;
  495. case Curses.KeyEnd: return Key.End;
  496. case Curses.KeyNPage: return Key.PageDown;
  497. case Curses.KeyPPage: return Key.PageUp;
  498. case Curses.KeyDeleteChar: return Key.DeleteChar;
  499. case Curses.KeyInsertChar: return Key.InsertChar;
  500. case Curses.KeyBackTab: return Key.BackTab;
  501. default: return Key.Unknown;
  502. }
  503. }
  504. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  505. {
  506. return new MouseEvent () {
  507. X = cev.X,
  508. Y = cev.Y,
  509. Flags = (MouseFlags)cev.ButtonState
  510. };
  511. }
  512. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  513. {
  514. int wch;
  515. var code = Curses.get_wch (out wch);
  516. if (code == Curses.ERR)
  517. return;
  518. if (code == Curses.KEY_CODE_YES) {
  519. if (wch == Curses.KeyResize) {
  520. if (Curses.CheckWinChange ()) {
  521. terminalResized ();
  522. return;
  523. }
  524. }
  525. if (wch == Curses.KeyMouse) {
  526. Curses.MouseEvent ev;
  527. Curses.getmouse (out ev);
  528. mouseHandler (ToDriverMouse (ev));
  529. return;
  530. }
  531. keyHandler (new KeyEvent (MapCursesKey (wch)));
  532. return;
  533. }
  534. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  535. if (wch == 27) {
  536. Curses.timeout (200);
  537. code = Curses.get_wch (out wch);
  538. if (code == Curses.KEY_CODE_YES)
  539. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  540. if (code == 0) {
  541. KeyEvent key;
  542. // The ESC-number handling, debatable.
  543. if (wch >= '1' && wch <= '9')
  544. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  545. else if (wch == '0')
  546. key = new KeyEvent (Key.F10);
  547. else if (wch == 27)
  548. key = new KeyEvent ((Key)wch);
  549. else
  550. key = new KeyEvent (Key.AltMask | (Key)wch);
  551. keyHandler (key);
  552. } else
  553. keyHandler (new KeyEvent (Key.Esc));
  554. } else
  555. keyHandler (new KeyEvent ((Key)wch));
  556. }
  557. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  558. {
  559. Curses.timeout (-1);
  560. mainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  561. ProcessInput (keyHandler, mouseHandler);
  562. return true;
  563. });
  564. }
  565. Curses.Event oldMouseEvents, reportableMouseEvents;
  566. public override void Init (Action terminalResized)
  567. {
  568. if (window != null)
  569. return;
  570. try {
  571. window = Curses.initscr ();
  572. } catch (Exception e) {
  573. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  574. }
  575. Curses.raw ();
  576. Curses.noecho ();
  577. Curses.Window.Standard.keypad (true);
  578. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  579. this.terminalResized = terminalResized;
  580. StartReportingMouseMoves ();
  581. HLine = Curses.ACS_HLINE;
  582. VLine = Curses.ACS_VLINE;
  583. Stipple = Curses.ACS_CKBOARD;
  584. Diamond = Curses.ACS_DIAMOND;
  585. ULCorner = Curses.ACS_ULCORNER;
  586. LLCorner = Curses.ACS_LLCORNER;
  587. URCorner = Curses.ACS_URCORNER;
  588. LRCorner = Curses.ACS_LRCORNER;
  589. LeftTee = Curses.ACS_LTEE;
  590. RightTee = Curses.ACS_RTEE;
  591. TopTee = Curses.ACS_TTEE;
  592. BottomTee = Curses.ACS_BTEE;
  593. Colors.Base = new ColorScheme ();
  594. Colors.Dialog = new ColorScheme ();
  595. Colors.Menu = new ColorScheme ();
  596. Colors.Error = new ColorScheme ();
  597. Clip = new Rect (0, 0, Cols, Rows);
  598. if (Curses.HasColors) {
  599. Curses.StartColor ();
  600. Curses.UseDefaultColors ();
  601. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  602. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  603. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  604. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  605. // Focused,
  606. // Selected, Hot: Yellow on Black
  607. // Selected, text: white on black
  608. // Unselected, hot: yellow on cyan
  609. // unselected, text: same as unfocused
  610. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  611. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  612. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  613. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  614. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  615. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  616. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  617. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  618. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  619. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  620. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  621. Colors.Error.HotFocus = Colors.Error.HotNormal;
  622. } else {
  623. Colors.Base.Normal = Curses.A_NORMAL;
  624. Colors.Base.Focus = Curses.A_REVERSE;
  625. Colors.Base.HotNormal = Curses.A_BOLD;
  626. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  627. Colors.Menu.Normal = Curses.A_REVERSE;
  628. Colors.Menu.Focus = Curses.A_NORMAL;
  629. Colors.Menu.HotNormal = Curses.A_BOLD;
  630. Colors.Menu.HotFocus = Curses.A_NORMAL;
  631. Colors.Dialog.Normal = Curses.A_REVERSE;
  632. Colors.Dialog.Focus = Curses.A_NORMAL;
  633. Colors.Dialog.HotNormal = Curses.A_BOLD;
  634. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  635. Colors.Error.Normal = Curses.A_BOLD;
  636. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  637. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  638. Colors.Error.HotFocus = Curses.A_REVERSE;
  639. }
  640. }
  641. public override void Suspend ()
  642. {
  643. StopReportingMouseMoves ();
  644. Platform.Suspend ();
  645. Curses.Window.Standard.redrawwin ();
  646. Curses.refresh ();
  647. StartReportingMouseMoves ();
  648. }
  649. public override void StartReportingMouseMoves()
  650. {
  651. Console.Out.Write ("\x1b[?1003h");
  652. Console.Out.Flush ();
  653. }
  654. public override void StopReportingMouseMoves()
  655. {
  656. Console.Out.Write ("\x1b[?1003l");
  657. Console.Out.Flush ();
  658. }
  659. int lastMouseInterval;
  660. bool mouseGrabbed;
  661. public override void UncookMouse()
  662. {
  663. if (mouseGrabbed)
  664. return;
  665. lastMouseInterval = Curses.mouseinterval (0);
  666. mouseGrabbed = true;
  667. }
  668. public override void CookMouse()
  669. {
  670. mouseGrabbed = false;
  671. Curses.mouseinterval (lastMouseInterval);
  672. }
  673. }
  674. internal static class Platform {
  675. [DllImport ("libc")]
  676. static extern int uname (IntPtr buf);
  677. [DllImport ("libc")]
  678. static extern int killpg (int pgrp, int pid);
  679. static int suspendSignal;
  680. static int GetSuspendSignal ()
  681. {
  682. if (suspendSignal != 0)
  683. return suspendSignal;
  684. IntPtr buf = Marshal.AllocHGlobal (8192);
  685. if (uname (buf) != 0) {
  686. Marshal.FreeHGlobal (buf);
  687. suspendSignal = -1;
  688. return suspendSignal;
  689. }
  690. try {
  691. switch (Marshal.PtrToStringAnsi (buf)) {
  692. case "Darwin":
  693. case "DragonFly":
  694. case "FreeBSD":
  695. case "NetBSD":
  696. case "OpenBSD":
  697. suspendSignal = 18;
  698. break;
  699. case "Linux":
  700. // TODO: should fetch the machine name and
  701. // if it is MIPS return 24
  702. suspendSignal = 20;
  703. break;
  704. case "Solaris":
  705. suspendSignal = 24;
  706. break;
  707. default:
  708. suspendSignal = -1;
  709. break;
  710. }
  711. return suspendSignal;
  712. } finally {
  713. Marshal.FreeHGlobal (buf);
  714. }
  715. }
  716. /// <summary>
  717. /// Suspends the process by sending SIGTSTP to itself
  718. /// </summary>
  719. /// <returns>The suspend.</returns>
  720. static public bool Suspend ()
  721. {
  722. int signal = GetSuspendSignal ();
  723. if (signal == -1)
  724. return false;
  725. killpg (0, signal);
  726. return true;
  727. }
  728. }
  729. internal class NetDriver : ConsoleDriver {
  730. int cols, rows;
  731. public override int Cols => cols;
  732. public override int Rows => rows;
  733. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  734. int [,,] contents;
  735. bool [] dirtyLine;
  736. void UpdateOffscreen ()
  737. {
  738. int cols = Cols;
  739. int rows = Rows;
  740. contents = new int [rows, cols, 3];
  741. for (int r = 0; r < rows; r++) {
  742. for (int c = 0; c < cols; c++) {
  743. contents [r, c, 0] = ' ';
  744. contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
  745. contents [r, c, 2] = 0;
  746. }
  747. }
  748. dirtyLine = new bool [rows];
  749. for (int row = 0; row < rows; row++)
  750. dirtyLine [row] = true;
  751. }
  752. static bool sync;
  753. public NetDriver ()
  754. {
  755. cols = Console.WindowWidth;
  756. rows = Console.WindowHeight - 1;
  757. UpdateOffscreen ();
  758. }
  759. bool needMove;
  760. // Current row, and current col, tracked by Move/AddCh only
  761. int ccol, crow;
  762. public override void Move (int col, int row)
  763. {
  764. ccol = col;
  765. crow = row;
  766. if (Clip.Contains (col, row)) {
  767. Console.CursorTop = row;
  768. Console.CursorLeft = col;
  769. needMove = false;
  770. } else {
  771. Console.CursorTop = Clip.Y;
  772. Console.CursorLeft = Clip.X;
  773. needMove = true;
  774. }
  775. }
  776. public override void AddRune (Rune rune)
  777. {
  778. if (Clip.Contains (ccol, crow)) {
  779. if (needMove) {
  780. //Console.CursorLeft = ccol;
  781. //Console.CursorTop = crow;
  782. needMove = false;
  783. }
  784. contents [crow, ccol, 0] = (int)(uint)rune;
  785. contents [crow, ccol, 1] = currentAttribute;
  786. contents [crow, ccol, 2] = 1;
  787. dirtyLine [crow] = true;
  788. } else
  789. needMove = true;
  790. ccol++;
  791. if (ccol == Cols) {
  792. ccol = 0;
  793. if (crow + 1 < Rows)
  794. crow++;
  795. }
  796. if (sync)
  797. UpdateScreen ();
  798. }
  799. public override void AddStr (ustring str)
  800. {
  801. foreach (var rune in str)
  802. AddRune (rune);
  803. }
  804. public override void End ()
  805. {
  806. Console.ResetColor ();
  807. Console.Clear ();
  808. }
  809. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  810. {
  811. // Encode the colors into the int value.
  812. return new Attribute () { value = ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff) };
  813. }
  814. public override void Init (Action terminalResized)
  815. {
  816. Colors.Base = new ColorScheme ();
  817. Colors.Dialog = new ColorScheme ();
  818. Colors.Menu = new ColorScheme ();
  819. Colors.Error = new ColorScheme ();
  820. Clip = new Rect (0, 0, Cols, Rows);
  821. HLine = '\u2500';
  822. VLine = '\u2502';
  823. Stipple = '\u2592';
  824. Diamond = '\u25c6';
  825. ULCorner = '\u250C';
  826. LLCorner = '\u2514';
  827. URCorner = '\u2510';
  828. LRCorner = '\u2518';
  829. LeftTee = '\u251c';
  830. RightTee = '\u2524';
  831. TopTee = '\u22a4';
  832. BottomTee = '\u22a5';
  833. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  834. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  835. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  836. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  837. // Focused,
  838. // Selected, Hot: Yellow on Black
  839. // Selected, text: white on black
  840. // Unselected, hot: yellow on cyan
  841. // unselected, text: same as unfocused
  842. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  843. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  844. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  845. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  846. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  847. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  848. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  849. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  850. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  851. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  852. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  853. Colors.Error.HotFocus = Colors.Error.HotNormal;
  854. Console.Clear ();
  855. }
  856. int redrawColor = -1;
  857. void SetColor (int color)
  858. {
  859. redrawColor = color;
  860. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  861. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  862. }
  863. public override void UpdateScreen ()
  864. {
  865. int rows = Rows;
  866. int cols = Cols;
  867. Console.CursorTop = 0;
  868. Console.CursorLeft = 0;
  869. for (int row = 0; row < rows; row++) {
  870. dirtyLine [row] = false;
  871. for (int col = 0; col < cols; col++) {
  872. contents [row, col, 2] = 0;
  873. var color = contents [row, col, 1];
  874. if (color != redrawColor)
  875. SetColor (color);
  876. Console.Write ((char)contents [row, col, 0]);
  877. }
  878. }
  879. }
  880. public override void Refresh ()
  881. {
  882. int rows = Rows;
  883. int cols = Cols;
  884. var savedRow = Console.CursorTop;
  885. var savedCol = Console.CursorLeft;
  886. for (int row = 0; row < rows; row++) {
  887. if (!dirtyLine [row])
  888. continue;
  889. dirtyLine [row] = false;
  890. for (int col = 0; col < cols; col++) {
  891. if (contents [row, col, 2] != 1)
  892. continue;
  893. Console.CursorTop = row;
  894. Console.CursorLeft = col;
  895. for (; col < cols && contents [row, col, 2] == 1; col++) {
  896. var color = contents [row, col, 1];
  897. if (color != redrawColor)
  898. SetColor (color);
  899. Console.Write ((char)contents [row, col, 0]);
  900. contents [row, col, 2] = 0;
  901. }
  902. }
  903. }
  904. Console.CursorTop = savedRow;
  905. Console.CursorLeft = savedCol;
  906. }
  907. public override void UpdateCursor ()
  908. {
  909. //
  910. }
  911. public override void StartReportingMouseMoves()
  912. {
  913. }
  914. public override void StopReportingMouseMoves ()
  915. {
  916. }
  917. public override void Suspend ()
  918. {
  919. }
  920. int currentAttribute;
  921. public override void SetAttribute (Attribute c)
  922. {
  923. currentAttribute = c.value;
  924. }
  925. Key MapKey (ConsoleKeyInfo keyInfo)
  926. {
  927. switch (keyInfo.Key) {
  928. case ConsoleKey.Escape:
  929. return Key.Esc;
  930. case ConsoleKey.Tab:
  931. return Key.Tab;
  932. case ConsoleKey.Home:
  933. return Key.Home;
  934. case ConsoleKey.End:
  935. return Key.End;
  936. case ConsoleKey.LeftArrow:
  937. return Key.CursorLeft;
  938. case ConsoleKey.RightArrow:
  939. return Key.CursorRight;
  940. case ConsoleKey.UpArrow:
  941. return Key.CursorUp;
  942. case ConsoleKey.DownArrow:
  943. return Key.CursorDown;
  944. case ConsoleKey.PageUp:
  945. return Key.PageUp;
  946. case ConsoleKey.PageDown:
  947. return Key.PageDown;
  948. case ConsoleKey.Enter:
  949. return Key.Enter;
  950. case ConsoleKey.Spacebar:
  951. return Key.Space;
  952. case ConsoleKey.Backspace:
  953. return Key.Backspace;
  954. case ConsoleKey.Delete:
  955. return Key.Delete;
  956. }
  957. var key = keyInfo.Key;
  958. if (key >= ConsoleKey.A && key <= ConsoleKey.Z){
  959. var delta = key - ConsoleKey.A;
  960. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  961. return (Key)((uint)Key.ControlA + delta);
  962. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  963. return (Key) (((uint)Key.AltMask) | ((uint)'A' + delta));
  964. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  965. return (Key)((uint)'A' + delta);
  966. else
  967. return (Key)((uint)'a' + delta);
  968. }
  969. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  970. var delta = key - ConsoleKey.F1;
  971. return (Key)((int) Key.F1 + delta);
  972. }
  973. return (Key)(0xffffffff);
  974. }
  975. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  976. {
  977. mainLoop.WindowsKeyPressed = delegate (ConsoleKeyInfo consoleKey) {
  978. var map = MapKey (consoleKey);
  979. if (map == (Key) 0xffffffff)
  980. return;
  981. keyHandler (new KeyEvent (map));
  982. };
  983. }
  984. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  985. {
  986. throw new NotImplementedException ();
  987. }
  988. public override void SetColors (short foregroundColorId, short backgroundColorId)
  989. {
  990. throw new NotImplementedException ();
  991. }
  992. public override void CookMouse ()
  993. {
  994. }
  995. public override void UncookMouse ()
  996. {
  997. }
  998. //
  999. // These are for the .NET driver, but running natively on Windows, wont run
  1000. // on the Mono emulation
  1001. //
  1002. }
  1003. internal class WindowsConsole {
  1004. public const int STD_OUTPUT_HANDLE = -11;
  1005. public const int STD_INPUT_HANDLE = -10;
  1006. public const int STD_ERROR_HANDLE = -12;
  1007. [DllImport ("kernel32.dll", SetLastError = true)]
  1008. static extern IntPtr GetStdHandle (int nStdHandle);
  1009. IntPtr inputHandle, outputHandle;
  1010. public WindowsConsole ()
  1011. {
  1012. inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  1013. outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  1014. }
  1015. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  1016. public struct KeyEventRecord {
  1017. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  1018. public bool bKeyDown;
  1019. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  1020. public ushort wRepeatCount;
  1021. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  1022. public ushort wVirtualKeyCode;
  1023. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  1024. public ushort wVirtualScanCode;
  1025. [FieldOffset (10)]
  1026. public char UnicodeChar;
  1027. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  1028. public ControlKeyState dwControlKeyState;
  1029. }
  1030. [Flags]
  1031. public enum ButtonState {
  1032. Button1Pressed = 1,
  1033. Button2Pressed = 4,
  1034. Button3Pressed = 8,
  1035. Button4Pressed = 16,
  1036. RightmostButtonPressed = 2,
  1037. }
  1038. [Flags]
  1039. public enum ControlKeyState {
  1040. RightAltPressed = 1,
  1041. LeftAltPressed = 2,
  1042. RightControlPressed = 4,
  1043. LeftControlPressed = 8,
  1044. ShiftPressed = 16,
  1045. NumlockOn = 32,
  1046. ScrolllockOn = 64,
  1047. CapslockOn = 128,
  1048. EnhancedKey = 256
  1049. }
  1050. [Flags]
  1051. public enum EventFlags {
  1052. MouseMoved = 1,
  1053. DoubleClick = 2,
  1054. MouseWheeled = 4,
  1055. MouseHorizontalWheeled = 8
  1056. }
  1057. [StructLayout (LayoutKind.Explicit)]
  1058. public struct MouseEventRecord {
  1059. [FieldOffset (0)]
  1060. public Coordinate MousePosition;
  1061. [FieldOffset (4)]
  1062. public ButtonState ButtonState;
  1063. [FieldOffset (8)]
  1064. public ControlKeyState ControlKeyState;
  1065. [FieldOffset (12)]
  1066. public EventFlags EventFlags;
  1067. public override string ToString ()
  1068. {
  1069. return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  1070. }
  1071. }
  1072. [StructLayout (LayoutKind.Sequential)]
  1073. public struct Coordinate {
  1074. public short X;
  1075. public short Y;
  1076. public Coordinate (short X, short Y)
  1077. {
  1078. this.X = X;
  1079. this.Y = Y;
  1080. }
  1081. public override string ToString () => $"({X},{Y})";
  1082. };
  1083. internal struct WindowBufferSizeRecord {
  1084. public Coordinate size;
  1085. public WindowBufferSizeRecord (short x, short y)
  1086. {
  1087. this.size = new Coordinate (x, y);
  1088. }
  1089. public override string ToString () => $"[WindowBufferSize{size}";
  1090. }
  1091. [StructLayout (LayoutKind.Sequential)]
  1092. public struct MenuEventRecord {
  1093. public uint dwCommandId;
  1094. }
  1095. [StructLayout (LayoutKind.Sequential)]
  1096. public struct FocusEventRecord {
  1097. public uint bSetFocus;
  1098. }
  1099. public enum EventType {
  1100. Focus = 0x10,
  1101. Key = 0x1,
  1102. Menu = 0x8,
  1103. Mouse = 2,
  1104. WindowBufferSize = 4
  1105. }
  1106. [StructLayout (LayoutKind.Explicit)]
  1107. public struct InputRecord {
  1108. [FieldOffset (0)]
  1109. public EventType EventType;
  1110. [FieldOffset (4)]
  1111. public KeyEventRecord KeyEvent;
  1112. [FieldOffset (4)]
  1113. public MouseEventRecord MouseEvent;
  1114. [FieldOffset (4)]
  1115. public WindowBufferSizeRecord WindowBufferSizeEvent;
  1116. [FieldOffset (4)]
  1117. public MenuEventRecord MenuEvent;
  1118. [FieldOffset (4)]
  1119. public FocusEventRecord FocusEvent;
  1120. public override string ToString ()
  1121. {
  1122. switch (EventType) {
  1123. case EventType.Focus:
  1124. return FocusEvent.ToString ();
  1125. case EventType.Key:
  1126. return KeyEvent.ToString ();
  1127. case EventType.Menu:
  1128. return MenuEvent.ToString ();
  1129. case EventType.Mouse:
  1130. return MouseEvent.ToString ();
  1131. case EventType.WindowBufferSize:
  1132. return WindowBufferSizeEvent.ToString ();
  1133. default:
  1134. return "Unknown event type: " + EventType;
  1135. }
  1136. }
  1137. };
  1138. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  1139. public static extern bool ReadConsoleInput (
  1140. IntPtr hConsoleInput,
  1141. [Out] InputRecord [] lpBuffer,
  1142. uint nLength,
  1143. out uint lpNumberOfEventsRead);
  1144. [DllImport ("kernel32.dll")]
  1145. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  1146. [DllImport ("kernel32.dll")]
  1147. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  1148. public uint ConsoleMode {
  1149. get {
  1150. uint v;
  1151. GetConsoleMode (inputHandle, out v);
  1152. return v;
  1153. }
  1154. set {
  1155. SetConsoleMode (inputHandle, value);
  1156. }
  1157. }
  1158. }
  1159. }