ConsoleDriver.cs 49 KB

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