ConsoleDriverFacade.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. #nullable enable
  2. using System.Runtime.InteropServices;
  3. namespace Terminal.Gui.Drivers;
  4. internal class ConsoleDriverFacade<T> : IConsoleDriver, IConsoleDriverFacade
  5. {
  6. private readonly IConsoleOutput _output;
  7. private readonly IOutputBuffer _outputBuffer;
  8. private readonly AnsiRequestScheduler _ansiRequestScheduler;
  9. private CursorVisibility _lastCursor = CursorVisibility.Default;
  10. /// <summary>
  11. /// The event fired when the screen changes (size, position, etc.).
  12. /// </summary>
  13. public event EventHandler<SizeChangedEventArgs>? SizeChanged;
  14. public IInputProcessor InputProcessor { get; }
  15. public IOutputBuffer OutputBuffer => _outputBuffer;
  16. public IConsoleSizeMonitor ConsoleSizeMonitor { get; }
  17. public ConsoleDriverFacade (
  18. IInputProcessor inputProcessor,
  19. IOutputBuffer outputBuffer,
  20. IConsoleOutput output,
  21. AnsiRequestScheduler ansiRequestScheduler,
  22. IConsoleSizeMonitor sizeMonitor
  23. )
  24. {
  25. InputProcessor = inputProcessor;
  26. _output = output;
  27. _outputBuffer = outputBuffer;
  28. _ansiRequestScheduler = ansiRequestScheduler;
  29. InputProcessor.KeyDown += (s, e) => KeyDown?.Invoke (s, e);
  30. InputProcessor.KeyUp += (s, e) => KeyUp?.Invoke (s, e);
  31. InputProcessor.MouseEvent += (s, e) =>
  32. {
  33. //Logging.Logger.LogTrace ($"Mouse {e.Flags} at x={e.ScreenPosition.X} y={e.ScreenPosition.Y}");
  34. MouseEvent?.Invoke (s, e);
  35. };
  36. ConsoleSizeMonitor = sizeMonitor;
  37. sizeMonitor.SizeChanged += (_, e) =>
  38. {
  39. SetScreenSize(e.Size!.Value.Width, e.Size.Value.Height);
  40. //SizeChanged?.Invoke (this, e);
  41. };
  42. CreateClipboard ();
  43. }
  44. private void CreateClipboard ()
  45. {
  46. if (FakeDriver.FakeBehaviors.UseFakeClipboard)
  47. {
  48. Clipboard = new FakeClipboard (
  49. FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException,
  50. FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse);
  51. return;
  52. }
  53. PlatformID p = Environment.OSVersion.Platform;
  54. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  55. {
  56. Clipboard = new WindowsClipboard ();
  57. }
  58. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  59. {
  60. Clipboard = new MacOSXClipboard ();
  61. }
  62. else if (PlatformDetection.IsWSLPlatform ())
  63. {
  64. Clipboard = new WSLClipboard ();
  65. }
  66. else
  67. {
  68. Clipboard = new FakeClipboard ();
  69. }
  70. }
  71. /// <summary>Gets the location and size of the terminal screen.</summary>
  72. public Rectangle Screen
  73. {
  74. get
  75. {
  76. if (ConsoleDriver.RunningUnitTests && _output is WindowsOutput or NetOutput)
  77. {
  78. // In unit tests, we don't have a real output, so we return an empty rectangle.
  79. return Rectangle.Empty;
  80. }
  81. return new (0, 0, _outputBuffer.Cols, _outputBuffer.Rows);
  82. }
  83. }
  84. /// <summary>
  85. /// Sets the screen size for testing purposes. Only supported by FakeDriver.
  86. /// </summary>
  87. /// <param name="width">The new width in columns.</param>
  88. /// <param name="height">The new height in rows.</param>
  89. /// <exception cref="NotSupportedException">Thrown when called on non-FakeDriver instances.</exception>
  90. public virtual void SetScreenSize (int width, int height)
  91. {
  92. _outputBuffer.SetSize (width, height);
  93. _output.SetSize (width, height);
  94. SizeChanged?.Invoke(this, new (new (width, height)));
  95. }
  96. /// <summary>
  97. /// Gets or sets the clip rectangle that <see cref="AddRune(Rune)"/> and <see cref="AddStr(string)"/> are subject
  98. /// to.
  99. /// </summary>
  100. /// <value>The rectangle describing the of <see cref="Clip"/> region.</value>
  101. public Region? Clip
  102. {
  103. get => _outputBuffer.Clip;
  104. set => _outputBuffer.Clip = value;
  105. }
  106. /// <summary>Get the operating system clipboard.</summary>
  107. public IClipboard Clipboard { get; private set; } = new FakeClipboard ();
  108. /// <summary>
  109. /// Gets the column last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  110. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  111. /// </summary>
  112. public int Col => _outputBuffer.Col;
  113. /// <summary>The number of columns visible in the terminal.</summary>
  114. public int Cols
  115. {
  116. get => _outputBuffer.Cols;
  117. set => _outputBuffer.Cols = value;
  118. }
  119. /// <summary>
  120. /// The contents of the application output. The driver outputs this buffer to the terminal.
  121. /// <remarks>The format of the array is rows, columns. The first index is the row, the second index is the column.</remarks>
  122. /// </summary>
  123. public Cell [,]? Contents
  124. {
  125. get => _outputBuffer.Contents;
  126. set => _outputBuffer.Contents = value;
  127. }
  128. /// <summary>The leftmost column in the terminal.</summary>
  129. public int Left
  130. {
  131. get => _outputBuffer.Left;
  132. set => _outputBuffer.Left = value;
  133. }
  134. /// <summary>
  135. /// Gets the row last set by <see cref="Move"/>. <see cref="Col"/> and <see cref="Row"/> are used by
  136. /// <see cref="AddRune(Rune)"/> and <see cref="AddStr"/> to determine where to add content.
  137. /// </summary>
  138. public int Row => _outputBuffer.Row;
  139. /// <summary>The number of rows visible in the terminal.</summary>
  140. public int Rows
  141. {
  142. get => _outputBuffer.Rows;
  143. set => _outputBuffer.Rows = value;
  144. }
  145. /// <summary>The topmost row in the terminal.</summary>
  146. public int Top
  147. {
  148. get => _outputBuffer.Top;
  149. set => _outputBuffer.Top = value;
  150. }
  151. // TODO: Probably not everyone right?
  152. /// <summary>Gets whether the <see cref="ConsoleDriver"/> supports TrueColor output.</summary>
  153. public bool SupportsTrueColor => true;
  154. // TODO: Currently ignored
  155. /// <summary>
  156. /// Gets or sets whether the <see cref="ConsoleDriver"/> should use 16 colors instead of the default TrueColors.
  157. /// See <see cref="Application.Force16Colors"/> to change this setting via <see cref="ConfigurationManager"/>.
  158. /// </summary>
  159. /// <remarks>
  160. /// <para>
  161. /// Will be forced to <see langword="true"/> if <see cref="ConsoleDriver.SupportsTrueColor"/> is
  162. /// <see langword="false"/>, indicating that the <see cref="ConsoleDriver"/> cannot support TrueColor.
  163. /// </para>
  164. /// </remarks>
  165. public bool Force16Colors
  166. {
  167. get => Application.Force16Colors || !SupportsTrueColor;
  168. set => Application.Force16Colors = value || !SupportsTrueColor;
  169. }
  170. /// <summary>
  171. /// The <see cref="System.Attribute"/> that will be used for the next <see cref="AddRune(Rune)"/> or <see cref="AddStr"/>
  172. /// call.
  173. /// </summary>
  174. public Attribute CurrentAttribute
  175. {
  176. get => _outputBuffer.CurrentAttribute;
  177. set => _outputBuffer.CurrentAttribute = value;
  178. }
  179. /// <summary>Adds the specified rune to the display at the current cursor position.</summary>
  180. /// <remarks>
  181. /// <para>
  182. /// When the method returns, <see cref="ConsoleDriver.Col"/> will be incremented by the number of columns
  183. /// <paramref name="rune"/> required, even if the new column value is outside of the
  184. /// <see cref="ConsoleDriver.Clip"/> or screen
  185. /// dimensions defined by <see cref="ConsoleDriver.Cols"/>.
  186. /// </para>
  187. /// <para>
  188. /// If <paramref name="rune"/> requires more than one column, and <see cref="ConsoleDriver.Col"/> plus the number
  189. /// of columns
  190. /// needed exceeds the <see cref="ConsoleDriver.Clip"/> or screen dimensions, the default Unicode replacement
  191. /// character (U+FFFD)
  192. /// will be added instead.
  193. /// </para>
  194. /// </remarks>
  195. /// <param name="rune">Rune to add.</param>
  196. public void AddRune (Rune rune) { _outputBuffer.AddRune (rune); }
  197. /// <summary>
  198. /// Adds the specified <see langword="char"/> to the display at the current cursor position. This method is a
  199. /// convenience method that calls <see cref="ConsoleDriver.AddRune(System.Text.Rune)"/> with the <see cref="Rune"/>
  200. /// constructor.
  201. /// </summary>
  202. /// <param name="c">Character to add.</param>
  203. public void AddRune (char c) { _outputBuffer.AddRune (c); }
  204. /// <summary>Adds the <paramref name="str"/> to the display at the cursor position.</summary>
  205. /// <remarks>
  206. /// <para>
  207. /// When the method returns, <see cref="ConsoleDriver.Col"/> will be incremented by the number of columns
  208. /// <paramref name="str"/> required, unless the new column value is outside of the <see cref="ConsoleDriver.Clip"/>
  209. /// or screen
  210. /// dimensions defined by <see cref="ConsoleDriver.Cols"/>.
  211. /// </para>
  212. /// <para>If <paramref name="str"/> requires more columns than are available, the output will be clipped.</para>
  213. /// </remarks>
  214. /// <param name="str">String.</param>
  215. public void AddStr (string str) { _outputBuffer.AddStr (str); }
  216. /// <summary>Clears the <see cref="ConsoleDriver.Contents"/> of the driver.</summary>
  217. public void ClearContents ()
  218. {
  219. _outputBuffer.ClearContents ();
  220. ClearedContents?.Invoke (this, new MouseEventArgs ());
  221. }
  222. /// <summary>
  223. /// Raised each time <see cref="ConsoleDriver.ClearContents"/> is called. For benchmarking.
  224. /// </summary>
  225. public event EventHandler<EventArgs>? ClearedContents;
  226. /// <summary>
  227. /// Fills the specified rectangle with the specified rune, using <see cref="ConsoleDriver.CurrentAttribute"/>
  228. /// </summary>
  229. /// <remarks>
  230. /// The value of <see cref="ConsoleDriver.Clip"/> is honored. Any parts of the rectangle not in the clip will not be
  231. /// drawn.
  232. /// </remarks>
  233. /// <param name="rect">The Screen-relative rectangle.</param>
  234. /// <param name="rune">The Rune used to fill the rectangle</param>
  235. public void FillRect (Rectangle rect, Rune rune = default) { _outputBuffer.FillRect (rect, rune); }
  236. /// <summary>
  237. /// Fills the specified rectangle with the specified <see langword="char"/>. This method is a convenience method
  238. /// that calls <see cref="ConsoleDriver.FillRect(System.Drawing.Rectangle,System.Text.Rune)"/>.
  239. /// </summary>
  240. /// <param name="rect"></param>
  241. /// <param name="c"></param>
  242. public void FillRect (Rectangle rect, char c) { _outputBuffer.FillRect (rect, c); }
  243. /// <inheritdoc/>
  244. public virtual string GetVersionInfo ()
  245. {
  246. string type = InputProcessor.DriverName ?? throw new ArgumentNullException (nameof (InputProcessor.DriverName));
  247. return type;
  248. }
  249. /// <summary>Tests if the specified rune is supported by the driver.</summary>
  250. /// <param name="rune"></param>
  251. /// <returns>
  252. /// <see langword="true"/> if the rune can be properly presented; <see langword="false"/> if the driver does not
  253. /// support displaying this rune.
  254. /// </returns>
  255. public bool IsRuneSupported (Rune rune) { return Rune.IsValid (rune.Value); }
  256. /// <summary>Tests whether the specified coordinate are valid for drawing the specified Rune.</summary>
  257. /// <param name="rune">Used to determine if one or two columns are required.</param>
  258. /// <param name="col">The column.</param>
  259. /// <param name="row">The row.</param>
  260. /// <returns>
  261. /// <see langword="false"/> if the coordinate is outside the screen bounds or outside of
  262. /// <see cref="ConsoleDriver.Clip"/>.
  263. /// <see langword="true"/> otherwise.
  264. /// </returns>
  265. public bool IsValidLocation (Rune rune, int col, int row) { return _outputBuffer.IsValidLocation (rune, col, row); }
  266. /// <summary>
  267. /// Updates <see cref="ConsoleDriver.Col"/> and <see cref="ConsoleDriver.Row"/> to the specified column and row in
  268. /// <see cref="ConsoleDriver.Contents"/>.
  269. /// Used by <see cref="ConsoleDriver.AddRune(System.Text.Rune)"/> and <see cref="ConsoleDriver.AddStr"/> to determine
  270. /// where to add content.
  271. /// </summary>
  272. /// <remarks>
  273. /// <para>This does not move the cursor on the screen, it only updates the internal state of the driver.</para>
  274. /// <para>
  275. /// If <paramref name="col"/> or <paramref name="row"/> are negative or beyond <see cref="ConsoleDriver.Cols"/>
  276. /// and
  277. /// <see cref="ConsoleDriver.Rows"/>, the method still sets those properties.
  278. /// </para>
  279. /// </remarks>
  280. /// <param name="col">Column to move to.</param>
  281. /// <param name="row">Row to move to.</param>
  282. public void Move (int col, int row) { _outputBuffer.Move (col, row); }
  283. // TODO: Probably part of output
  284. /// <summary>Sets the terminal cursor visibility.</summary>
  285. /// <param name="visibility">The wished <see cref="CursorVisibility"/></param>
  286. /// <returns><see langword="true"/> upon success</returns>
  287. public bool SetCursorVisibility (CursorVisibility visibility)
  288. {
  289. _lastCursor = visibility;
  290. _output.SetCursorVisibility (visibility);
  291. return true;
  292. }
  293. /// <inheritdoc/>
  294. public bool GetCursorVisibility (out CursorVisibility current)
  295. {
  296. current = _lastCursor;
  297. return true;
  298. }
  299. /// <inheritdoc/>
  300. public void Suspend ()
  301. {
  302. if (Environment.OSVersion.Platform != PlatformID.Unix)
  303. {
  304. return;
  305. }
  306. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  307. if (!ConsoleDriver.RunningUnitTests)
  308. {
  309. Console.ResetColor ();
  310. Console.Clear ();
  311. //Disable alternative screen buffer.
  312. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  313. //Set cursor key to cursor.
  314. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  315. Platform.Suspend ();
  316. //Enable alternative screen buffer.
  317. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  318. Application.LayoutAndDraw ();
  319. }
  320. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  321. }
  322. /// <summary>
  323. /// Sets the position of the terminal cursor to <see cref="ConsoleDriver.Col"/> and
  324. /// <see cref="ConsoleDriver.Row"/>.
  325. /// </summary>
  326. public void UpdateCursor () { _output.SetCursorPosition (Col, Row); }
  327. /// <summary>Initializes the driver</summary>
  328. public void Init () { throw new NotSupportedException (); }
  329. /// <summary>Ends the execution of the console driver.</summary>
  330. public void End ()
  331. {
  332. // TODO: Nope
  333. }
  334. /// <summary>Selects the specified attribute as the attribute to use for future calls to AddRune and AddString.</summary>
  335. /// <remarks>Implementations should call <c>base.SetAttribute(c)</c>.</remarks>
  336. /// <param name="newAttribute">C.</param>
  337. /// <returns>The previously set Attribute.</returns>
  338. public Attribute SetAttribute (Attribute newAttribute)
  339. {
  340. Attribute currentAttribute = _outputBuffer.CurrentAttribute;
  341. _outputBuffer.CurrentAttribute = newAttribute;
  342. return currentAttribute;
  343. }
  344. /// <summary>Gets the current <see cref="Attribute"/>.</summary>
  345. /// <returns>The current attribute.</returns>
  346. public Attribute GetAttribute () { return _outputBuffer.CurrentAttribute; }
  347. /// <summary>Event fired when a key is pressed down. This is a precursor to <see cref="ConsoleDriver.KeyUp"/>.</summary>
  348. public event EventHandler<Key>? KeyDown;
  349. /// <summary>Event fired when a key is released.</summary>
  350. /// <remarks>
  351. /// Drivers that do not support key release events will fire this event after <see cref="ConsoleDriver.KeyDown"/>
  352. /// processing is
  353. /// complete.
  354. /// </remarks>
  355. public event EventHandler<Key>? KeyUp;
  356. /// <summary>Event fired when a mouse event occurs.</summary>
  357. public event EventHandler<MouseEventArgs>? MouseEvent;
  358. /// <summary>
  359. /// Provide proper writing to send escape sequence recognized by the <see cref="ConsoleDriver"/>.
  360. /// </summary>
  361. /// <param name="ansi"></param>
  362. public void WriteRaw (string ansi) { _output.Write (ansi); }
  363. /// <summary>
  364. /// Queues the given <paramref name="request"/> for execution
  365. /// </summary>
  366. /// <param name="request"></param>
  367. public void QueueAnsiRequest (AnsiEscapeSequenceRequest request) { _ansiRequestScheduler.SendOrSchedule (request); }
  368. public AnsiRequestScheduler GetRequestScheduler () { return _ansiRequestScheduler; }
  369. /// <inheritdoc/>
  370. public void Refresh ()
  371. {
  372. // No need we will always draw when dirty
  373. }
  374. }