ConsoleDriverFacade.cs 17 KB

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