ConsoleDriver.cs 46 KB

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