Driver.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. case Curses.KeyBackspace: return Key.Backspace;
  502. default: return Key.Unknown;
  503. }
  504. }
  505. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  506. {
  507. return new MouseEvent () {
  508. X = cev.X,
  509. Y = cev.Y,
  510. Flags = (MouseFlags)cev.ButtonState
  511. };
  512. }
  513. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  514. {
  515. int wch;
  516. var code = Curses.get_wch (out wch);
  517. if (code == Curses.ERR)
  518. return;
  519. if (code == Curses.KEY_CODE_YES) {
  520. if (wch == Curses.KeyResize) {
  521. if (Curses.CheckWinChange ()) {
  522. terminalResized ();
  523. return;
  524. }
  525. }
  526. if (wch == Curses.KeyMouse) {
  527. Curses.MouseEvent ev;
  528. Curses.getmouse (out ev);
  529. mouseHandler (ToDriverMouse (ev));
  530. return;
  531. }
  532. keyHandler (new KeyEvent (MapCursesKey (wch)));
  533. return;
  534. }
  535. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  536. if (wch == 27) {
  537. Curses.timeout (200);
  538. code = Curses.get_wch (out wch);
  539. if (code == Curses.KEY_CODE_YES)
  540. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  541. if (code == 0) {
  542. KeyEvent key;
  543. // The ESC-number handling, debatable.
  544. if (wch >= '1' && wch <= '9')
  545. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  546. else if (wch == '0')
  547. key = new KeyEvent (Key.F10);
  548. else if (wch == 27)
  549. key = new KeyEvent ((Key)wch);
  550. else
  551. key = new KeyEvent (Key.AltMask | (Key)wch);
  552. keyHandler (key);
  553. } else
  554. keyHandler (new KeyEvent (Key.Esc));
  555. } else
  556. keyHandler (new KeyEvent ((Key)wch));
  557. }
  558. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  559. {
  560. Curses.timeout (-1);
  561. mainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  562. ProcessInput (keyHandler, mouseHandler);
  563. return true;
  564. });
  565. }
  566. Curses.Event oldMouseEvents, reportableMouseEvents;
  567. public override void Init (Action terminalResized)
  568. {
  569. if (window != null)
  570. return;
  571. try {
  572. window = Curses.initscr ();
  573. } catch (Exception e) {
  574. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  575. }
  576. Curses.raw ();
  577. Curses.noecho ();
  578. Curses.Window.Standard.keypad (true);
  579. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  580. this.terminalResized = terminalResized;
  581. StartReportingMouseMoves ();
  582. HLine = Curses.ACS_HLINE;
  583. VLine = Curses.ACS_VLINE;
  584. Stipple = Curses.ACS_CKBOARD;
  585. Diamond = Curses.ACS_DIAMOND;
  586. ULCorner = Curses.ACS_ULCORNER;
  587. LLCorner = Curses.ACS_LLCORNER;
  588. URCorner = Curses.ACS_URCORNER;
  589. LRCorner = Curses.ACS_LRCORNER;
  590. LeftTee = Curses.ACS_LTEE;
  591. RightTee = Curses.ACS_RTEE;
  592. TopTee = Curses.ACS_TTEE;
  593. BottomTee = Curses.ACS_BTEE;
  594. Colors.Base = new ColorScheme ();
  595. Colors.Dialog = new ColorScheme ();
  596. Colors.Menu = new ColorScheme ();
  597. Colors.Error = new ColorScheme ();
  598. Clip = new Rect (0, 0, Cols, Rows);
  599. if (Curses.HasColors) {
  600. Curses.StartColor ();
  601. Curses.UseDefaultColors ();
  602. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  603. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  604. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  605. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  606. // Focused,
  607. // Selected, Hot: Yellow on Black
  608. // Selected, text: white on black
  609. // Unselected, hot: yellow on cyan
  610. // unselected, text: same as unfocused
  611. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  612. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  613. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  614. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  615. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  616. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  617. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  618. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  619. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  620. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  621. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  622. Colors.Error.HotFocus = Colors.Error.HotNormal;
  623. } else {
  624. Colors.Base.Normal = Curses.A_NORMAL;
  625. Colors.Base.Focus = Curses.A_REVERSE;
  626. Colors.Base.HotNormal = Curses.A_BOLD;
  627. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  628. Colors.Menu.Normal = Curses.A_REVERSE;
  629. Colors.Menu.Focus = Curses.A_NORMAL;
  630. Colors.Menu.HotNormal = Curses.A_BOLD;
  631. Colors.Menu.HotFocus = Curses.A_NORMAL;
  632. Colors.Dialog.Normal = Curses.A_REVERSE;
  633. Colors.Dialog.Focus = Curses.A_NORMAL;
  634. Colors.Dialog.HotNormal = Curses.A_BOLD;
  635. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  636. Colors.Error.Normal = Curses.A_BOLD;
  637. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  638. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  639. Colors.Error.HotFocus = Curses.A_REVERSE;
  640. }
  641. }
  642. public override void Suspend ()
  643. {
  644. StopReportingMouseMoves ();
  645. Platform.Suspend ();
  646. Curses.Window.Standard.redrawwin ();
  647. Curses.refresh ();
  648. StartReportingMouseMoves ();
  649. }
  650. public override void StartReportingMouseMoves()
  651. {
  652. Console.Out.Write ("\x1b[?1003h");
  653. Console.Out.Flush ();
  654. }
  655. public override void StopReportingMouseMoves()
  656. {
  657. Console.Out.Write ("\x1b[?1003l");
  658. Console.Out.Flush ();
  659. }
  660. int lastMouseInterval;
  661. bool mouseGrabbed;
  662. public override void UncookMouse()
  663. {
  664. if (mouseGrabbed)
  665. return;
  666. lastMouseInterval = Curses.mouseinterval (0);
  667. mouseGrabbed = true;
  668. }
  669. public override void CookMouse()
  670. {
  671. mouseGrabbed = false;
  672. Curses.mouseinterval (lastMouseInterval);
  673. }
  674. }
  675. internal static class Platform {
  676. [DllImport ("libc")]
  677. static extern int uname (IntPtr buf);
  678. [DllImport ("libc")]
  679. static extern int killpg (int pgrp, int pid);
  680. static int suspendSignal;
  681. static int GetSuspendSignal ()
  682. {
  683. if (suspendSignal != 0)
  684. return suspendSignal;
  685. IntPtr buf = Marshal.AllocHGlobal (8192);
  686. if (uname (buf) != 0) {
  687. Marshal.FreeHGlobal (buf);
  688. suspendSignal = -1;
  689. return suspendSignal;
  690. }
  691. try {
  692. switch (Marshal.PtrToStringAnsi (buf)) {
  693. case "Darwin":
  694. case "DragonFly":
  695. case "FreeBSD":
  696. case "NetBSD":
  697. case "OpenBSD":
  698. suspendSignal = 18;
  699. break;
  700. case "Linux":
  701. // TODO: should fetch the machine name and
  702. // if it is MIPS return 24
  703. suspendSignal = 20;
  704. break;
  705. case "Solaris":
  706. suspendSignal = 24;
  707. break;
  708. default:
  709. suspendSignal = -1;
  710. break;
  711. }
  712. return suspendSignal;
  713. } finally {
  714. Marshal.FreeHGlobal (buf);
  715. }
  716. }
  717. /// <summary>
  718. /// Suspends the process by sending SIGTSTP to itself
  719. /// </summary>
  720. /// <returns>The suspend.</returns>
  721. static public bool Suspend ()
  722. {
  723. int signal = GetSuspendSignal ();
  724. if (signal == -1)
  725. return false;
  726. killpg (0, signal);
  727. return true;
  728. }
  729. }
  730. internal class NetDriver : ConsoleDriver {
  731. int cols, rows;
  732. public override int Cols => cols;
  733. public override int Rows => rows;
  734. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  735. int [,,] contents;
  736. bool [] dirtyLine;
  737. void UpdateOffscreen ()
  738. {
  739. int cols = Cols;
  740. int rows = Rows;
  741. contents = new int [rows, cols, 3];
  742. for (int r = 0; r < rows; r++) {
  743. for (int c = 0; c < cols; c++) {
  744. contents [r, c, 0] = ' ';
  745. contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
  746. contents [r, c, 2] = 0;
  747. }
  748. }
  749. dirtyLine = new bool [rows];
  750. for (int row = 0; row < rows; row++)
  751. dirtyLine [row] = true;
  752. }
  753. static bool sync;
  754. public NetDriver ()
  755. {
  756. cols = Console.WindowWidth;
  757. rows = Console.WindowHeight - 1;
  758. UpdateOffscreen ();
  759. }
  760. bool needMove;
  761. // Current row, and current col, tracked by Move/AddCh only
  762. int ccol, crow;
  763. public override void Move (int col, int row)
  764. {
  765. ccol = col;
  766. crow = row;
  767. if (Clip.Contains (col, row)) {
  768. Console.CursorTop = row;
  769. Console.CursorLeft = col;
  770. needMove = false;
  771. } else {
  772. Console.CursorTop = Clip.Y;
  773. Console.CursorLeft = Clip.X;
  774. needMove = true;
  775. }
  776. }
  777. public override void AddRune (Rune rune)
  778. {
  779. if (Clip.Contains (ccol, crow)) {
  780. if (needMove) {
  781. //Console.CursorLeft = ccol;
  782. //Console.CursorTop = crow;
  783. needMove = false;
  784. }
  785. contents [crow, ccol, 0] = (int)(uint)rune;
  786. contents [crow, ccol, 1] = currentAttribute;
  787. contents [crow, ccol, 2] = 1;
  788. dirtyLine [crow] = true;
  789. } else
  790. needMove = true;
  791. ccol++;
  792. if (ccol == Cols) {
  793. ccol = 0;
  794. if (crow + 1 < Rows)
  795. crow++;
  796. }
  797. if (sync)
  798. UpdateScreen ();
  799. }
  800. public override void AddStr (ustring str)
  801. {
  802. foreach (var rune in str)
  803. AddRune (rune);
  804. }
  805. public override void End ()
  806. {
  807. Console.ResetColor ();
  808. Console.Clear ();
  809. }
  810. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  811. {
  812. // Encode the colors into the int value.
  813. return new Attribute () { value = ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff) };
  814. }
  815. public override void Init (Action terminalResized)
  816. {
  817. Colors.Base = new ColorScheme ();
  818. Colors.Dialog = new ColorScheme ();
  819. Colors.Menu = new ColorScheme ();
  820. Colors.Error = new ColorScheme ();
  821. Clip = new Rect (0, 0, Cols, Rows);
  822. HLine = '\u2500';
  823. VLine = '\u2502';
  824. Stipple = '\u2592';
  825. Diamond = '\u25c6';
  826. ULCorner = '\u250C';
  827. LLCorner = '\u2514';
  828. URCorner = '\u2510';
  829. LRCorner = '\u2518';
  830. LeftTee = '\u251c';
  831. RightTee = '\u2524';
  832. TopTee = '\u22a4';
  833. BottomTee = '\u22a5';
  834. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  835. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  836. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  837. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  838. // Focused,
  839. // Selected, Hot: Yellow on Black
  840. // Selected, text: white on black
  841. // Unselected, hot: yellow on cyan
  842. // unselected, text: same as unfocused
  843. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  844. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  845. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  846. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  847. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  848. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  849. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  850. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  851. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  852. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  853. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  854. Colors.Error.HotFocus = Colors.Error.HotNormal;
  855. Console.Clear ();
  856. }
  857. int redrawColor = -1;
  858. void SetColor (int color)
  859. {
  860. redrawColor = color;
  861. Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
  862. Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
  863. }
  864. public override void UpdateScreen ()
  865. {
  866. int rows = Rows;
  867. int cols = Cols;
  868. Console.CursorTop = 0;
  869. Console.CursorLeft = 0;
  870. for (int row = 0; row < rows; row++) {
  871. dirtyLine [row] = false;
  872. for (int col = 0; col < cols; col++) {
  873. contents [row, col, 2] = 0;
  874. var color = contents [row, col, 1];
  875. if (color != redrawColor)
  876. SetColor (color);
  877. Console.Write ((char)contents [row, col, 0]);
  878. }
  879. }
  880. }
  881. public override void Refresh ()
  882. {
  883. int rows = Rows;
  884. int cols = Cols;
  885. var savedRow = Console.CursorTop;
  886. var savedCol = Console.CursorLeft;
  887. for (int row = 0; row < rows; row++) {
  888. if (!dirtyLine [row])
  889. continue;
  890. dirtyLine [row] = false;
  891. for (int col = 0; col < cols; col++) {
  892. if (contents [row, col, 2] != 1)
  893. continue;
  894. Console.CursorTop = row;
  895. Console.CursorLeft = col;
  896. for (; col < cols && contents [row, col, 2] == 1; col++) {
  897. var color = contents [row, col, 1];
  898. if (color != redrawColor)
  899. SetColor (color);
  900. Console.Write ((char)contents [row, col, 0]);
  901. contents [row, col, 2] = 0;
  902. }
  903. }
  904. }
  905. Console.CursorTop = savedRow;
  906. Console.CursorLeft = savedCol;
  907. }
  908. public override void UpdateCursor ()
  909. {
  910. //
  911. }
  912. public override void StartReportingMouseMoves()
  913. {
  914. }
  915. public override void StopReportingMouseMoves ()
  916. {
  917. }
  918. public override void Suspend ()
  919. {
  920. }
  921. int currentAttribute;
  922. public override void SetAttribute (Attribute c)
  923. {
  924. currentAttribute = c.value;
  925. }
  926. Key MapKey (ConsoleKeyInfo keyInfo)
  927. {
  928. switch (keyInfo.Key) {
  929. case ConsoleKey.Escape:
  930. return Key.Esc;
  931. case ConsoleKey.Tab:
  932. return Key.Tab;
  933. case ConsoleKey.Home:
  934. return Key.Home;
  935. case ConsoleKey.End:
  936. return Key.End;
  937. case ConsoleKey.LeftArrow:
  938. return Key.CursorLeft;
  939. case ConsoleKey.RightArrow:
  940. return Key.CursorRight;
  941. case ConsoleKey.UpArrow:
  942. return Key.CursorUp;
  943. case ConsoleKey.DownArrow:
  944. return Key.CursorDown;
  945. case ConsoleKey.PageUp:
  946. return Key.PageUp;
  947. case ConsoleKey.PageDown:
  948. return Key.PageDown;
  949. case ConsoleKey.Enter:
  950. return Key.Enter;
  951. case ConsoleKey.Spacebar:
  952. return Key.Space;
  953. case ConsoleKey.Backspace:
  954. return Key.Backspace;
  955. case ConsoleKey.Delete:
  956. return Key.Delete;
  957. }
  958. var key = keyInfo.Key;
  959. if (key >= ConsoleKey.A && key <= ConsoleKey.Z){
  960. var delta = key - ConsoleKey.A;
  961. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  962. return (Key)((uint)Key.ControlA + delta);
  963. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  964. return (Key) (((uint)Key.AltMask) | ((uint)'A' + delta));
  965. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  966. return (Key)((uint)'A' + delta);
  967. else
  968. return (Key)((uint)'a' + delta);
  969. }
  970. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  971. var delta = key - ConsoleKey.F1;
  972. return (Key)((int) Key.F1 + delta);
  973. }
  974. return (Key)(0xffffffff);
  975. }
  976. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  977. {
  978. mainLoop.WindowsKeyPressed = delegate (ConsoleKeyInfo consoleKey) {
  979. var map = MapKey (consoleKey);
  980. if (map == (Key) 0xffffffff)
  981. return;
  982. keyHandler (new KeyEvent (map));
  983. };
  984. }
  985. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  986. {
  987. throw new NotImplementedException ();
  988. }
  989. public override void SetColors (short foregroundColorId, short backgroundColorId)
  990. {
  991. throw new NotImplementedException ();
  992. }
  993. public override void CookMouse ()
  994. {
  995. }
  996. public override void UncookMouse ()
  997. {
  998. }
  999. //
  1000. // These are for the .NET driver, but running natively on Windows, wont run
  1001. // on the Mono emulation
  1002. //
  1003. }
  1004. internal class WindowsConsole {
  1005. public const int STD_OUTPUT_HANDLE = -11;
  1006. public const int STD_INPUT_HANDLE = -10;
  1007. public const int STD_ERROR_HANDLE = -12;
  1008. [DllImport ("kernel32.dll", SetLastError = true)]
  1009. static extern IntPtr GetStdHandle (int nStdHandle);
  1010. IntPtr inputHandle, outputHandle;
  1011. public WindowsConsole ()
  1012. {
  1013. inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  1014. outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  1015. }
  1016. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  1017. public struct KeyEventRecord {
  1018. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  1019. public bool bKeyDown;
  1020. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  1021. public ushort wRepeatCount;
  1022. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  1023. public ushort wVirtualKeyCode;
  1024. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  1025. public ushort wVirtualScanCode;
  1026. [FieldOffset (10)]
  1027. public char UnicodeChar;
  1028. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  1029. public ControlKeyState dwControlKeyState;
  1030. }
  1031. [Flags]
  1032. public enum ButtonState {
  1033. Button1Pressed = 1,
  1034. Button2Pressed = 4,
  1035. Button3Pressed = 8,
  1036. Button4Pressed = 16,
  1037. RightmostButtonPressed = 2,
  1038. }
  1039. [Flags]
  1040. public enum ControlKeyState {
  1041. RightAltPressed = 1,
  1042. LeftAltPressed = 2,
  1043. RightControlPressed = 4,
  1044. LeftControlPressed = 8,
  1045. ShiftPressed = 16,
  1046. NumlockOn = 32,
  1047. ScrolllockOn = 64,
  1048. CapslockOn = 128,
  1049. EnhancedKey = 256
  1050. }
  1051. [Flags]
  1052. public enum EventFlags {
  1053. MouseMoved = 1,
  1054. DoubleClick = 2,
  1055. MouseWheeled = 4,
  1056. MouseHorizontalWheeled = 8
  1057. }
  1058. [StructLayout (LayoutKind.Explicit)]
  1059. public struct MouseEventRecord {
  1060. [FieldOffset (0)]
  1061. public Coordinate MousePosition;
  1062. [FieldOffset (4)]
  1063. public ButtonState ButtonState;
  1064. [FieldOffset (8)]
  1065. public ControlKeyState ControlKeyState;
  1066. [FieldOffset (12)]
  1067. public EventFlags EventFlags;
  1068. public override string ToString ()
  1069. {
  1070. return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  1071. }
  1072. }
  1073. [StructLayout (LayoutKind.Sequential)]
  1074. public struct Coordinate {
  1075. public short X;
  1076. public short Y;
  1077. public Coordinate (short X, short Y)
  1078. {
  1079. this.X = X;
  1080. this.Y = Y;
  1081. }
  1082. public override string ToString () => $"({X},{Y})";
  1083. };
  1084. internal struct WindowBufferSizeRecord {
  1085. public Coordinate size;
  1086. public WindowBufferSizeRecord (short x, short y)
  1087. {
  1088. this.size = new Coordinate (x, y);
  1089. }
  1090. public override string ToString () => $"[WindowBufferSize{size}";
  1091. }
  1092. [StructLayout (LayoutKind.Sequential)]
  1093. public struct MenuEventRecord {
  1094. public uint dwCommandId;
  1095. }
  1096. [StructLayout (LayoutKind.Sequential)]
  1097. public struct FocusEventRecord {
  1098. public uint bSetFocus;
  1099. }
  1100. public enum EventType {
  1101. Focus = 0x10,
  1102. Key = 0x1,
  1103. Menu = 0x8,
  1104. Mouse = 2,
  1105. WindowBufferSize = 4
  1106. }
  1107. [StructLayout (LayoutKind.Explicit)]
  1108. public struct InputRecord {
  1109. [FieldOffset (0)]
  1110. public EventType EventType;
  1111. [FieldOffset (4)]
  1112. public KeyEventRecord KeyEvent;
  1113. [FieldOffset (4)]
  1114. public MouseEventRecord MouseEvent;
  1115. [FieldOffset (4)]
  1116. public WindowBufferSizeRecord WindowBufferSizeEvent;
  1117. [FieldOffset (4)]
  1118. public MenuEventRecord MenuEvent;
  1119. [FieldOffset (4)]
  1120. public FocusEventRecord FocusEvent;
  1121. public override string ToString ()
  1122. {
  1123. switch (EventType) {
  1124. case EventType.Focus:
  1125. return FocusEvent.ToString ();
  1126. case EventType.Key:
  1127. return KeyEvent.ToString ();
  1128. case EventType.Menu:
  1129. return MenuEvent.ToString ();
  1130. case EventType.Mouse:
  1131. return MouseEvent.ToString ();
  1132. case EventType.WindowBufferSize:
  1133. return WindowBufferSizeEvent.ToString ();
  1134. default:
  1135. return "Unknown event type: " + EventType;
  1136. }
  1137. }
  1138. };
  1139. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  1140. public static extern bool ReadConsoleInput (
  1141. IntPtr hConsoleInput,
  1142. [Out] InputRecord [] lpBuffer,
  1143. uint nLength,
  1144. out uint lpNumberOfEventsRead);
  1145. [DllImport ("kernel32.dll")]
  1146. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  1147. [DllImport ("kernel32.dll")]
  1148. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  1149. public uint ConsoleMode {
  1150. get {
  1151. uint v;
  1152. GetConsoleMode (inputHandle, out v);
  1153. return v;
  1154. }
  1155. set {
  1156. SetConsoleMode (inputHandle, value);
  1157. }
  1158. }
  1159. }
  1160. }