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: This functionaliy is currently broken on Windows Terminal.
  639. /// </remarks>
  640. public abstract bool EnableConsoleScrolling { get; set; }
  641. /// <summary>
  642. /// This API is deprecated; use <see cref="EnableConsoleScrolling"/> instead.
  643. /// </summary>
  644. [Obsolete ("This API is deprecated; use EnableConsoleScrolling instead.", false)]
  645. public abstract bool HeightAsBuffer { get; set; }
  646. /// <summary>
  647. /// The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  648. /// </summary>
  649. public virtual int [,,] Contents { get; }
  650. /// <summary>
  651. /// Initializes the driver
  652. /// </summary>
  653. /// <param name="terminalResized">Method to invoke when the terminal is resized.</param>
  654. public abstract void Init (Action terminalResized);
  655. /// <summary>
  656. /// Moves the cursor to the specified column and row.
  657. /// </summary>
  658. /// <param name="col">Column to move the cursor to.</param>
  659. /// <param name="row">Row to move the cursor to.</param>
  660. public abstract void Move (int col, int row);
  661. /// <summary>
  662. /// Adds the specified rune to the display at the current cursor position.
  663. /// </summary>
  664. /// <param name="rune">Rune to add.</param>
  665. public abstract void AddRune (Rune rune);
  666. /// <summary>
  667. /// Ensures a Rune is not a control character and can be displayed by translating characters below 0x20
  668. /// to equivalent, printable, Unicode chars.
  669. /// </summary>
  670. /// <param name="c">Rune to translate</param>
  671. /// <returns></returns>
  672. public static Rune MakePrintable (Rune c)
  673. {
  674. if (c <= 0x1F || (c >= 0X7F && c <= 0x9F)) {
  675. // ASCII (C0) control characters.
  676. // C1 control characters (https://www.aivosto.com/articles/control-characters.html#c1)
  677. return new Rune (c + 0x2400);
  678. }
  679. return c;
  680. }
  681. /// <summary>
  682. /// Ensures that the column and line are in a valid range from the size of the driver.
  683. /// </summary>
  684. /// <param name="col">The column.</param>
  685. /// <param name="row">The row.</param>
  686. /// <param name="clip">The clip.</param>
  687. /// <returns><c>true</c>if it's a valid range,<c>false</c>otherwise.</returns>
  688. public bool IsValidContent (int col, int row, Rect clip) =>
  689. col >= 0 && row >= 0 && col < Cols && row < Rows && clip.Contains (col, row);
  690. /// <summary>
  691. /// Adds the <paramref name="str"/> to the display at the cursor position.
  692. /// </summary>
  693. /// <param name="str">String.</param>
  694. public abstract void AddStr (ustring str);
  695. /// <summary>
  696. /// Prepare the driver and set the key and mouse events handlers.
  697. /// </summary>
  698. /// <param name="mainLoop">The main loop.</param>
  699. /// <param name="keyHandler">The handler for ProcessKey</param>
  700. /// <param name="keyDownHandler">The handler for key down events</param>
  701. /// <param name="keyUpHandler">The handler for key up events</param>
  702. /// <param name="mouseHandler">The handler for mouse events</param>
  703. public abstract void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler);
  704. /// <summary>
  705. /// Updates the screen to reflect all the changes that have been done to the display buffer
  706. /// </summary>
  707. public abstract void Refresh ();
  708. /// <summary>
  709. /// Updates the location of the cursor position
  710. /// </summary>
  711. public abstract void UpdateCursor ();
  712. /// <summary>
  713. /// Retreive the cursor caret visibility
  714. /// </summary>
  715. /// <param name="visibility">The current <see cref="CursorVisibility"/></param>
  716. /// <returns>true upon success</returns>
  717. public abstract bool GetCursorVisibility (out CursorVisibility visibility);
  718. /// <summary>
  719. /// Change the cursor caret visibility
  720. /// </summary>
  721. /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
  722. /// <returns>true upon success</returns>
  723. public abstract bool SetCursorVisibility (CursorVisibility visibility);
  724. /// <summary>
  725. /// Ensure the cursor visibility
  726. /// </summary>
  727. /// <returns>true upon success</returns>
  728. public abstract bool EnsureCursorVisibility ();
  729. /// <summary>
  730. /// Ends the execution of the console driver.
  731. /// </summary>
  732. public abstract void End ();
  733. /// <summary>
  734. /// Resizes the clip area when the screen is resized.
  735. /// </summary>
  736. public abstract void ResizeScreen ();
  737. /// <summary>
  738. /// Reset and recreate the contents and the driver buffer.
  739. /// </summary>
  740. public abstract void UpdateOffScreen ();
  741. /// <summary>
  742. /// Redraws the physical screen with the contents that have been queued up via any of the printing commands.
  743. /// </summary>
  744. public abstract void UpdateScreen ();
  745. /// <summary>
  746. /// The current attribute the driver is using.
  747. /// </summary>
  748. public virtual Attribute CurrentAttribute {
  749. get => currentAttribute;
  750. set {
  751. if (!value.Initialized && value.HasValidColors && Application.Driver != null) {
  752. CurrentAttribute = Application.Driver.MakeAttribute (value.Foreground, value.Background);
  753. return;
  754. }
  755. if (!value.Initialized) Debug.WriteLine ("ConsoleDriver.CurrentAttribute: Attributes must be initialized before use.");
  756. currentAttribute = value;
  757. }
  758. }
  759. /// <summary>
  760. /// Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.
  761. /// </summary>
  762. /// <remarks>
  763. /// Implementations should call <c>base.SetAttribute(c)</c>.
  764. /// </remarks>
  765. /// <param name="c">C.</param>
  766. public virtual void SetAttribute (Attribute c)
  767. {
  768. CurrentAttribute = c;
  769. }
  770. /// <summary>
  771. /// Set Colors from limit sets of colors. Not implemented by any driver: See Issue #2300.
  772. /// </summary>
  773. /// <param name="foreground">Foreground.</param>
  774. /// <param name="background">Background.</param>
  775. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  776. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  777. // that independently with the R, G, B values.
  778. /// <summary>
  779. /// Advanced uses - set colors to any pre-set pairs, you would need to init_color
  780. /// that independently with the R, G, B values. Not implemented by any driver: See Issue #2300.
  781. /// </summary>
  782. /// <param name="foregroundColorId">Foreground color identifier.</param>
  783. /// <param name="backgroundColorId">Background color identifier.</param>
  784. public abstract void SetColors (short foregroundColorId, short backgroundColorId);
  785. /// <summary>
  786. /// Gets the foreground and background colors based on the value.
  787. /// </summary>
  788. /// <param name="value">The value.</param>
  789. /// <param name="foreground">The foreground.</param>
  790. /// <param name="background">The background.</param>
  791. /// <returns></returns>
  792. public abstract bool GetColors (int value, out Color foreground, out Color background);
  793. /// <summary>
  794. /// Allows sending keys without typing on a keyboard.
  795. /// </summary>
  796. /// <param name="keyChar">The character key.</param>
  797. /// <param name="key">The key.</param>
  798. /// <param name="shift">If shift key is sending.</param>
  799. /// <param name="alt">If alt key is sending.</param>
  800. /// <param name="control">If control key is sending.</param>
  801. public abstract void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control);
  802. /// <summary>
  803. /// Set the handler when the terminal is resized.
  804. /// </summary>
  805. /// <param name="terminalResized"></param>
  806. public void SetTerminalResized (Action terminalResized)
  807. {
  808. TerminalResized = terminalResized;
  809. }
  810. /// <summary>
  811. /// Draws the title for a Window-style view incorporating padding.
  812. /// </summary>
  813. /// <param name="region">Screen relative region where the frame will be drawn.</param>
  814. /// <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>
  815. /// <param name="paddingLeft">Number of columns to pad on the left (if 0 the border will not appear on the left).</param>
  816. /// <param name="paddingTop">Number of rows to pad on the top (if 0 the border and title will not appear on the top).</param>
  817. /// <param name="paddingRight">Number of columns to pad on the right (if 0 the border will not appear on the right).</param>
  818. /// <param name="paddingBottom">Number of rows to pad on the bottom (if 0 the border will not appear on the bottom).</param>
  819. /// <param name="textAlignment">Not yet implemented.</param>
  820. /// <remarks></remarks>
  821. public virtual void DrawWindowTitle (Rect region, ustring title, int paddingLeft, int paddingTop, int paddingRight, int paddingBottom, TextAlignment textAlignment = TextAlignment.Left)
  822. {
  823. var width = region.Width - (paddingLeft + 2) * 2;
  824. if (!ustring.IsNullOrEmpty (title) && width > 4 && region.Y + paddingTop <= region.Y + paddingBottom) {
  825. Move (region.X + 1 + paddingLeft, region.Y + paddingTop);
  826. AddRune (' ');
  827. var str = title.Sum (r => Math.Max (Rune.ColumnWidth (r), 1)) >= width
  828. ? TextFormatter.Format (title, width - 2, false, false) [0] : title;
  829. AddStr (str);
  830. AddRune (' ');
  831. }
  832. }
  833. /// <summary>
  834. /// Enables diagnostic functions
  835. /// </summary>
  836. [Flags]
  837. public enum DiagnosticFlags : uint {
  838. /// <summary>
  839. /// All diagnostics off
  840. /// </summary>
  841. Off = 0b_0000_0000,
  842. /// <summary>
  843. /// When enabled, <see cref="DrawWindowFrame(Rect, int, int, int, int, bool, bool, Border)"/> will draw a
  844. /// ruler in the frame for any side with a padding value greater than 0.
  845. /// </summary>
  846. FrameRuler = 0b_0000_0001,
  847. /// <summary>
  848. /// When Enabled, <see cref="DrawWindowFrame(Rect, int, int, int, int, bool, bool, Border)"/> will use
  849. /// 'L', 'R', 'T', and 'B' for padding instead of ' '.
  850. /// </summary>
  851. FramePadding = 0b_0000_0010,
  852. }
  853. /// <summary>
  854. /// Set flags to enable/disable <see cref="ConsoleDriver"/> diagnostics.
  855. /// </summary>
  856. public static DiagnosticFlags Diagnostics { get; set; }
  857. /// <summary>
  858. /// Draws a frame for a window with padding and an optional visible border inside the padding.
  859. /// </summary>
  860. /// <param name="region">Screen relative region where the frame will be drawn.</param>
  861. /// <param name="paddingLeft">Number of columns to pad on the left (if 0 the border will not appear on the left).</param>
  862. /// <param name="paddingTop">Number of rows to pad on the top (if 0 the border and title will not appear on the top).</param>
  863. /// <param name="paddingRight">Number of columns to pad on the right (if 0 the border will not appear on the right).</param>
  864. /// <param name="paddingBottom">Number of rows to pad on the bottom (if 0 the border will not appear on the bottom).</param>
  865. /// <param name="border">If set to <c>true</c> and any padding dimension is > 0 the border will be drawn.</param>
  866. /// <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>
  867. /// <param name="borderContent">The <see cref="Border"/> to be used if defined.</param>
  868. public virtual void DrawWindowFrame (Rect region, int paddingLeft = 0, int paddingTop = 0, int paddingRight = 0,
  869. int paddingBottom = 0, bool border = true, bool fill = false, Border borderContent = null)
  870. {
  871. char clearChar = ' ';
  872. char leftChar = clearChar;
  873. char rightChar = clearChar;
  874. char topChar = clearChar;
  875. char bottomChar = clearChar;
  876. if ((Diagnostics & DiagnosticFlags.FramePadding) == DiagnosticFlags.FramePadding) {
  877. leftChar = 'L';
  878. rightChar = 'R';
  879. topChar = 'T';
  880. bottomChar = 'B';
  881. clearChar = 'C';
  882. }
  883. void AddRuneAt (int col, int row, Rune ch)
  884. {
  885. Move (col, row);
  886. AddRune (ch);
  887. }
  888. // fwidth is count of hLine chars
  889. int fwidth = (int)(region.Width - (paddingRight + paddingLeft));
  890. // fheight is count of vLine chars
  891. int fheight = (int)(region.Height - (paddingBottom + paddingTop));
  892. // fleft is location of left frame line
  893. int fleft = region.X + paddingLeft - 1;
  894. // fright is location of right frame line
  895. int fright = fleft + fwidth + 1;
  896. // ftop is location of top frame line
  897. int ftop = region.Y + paddingTop - 1;
  898. // fbottom is location of bottom frame line
  899. int fbottom = ftop + fheight + 1;
  900. var borderStyle = borderContent == null ? BorderStyle.Single : borderContent.BorderStyle;
  901. Rune hLine = default, vLine = default,
  902. uRCorner = default, uLCorner = default, lLCorner = default, lRCorner = default;
  903. if (border) {
  904. switch (borderStyle) {
  905. case BorderStyle.None:
  906. break;
  907. case BorderStyle.Single:
  908. hLine = HLine;
  909. vLine = VLine;
  910. uRCorner = URCorner;
  911. uLCorner = ULCorner;
  912. lLCorner = LLCorner;
  913. lRCorner = LRCorner;
  914. break;
  915. case BorderStyle.Double:
  916. hLine = HDLine;
  917. vLine = VDLine;
  918. uRCorner = URDCorner;
  919. uLCorner = ULDCorner;
  920. lLCorner = LLDCorner;
  921. lRCorner = LRDCorner;
  922. break;
  923. case BorderStyle.Rounded:
  924. hLine = HRLine;
  925. vLine = VRLine;
  926. uRCorner = URRCorner;
  927. uLCorner = ULRCorner;
  928. lLCorner = LLRCorner;
  929. lRCorner = LRRCorner;
  930. break;
  931. }
  932. } else {
  933. hLine = vLine = uRCorner = uLCorner = lLCorner = lRCorner = clearChar;
  934. }
  935. // Outside top
  936. if (paddingTop > 1) {
  937. for (int r = region.Y; r < ftop; r++) {
  938. for (int c = region.X; c < region.X + region.Width; c++) {
  939. AddRuneAt (c, r, topChar);
  940. }
  941. }
  942. }
  943. // Outside top-left
  944. for (int c = region.X; c < fleft; c++) {
  945. AddRuneAt (c, ftop, leftChar);
  946. }
  947. // Frame top-left corner
  948. AddRuneAt (fleft, ftop, paddingTop >= 0 ? (paddingLeft >= 0 ? uLCorner : hLine) : leftChar);
  949. // Frame top
  950. for (int c = fleft + 1; c < fleft + 1 + fwidth; c++) {
  951. AddRuneAt (c, ftop, paddingTop > 0 ? hLine : topChar);
  952. }
  953. // Frame top-right corner
  954. if (fright > fleft) {
  955. AddRuneAt (fright, ftop, paddingTop >= 0 ? (paddingRight >= 0 ? uRCorner : hLine) : rightChar);
  956. }
  957. // Outside top-right corner
  958. for (int c = fright + 1; c < fright + paddingRight; c++) {
  959. AddRuneAt (c, ftop, rightChar);
  960. }
  961. // Left, Fill, Right
  962. if (fbottom > ftop) {
  963. for (int r = ftop + 1; r < fbottom; r++) {
  964. // Outside left
  965. for (int c = region.X; c < fleft; c++) {
  966. AddRuneAt (c, r, leftChar);
  967. }
  968. // Frame left
  969. AddRuneAt (fleft, r, paddingLeft > 0 ? vLine : leftChar);
  970. // Fill
  971. if (fill) {
  972. for (int x = fleft + 1; x < fright; x++) {
  973. AddRuneAt (x, r, clearChar);
  974. }
  975. }
  976. // Frame right
  977. if (fright > fleft) {
  978. var v = vLine;
  979. if ((Diagnostics & DiagnosticFlags.FrameRuler) == DiagnosticFlags.FrameRuler) {
  980. v = (char)(((int)'0') + ((r - ftop) % 10)); // vLine;
  981. }
  982. AddRuneAt (fright, r, paddingRight > 0 ? v : rightChar);
  983. }
  984. // Outside right
  985. for (int c = fright + 1; c < fright + paddingRight; c++) {
  986. AddRuneAt (c, r, rightChar);
  987. }
  988. }
  989. // Outside Bottom
  990. for (int c = region.X; c < region.X + region.Width; c++) {
  991. AddRuneAt (c, fbottom, leftChar);
  992. }
  993. // Frame bottom-left
  994. AddRuneAt (fleft, fbottom, paddingLeft > 0 ? lLCorner : leftChar);
  995. if (fright > fleft) {
  996. // Frame bottom
  997. for (int c = fleft + 1; c < fright; c++) {
  998. var h = hLine;
  999. if ((Diagnostics & DiagnosticFlags.FrameRuler) == DiagnosticFlags.FrameRuler) {
  1000. h = (char)(((int)'0') + ((c - fleft) % 10)); // hLine;
  1001. }
  1002. AddRuneAt (c, fbottom, paddingBottom > 0 ? h : bottomChar);
  1003. }
  1004. // Frame bottom-right
  1005. AddRuneAt (fright, fbottom, paddingRight > 0 ? (paddingBottom > 0 ? lRCorner : hLine) : rightChar);
  1006. }
  1007. // Outside right
  1008. for (int c = fright + 1; c < fright + paddingRight; c++) {
  1009. AddRuneAt (c, fbottom, rightChar);
  1010. }
  1011. }
  1012. // Out bottom - ensure top is always drawn if we overlap
  1013. if (paddingBottom > 0) {
  1014. for (int r = fbottom + 1; r < fbottom + paddingBottom; r++) {
  1015. for (int c = region.X; c < region.X + region.Width; c++) {
  1016. AddRuneAt (c, r, bottomChar);
  1017. }
  1018. }
  1019. }
  1020. }
  1021. /// <summary>
  1022. /// Draws a frame on the specified region with the specified padding around the frame.
  1023. /// </summary>
  1024. /// <param name="region">Screen relative region where the frame will be drawn.</param>
  1025. /// <param name="padding">Padding to add on the sides.</param>
  1026. /// <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>
  1027. /// <remarks>This API has been superseded by <see cref="DrawWindowFrame(Rect, int, int, int, int, bool, bool, Border)"/>.</remarks>
  1028. /// <remarks>This API is equivalent to calling <c>DrawWindowFrame(Rect, p - 1, p - 1, p - 1, p - 1)</c>. In other words,
  1029. /// A padding value of 0 means there is actually a one cell border.
  1030. /// </remarks>
  1031. public virtual void DrawFrame (Rect region, int padding, bool fill)
  1032. {
  1033. // DrawFrame assumes the border is always at least one row/col thick
  1034. // DrawWindowFrame assumes a padding of 0 means NO padding and no frame
  1035. DrawWindowFrame (new Rect (region.X, region.Y, region.Width, region.Height),
  1036. padding + 1, padding + 1, padding + 1, padding + 1, border: false, fill: fill);
  1037. }
  1038. /// <summary>
  1039. /// Suspend the application, typically needs to save the state, suspend the app and upon return, reset the console driver.
  1040. /// </summary>
  1041. public abstract void Suspend ();
  1042. Rect clip;
  1043. /// <summary>
  1044. /// Controls the current clipping region that AddRune/AddStr is subject to.
  1045. /// </summary>
  1046. /// <value>The clip.</value>
  1047. public Rect Clip {
  1048. get => clip;
  1049. set => this.clip = value;
  1050. }
  1051. /// <summary>
  1052. /// Start of mouse moves.
  1053. /// </summary>
  1054. public abstract void StartReportingMouseMoves ();
  1055. /// <summary>
  1056. /// Stop reporting mouses moves.
  1057. /// </summary>
  1058. public abstract void StopReportingMouseMoves ();
  1059. /// <summary>
  1060. /// Disables the cooked event processing from the mouse driver.
  1061. /// At startup, it is assumed mouse events are cooked. Not implemented by any driver: See Issue #2300.
  1062. /// </summary>
  1063. public abstract void UncookMouse ();
  1064. /// <summary>
  1065. /// Enables the cooked event processing from the mouse driver. Not implemented by any driver: See Issue #2300.
  1066. /// </summary>
  1067. public abstract void CookMouse ();
  1068. /// <summary>
  1069. /// Horizontal line character.
  1070. /// </summary>
  1071. public Rune HLine = '\u2500';
  1072. /// <summary>
  1073. /// Vertical line character.
  1074. /// </summary>
  1075. public Rune VLine = '\u2502';
  1076. /// <summary>
  1077. /// Stipple pattern
  1078. /// </summary>
  1079. public Rune Stipple = '\u2591';
  1080. /// <summary>
  1081. /// Diamond character
  1082. /// </summary>
  1083. public Rune Diamond = '\u25ca';
  1084. /// <summary>
  1085. /// Upper left corner
  1086. /// </summary>
  1087. public Rune ULCorner = '\u250C';
  1088. /// <summary>
  1089. /// Lower left corner
  1090. /// </summary>
  1091. public Rune LLCorner = '\u2514';
  1092. /// <summary>
  1093. /// Upper right corner
  1094. /// </summary>
  1095. public Rune URCorner = '\u2510';
  1096. /// <summary>
  1097. /// Lower right corner
  1098. /// </summary>
  1099. public Rune LRCorner = '\u2518';
  1100. /// <summary>
  1101. /// Left tee
  1102. /// </summary>
  1103. public Rune LeftTee = '\u251c';
  1104. /// <summary>
  1105. /// Right tee
  1106. /// </summary>
  1107. public Rune RightTee = '\u2524';
  1108. /// <summary>
  1109. /// Top tee
  1110. /// </summary>
  1111. public Rune TopTee = '\u252c';
  1112. /// <summary>
  1113. /// The bottom tee.
  1114. /// </summary>
  1115. public Rune BottomTee = '\u2534';
  1116. /// <summary>
  1117. /// Checkmark.
  1118. /// </summary>
  1119. public Rune Checked = '\u221a';
  1120. /// <summary>
  1121. /// Un-checked checkmark.
  1122. /// </summary>
  1123. public Rune UnChecked = '\u2574';
  1124. /// <summary>
  1125. /// Selected mark.
  1126. /// </summary>
  1127. public Rune Selected = '\u25cf';
  1128. /// <summary>
  1129. /// Un-selected selected mark.
  1130. /// </summary>
  1131. public Rune UnSelected = '\u25cc';
  1132. /// <summary>
  1133. /// Right Arrow.
  1134. /// </summary>
  1135. public Rune RightArrow = '\u25ba';
  1136. /// <summary>
  1137. /// Left Arrow.
  1138. /// </summary>
  1139. public Rune LeftArrow = '\u25c4';
  1140. /// <summary>
  1141. /// Down Arrow.
  1142. /// </summary>
  1143. public Rune DownArrow = '\u25bc';
  1144. /// <summary>
  1145. /// Up Arrow.
  1146. /// </summary>
  1147. public Rune UpArrow = '\u25b2';
  1148. /// <summary>
  1149. /// Left indicator for default action (e.g. for <see cref="Button"/>).
  1150. /// </summary>
  1151. public Rune LeftDefaultIndicator = '\u25e6';
  1152. /// <summary>
  1153. /// Right indicator for default action (e.g. for <see cref="Button"/>).
  1154. /// </summary>
  1155. public Rune RightDefaultIndicator = '\u25e6';
  1156. /// <summary>
  1157. /// Left frame/bracket (e.g. '[' for <see cref="Button"/>).
  1158. /// </summary>
  1159. public Rune LeftBracket = '[';
  1160. /// <summary>
  1161. /// Right frame/bracket (e.g. ']' for <see cref="Button"/>).
  1162. /// </summary>
  1163. public Rune RightBracket = ']';
  1164. /// <summary>
  1165. /// Blocks Segment indicator for meter views (e.g. <see cref="ProgressBar"/>.
  1166. /// </summary>
  1167. public Rune BlocksMeterSegment = '\u258c';
  1168. /// <summary>
  1169. /// Continuous Segment indicator for meter views (e.g. <see cref="ProgressBar"/>.
  1170. /// </summary>
  1171. public Rune ContinuousMeterSegment = '\u2588';
  1172. /// <summary>
  1173. /// Horizontal double line character.
  1174. /// </summary>
  1175. public Rune HDLine = '\u2550';
  1176. /// <summary>
  1177. /// Vertical double line character.
  1178. /// </summary>
  1179. public Rune VDLine = '\u2551';
  1180. /// <summary>
  1181. /// Upper left double corner
  1182. /// </summary>
  1183. public Rune ULDCorner = '\u2554';
  1184. /// <summary>
  1185. /// Lower left double corner
  1186. /// </summary>
  1187. public Rune LLDCorner = '\u255a';
  1188. /// <summary>
  1189. /// Upper right double corner
  1190. /// </summary>
  1191. public Rune URDCorner = '\u2557';
  1192. /// <summary>
  1193. /// Lower right double corner
  1194. /// </summary>
  1195. public Rune LRDCorner = '\u255d';
  1196. /// <summary>
  1197. /// Horizontal line character for rounded corners.
  1198. /// </summary>
  1199. public Rune HRLine = '\u2500';
  1200. /// <summary>
  1201. /// Vertical line character for rounded corners.
  1202. /// </summary>
  1203. public Rune VRLine = '\u2502';
  1204. /// <summary>
  1205. /// Upper left rounded corner
  1206. /// </summary>
  1207. public Rune ULRCorner = '\u256d';
  1208. /// <summary>
  1209. /// Lower left rounded corner
  1210. /// </summary>
  1211. public Rune LLRCorner = '\u2570';
  1212. /// <summary>
  1213. /// Upper right rounded corner
  1214. /// </summary>
  1215. public Rune URRCorner = '\u256e';
  1216. /// <summary>
  1217. /// Lower right rounded corner
  1218. /// </summary>
  1219. public Rune LRRCorner = '\u256f';
  1220. private Attribute currentAttribute;
  1221. /// <summary>
  1222. /// Make the attribute for the foreground and background colors.
  1223. /// </summary>
  1224. /// <param name="fore">Foreground.</param>
  1225. /// <param name="back">Background.</param>
  1226. /// <returns></returns>
  1227. public abstract Attribute MakeAttribute (Color fore, Color back);
  1228. /// <summary>
  1229. /// Gets the current <see cref="Attribute"/>.
  1230. /// </summary>
  1231. /// <returns>The current attribute.</returns>
  1232. public Attribute GetAttribute () => CurrentAttribute;
  1233. /// <summary>
  1234. /// Make the <see cref="Colors"/> for the <see cref="ColorScheme"/>.
  1235. /// </summary>
  1236. /// <param name="foreground">The foreground color.</param>
  1237. /// <param name="background">The background color.</param>
  1238. /// <returns>The attribute for the foreground and background colors.</returns>
  1239. public abstract Attribute MakeColor (Color foreground, Color background);
  1240. /// <summary>
  1241. /// Ensures all <see cref="Attribute"/>s in <see cref="Colors.ColorSchemes"/> are correctly
  1242. /// initialized by the driver.
  1243. /// </summary>
  1244. /// <param name="supportsColors">Flag indicating if colors are supported (not used).</param>
  1245. public void InitalizeColorSchemes (bool supportsColors = true)
  1246. {
  1247. // Ensure all Attributes are initialized by the driver
  1248. foreach (var s in Colors.ColorSchemes) {
  1249. s.Value.Initialize ();
  1250. }
  1251. if (!supportsColors) {
  1252. return;
  1253. }
  1254. // Define the default color theme only if the user has not defined one.
  1255. Colors.TopLevel.Normal = MakeColor (Color.BrightGreen, Color.Black);
  1256. Colors.TopLevel.Focus = MakeColor (Color.White, Color.Cyan);
  1257. Colors.TopLevel.HotNormal = MakeColor (Color.Brown, Color.Black);
  1258. Colors.TopLevel.HotFocus = MakeColor (Color.Blue, Color.Cyan);
  1259. Colors.TopLevel.Disabled = MakeColor (Color.DarkGray, Color.Black);
  1260. Colors.Base.Normal = MakeColor (Color.White, Color.Blue);
  1261. Colors.Base.Focus = MakeColor (Color.Black, Color.Gray);
  1262. Colors.Base.HotNormal = MakeColor (Color.BrightCyan, Color.Blue);
  1263. Colors.Base.HotFocus = MakeColor (Color.BrightBlue, Color.Gray);
  1264. Colors.Base.Disabled = MakeColor (Color.DarkGray, Color.Blue);
  1265. Colors.Dialog.Normal = MakeColor (Color.Black, Color.Gray);
  1266. Colors.Dialog.Focus = MakeColor (Color.White, Color.DarkGray);
  1267. Colors.Dialog.HotNormal = MakeColor (Color.Blue, Color.Gray);
  1268. Colors.Dialog.HotFocus = MakeColor (Color.BrightYellow, Color.DarkGray);
  1269. Colors.Dialog.Disabled = MakeColor (Color.Gray, Color.DarkGray);
  1270. Colors.Menu.Normal = MakeColor (Color.White, Color.DarkGray);
  1271. Colors.Menu.Focus = MakeColor (Color.White, Color.Black);
  1272. Colors.Menu.HotNormal = MakeColor (Color.BrightYellow, Color.DarkGray);
  1273. Colors.Menu.HotFocus = MakeColor (Color.BrightYellow, Color.Black);
  1274. Colors.Menu.Disabled = MakeColor (Color.Gray, Color.DarkGray);
  1275. Colors.Error.Normal = MakeColor (Color.Red, Color.White);
  1276. Colors.Error.Focus = MakeColor (Color.Black, Color.BrightRed);
  1277. Colors.Error.HotNormal = MakeColor (Color.Black, Color.White);
  1278. Colors.Error.HotFocus = MakeColor (Color.White, Color.BrightRed);
  1279. Colors.Error.Disabled = MakeColor (Color.DarkGray, Color.White);
  1280. }
  1281. }
  1282. /// <summary>
  1283. /// Helper class for console drivers to invoke shell commands to interact with the clipboard.
  1284. /// Used primarily by CursesDriver, but also used in Unit tests which is why it is in
  1285. /// ConsoleDriver.cs.
  1286. /// </summary>
  1287. internal static class ClipboardProcessRunner {
  1288. public static (int exitCode, string result) Bash (string commandLine, string inputText = "", bool waitForOutput = false)
  1289. {
  1290. var arguments = $"-c \"{commandLine}\"";
  1291. var (exitCode, result) = Process ("bash", arguments, inputText, waitForOutput);
  1292. return (exitCode, result.TrimEnd ());
  1293. }
  1294. public static (int exitCode, string result) Process (string cmd, string arguments, string input = null, bool waitForOutput = true)
  1295. {
  1296. var output = string.Empty;
  1297. using (Process process = new Process {
  1298. StartInfo = new ProcessStartInfo {
  1299. FileName = cmd,
  1300. Arguments = arguments,
  1301. RedirectStandardOutput = true,
  1302. RedirectStandardError = true,
  1303. RedirectStandardInput = true,
  1304. UseShellExecute = false,
  1305. CreateNoWindow = true,
  1306. }
  1307. }) {
  1308. var eventHandled = new TaskCompletionSource<bool> ();
  1309. process.Start ();
  1310. if (!string.IsNullOrEmpty (input)) {
  1311. process.StandardInput.Write (input);
  1312. process.StandardInput.Close ();
  1313. }
  1314. if (!process.WaitForExit (5000)) {
  1315. var timeoutError = $@"Process timed out. Command line: {process.StartInfo.FileName} {process.StartInfo.Arguments}.";
  1316. throw new TimeoutException (timeoutError);
  1317. }
  1318. if (waitForOutput && process.StandardOutput.Peek () != -1) {
  1319. output = process.StandardOutput.ReadToEnd ();
  1320. }
  1321. if (process.ExitCode > 0) {
  1322. output = $@"Process failed to run. Command line: {cmd} {arguments}.
  1323. Output: {output}
  1324. Error: {process.StandardError.ReadToEnd ()}";
  1325. }
  1326. return (process.ExitCode, output);
  1327. }
  1328. }
  1329. public static bool DoubleWaitForExit (this System.Diagnostics.Process process)
  1330. {
  1331. var result = process.WaitForExit (500);
  1332. if (result) {
  1333. process.WaitForExit ();
  1334. }
  1335. return result;
  1336. }
  1337. public static bool FileExists (this string value)
  1338. {
  1339. return !string.IsNullOrEmpty (value) && !value.Contains ("not found");
  1340. }
  1341. }
  1342. }