ConsoleDriver.cs 49 KB

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