Driver.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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. public override int Cols => Console.WindowWidth;
  731. public override int Rows => Console.WindowHeight;
  732. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  733. int [,,] contents;
  734. bool [] dirtyLine;
  735. void UpdateOffscreen ()
  736. {
  737. int cols = Cols;
  738. int rows = Rows;
  739. contents = new int [rows, cols, 3];
  740. for (int r = 0; r < rows; r++) {
  741. for (int c = 0; c < cols; c++) {
  742. contents [r, c, 0] = ' ';
  743. contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
  744. contents [r, c, 2] = 0;
  745. }
  746. }
  747. dirtyLine = new bool [rows];
  748. for (int row = 0; row < rows; row++)
  749. dirtyLine [row] = true;
  750. }
  751. static bool sync;
  752. public NetDriver ()
  753. {
  754. UpdateOffscreen ();
  755. }
  756. bool needMove;
  757. // Current row, and current col, tracked by Move/AddCh only
  758. int ccol, crow;
  759. public override void Move (int col, int row)
  760. {
  761. ccol = col;
  762. crow = row;
  763. if (Clip.Contains (col, row)) {
  764. Console.CursorTop = row;
  765. Console.CursorLeft = col;
  766. needMove = false;
  767. } else {
  768. Console.CursorTop = Clip.Y;
  769. Console.CursorLeft = Clip.X;
  770. needMove = true;
  771. }
  772. }
  773. public override void AddRune (Rune rune)
  774. {
  775. if (Clip.Contains (ccol, crow)) {
  776. if (needMove) {
  777. Console.CursorLeft = ccol;
  778. Console.CursorTop = crow;
  779. needMove = false;
  780. }
  781. contents [crow, ccol, 0] = (int)(uint)rune;
  782. contents [crow, ccol, 1] = currentAttribute;
  783. contents [crow, ccol, 2] = 1;
  784. dirtyLine [crow] = true;
  785. } else
  786. needMove = true;
  787. ccol++;
  788. if (ccol == Cols) {
  789. ccol = 0;
  790. if (crow + 1 < Rows)
  791. crow++;
  792. }
  793. if (sync)
  794. UpdateScreen ();
  795. }
  796. public override void AddStr (ustring str)
  797. {
  798. foreach (var rune in str)
  799. AddRune (rune);
  800. }
  801. public override void End ()
  802. {
  803. Console.ResetColor ();
  804. Console.Clear ();
  805. }
  806. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  807. {
  808. // Encode the colors into the int value.
  809. return new Attribute () { value = ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff) };
  810. }
  811. public override void Init (Action terminalResized)
  812. {
  813. Colors.Base = new ColorScheme ();
  814. Colors.Dialog = new ColorScheme ();
  815. Colors.Menu = new ColorScheme ();
  816. Colors.Error = new ColorScheme ();
  817. Clip = new Rect (0, 0, Cols, Rows);
  818. HLine = '\u2500';
  819. VLine = '\u2502';
  820. Stipple = '\u2592';
  821. Diamond = '\u25c6';
  822. ULCorner = '\u250C';
  823. LLCorner = '\u2514';
  824. URCorner = '\u2510';
  825. LRCorner = '\u2518';
  826. LeftTee = '\u251c';
  827. RightTee = '\u2524';
  828. TopTee = '\u22a4';
  829. BottomTee = '\u22a5';
  830. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  831. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  832. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  833. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  834. // Focused,
  835. // Selected, Hot: Yellow on Black
  836. // Selected, text: white on black
  837. // Unselected, hot: yellow on cyan
  838. // unselected, text: same as unfocused
  839. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  840. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  841. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  842. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  843. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  844. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  845. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  846. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  847. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  848. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  849. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  850. Colors.Error.HotFocus = Colors.Error.HotNormal;
  851. }
  852. int redrawColor = -1;
  853. void SetColor (int color)
  854. {
  855. redrawColor = color;
  856. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  857. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  858. }
  859. public override void UpdateScreen ()
  860. {
  861. int rows = Rows;
  862. int cols = Cols;
  863. Console.CursorTop = 0;
  864. Console.CursorLeft = 0;
  865. for (int row = 0; row < rows; row++) {
  866. dirtyLine [row] = false;
  867. for (int col = 0; col < cols; col++) {
  868. contents [row, col, 2] = 0;
  869. var color = contents [row, col, 1];
  870. if (color != redrawColor)
  871. SetColor (color);
  872. Console.Write ((char)contents [row, col, 0]);
  873. }
  874. }
  875. }
  876. public override void Refresh ()
  877. {
  878. int rows = Rows;
  879. int cols = Cols;
  880. var savedRow = Console.CursorTop;
  881. var savedCol = Console.CursorLeft;
  882. for (int row = 0; row < rows; row++) {
  883. if (!dirtyLine [row])
  884. continue;
  885. dirtyLine [row] = false;
  886. for (int col = 0; col < cols; col++) {
  887. if (contents [row, col, 2] != 1)
  888. continue;
  889. Console.CursorTop = row;
  890. Console.CursorLeft = col;
  891. for (; col < cols && contents [row, col, 2] == 1; col++) {
  892. var color = contents [row, col, 1];
  893. if (color != redrawColor)
  894. SetColor (color);
  895. Console.Write ((char)contents [row, col, 0]);
  896. contents [row, col, 2] = 0;
  897. }
  898. }
  899. }
  900. Console.CursorTop = savedRow;
  901. Console.CursorLeft = savedCol;
  902. }
  903. public override void UpdateCursor ()
  904. {
  905. //
  906. }
  907. public override void StartReportingMouseMoves()
  908. {
  909. }
  910. public override void StopReportingMouseMoves ()
  911. {
  912. }
  913. public override void Suspend ()
  914. {
  915. }
  916. int currentAttribute;
  917. public override void SetAttribute (Attribute c)
  918. {
  919. currentAttribute = c.value;
  920. }
  921. Key MapKey (ConsoleKeyInfo keyInfo)
  922. {
  923. switch (keyInfo.Key) {
  924. case ConsoleKey.Escape:
  925. return Key.Esc;
  926. case ConsoleKey.Tab:
  927. return Key.Tab;
  928. case ConsoleKey.Home:
  929. return Key.Home;
  930. case ConsoleKey.End:
  931. return Key.End;
  932. case ConsoleKey.LeftArrow:
  933. return Key.CursorLeft;
  934. case ConsoleKey.RightArrow:
  935. return Key.CursorRight;
  936. case ConsoleKey.UpArrow:
  937. return Key.CursorUp;
  938. case ConsoleKey.DownArrow:
  939. return Key.CursorDown;
  940. case ConsoleKey.PageUp:
  941. return Key.PageUp;
  942. case ConsoleKey.PageDown:
  943. return Key.PageDown;
  944. case ConsoleKey.Enter:
  945. return Key.Enter;
  946. case ConsoleKey.Spacebar:
  947. return Key.Space;
  948. case ConsoleKey.Backspace:
  949. return Key.Backspace;
  950. case ConsoleKey.Delete:
  951. return Key.Delete;
  952. }
  953. var key = keyInfo.Key;
  954. if (key >= ConsoleKey.A && key <= ConsoleKey.Z){
  955. var delta = key - ConsoleKey.A;
  956. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  957. return (Key)((uint)Key.ControlA + delta);
  958. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  959. return (Key) (((uint)Key.AltMask) | ((uint)'A' + delta));
  960. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  961. return (Key)((uint)'A' + delta);
  962. else
  963. return (Key)((uint)'a' + delta);
  964. }
  965. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  966. var delta = key - ConsoleKey.F1;
  967. return (Key)((int) Key.F1 + delta);
  968. }
  969. return (Key)(0xffffffff);
  970. }
  971. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  972. {
  973. mainLoop.WindowsKeyPressed = delegate (ConsoleKeyInfo consoleKey) {
  974. var map = MapKey (consoleKey);
  975. if (map == (Key) 0xffffffff)
  976. return;
  977. keyHandler (new KeyEvent (map));
  978. };
  979. }
  980. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  981. {
  982. throw new NotImplementedException ();
  983. }
  984. public override void SetColors (short foregroundColorId, short backgroundColorId)
  985. {
  986. throw new NotImplementedException ();
  987. }
  988. public override void CookMouse ()
  989. {
  990. }
  991. public override void UncookMouse ()
  992. {
  993. }
  994. }
  995. }