ConsoleDriver.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. //
  2. // ConsoleDriver.cs: Base class for Terminal.Gui ConsoleDriver implementations.
  3. //
  4. using NStack;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Runtime.CompilerServices;
  11. using System.Threading.Tasks;
  12. namespace Terminal.Gui {
  13. /// <summary>
  14. /// Colors that can be used to set the foreground and background colors in console applications.
  15. /// </summary>
  16. /// <remarks>
  17. /// The <see cref="Color.Invalid"/> value indicates either no-color has been set or the color is invalid.
  18. /// </remarks>
  19. public enum Color {
  20. /// <summary>
  21. /// The black color.
  22. /// </summary>
  23. Black,
  24. /// <summary>
  25. /// The blue color.
  26. /// </summary>
  27. Blue,
  28. /// <summary>
  29. /// The green color.
  30. /// </summary>
  31. Green,
  32. /// <summary>
  33. /// The cyan color.
  34. /// </summary>
  35. Cyan,
  36. /// <summary>
  37. /// The red color.
  38. /// </summary>
  39. Red,
  40. /// <summary>
  41. /// The magenta color.
  42. /// </summary>
  43. Magenta,
  44. /// <summary>
  45. /// The brown color.
  46. /// </summary>
  47. Brown,
  48. /// <summary>
  49. /// The gray color.
  50. /// </summary>
  51. Gray,
  52. /// <summary>
  53. /// The dark gray color.
  54. /// </summary>
  55. DarkGray,
  56. /// <summary>
  57. /// The bright bBlue color.
  58. /// </summary>
  59. BrightBlue,
  60. /// <summary>
  61. /// The bright green color.
  62. /// </summary>
  63. BrightGreen,
  64. /// <summary>
  65. /// The bright cyan color.
  66. /// </summary>
  67. BrightCyan,
  68. /// <summary>
  69. /// The bright red color.
  70. /// </summary>
  71. BrightRed,
  72. /// <summary>
  73. /// The bright magenta color.
  74. /// </summary>
  75. BrightMagenta,
  76. /// <summary>
  77. /// The bright yellow color.
  78. /// </summary>
  79. BrightYellow,
  80. /// <summary>
  81. /// The White color.
  82. /// </summary>
  83. White,
  84. /// <summary>
  85. /// Indicates an invalid or un-set color value.
  86. /// </summary>
  87. Invalid = -1
  88. }
  89. /// <summary>
  90. ///
  91. /// </summary>
  92. public class TrueColor {
  93. /// <summary>
  94. /// Red color component.
  95. /// </summary>
  96. public int Red { get; }
  97. /// <summary>
  98. /// Green color component.
  99. /// </summary>
  100. public int Green { get; }
  101. /// <summary>
  102. /// Blue color component.
  103. /// </summary>
  104. public int Blue { get; }
  105. /// <summary>
  106. /// Initializes a new instance of the <see cref="TrueColor"/> struct.
  107. /// </summary>
  108. /// <param name="red"></param>
  109. /// <param name="green"></param>
  110. /// <param name="blue"></param>
  111. public TrueColor (int red, int green, int blue)
  112. {
  113. Red = red;
  114. Green = green;
  115. Blue = blue;
  116. }
  117. /// <summary>
  118. ///
  119. /// </summary>
  120. /// <returns></returns>
  121. public Color ToConsoleColor ()
  122. {
  123. var trueColorMap = new Dictionary<TrueColor, Color> () {
  124. { new TrueColor (0,0,0),Color.Black},
  125. { new TrueColor (0, 0, 0x80),Color.Blue},
  126. { new TrueColor (0, 0x80, 0),Color.Green},
  127. { new TrueColor (0, 0x80, 0x80),Color.Cyan},
  128. { new TrueColor (0x80, 0, 0),Color.Red},
  129. { new TrueColor (0x80, 0, 0x80),Color.Magenta},
  130. { new TrueColor (0xC1, 0x9C, 0x00),Color.Brown}, // TODO confirm this
  131. { new TrueColor (0xC0, 0xC0, 0xC0),Color.Gray},
  132. { new TrueColor (0x80, 0x80, 0x80),Color.DarkGray},
  133. { new TrueColor (0, 0, 0xFF),Color.BrightBlue},
  134. { new TrueColor (0, 0xFF, 0),Color.BrightGreen},
  135. { new TrueColor (0, 0xFF, 0xFF),Color.BrightCyan},
  136. { new TrueColor (0xFF, 0, 0),Color.BrightRed},
  137. { new TrueColor (0xFF, 0, 0xFF),Color.BrightMagenta },
  138. { new TrueColor (0xFF, 0xFF, 0),Color.BrightYellow},
  139. { new TrueColor (0xFF, 0xFF, 0xFF),Color.White},
  140. };
  141. // Iterate over all colors in the map
  142. var distances = trueColorMap.Select (
  143. k => Tuple.Create (
  144. // the candidate we are considering matching against (RGB)
  145. k.Key,
  146. CalculateDistance (k.Key, this)
  147. ));
  148. // get the closest
  149. var match = distances.OrderBy (t => t.Item2).First ();
  150. return trueColorMap [match.Item1];
  151. }
  152. private float CalculateDistance (TrueColor color1, TrueColor color2)
  153. {
  154. // use RGB distance
  155. return
  156. Math.Abs (color1.Red - color2.Red) +
  157. Math.Abs (color1.Green - color2.Green) +
  158. Math.Abs (color1.Blue - color2.Blue);
  159. }
  160. }
  161. /// <summary>
  162. /// Attributes are used as elements that contain both a foreground and a background or platform specific features.
  163. /// </summary>
  164. /// <remarks>
  165. /// <see cref="Attribute"/>s are needed to map colors to terminal capabilities that might lack colors.
  166. /// They encode both the foreground and the background color and are used in the <see cref="ColorScheme"/>
  167. /// class to define color schemes that can be used in an application.
  168. /// </remarks>
  169. public struct Attribute {
  170. /// <summary>
  171. /// The <see cref="ConsoleDriver"/>-specific color attribute value. If <see cref="Initialized"/> is <see langword="false"/>
  172. /// the value of this property is invalid (typcially because the Attribute was created before a driver was loaded)
  173. /// and the attribute should be re-made (see <see cref="Make(Color, Color)"/>) before it is used.
  174. /// </summary>
  175. public int Value { get; }
  176. /// <summary>
  177. /// The foreground color.
  178. /// </summary>
  179. public Color Foreground { get; }
  180. /// <summary>
  181. /// The background color.
  182. /// </summary>
  183. public Color Background { get; }
  184. /// <summary>
  185. /// Initializes a new instance of the <see cref="Attribute"/> struct with only the value passed to
  186. /// and trying to get the colors if defined.
  187. /// </summary>
  188. /// <param name="value">Value.</param>
  189. public Attribute (int value)
  190. {
  191. Color foreground = Color.Invalid;
  192. Color background = Color.Invalid;
  193. Initialized = false;
  194. if (Application.Driver != null) {
  195. Application.Driver.GetColors (value, out foreground, out background);
  196. Initialized = true;
  197. }
  198. Value = value;
  199. Foreground = foreground;
  200. Background = background;
  201. }
  202. /// <summary>
  203. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  204. /// </summary>
  205. /// <param name="value">Value.</param>
  206. /// <param name="foreground">Foreground</param>
  207. /// <param name="background">Background</param>
  208. public Attribute (int value, Color foreground, Color background)
  209. {
  210. Value = value;
  211. Foreground = foreground;
  212. Background = background;
  213. Initialized = true;
  214. }
  215. /// <summary>
  216. /// Initializes a new instance of the <see cref="Attribute"/> struct.
  217. /// </summary>
  218. /// <param name="foreground">Foreground</param>
  219. /// <param name="background">Background</param>
  220. public Attribute (Color foreground = new Color (), Color background = new Color ())
  221. {
  222. var make = Make (foreground, background);
  223. Initialized = make.Initialized;
  224. Value = make.Value;
  225. Foreground = foreground;
  226. Background = background;
  227. }
  228. /// <summary>
  229. /// Initializes a new instance of the <see cref="Attribute"/> struct
  230. /// with the same colors for the foreground and background.
  231. /// </summary>
  232. /// <param name="color">The color.</param>
  233. public Attribute (Color color) : this (color, color) { }
  234. /// <summary>
  235. /// Implicit conversion from an <see cref="Attribute"/> to the underlying, driver-specific, Int32 representation
  236. /// of the color.
  237. /// </summary>
  238. /// <returns>The driver-specific color value stored in the attribute.</returns>
  239. /// <param name="c">The attribute to convert</param>
  240. public static implicit operator int (Attribute c)
  241. {
  242. if (!c.Initialized) throw new InvalidOperationException ("Attribute: Attributes must be initialized by a driver before use.");
  243. return c.Value;
  244. }
  245. /// <summary>
  246. /// Implicitly convert an driver-specific color value into an <see cref="Attribute"/>
  247. /// </summary>
  248. /// <returns>An attribute with the specified driver-specific color value.</returns>
  249. /// <param name="v">value</param>
  250. public static implicit operator Attribute (int v) => new Attribute (v);
  251. /// <summary>
  252. /// Creates an <see cref="Attribute"/> from the specified foreground and background colors.
  253. /// </summary>
  254. /// <remarks>
  255. /// If a <see cref="ConsoleDriver"/> has not been loaded (<c>Application.Driver == null</c>) this
  256. /// method will return an attribute with <see cref="Initialized"/> set to <see langword="false"/>.
  257. /// </remarks>
  258. /// <returns>The new attribute.</returns>
  259. /// <param name="foreground">Foreground color to use.</param>
  260. /// <param name="background">Background color to use.</param>
  261. public static Attribute Make (Color foreground, Color background)
  262. {
  263. if (Application.Driver == null) {
  264. // Create the attribute, but show it's not been initialized
  265. var a = new Attribute (-1, foreground, background);
  266. a.Initialized = false;
  267. return a;
  268. }
  269. return Application.Driver.MakeAttribute (foreground, background);
  270. }
  271. /// <summary>
  272. /// Gets the current <see cref="Attribute"/> from the driver.
  273. /// </summary>
  274. /// <returns>The current attribute.</returns>
  275. public static Attribute Get ()
  276. {
  277. if (Application.Driver == null)
  278. throw new InvalidOperationException ("The Application has not been initialized");
  279. return Application.Driver.GetAttribute ();
  280. }
  281. /// <summary>
  282. /// If <see langword="true"/> the attribute has been initialzed by a <see cref="ConsoleDriver"/> and
  283. /// thus has <see cref="Value"/> that is valid for that driver. If <see langword="false"/> the <see cref="Foreground"/>
  284. /// and <see cref="Background"/> colors may have been set (see <see cref="Color.Invalid"/>) but
  285. /// the attribute has not been mapped to a <see cref="ConsoleDriver"/> specific color value.
  286. /// </summary>
  287. /// <remarks>
  288. /// Attributes that have not been initialized must eventually be initialized before being passed to a driver.
  289. /// </remarks>
  290. public bool Initialized { get; internal set; }
  291. /// <summary>
  292. /// Returns <see langword="true"/> if the Atrribute is valid (both foreground and background have valid color values).
  293. /// </summary>
  294. /// <returns></returns>
  295. public bool HasValidColors {
  296. get {
  297. return Foreground != Color.Invalid && Background != Color.Invalid;
  298. }
  299. }
  300. }
  301. /// <summary>
  302. /// Defines the color <see cref="Attribute"/>s for common visible elements in a <see cref="View"/>.
  303. /// Containers such as <see cref="Window"/> and <see cref="FrameView"/> use <see cref="ColorScheme"/> to determine
  304. /// the colors used by sub-views.
  305. /// </summary>
  306. /// <remarks>
  307. /// See also: <see cref="Colors.ColorSchemes"/>.
  308. /// </remarks>
  309. public class ColorScheme : IEquatable<ColorScheme> {
  310. Attribute _normal = new Attribute(Color.White, Color.Black);
  311. Attribute _focus = new Attribute (Color.White, Color.Black);
  312. Attribute _hotNormal = new Attribute (Color.White, Color.Black);
  313. Attribute _hotFocus = new Attribute (Color.White, Color.Black);
  314. Attribute _disabled = new Attribute (Color.White, Color.Black);
  315. /// <summary>
  316. /// Used by <see cref="Colors.SetColorScheme(ColorScheme, string)"/> and <see cref="Colors.GetColorScheme(string)"/> to track which ColorScheme
  317. /// is being accessed.
  318. /// </summary>
  319. internal string schemeBeingSet = "";
  320. /// <summary>
  321. /// The foreground and background color for text when the view is not focused, hot, or disabled.
  322. /// </summary>
  323. public Attribute Normal {
  324. get { return _normal; }
  325. set {
  326. if (!value.HasValidColors) {
  327. return;
  328. }
  329. _normal = value;
  330. }
  331. }
  332. /// <summary>
  333. /// The foreground and background color for text when the view has the focus.
  334. /// </summary>
  335. public Attribute Focus {
  336. get { return _focus; }
  337. set {
  338. if (!value.HasValidColors) {
  339. return;
  340. }
  341. _focus = value;
  342. }
  343. }
  344. /// <summary>
  345. /// The foreground and background color for text when the view is highlighted (hot).
  346. /// </summary>
  347. public Attribute HotNormal {
  348. get { return _hotNormal; }
  349. set {
  350. if (!value.HasValidColors) {
  351. return;
  352. }
  353. _hotNormal = value;
  354. }
  355. }
  356. /// <summary>
  357. /// The foreground and background color for text when the view is highlighted (hot) and has focus.
  358. /// </summary>
  359. public Attribute HotFocus {
  360. get { return _hotFocus; }
  361. set {
  362. if (!value.HasValidColors) {
  363. return;
  364. }
  365. _hotFocus = value;
  366. }
  367. }
  368. /// <summary>
  369. /// The default foreground and background color for text, when the view is disabled.
  370. /// </summary>
  371. public Attribute Disabled {
  372. get { return _disabled; }
  373. set {
  374. if (!value.HasValidColors) {
  375. return;
  376. }
  377. _disabled = value;
  378. }
  379. }
  380. /// <summary>
  381. /// Compares two <see cref="ColorScheme"/> objects for equality.
  382. /// </summary>
  383. /// <param name="obj"></param>
  384. /// <returns>true if the two objects are equal</returns>
  385. public override bool Equals (object obj)
  386. {
  387. return Equals (obj as ColorScheme);
  388. }
  389. /// <summary>
  390. /// Compares two <see cref="ColorScheme"/> objects for equality.
  391. /// </summary>
  392. /// <param name="other"></param>
  393. /// <returns>true if the two objects are equal</returns>
  394. public bool Equals (ColorScheme other)
  395. {
  396. return other != null &&
  397. EqualityComparer<Attribute>.Default.Equals (_normal, other._normal) &&
  398. EqualityComparer<Attribute>.Default.Equals (_focus, other._focus) &&
  399. EqualityComparer<Attribute>.Default.Equals (_hotNormal, other._hotNormal) &&
  400. EqualityComparer<Attribute>.Default.Equals (_hotFocus, other._hotFocus) &&
  401. EqualityComparer<Attribute>.Default.Equals (_disabled, other._disabled);
  402. }
  403. /// <summary>
  404. /// Returns a hashcode for this instance.
  405. /// </summary>
  406. /// <returns>hashcode for this instance</returns>
  407. public override int GetHashCode ()
  408. {
  409. int hashCode = -1242460230;
  410. hashCode = hashCode * -1521134295 + _normal.GetHashCode ();
  411. hashCode = hashCode * -1521134295 + _focus.GetHashCode ();
  412. hashCode = hashCode * -1521134295 + _hotNormal.GetHashCode ();
  413. hashCode = hashCode * -1521134295 + _hotFocus.GetHashCode ();
  414. hashCode = hashCode * -1521134295 + _disabled.GetHashCode ();
  415. return hashCode;
  416. }
  417. /// <summary>
  418. /// Compares two <see cref="ColorScheme"/> objects for equality.
  419. /// </summary>
  420. /// <param name="left"></param>
  421. /// <param name="right"></param>
  422. /// <returns><c>true</c> if the two objects are equivalent</returns>
  423. public static bool operator == (ColorScheme left, ColorScheme right)
  424. {
  425. return EqualityComparer<ColorScheme>.Default.Equals (left, right);
  426. }
  427. /// <summary>
  428. /// Compares two <see cref="ColorScheme"/> objects for inequality.
  429. /// </summary>
  430. /// <param name="left"></param>
  431. /// <param name="right"></param>
  432. /// <returns><c>true</c> if the two objects are not equivalent</returns>
  433. public static bool operator != (ColorScheme left, ColorScheme right)
  434. {
  435. return !(left == right);
  436. }
  437. internal void Initialize ()
  438. {
  439. // If the new scheme was created before a driver was loaded, we need to re-make
  440. // the attributes
  441. if (!_normal.Initialized) {
  442. _normal = new Attribute (_normal.Foreground, _normal.Background);
  443. }
  444. if (!_focus.Initialized) {
  445. _focus = new Attribute (_focus.Foreground, _focus.Background);
  446. }
  447. if (!_hotNormal.Initialized) {
  448. _hotNormal = new Attribute (_hotNormal.Foreground, _hotNormal.Background);
  449. }
  450. if (!_hotFocus.Initialized) {
  451. _hotFocus = new Attribute (_hotFocus.Foreground, _hotFocus.Background);
  452. }
  453. if (!_disabled.Initialized) {
  454. _disabled = new Attribute (_disabled.Foreground, _disabled.Background);
  455. }
  456. }
  457. }
  458. /// <summary>
  459. /// The default <see cref="ColorScheme"/>s for the application.
  460. /// </summary>
  461. /// <remarks>
  462. /// This property can be set in a Theme to change the default <see cref="Colors"/> for the application.
  463. /// </remarks>
  464. public static class Colors {
  465. private class SchemeNameComparerIgnoreCase : IEqualityComparer<string> {
  466. public bool Equals (string x, string y)
  467. {
  468. if (x != null && y != null) {
  469. return x.ToLowerInvariant () == y.ToLowerInvariant ();
  470. }
  471. return false;
  472. }
  473. public int GetHashCode (string obj)
  474. {
  475. return obj.ToLowerInvariant ().GetHashCode ();
  476. }
  477. }
  478. static Colors ()
  479. {
  480. ColorSchemes = Create ();
  481. }
  482. /// <summary>
  483. /// Creates a new dictionary of new <see cref="ColorScheme"/> objects.
  484. /// </summary>
  485. public static Dictionary<string, ColorScheme> Create ()
  486. {
  487. // Use reflection to dynamically create the default set of ColorSchemes from the list defined
  488. // by the class.
  489. return typeof (Colors).GetProperties ()
  490. .Where (p => p.PropertyType == typeof (ColorScheme))
  491. .Select (p => new KeyValuePair<string, ColorScheme> (p.Name, new ColorScheme()))
  492. .ToDictionary (t => t.Key, t => t.Value, comparer: new SchemeNameComparerIgnoreCase ());
  493. }
  494. /// <summary>
  495. /// The application toplevel color scheme, for the default toplevel views.
  496. /// </summary>
  497. /// <remarks>
  498. /// <para>
  499. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["TopLevel"];</c>
  500. /// </para>
  501. /// </remarks>
  502. public static ColorScheme TopLevel { get => GetColorScheme (); set => SetColorScheme (value); }
  503. /// <summary>
  504. /// The base color scheme, for the default toplevel views.
  505. /// </summary>
  506. /// <remarks>
  507. /// <para>
  508. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Base"];</c>
  509. /// </para>
  510. /// </remarks>
  511. public static ColorScheme Base { get => GetColorScheme (); set => SetColorScheme (value); }
  512. /// <summary>
  513. /// The dialog color scheme, for standard popup dialog boxes
  514. /// </summary>
  515. /// <remarks>
  516. /// <para>
  517. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Dialog"];</c>
  518. /// </para>
  519. /// </remarks>
  520. public static ColorScheme Dialog { get => GetColorScheme (); set => SetColorScheme (value); }
  521. /// <summary>
  522. /// The menu bar color
  523. /// </summary>
  524. /// <remarks>
  525. /// <para>
  526. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Menu"];</c>
  527. /// </para>
  528. /// </remarks>
  529. public static ColorScheme Menu { get => GetColorScheme (); set => SetColorScheme (value); }
  530. /// <summary>
  531. /// The color scheme for showing errors.
  532. /// </summary>
  533. /// <remarks>
  534. /// <para>
  535. /// This API will be deprecated in the future. Use <see cref="Colors.ColorSchemes"/> instead (e.g. <c>edit.ColorScheme = Colors.ColorSchemes["Error"];</c>
  536. /// </para>
  537. /// </remarks>
  538. public static ColorScheme Error { get => GetColorScheme (); set => SetColorScheme (value); }
  539. static ColorScheme GetColorScheme ([CallerMemberName] string schemeBeingSet = null)
  540. {
  541. return ColorSchemes [schemeBeingSet];
  542. }
  543. static void SetColorScheme (ColorScheme colorScheme, [CallerMemberName] string schemeBeingSet = null)
  544. {
  545. ColorSchemes [schemeBeingSet] = colorScheme;
  546. colorScheme.schemeBeingSet = schemeBeingSet;
  547. }
  548. /// <summary>
  549. /// Provides the defined <see cref="ColorScheme"/>s.
  550. /// </summary>
  551. public static Dictionary<string, ColorScheme> ColorSchemes { get; private set; }
  552. }
  553. /// <summary>
  554. /// Cursors Visibility that are displayed
  555. /// </summary>
  556. //
  557. // Hexa value are set as 0xAABBCCDD where :
  558. //
  559. // AA stand for the TERMINFO DECSUSR parameter value to be used under Linux & MacOS
  560. // BB stand for the NCurses curs_set parameter value to be used under Linux & MacOS
  561. // CC stand for the CONSOLE_CURSOR_INFO.bVisible parameter value to be used under Windows
  562. // DD stand for the CONSOLE_CURSOR_INFO.dwSize parameter value to be used under Windows
  563. //
  564. public enum CursorVisibility {
  565. /// <summary>
  566. /// Cursor caret has default
  567. /// </summary>
  568. /// <remarks>Works under Xterm-like terminal otherwise this is equivalent to <see ref="Underscore"/>. This default directly depends of the XTerm user configuration settings so it could be Block, I-Beam, Underline with possible blinking.</remarks>
  569. Default = 0x00010119,
  570. /// <summary>
  571. /// Cursor caret is hidden
  572. /// </summary>
  573. Invisible = 0x03000019,
  574. /// <summary>
  575. /// Cursor caret is normally shown as a blinking underline bar _
  576. /// </summary>
  577. Underline = 0x03010119,
  578. /// <summary>
  579. /// Cursor caret is normally shown as a underline bar _
  580. /// </summary>
  581. /// <remarks>Under Windows, this is equivalent to <see ref="UnderscoreBlinking"/></remarks>
  582. UnderlineFix = 0x04010119,
  583. /// <summary>
  584. /// Cursor caret is displayed a blinking vertical bar |
  585. /// </summary>
  586. /// <remarks>Works under Xterm-like terminal otherwise this is equivalent to <see ref="Underscore"/></remarks>
  587. Vertical = 0x05010119,
  588. /// <summary>
  589. /// Cursor caret is displayed a blinking vertical bar |
  590. /// </summary>
  591. /// <remarks>Works under Xterm-like terminal otherwise this is equivalent to <see ref="Underscore"/></remarks>
  592. VerticalFix = 0x06010119,
  593. /// <summary>
  594. /// Cursor caret is displayed as a blinking block ▉
  595. /// </summary>
  596. Box = 0x01020164,
  597. /// <summary>
  598. /// Cursor caret is displayed a block ▉
  599. /// </summary>
  600. /// <remarks>Works under Xterm-like terminal otherwise this is equivalent to <see ref="Block"/></remarks>
  601. BoxFix = 0x02020164,
  602. }
  603. ///// <summary>
  604. ///// Special characters that can be drawn with
  605. ///// </summary>
  606. //public enum SpecialChar {
  607. // /// <summary>
  608. // /// Horizontal line character.
  609. // /// </summary>
  610. // HLine,
  611. // /// <summary>
  612. // /// Vertical line character.
  613. // /// </summary>
  614. // VLine,
  615. // /// <summary>
  616. // /// Stipple pattern
  617. // /// </summary>
  618. // Stipple,
  619. // /// <summary>
  620. // /// Diamond character
  621. // /// </summary>
  622. // Diamond,
  623. // /// <summary>
  624. // /// Upper left corner
  625. // /// </summary>
  626. // ULCorner,
  627. // /// <summary>
  628. // /// Lower left corner
  629. // /// </summary>
  630. // LLCorner,
  631. // /// <summary>
  632. // /// Upper right corner
  633. // /// </summary>
  634. // URCorner,
  635. // /// <summary>
  636. // /// Lower right corner
  637. // /// </summary>
  638. // LRCorner,
  639. // /// <summary>
  640. // /// Left tee
  641. // /// </summary>
  642. // LeftTee,
  643. // /// <summary>
  644. // /// Right tee
  645. // /// </summary>
  646. // RightTee,
  647. // /// <summary>
  648. // /// Top tee
  649. // /// </summary>
  650. // TopTee,
  651. // /// <summary>
  652. // /// The bottom tee.
  653. // /// </summary>
  654. // BottomTee,
  655. //}
  656. /// <summary>
  657. /// ConsoleDriver is an abstract class that defines the requirements for a console driver.
  658. /// There are currently three implementations: <see cref="CursesDriver"/> (for Unix and Mac), <see cref="WindowsDriver"/>, and <see cref="NetDriver"/> that uses the .NET Console API.
  659. /// </summary>
  660. public abstract class ConsoleDriver {
  661. /// <summary>
  662. /// The handler fired when the terminal is resized.
  663. /// </summary>
  664. protected Action TerminalResized;
  665. /// <summary>
  666. /// The current number of columns in the terminal.
  667. /// </summary>
  668. public abstract int Cols { get; }
  669. /// <summary>
  670. /// The current number of rows in the terminal.
  671. /// </summary>
  672. public abstract int Rows { get; }
  673. /// <summary>
  674. /// The current left in the terminal.
  675. /// </summary>
  676. public abstract int Left { get; }
  677. /// <summary>
  678. /// The current top in the terminal.
  679. /// </summary>
  680. public abstract int Top { get; }
  681. /// <summary>
  682. /// Get the operation system clipboard.
  683. /// </summary>
  684. public abstract IClipboard Clipboard { get; }
  685. /// <summary>
  686. /// If false height is measured by the window height and thus no scrolling.
  687. /// If true then height is measured by the buffer height, enabling scrolling.
  688. /// </summary>
  689. public abstract bool HeightAsBuffer { get; set; }
  690. /// <summary>
  691. /// The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  692. /// </summary>
  693. public virtual int [,,] Contents { get; }
  694. /// <summary>
  695. /// Initializes the driver
  696. /// </summary>
  697. /// <param name="terminalResized">Method to invoke when the terminal is resized.</param>
  698. public abstract void Init (Action terminalResized);
  699. /// <summary>
  700. /// Moves the cursor to the specified column and row.
  701. /// </summary>
  702. /// <param name="col">Column to move the cursor to.</param>
  703. /// <param name="row">Row to move the cursor to.</param>
  704. public abstract void Move (int col, int row);
  705. /// <summary>
  706. /// Adds the specified rune to the display at the current cursor position.
  707. /// </summary>
  708. /// <param name="rune">Rune to add.</param>
  709. public abstract void AddRune (Rune rune);
  710. /// <summary>
  711. /// Ensures a Rune is not a control character and can be displayed by translating characters below 0x20
  712. /// to equivalent, printable, Unicode chars.
  713. /// </summary>
  714. /// <param name="c">Rune to translate</param>
  715. /// <returns></returns>
  716. public static Rune MakePrintable (Rune c)
  717. {
  718. if (c <= 0x1F || (c >= 0X7F && c <= 0x9F)) {
  719. // ASCII (C0) control characters.
  720. // C1 control characters (https://www.aivosto.com/articles/control-characters.html#c1)
  721. return new Rune (c + 0x2400);
  722. }
  723. return c;
  724. }
  725. /// <summary>
  726. /// Ensures that the column and line are in a valid range from the size of the driver.
  727. /// </summary>
  728. /// <param name="col">The column.</param>
  729. /// <param name="row">The row.</param>
  730. /// <param name="clip">The clip.</param>
  731. /// <returns><c>true</c>if it's a valid range,<c>false</c>otherwise.</returns>
  732. public bool IsValidContent (int col, int row, Rect clip) =>
  733. col >= 0 && row >= 0 && col < Cols && row < Rows && clip.Contains (col, row);
  734. /// <summary>
  735. /// Adds the <paramref name="str"/> to the display at the cursor position.
  736. /// </summary>
  737. /// <param name="str">String.</param>
  738. public abstract void AddStr (ustring str);
  739. /// <summary>
  740. /// Prepare the driver and set the key and mouse events handlers.
  741. /// </summary>
  742. /// <param name="mainLoop">The main loop.</param>
  743. /// <param name="keyHandler">The handler for ProcessKey</param>
  744. /// <param name="keyDownHandler">The handler for key down events</param>
  745. /// <param name="keyUpHandler">The handler for key up events</param>
  746. /// <param name="mouseHandler">The handler for mouse events</param>
  747. public abstract void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler);
  748. /// <summary>
  749. /// Updates the screen to reflect all the changes that have been done to the display buffer
  750. /// </summary>
  751. public abstract void Refresh ();
  752. /// <summary>
  753. /// Updates the location of the cursor position
  754. /// </summary>
  755. public abstract void UpdateCursor ();
  756. /// <summary>
  757. /// Retreive the cursor caret visibility
  758. /// </summary>
  759. /// <param name="visibility">The current <see cref="CursorVisibility"/></param>
  760. /// <returns>true upon success</returns>
  761. public abstract bool GetCursorVisibility (out CursorVisibility visibility);
  762. /// <summary>
  763. /// Change the cursor caret visibility
  764. /// </summary>
  765. /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
  766. /// <returns>true upon success</returns>
  767. public abstract bool SetCursorVisibility (CursorVisibility visibility);
  768. /// <summary>
  769. /// Ensure the cursor visibility
  770. /// </summary>
  771. /// <returns>true upon success</returns>
  772. public abstract bool EnsureCursorVisibility ();
  773. /// <summary>
  774. /// Ends the execution of the console driver.
  775. /// </summary>
  776. public abstract void End ();
  777. /// <summary>
  778. /// Resizes the clip area when the screen is resized.
  779. /// </summary>
  780. public abstract void ResizeScreen ();
  781. /// <summary>
  782. /// Reset and recreate the contents and the driver buffer.
  783. /// </summary>
  784. public abstract void UpdateOffScreen ();
  785. /// <summary>
  786. /// Redraws the physical screen with the contents that have been queued up via any of the printing commands.
  787. /// </summary>
  788. public abstract void UpdateScreen ();
  789. /// <summary>
  790. /// The current attribute the driver is using.
  791. /// </summary>
  792. public virtual Attribute CurrentAttribute {
  793. get => currentAttribute;
  794. set {
  795. if (!value.Initialized && value.HasValidColors && Application.Driver != null) {
  796. CurrentAttribute = Application.Driver.MakeAttribute (value.Foreground, value.Background);
  797. return;
  798. }
  799. if (!value.Initialized) Debug.WriteLine ("ConsoleDriver.CurrentAttribute: Attributes must be initialized before use.");
  800. currentAttribute = value;
  801. }
  802. }
  803. /// <summary>
  804. /// Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.
  805. /// </summary>
  806. /// <remarks>
  807. /// Implementations should call <c>base.SetAttribute(c)</c>.
  808. /// </remarks>
  809. /// <param name="c">C.</param>
  810. public virtual void SetAttribute (Attribute c)
  811. {
  812. CurrentAttribute = c;
  813. }
  814. /// <summary>
  815. /// Set Colors from limit sets of colors. Not implemented by any driver: See Issue #2300.
  816. /// </summary>
  817. /// <param name="foreground">Foreground.</param>
  818. /// <param name="background">Background.</param>
  819. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  820. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  821. // that independently with the R, G, B values.
  822. /// <summary>
  823. /// Advanced uses - set colors to any pre-set pairs, you would need to init_color
  824. /// that independently with the R, G, B values. Not implemented by any driver: See Issue #2300.
  825. /// </summary>
  826. /// <param name="foregroundColorId">Foreground color identifier.</param>
  827. /// <param name="backgroundColorId">Background color identifier.</param>
  828. public abstract void SetColors (short foregroundColorId, short backgroundColorId);
  829. /// <summary>
  830. /// Gets the foreground and background colors based on the value.
  831. /// </summary>
  832. /// <param name="value">The value.</param>
  833. /// <param name="foreground">The foreground.</param>
  834. /// <param name="background">The background.</param>
  835. /// <returns></returns>
  836. public abstract bool GetColors (int value, out Color foreground, out Color background);
  837. /// <summary>
  838. /// Allows sending keys without typing on a keyboard.
  839. /// </summary>
  840. /// <param name="keyChar">The character key.</param>
  841. /// <param name="key">The key.</param>
  842. /// <param name="shift">If shift key is sending.</param>
  843. /// <param name="alt">If alt key is sending.</param>
  844. /// <param name="control">If control key is sending.</param>
  845. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control);
  846. /// <summary>
  847. /// Set the handler when the terminal is resized.
  848. /// </summary>
  849. /// <param name="terminalResized"></param>
  850. public void SetTerminalResized (Action terminalResized)
  851. {
  852. TerminalResized = terminalResized;
  853. }
  854. /// <summary>
  855. /// Draws the title for a Window-style view incorporating padding.
  856. /// </summary>
  857. /// <param name="region">Screen relative region where the frame will be drawn.</param>
  858. /// <param name="title">The title for the window. The title will only be drawn if <c>title</c> is not null or empty and paddingTop is greater than 0.</param>
  859. /// <param name="paddingLeft">Number of columns to pad on the left (if 0 the border will not appear on the left).</param>
  860. /// <param name="paddingTop">Number of rows to pad on the top (if 0 the border and title will not appear on the top).</param>
  861. /// <param name="paddingRight">Number of columns to pad on the right (if 0 the border will not appear on the right).</param>
  862. /// <param name="paddingBottom">Number of rows to pad on the bottom (if 0 the border will not appear on the bottom).</param>
  863. /// <param name="textAlignment">Not yet implemented.</param>
  864. /// <remarks></remarks>
  865. public virtual void DrawWindowTitle (Rect region, ustring title, int paddingLeft, int paddingTop, int paddingRight, int paddingBottom, TextAlignment textAlignment = TextAlignment.Left)
  866. {
  867. var width = region.Width - (paddingLeft + 2) * 2;
  868. if (!ustring.IsNullOrEmpty (title) && width > 4 && region.Y + paddingTop <= region.Y + paddingBottom) {
  869. Move (region.X + 1 + paddingLeft, region.Y + paddingTop);
  870. AddRune (' ');
  871. var str = title.Sum (r => Math.Max (Rune.ColumnWidth (r), 1)) >= width
  872. ? TextFormatter.Format (title, width - 2, false, false) [0] : title;
  873. AddStr (str);
  874. AddRune (' ');
  875. }
  876. }
  877. /// <summary>
  878. /// Enables diagnostic functions
  879. /// </summary>
  880. [Flags]
  881. public enum DiagnosticFlags : uint {
  882. /// <summary>
  883. /// All diagnostics off
  884. /// </summary>
  885. Off = 0b_0000_0000,
  886. /// <summary>
  887. /// When enabled, <see cref="DrawWindowFrame(Rect, int, int, int, int, bool, bool, Border)"/> will draw a
  888. /// ruler in the frame for any side with a padding value greater than 0.
  889. /// </summary>
  890. FrameRuler = 0b_0000_0001,
  891. /// <summary>
  892. /// When Enabled, <see cref="DrawWindowFrame(Rect, int, int, int, int, bool, bool, Border)"/> will use
  893. /// 'L', 'R', 'T', and 'B' for padding instead of ' '.
  894. /// </summary>
  895. FramePadding = 0b_0000_0010,
  896. }
  897. /// <summary>
  898. /// Set flags to enable/disable <see cref="ConsoleDriver"/> diagnostics.
  899. /// </summary>
  900. public static DiagnosticFlags Diagnostics { get; set; }
  901. /// <summary>
  902. /// Draws a frame for a window with padding and an optional visible border inside the padding.
  903. /// </summary>
  904. /// <param name="region">Screen relative region where the frame will be drawn.</param>
  905. /// <param name="paddingLeft">Number of columns to pad on the left (if 0 the border will not appear on the left).</param>
  906. /// <param name="paddingTop">Number of rows to pad on the top (if 0 the border and title will not appear on the top).</param>
  907. /// <param name="paddingRight">Number of columns to pad on the right (if 0 the border will not appear on the right).</param>
  908. /// <param name="paddingBottom">Number of rows to pad on the bottom (if 0 the border will not appear on the bottom).</param>
  909. /// <param name="border">If set to <c>true</c> and any padding dimension is > 0 the border will be drawn.</param>
  910. /// <param name="fill">If set to <c>true</c> it will clear the content area (the area inside the padding) with the current color, otherwise the content area will be left untouched.</param>
  911. /// <param name="borderContent">The <see cref="Border"/> to be used if defined.</param>
  912. public virtual void DrawWindowFrame (Rect region, int paddingLeft = 0, int paddingTop = 0, int paddingRight = 0,
  913. int paddingBottom = 0, bool border = true, bool fill = false, Border borderContent = null)
  914. {
  915. char clearChar = ' ';
  916. char leftChar = clearChar;
  917. char rightChar = clearChar;
  918. char topChar = clearChar;
  919. char bottomChar = clearChar;
  920. if ((Diagnostics & DiagnosticFlags.FramePadding) == DiagnosticFlags.FramePadding) {
  921. leftChar = 'L';
  922. rightChar = 'R';
  923. topChar = 'T';
  924. bottomChar = 'B';
  925. clearChar = 'C';
  926. }
  927. void AddRuneAt (int col, int row, Rune ch)
  928. {
  929. Move (col, row);
  930. AddRune (ch);
  931. }
  932. // fwidth is count of hLine chars
  933. int fwidth = (int)(region.Width - (paddingRight + paddingLeft));
  934. // fheight is count of vLine chars
  935. int fheight = (int)(region.Height - (paddingBottom + paddingTop));
  936. // fleft is location of left frame line
  937. int fleft = region.X + paddingLeft - 1;
  938. // fright is location of right frame line
  939. int fright = fleft + fwidth + 1;
  940. // ftop is location of top frame line
  941. int ftop = region.Y + paddingTop - 1;
  942. // fbottom is location of bottom frame line
  943. int fbottom = ftop + fheight + 1;
  944. var borderStyle = borderContent == null ? BorderStyle.Single : borderContent.BorderStyle;
  945. Rune hLine = default, vLine = default,
  946. uRCorner = default, uLCorner = default, lLCorner = default, lRCorner = default;
  947. if (border) {
  948. switch (borderStyle) {
  949. case BorderStyle.None:
  950. break;
  951. case BorderStyle.Single:
  952. hLine = HLine;
  953. vLine = VLine;
  954. uRCorner = URCorner;
  955. uLCorner = ULCorner;
  956. lLCorner = LLCorner;
  957. lRCorner = LRCorner;
  958. break;
  959. case BorderStyle.Double:
  960. hLine = HDLine;
  961. vLine = VDLine;
  962. uRCorner = URDCorner;
  963. uLCorner = ULDCorner;
  964. lLCorner = LLDCorner;
  965. lRCorner = LRDCorner;
  966. break;
  967. case BorderStyle.Rounded:
  968. hLine = HRLine;
  969. vLine = VRLine;
  970. uRCorner = URRCorner;
  971. uLCorner = ULRCorner;
  972. lLCorner = LLRCorner;
  973. lRCorner = LRRCorner;
  974. break;
  975. }
  976. } else {
  977. hLine = vLine = uRCorner = uLCorner = lLCorner = lRCorner = clearChar;
  978. }
  979. // Outside top
  980. if (paddingTop > 1) {
  981. for (int r = region.Y; r < ftop; r++) {
  982. for (int c = region.X; c < region.X + region.Width; c++) {
  983. AddRuneAt (c, r, topChar);
  984. }
  985. }
  986. }
  987. // Outside top-left
  988. for (int c = region.X; c < fleft; c++) {
  989. AddRuneAt (c, ftop, leftChar);
  990. }
  991. // Frame top-left corner
  992. AddRuneAt (fleft, ftop, paddingTop >= 0 ? (paddingLeft >= 0 ? uLCorner : hLine) : leftChar);
  993. // Frame top
  994. for (int c = fleft + 1; c < fleft + 1 + fwidth; c++) {
  995. AddRuneAt (c, ftop, paddingTop > 0 ? hLine : topChar);
  996. }
  997. // Frame top-right corner
  998. if (fright > fleft) {
  999. AddRuneAt (fright, ftop, paddingTop >= 0 ? (paddingRight >= 0 ? uRCorner : hLine) : rightChar);
  1000. }
  1001. // Outside top-right corner
  1002. for (int c = fright + 1; c < fright + paddingRight; c++) {
  1003. AddRuneAt (c, ftop, rightChar);
  1004. }
  1005. // Left, Fill, Right
  1006. if (fbottom > ftop) {
  1007. for (int r = ftop + 1; r < fbottom; r++) {
  1008. // Outside left
  1009. for (int c = region.X; c < fleft; c++) {
  1010. AddRuneAt (c, r, leftChar);
  1011. }
  1012. // Frame left
  1013. AddRuneAt (fleft, r, paddingLeft > 0 ? vLine : leftChar);
  1014. // Fill
  1015. if (fill) {
  1016. for (int x = fleft + 1; x < fright; x++) {
  1017. AddRuneAt (x, r, clearChar);
  1018. }
  1019. }
  1020. // Frame right
  1021. if (fright > fleft) {
  1022. var v = vLine;
  1023. if ((Diagnostics & DiagnosticFlags.FrameRuler) == DiagnosticFlags.FrameRuler) {
  1024. v = (char)(((int)'0') + ((r - ftop) % 10)); // vLine;
  1025. }
  1026. AddRuneAt (fright, r, paddingRight > 0 ? v : rightChar);
  1027. }
  1028. // Outside right
  1029. for (int c = fright + 1; c < fright + paddingRight; c++) {
  1030. AddRuneAt (c, r, rightChar);
  1031. }
  1032. }
  1033. // Outside Bottom
  1034. for (int c = region.X; c < region.X + region.Width; c++) {
  1035. AddRuneAt (c, fbottom, leftChar);
  1036. }
  1037. // Frame bottom-left
  1038. AddRuneAt (fleft, fbottom, paddingLeft > 0 ? lLCorner : leftChar);
  1039. if (fright > fleft) {
  1040. // Frame bottom
  1041. for (int c = fleft + 1; c < fright; c++) {
  1042. var h = hLine;
  1043. if ((Diagnostics & DiagnosticFlags.FrameRuler) == DiagnosticFlags.FrameRuler) {
  1044. h = (char)(((int)'0') + ((c - fleft) % 10)); // hLine;
  1045. }
  1046. AddRuneAt (c, fbottom, paddingBottom > 0 ? h : bottomChar);
  1047. }
  1048. // Frame bottom-right
  1049. AddRuneAt (fright, fbottom, paddingRight > 0 ? (paddingBottom > 0 ? lRCorner : hLine) : rightChar);
  1050. }
  1051. // Outside right
  1052. for (int c = fright + 1; c < fright + paddingRight; c++) {
  1053. AddRuneAt (c, fbottom, rightChar);
  1054. }
  1055. }
  1056. // Out bottom - ensure top is always drawn if we overlap
  1057. if (paddingBottom > 0) {
  1058. for (int r = fbottom + 1; r < fbottom + paddingBottom; r++) {
  1059. for (int c = region.X; c < region.X + region.Width; c++) {
  1060. AddRuneAt (c, r, bottomChar);
  1061. }
  1062. }
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// Draws a frame on the specified region with the specified padding around the frame.
  1067. /// </summary>
  1068. /// <param name="region">Screen relative region where the frame will be drawn.</param>
  1069. /// <param name="padding">Padding to add on the sides.</param>
  1070. /// <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>
  1071. /// <remarks>This API has been superseded by <see cref="DrawWindowFrame(Rect, int, int, int, int, bool, bool, Border)"/>.</remarks>
  1072. /// <remarks>This API is equivalent to calling <c>DrawWindowFrame(Rect, p - 1, p - 1, p - 1, p - 1)</c>. In other words,
  1073. /// A padding value of 0 means there is actually a one cell border.
  1074. /// </remarks>
  1075. public virtual void DrawFrame (Rect region, int padding, bool fill)
  1076. {
  1077. // DrawFrame assumes the border is always at least one row/col thick
  1078. // DrawWindowFrame assumes a padding of 0 means NO padding and no frame
  1079. DrawWindowFrame (new Rect (region.X, region.Y, region.Width, region.Height),
  1080. padding + 1, padding + 1, padding + 1, padding + 1, border: false, fill: fill);
  1081. }
  1082. /// <summary>
  1083. /// Suspend the application, typically needs to save the state, suspend the app and upon return, reset the console driver.
  1084. /// </summary>
  1085. public abstract void Suspend ();
  1086. Rect clip;
  1087. /// <summary>
  1088. /// Controls the current clipping region that AddRune/AddStr is subject to.
  1089. /// </summary>
  1090. /// <value>The clip.</value>
  1091. public Rect Clip {
  1092. get => clip;
  1093. set => this.clip = value;
  1094. }
  1095. /// <summary>
  1096. /// Start of mouse moves.
  1097. /// </summary>
  1098. public abstract void StartReportingMouseMoves ();
  1099. /// <summary>
  1100. /// Stop reporting mouses moves.
  1101. /// </summary>
  1102. public abstract void StopReportingMouseMoves ();
  1103. /// <summary>
  1104. /// Disables the cooked event processing from the mouse driver.
  1105. /// At startup, it is assumed mouse events are cooked. Not implemented by any driver: See Issue #2300.
  1106. /// </summary>
  1107. public abstract void UncookMouse ();
  1108. /// <summary>
  1109. /// Enables the cooked event processing from the mouse driver. Not implemented by any driver: See Issue #2300.
  1110. /// </summary>
  1111. public abstract void CookMouse ();
  1112. /// <summary>
  1113. /// Horizontal line character.
  1114. /// </summary>
  1115. public Rune HLine = '\u2500';
  1116. /// <summary>
  1117. /// Vertical line character.
  1118. /// </summary>
  1119. public Rune VLine = '\u2502';
  1120. /// <summary>
  1121. /// Stipple pattern
  1122. /// </summary>
  1123. public Rune Stipple = '\u2591';
  1124. /// <summary>
  1125. /// Diamond character
  1126. /// </summary>
  1127. public Rune Diamond = '\u25ca';
  1128. /// <summary>
  1129. /// Upper left corner
  1130. /// </summary>
  1131. public Rune ULCorner = '\u250C';
  1132. /// <summary>
  1133. /// Lower left corner
  1134. /// </summary>
  1135. public Rune LLCorner = '\u2514';
  1136. /// <summary>
  1137. /// Upper right corner
  1138. /// </summary>
  1139. public Rune URCorner = '\u2510';
  1140. /// <summary>
  1141. /// Lower right corner
  1142. /// </summary>
  1143. public Rune LRCorner = '\u2518';
  1144. /// <summary>
  1145. /// Left tee
  1146. /// </summary>
  1147. public Rune LeftTee = '\u251c';
  1148. /// <summary>
  1149. /// Right tee
  1150. /// </summary>
  1151. public Rune RightTee = '\u2524';
  1152. /// <summary>
  1153. /// Top tee
  1154. /// </summary>
  1155. public Rune TopTee = '\u252c';
  1156. /// <summary>
  1157. /// The bottom tee.
  1158. /// </summary>
  1159. public Rune BottomTee = '\u2534';
  1160. /// <summary>
  1161. /// Checkmark.
  1162. /// </summary>
  1163. public Rune Checked = '\u221a';
  1164. /// <summary>
  1165. /// Un-checked checkmark.
  1166. /// </summary>
  1167. public Rune UnChecked = '\u2574';
  1168. /// <summary>
  1169. /// Null-checked checkmark.
  1170. /// </summary>
  1171. public Rune NullChecked = '\u2370';
  1172. /// <summary>
  1173. /// Selected mark.
  1174. /// </summary>
  1175. public Rune Selected = '\u25cf';
  1176. /// <summary>
  1177. /// Un-selected selected mark.
  1178. /// </summary>
  1179. public Rune UnSelected = '\u25cc';
  1180. /// <summary>
  1181. /// Right Arrow.
  1182. /// </summary>
  1183. public Rune RightArrow = '\u25ba';
  1184. /// <summary>
  1185. /// Left Arrow.
  1186. /// </summary>
  1187. public Rune LeftArrow = '\u25c4';
  1188. /// <summary>
  1189. /// Down Arrow.
  1190. /// </summary>
  1191. public Rune DownArrow = '\u25bc';
  1192. /// <summary>
  1193. /// Up Arrow.
  1194. /// </summary>
  1195. public Rune UpArrow = '\u25b2';
  1196. /// <summary>
  1197. /// Left indicator for default action (e.g. for <see cref="Button"/>).
  1198. /// </summary>
  1199. public Rune LeftDefaultIndicator = '\u25e6';
  1200. /// <summary>
  1201. /// Right indicator for default action (e.g. for <see cref="Button"/>).
  1202. /// </summary>
  1203. public Rune RightDefaultIndicator = '\u25e6';
  1204. /// <summary>
  1205. /// Left frame/bracket (e.g. '[' for <see cref="Button"/>).
  1206. /// </summary>
  1207. public Rune LeftBracket = '[';
  1208. /// <summary>
  1209. /// Right frame/bracket (e.g. ']' for <see cref="Button"/>).
  1210. /// </summary>
  1211. public Rune RightBracket = ']';
  1212. /// <summary>
  1213. /// Blocks Segment indicator for meter views (e.g. <see cref="ProgressBar"/>.
  1214. /// </summary>
  1215. public Rune BlocksMeterSegment = '\u258c';
  1216. /// <summary>
  1217. /// Continuous Segment indicator for meter views (e.g. <see cref="ProgressBar"/>.
  1218. /// </summary>
  1219. public Rune ContinuousMeterSegment = '\u2588';
  1220. /// <summary>
  1221. /// Horizontal double line character.
  1222. /// </summary>
  1223. public Rune HDLine = '\u2550';
  1224. /// <summary>
  1225. /// Vertical double line character.
  1226. /// </summary>
  1227. public Rune VDLine = '\u2551';
  1228. /// <summary>
  1229. /// Upper left double corner
  1230. /// </summary>
  1231. public Rune ULDCorner = '\u2554';
  1232. /// <summary>
  1233. /// Lower left double corner
  1234. /// </summary>
  1235. public Rune LLDCorner = '\u255a';
  1236. /// <summary>
  1237. /// Upper right double corner
  1238. /// </summary>
  1239. public Rune URDCorner = '\u2557';
  1240. /// <summary>
  1241. /// Lower right double corner
  1242. /// </summary>
  1243. public Rune LRDCorner = '\u255d';
  1244. /// <summary>
  1245. /// Horizontal line character for rounded corners.
  1246. /// </summary>
  1247. public Rune HRLine = '\u2500';
  1248. /// <summary>
  1249. /// Vertical line character for rounded corners.
  1250. /// </summary>
  1251. public Rune VRLine = '\u2502';
  1252. /// <summary>
  1253. /// Upper left rounded corner
  1254. /// </summary>
  1255. public Rune ULRCorner = '\u256d';
  1256. /// <summary>
  1257. /// Lower left rounded corner
  1258. /// </summary>
  1259. public Rune LLRCorner = '\u2570';
  1260. /// <summary>
  1261. /// Upper right rounded corner
  1262. /// </summary>
  1263. public Rune URRCorner = '\u256e';
  1264. /// <summary>
  1265. /// Lower right rounded corner
  1266. /// </summary>
  1267. public Rune LRRCorner = '\u256f';
  1268. private Attribute currentAttribute;
  1269. /// <summary>
  1270. /// Make the attribute for the foreground and background colors.
  1271. /// </summary>
  1272. /// <param name="fore">Foreground.</param>
  1273. /// <param name="back">Background.</param>
  1274. /// <returns></returns>
  1275. public abstract Attribute MakeAttribute (Color fore, Color back);
  1276. /// <summary>
  1277. /// Gets the current <see cref="Attribute"/>.
  1278. /// </summary>
  1279. /// <returns>The current attribute.</returns>
  1280. public Attribute GetAttribute () => CurrentAttribute;
  1281. /// <summary>
  1282. /// Make the <see cref="Colors"/> for the <see cref="ColorScheme"/>.
  1283. /// </summary>
  1284. /// <param name="foreground">The foreground color.</param>
  1285. /// <param name="background">The background color.</param>
  1286. /// <returns>The attribute for the foreground and background colors.</returns>
  1287. public abstract Attribute MakeColor (Color foreground, Color background);
  1288. /// <summary>
  1289. /// Ensures all <see cref="Attribute"/>s in <see cref="Colors.ColorSchemes"/> are correclty
  1290. /// initalized by the driver.
  1291. /// </summary>
  1292. /// <param name="supportsColors">Flag indicating if colors are supported (not used).</param>
  1293. public void InitalizeColorSchemes (bool supportsColors = true)
  1294. {
  1295. // Ensure all Attributes are initlaized by the driver
  1296. foreach (var s in Colors.ColorSchemes) {
  1297. s.Value.Initialize ();
  1298. }
  1299. if (!supportsColors) {
  1300. return;
  1301. }
  1302. // Define the default color theme only if the user has not defined one.
  1303. Colors.TopLevel.Normal = MakeColor (Color.BrightGreen, Color.Black);
  1304. Colors.TopLevel.Focus = MakeColor (Color.White, Color.Cyan);
  1305. Colors.TopLevel.HotNormal = MakeColor (Color.Brown, Color.Black);
  1306. Colors.TopLevel.HotFocus = MakeColor (Color.Blue, Color.Cyan);
  1307. Colors.TopLevel.Disabled = MakeColor (Color.DarkGray, Color.Black);
  1308. Colors.Base.Normal = MakeColor (Color.White, Color.Blue);
  1309. Colors.Base.Focus = MakeColor (Color.Black, Color.Gray);
  1310. Colors.Base.HotNormal = MakeColor (Color.BrightCyan, Color.Blue);
  1311. Colors.Base.HotFocus = MakeColor (Color.BrightBlue, Color.Gray);
  1312. Colors.Base.Disabled = MakeColor (Color.DarkGray, Color.Blue);
  1313. Colors.Dialog.Normal = MakeColor (Color.Black, Color.Gray);
  1314. Colors.Dialog.Focus = MakeColor (Color.White, Color.DarkGray);
  1315. Colors.Dialog.HotNormal = MakeColor (Color.Blue, Color.Gray);
  1316. Colors.Dialog.HotFocus = MakeColor (Color.BrightYellow, Color.DarkGray);
  1317. Colors.Dialog.Disabled = MakeColor (Color.Gray, Color.DarkGray);
  1318. Colors.Menu.Normal = MakeColor (Color.White, Color.DarkGray);
  1319. Colors.Menu.Focus = MakeColor (Color.White, Color.Black);
  1320. Colors.Menu.HotNormal = MakeColor (Color.BrightYellow, Color.DarkGray);
  1321. Colors.Menu.HotFocus = MakeColor (Color.BrightYellow, Color.Black);
  1322. Colors.Menu.Disabled = MakeColor (Color.Gray, Color.DarkGray);
  1323. Colors.Error.Normal = MakeColor (Color.Red, Color.White);
  1324. Colors.Error.Focus = MakeColor (Color.Black, Color.BrightRed);
  1325. Colors.Error.HotNormal = MakeColor (Color.Black, Color.White);
  1326. Colors.Error.HotFocus = MakeColor (Color.White, Color.BrightRed);
  1327. Colors.Error.Disabled = MakeColor (Color.DarkGray, Color.White);
  1328. }
  1329. }
  1330. /// <summary>
  1331. /// Helper class for console drivers to invoke shell commands to interact with the clipboard.
  1332. /// Used primarily by CursesDriver, but also used in Unit tests which is why it is in
  1333. /// ConsoleDriver.cs.
  1334. /// </summary>
  1335. internal static class ClipboardProcessRunner {
  1336. public static (int exitCode, string result) Bash (string commandLine, string inputText = "", bool waitForOutput = false)
  1337. {
  1338. var arguments = $"-c \"{commandLine}\"";
  1339. var (exitCode, result) = Process ("bash", arguments, inputText, waitForOutput);
  1340. return (exitCode, result.TrimEnd ());
  1341. }
  1342. public static (int exitCode, string result) Process (string cmd, string arguments, string input = null, bool waitForOutput = true)
  1343. {
  1344. var output = string.Empty;
  1345. using (Process process = new Process {
  1346. StartInfo = new ProcessStartInfo {
  1347. FileName = cmd,
  1348. Arguments = arguments,
  1349. RedirectStandardOutput = true,
  1350. RedirectStandardError = true,
  1351. RedirectStandardInput = true,
  1352. UseShellExecute = false,
  1353. CreateNoWindow = true,
  1354. }
  1355. }) {
  1356. var eventHandled = new TaskCompletionSource<bool> ();
  1357. process.Start ();
  1358. if (!string.IsNullOrEmpty (input)) {
  1359. process.StandardInput.Write (input);
  1360. process.StandardInput.Close ();
  1361. }
  1362. if (!process.WaitForExit (5000)) {
  1363. var timeoutError = $@"Process timed out. Command line: {process.StartInfo.FileName} {process.StartInfo.Arguments}.";
  1364. throw new TimeoutException (timeoutError);
  1365. }
  1366. if (waitForOutput && process.StandardOutput.Peek () != -1) {
  1367. output = process.StandardOutput.ReadToEnd ();
  1368. }
  1369. if (process.ExitCode > 0) {
  1370. output = $@"Process failed to run. Command line: {cmd} {arguments}.
  1371. Output: {output}
  1372. Error: {process.StandardError.ReadToEnd ()}";
  1373. }
  1374. return (process.ExitCode, output);
  1375. }
  1376. }
  1377. public static bool DoubleWaitForExit (this System.Diagnostics.Process process)
  1378. {
  1379. var result = process.WaitForExit (500);
  1380. if (result) {
  1381. process.WaitForExit ();
  1382. }
  1383. return result;
  1384. }
  1385. public static bool FileExists (this string value)
  1386. {
  1387. return !string.IsNullOrEmpty (value) && !value.Contains ("not found");
  1388. }
  1389. }
  1390. }