ConsoleDriverFacade.cs 18 KB

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