Driver.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. /// Ends the execution of the console driver.
  241. /// </summary>
  242. public abstract void End ();
  243. /// <summary>
  244. /// Redraws the physical screen with the contents that have been queued up via any of the printing commands.
  245. /// </summary>
  246. public abstract void UpdateScreen ();
  247. /// <summary>
  248. /// Selects the specified attribute as the attribute to use for future calls to AddRune, AddString.
  249. /// </summary>
  250. /// <param name="c">C.</param>
  251. public abstract void SetAttribute (Attribute c);
  252. // Set Colors from limit sets of colors
  253. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  254. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  255. // that independently with the R, G, B values.
  256. /// <summary>
  257. /// Advanced uses - set colors to any pre-set pairs, you would need to init_color
  258. /// that independently with the R, G, B values.
  259. /// </summary>
  260. /// <param name="foregroundColorId">Foreground color identifier.</param>
  261. /// <param name="backgroundColorId">Background color identifier.</param>
  262. public abstract void SetColors (short foregroundColorId, short backgroundColorId);
  263. /// <summary>
  264. /// Draws a frame on the specified region with the specified padding around the frame.
  265. /// </summary>
  266. /// <param name="region">Region where the frame will be drawn..</param>
  267. /// <param name="padding">Padding to add on the sides.</param>
  268. /// <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>
  269. public virtual void DrawFrame (Rect region, int padding, bool fill)
  270. {
  271. int width = region.Width;
  272. int height = region.Height;
  273. int b;
  274. int fwidth = width - padding * 2;
  275. int fheight = height - 1 - padding;
  276. Move (region.X, region.Y);
  277. if (padding > 0) {
  278. for (int l = 0; l < padding; l++)
  279. for (b = 0; b < width; b++)
  280. AddRune (' ');
  281. }
  282. Move (region.X, region.Y + padding);
  283. for (int c = 0; c < padding; c++)
  284. AddRune (' ');
  285. AddRune (ULCorner);
  286. for (b = 0; b < fwidth - 2; b++)
  287. AddRune (HLine);
  288. AddRune (URCorner);
  289. for (int c = 0; c < padding; c++)
  290. AddRune (' ');
  291. for (b = 1 + padding; b < fheight; b++) {
  292. Move (region.X, region.Y + b);
  293. for (int c = 0; c < padding; c++)
  294. AddRune (' ');
  295. AddRune (VLine);
  296. if (fill) {
  297. for (int x = 1; x < fwidth - 1; x++)
  298. AddRune (' ');
  299. } else
  300. Move (region.X + fwidth - 1, region.Y + b);
  301. AddRune (VLine);
  302. for (int c = 0; c < padding; c++)
  303. AddRune (' ');
  304. }
  305. Move (region.X, region.Y + fheight);
  306. for (int c = 0; c < padding; c++)
  307. AddRune (' ');
  308. AddRune (LLCorner);
  309. for (b = 0; b < fwidth - 2; b++)
  310. AddRune (HLine);
  311. AddRune (LRCorner);
  312. for (int c = 0; c < padding; c++)
  313. AddRune (' ');
  314. if (padding > 0) {
  315. Move (region.X, region.Y + height - padding);
  316. for (int l = 0; l < padding; l++)
  317. for (b = 0; b < width; b++)
  318. AddRune (' ');
  319. }
  320. }
  321. /// <summary>
  322. /// Suspend the application, typically needs to save the state, suspend the app and upon return, reset the console driver.
  323. /// </summary>
  324. public abstract void Suspend ();
  325. Rect clip;
  326. /// <summary>
  327. /// Controls the current clipping region that AddRune/AddStr is subject to.
  328. /// </summary>
  329. /// <value>The clip.</value>
  330. public Rect Clip {
  331. get => clip;
  332. set => this.clip = value;
  333. }
  334. public abstract void StartReportingMouseMoves ();
  335. public abstract void StopReportingMouseMoves ();
  336. /// <summary>
  337. /// Disables the cooked event processing from the mouse driver. At startup, it is assumed mouse events are cooked.
  338. /// </summary>
  339. public abstract void UncookMouse ();
  340. /// <summary>
  341. /// Enables the cooked event processing from the mouse driver
  342. /// </summary>
  343. public abstract void CookMouse ();
  344. /// <summary>
  345. /// Horizontal line character.
  346. /// </summary>
  347. public Rune HLine;
  348. /// <summary>
  349. /// Vertical line character.
  350. /// </summary>
  351. public Rune VLine;
  352. /// <summary>
  353. /// Stipple pattern
  354. /// </summary>
  355. public Rune Stipple;
  356. /// <summary>
  357. /// Diamond character
  358. /// </summary>
  359. public Rune Diamond;
  360. /// <summary>
  361. /// Upper left corner
  362. /// </summary>
  363. public Rune ULCorner;
  364. /// <summary>
  365. /// Lower left corner
  366. /// </summary>
  367. public Rune LLCorner;
  368. /// <summary>
  369. /// Upper right corner
  370. /// </summary>
  371. public Rune URCorner;
  372. /// <summary>
  373. /// Lower right corner
  374. /// </summary>
  375. public Rune LRCorner;
  376. /// <summary>
  377. /// Left tee
  378. /// </summary>
  379. public Rune LeftTee;
  380. /// <summary>
  381. /// Right tee
  382. /// </summary>
  383. public Rune RightTee;
  384. /// <summary>
  385. /// Top tee
  386. /// </summary>
  387. public Rune TopTee;
  388. /// <summary>
  389. /// The bottom tee.
  390. /// </summary>
  391. public Rune BottomTee;
  392. }
  393. /// <summary>
  394. /// This is the Curses driver for the gui.cs/Terminal framework.
  395. /// </summary>
  396. internal class CursesDriver : ConsoleDriver {
  397. Action terminalResized;
  398. public override int Cols => Curses.Cols;
  399. public override int Rows => Curses.Lines;
  400. // Current row, and current col, tracked by Move/AddRune only
  401. int ccol, crow;
  402. bool needMove;
  403. public override void Move (int col, int row)
  404. {
  405. ccol = col;
  406. crow = row;
  407. if (Clip.Contains (col, row)) {
  408. Curses.move (row, col);
  409. needMove = false;
  410. } else {
  411. Curses.move (Clip.Y, Clip.X);
  412. needMove = true;
  413. }
  414. }
  415. static bool sync;
  416. public override void AddRune (Rune rune)
  417. {
  418. if (Clip.Contains (ccol, crow)) {
  419. if (needMove) {
  420. Curses.move (crow, ccol);
  421. needMove = false;
  422. }
  423. Curses.addch ((int)(uint)rune);
  424. } else
  425. needMove = true;
  426. if (sync)
  427. Application.Driver.Refresh ();
  428. ccol++;
  429. }
  430. public override void AddStr (ustring str)
  431. {
  432. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  433. foreach (var rune in str)
  434. AddRune (rune);
  435. }
  436. public override void Refresh () => Curses.refresh ();
  437. public override void End () => Curses.endwin ();
  438. public override void UpdateScreen () => window.redrawwin ();
  439. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  440. public Curses.Window window;
  441. static short last_color_pair = 16;
  442. static Attribute MakeColor (short f, short b)
  443. {
  444. Curses.InitColorPair (++last_color_pair, f, b);
  445. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  446. }
  447. int [,] colorPairs = new int [16, 16];
  448. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  449. {
  450. int f = (short)foreground;
  451. int b = (short)background;
  452. var v = colorPairs [f, b];
  453. if ((v & 0x10000) == 0) {
  454. b = b & 0x7;
  455. bool bold = (f & 0x8) != 0;
  456. f = f & 0x7;
  457. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  458. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  459. }
  460. SetAttribute (v & 0xffff);
  461. }
  462. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  463. public override void SetColors (short foreColorId, short backgroundColorId)
  464. {
  465. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  466. if (!rawPairs.TryGetValue (key, out var v)) {
  467. v = MakeColor (foreColorId, backgroundColorId);
  468. rawPairs [key] = v;
  469. }
  470. SetAttribute (v);
  471. }
  472. static Key MapCursesKey (int cursesKey)
  473. {
  474. switch (cursesKey) {
  475. case Curses.KeyF1: return Key.F1;
  476. case Curses.KeyF2: return Key.F2;
  477. case Curses.KeyF3: return Key.F3;
  478. case Curses.KeyF4: return Key.F4;
  479. case Curses.KeyF5: return Key.F5;
  480. case Curses.KeyF6: return Key.F6;
  481. case Curses.KeyF7: return Key.F7;
  482. case Curses.KeyF8: return Key.F8;
  483. case Curses.KeyF9: return Key.F9;
  484. case Curses.KeyF10: return Key.F10;
  485. case Curses.KeyUp: return Key.CursorUp;
  486. case Curses.KeyDown: return Key.CursorDown;
  487. case Curses.KeyLeft: return Key.CursorLeft;
  488. case Curses.KeyRight: return Key.CursorRight;
  489. case Curses.KeyHome: return Key.Home;
  490. case Curses.KeyEnd: return Key.End;
  491. case Curses.KeyNPage: return Key.PageDown;
  492. case Curses.KeyPPage: return Key.PageUp;
  493. case Curses.KeyDeleteChar: return Key.DeleteChar;
  494. case Curses.KeyInsertChar: return Key.InsertChar;
  495. case Curses.KeyBackTab: return Key.BackTab;
  496. default: return Key.Unknown;
  497. }
  498. }
  499. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  500. {
  501. return new MouseEvent () {
  502. X = cev.X,
  503. Y = cev.Y,
  504. Flags = (MouseFlags)cev.ButtonState
  505. };
  506. }
  507. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  508. {
  509. int wch;
  510. var code = Curses.get_wch (out wch);
  511. if (code == Curses.KEY_CODE_YES) {
  512. if (wch == Curses.KeyResize) {
  513. if (Curses.CheckWinChange ()) {
  514. terminalResized ();
  515. return;
  516. }
  517. }
  518. if (wch == Curses.KeyMouse) {
  519. Curses.MouseEvent ev;
  520. Curses.getmouse (out ev);
  521. mouseHandler (ToDriverMouse (ev));
  522. return;
  523. }
  524. keyHandler (new KeyEvent (MapCursesKey (wch)));
  525. return;
  526. }
  527. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  528. if (wch == 27) {
  529. Curses.timeout (100);
  530. code = Curses.get_wch (out wch);
  531. if (code == Curses.KEY_CODE_YES)
  532. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  533. if (code == 0) {
  534. KeyEvent key;
  535. // The ESC-number handling, debatable.
  536. if (wch >= '1' && wch <= '9')
  537. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  538. else if (wch == '0')
  539. key = new KeyEvent (Key.F10);
  540. else if (wch == 27)
  541. key = new KeyEvent ((Key)wch);
  542. else
  543. key = new KeyEvent (Key.AltMask | (Key)wch);
  544. keyHandler (key);
  545. } else
  546. keyHandler (new KeyEvent (Key.Esc));
  547. } else
  548. keyHandler (new KeyEvent ((Key)wch));
  549. }
  550. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  551. {
  552. Curses.timeout (-1);
  553. mainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  554. ProcessInput (keyHandler, mouseHandler);
  555. return true;
  556. });
  557. }
  558. Curses.Event oldMouseEvents, reportableMouseEvents;
  559. public override void Init (Action terminalResized)
  560. {
  561. if (window != null)
  562. return;
  563. try {
  564. window = Curses.initscr ();
  565. } catch (Exception e) {
  566. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  567. }
  568. Curses.raw ();
  569. Curses.noecho ();
  570. Curses.Window.Standard.keypad (true);
  571. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  572. this.terminalResized = terminalResized;
  573. StartReportingMouseMoves ();
  574. HLine = Curses.ACS_HLINE;
  575. VLine = Curses.ACS_VLINE;
  576. Stipple = Curses.ACS_CKBOARD;
  577. Diamond = Curses.ACS_DIAMOND;
  578. ULCorner = Curses.ACS_ULCORNER;
  579. LLCorner = Curses.ACS_LLCORNER;
  580. URCorner = Curses.ACS_URCORNER;
  581. LRCorner = Curses.ACS_LRCORNER;
  582. LeftTee = Curses.ACS_LTEE;
  583. RightTee = Curses.ACS_RTEE;
  584. TopTee = Curses.ACS_TTEE;
  585. BottomTee = Curses.ACS_BTEE;
  586. Colors.Base = new ColorScheme ();
  587. Colors.Dialog = new ColorScheme ();
  588. Colors.Menu = new ColorScheme ();
  589. Colors.Error = new ColorScheme ();
  590. Clip = new Rect (0, 0, Cols, Rows);
  591. if (Curses.HasColors) {
  592. Curses.StartColor ();
  593. Curses.UseDefaultColors ();
  594. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  595. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  596. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  597. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  598. // Focused,
  599. // Selected, Hot: Yellow on Black
  600. // Selected, text: white on black
  601. // Unselected, hot: yellow on cyan
  602. // unselected, text: same as unfocused
  603. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  604. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  605. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  606. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  607. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  608. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  609. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  610. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  611. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  612. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  613. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  614. Colors.Error.HotFocus = Colors.Error.HotNormal;
  615. } else {
  616. Colors.Base.Normal = Curses.A_NORMAL;
  617. Colors.Base.Focus = Curses.A_REVERSE;
  618. Colors.Base.HotNormal = Curses.A_BOLD;
  619. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  620. Colors.Menu.Normal = Curses.A_REVERSE;
  621. Colors.Menu.Focus = Curses.A_NORMAL;
  622. Colors.Menu.HotNormal = Curses.A_BOLD;
  623. Colors.Menu.HotFocus = Curses.A_NORMAL;
  624. Colors.Dialog.Normal = Curses.A_REVERSE;
  625. Colors.Dialog.Focus = Curses.A_NORMAL;
  626. Colors.Dialog.HotNormal = Curses.A_BOLD;
  627. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  628. Colors.Error.Normal = Curses.A_BOLD;
  629. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  630. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  631. Colors.Error.HotFocus = Curses.A_REVERSE;
  632. }
  633. }
  634. public override void Suspend ()
  635. {
  636. StopReportingMouseMoves ();
  637. Platform.Suspend ();
  638. Curses.Window.Standard.redrawwin ();
  639. Curses.refresh ();
  640. StartReportingMouseMoves ();
  641. }
  642. public override void StartReportingMouseMoves()
  643. {
  644. Console.Out.Write ("\x1b[?1003h");
  645. Console.Out.Flush ();
  646. }
  647. public override void StopReportingMouseMoves()
  648. {
  649. Console.Out.Write ("\x1b[?1003l");
  650. Console.Out.Flush ();
  651. }
  652. int lastMouseInterval;
  653. bool mouseGrabbed;
  654. public override void UncookMouse()
  655. {
  656. if (mouseGrabbed)
  657. return;
  658. lastMouseInterval = Curses.mouseinterval (0);
  659. mouseGrabbed = true;
  660. }
  661. public override void CookMouse()
  662. {
  663. mouseGrabbed = false;
  664. Curses.mouseinterval (lastMouseInterval);
  665. }
  666. }
  667. internal static class Platform {
  668. [DllImport ("libc")]
  669. static extern int uname (IntPtr buf);
  670. [DllImport ("libc")]
  671. static extern int killpg (int pgrp, int pid);
  672. static int suspendSignal;
  673. static int GetSuspendSignal ()
  674. {
  675. if (suspendSignal != 0)
  676. return suspendSignal;
  677. IntPtr buf = Marshal.AllocHGlobal (8192);
  678. if (uname (buf) != 0) {
  679. Marshal.FreeHGlobal (buf);
  680. suspendSignal = -1;
  681. return suspendSignal;
  682. }
  683. try {
  684. switch (Marshal.PtrToStringAnsi (buf)) {
  685. case "Darwin":
  686. case "DragonFly":
  687. case "FreeBSD":
  688. case "NetBSD":
  689. case "OpenBSD":
  690. suspendSignal = 18;
  691. break;
  692. case "Linux":
  693. // TODO: should fetch the machine name and
  694. // if it is MIPS return 24
  695. suspendSignal = 20;
  696. break;
  697. case "Solaris":
  698. suspendSignal = 24;
  699. break;
  700. default:
  701. suspendSignal = -1;
  702. break;
  703. }
  704. return suspendSignal;
  705. } finally {
  706. Marshal.FreeHGlobal (buf);
  707. }
  708. }
  709. /// <summary>
  710. /// Suspends the process by sending SIGTSTP to itself
  711. /// </summary>
  712. /// <returns>The suspend.</returns>
  713. static public bool Suspend ()
  714. {
  715. int signal = GetSuspendSignal ();
  716. if (signal == -1)
  717. return false;
  718. killpg (0, signal);
  719. return true;
  720. }
  721. }
  722. internal class NetDriver : ConsoleDriver {
  723. public override int Cols => Console.WindowWidth;
  724. public override int Rows => Console.WindowHeight;
  725. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  726. int [,,] contents;
  727. bool [] dirtyLine;
  728. void UpdateOffscreen ()
  729. {
  730. int cols = Cols;
  731. int rows = Rows;
  732. contents = new int [rows, cols, 3];
  733. for (int r = 0; r < rows; r++) {
  734. for (int c = 0; c < cols; c++) {
  735. contents [r, c, 0] = ' ';
  736. contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
  737. contents [r, c, 2] = 0;
  738. }
  739. }
  740. dirtyLine = new bool [rows];
  741. for (int row = 0; row < rows; row++)
  742. dirtyLine [row] = true;
  743. }
  744. static bool sync;
  745. public NetDriver ()
  746. {
  747. UpdateOffscreen ();
  748. }
  749. bool needMove;
  750. // Current row, and current col, tracked by Move/AddCh only
  751. int ccol, crow;
  752. public override void Move (int col, int row)
  753. {
  754. ccol = col;
  755. crow = row;
  756. if (Clip.Contains (col, row)) {
  757. Console.CursorTop = row;
  758. Console.CursorLeft = col;
  759. needMove = false;
  760. } else {
  761. Console.CursorTop = Clip.Y;
  762. Console.CursorLeft = Clip.X;
  763. needMove = true;
  764. }
  765. }
  766. public override void AddRune (Rune rune)
  767. {
  768. if (Clip.Contains (ccol, crow)) {
  769. if (needMove) {
  770. Console.CursorLeft = ccol;
  771. Console.CursorTop = crow;
  772. needMove = false;
  773. }
  774. contents [crow, ccol, 0] = (int)(uint)rune;
  775. contents [crow, ccol, 1] = currentAttribute;
  776. contents [crow, ccol, 2] = 1;
  777. dirtyLine [crow] = true;
  778. } else
  779. needMove = true;
  780. ccol++;
  781. if (ccol == Cols) {
  782. ccol = 0;
  783. if (crow + 1 < Rows)
  784. crow++;
  785. }
  786. if (sync)
  787. UpdateScreen ();
  788. }
  789. public override void AddStr (ustring str)
  790. {
  791. foreach (var rune in str)
  792. AddRune (rune);
  793. }
  794. public override void End ()
  795. {
  796. }
  797. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  798. {
  799. // Encode the colors into the int value.
  800. return new Attribute () { value = ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff) };
  801. }
  802. public override void Init (Action terminalResized)
  803. {
  804. Colors.Base = new ColorScheme ();
  805. Colors.Dialog = new ColorScheme ();
  806. Colors.Menu = new ColorScheme ();
  807. Colors.Error = new ColorScheme ();
  808. Clip = new Rect (0, 0, Cols, Rows);
  809. HLine = '\u2500';
  810. VLine = '\u2502';
  811. Stipple = '\u2592';
  812. Diamond = '\u25c6';
  813. ULCorner = '\u250C';
  814. LLCorner = '\u2514';
  815. URCorner = '\u2510';
  816. LRCorner = '\u2518';
  817. LeftTee = '\u251c';
  818. RightTee = '\u2524';
  819. TopTee = '\u22a4';
  820. BottomTee = '\u22a5';
  821. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  822. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  823. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  824. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  825. // Focused,
  826. // Selected, Hot: Yellow on Black
  827. // Selected, text: white on black
  828. // Unselected, hot: yellow on cyan
  829. // unselected, text: same as unfocused
  830. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  831. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  832. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  833. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  834. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  835. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  836. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  837. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  838. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  839. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  840. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  841. Colors.Error.HotFocus = Colors.Error.HotNormal;
  842. }
  843. int redrawColor = -1;
  844. void SetColor (int color)
  845. {
  846. redrawColor = color;
  847. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  848. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  849. }
  850. public override void UpdateScreen ()
  851. {
  852. int rows = Rows;
  853. int cols = Cols;
  854. Console.CursorTop = 0;
  855. Console.CursorLeft = 0;
  856. for (int row = 0; row < rows; row++) {
  857. dirtyLine [row] = false;
  858. for (int col = 0; col < cols; col++) {
  859. contents [row, col, 2] = 0;
  860. var color = contents [row, col, 1];
  861. if (color != redrawColor)
  862. SetColor (color);
  863. Console.Write ((char)contents [row, col, 0]);
  864. }
  865. }
  866. }
  867. public override void Refresh ()
  868. {
  869. int rows = Rows;
  870. int cols = Cols;
  871. var savedRow = Console.CursorTop;
  872. var savedCol = Console.CursorLeft;
  873. for (int row = 0; row < rows; row++) {
  874. if (!dirtyLine [row])
  875. continue;
  876. dirtyLine [row] = false;
  877. for (int col = 0; col < cols; col++) {
  878. if (contents [row, col, 2] != 1)
  879. continue;
  880. Console.CursorTop = row;
  881. Console.CursorLeft = col;
  882. for (; col < cols && contents [row, col, 2] == 1; col++) {
  883. var color = contents [row, col, 1];
  884. if (color != redrawColor)
  885. SetColor (color);
  886. Console.Write ((char)contents [row, col, 0]);
  887. contents [row, col, 2] = 0;
  888. }
  889. }
  890. }
  891. Console.CursorTop = savedRow;
  892. Console.CursorLeft = savedCol;
  893. }
  894. public override void StartReportingMouseMoves()
  895. {
  896. }
  897. public override void StopReportingMouseMoves ()
  898. {
  899. }
  900. public override void Suspend ()
  901. {
  902. }
  903. int currentAttribute;
  904. public override void SetAttribute (Attribute c)
  905. {
  906. currentAttribute = c.value;
  907. }
  908. Key MapKey (ConsoleKeyInfo keyInfo)
  909. {
  910. switch (keyInfo.Key) {
  911. case ConsoleKey.Escape:
  912. return Key.Esc;
  913. case ConsoleKey.Tab:
  914. return Key.Tab;
  915. case ConsoleKey.Home:
  916. return Key.Home;
  917. case ConsoleKey.End:
  918. return Key.End;
  919. case ConsoleKey.LeftArrow:
  920. return Key.CursorLeft;
  921. case ConsoleKey.RightArrow:
  922. return Key.CursorRight;
  923. case ConsoleKey.UpArrow:
  924. return Key.CursorUp;
  925. case ConsoleKey.DownArrow:
  926. return Key.CursorDown;
  927. case ConsoleKey.PageUp:
  928. return Key.PageUp;
  929. case ConsoleKey.PageDown:
  930. return Key.PageDown;
  931. case ConsoleKey.Enter:
  932. return Key.Enter;
  933. case ConsoleKey.Spacebar:
  934. return Key.Space;
  935. case ConsoleKey.Backspace:
  936. return Key.Backspace;
  937. case ConsoleKey.Delete:
  938. return Key.Delete;
  939. }
  940. var key = keyInfo.Key;
  941. if (key >= ConsoleKey.A && key <= ConsoleKey.Z){
  942. var delta = key - ConsoleKey.A;
  943. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  944. return (Key)((uint)Key.ControlA + delta);
  945. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  946. return (Key) (((uint)Key.AltMask) | ((uint)'A' + delta));
  947. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  948. return (Key)((uint)'A' + delta);
  949. else
  950. return (Key)((uint)'a' + delta);
  951. }
  952. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  953. var delta = key - ConsoleKey.F1;
  954. return (Key)((int) Key.F1 + delta);
  955. }
  956. return (Key)(0xffffffff);
  957. }
  958. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  959. {
  960. mainLoop.WindowsKeyPressed = delegate (ConsoleKeyInfo consoleKey) {
  961. var map = MapKey (consoleKey);
  962. if (map == (Key) 0xffffffff)
  963. return;
  964. keyHandler (new KeyEvent (map));
  965. };
  966. }
  967. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  968. {
  969. throw new NotImplementedException ();
  970. }
  971. public override void SetColors (short foregroundColorId, short backgroundColorId)
  972. {
  973. throw new NotImplementedException ();
  974. }
  975. public override void CookMouse ()
  976. {
  977. }
  978. public override void UncookMouse ()
  979. {
  980. }
  981. }
  982. }