ConsoleDriver.cs 40 KB

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