ConsoleDriver.cs 49 KB

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