WindowsConsoleDriver.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using BepInEx.ConsoleUtil;
  5. using UnityInjector.ConsoleUtil;
  6. namespace BepInEx
  7. {
  8. internal class WindowsConsoleDriver : IConsoleDriver
  9. {
  10. public TextWriter StandardOut { get; private set; }
  11. public TextWriter ConsoleOut { get; private set; }
  12. public bool ConsoleActive { get; private set; }
  13. public bool ConsoleIsExternal => true;
  14. public void Initialize(bool alreadyActive)
  15. {
  16. ConsoleActive = alreadyActive;
  17. StandardOut = Console.Out;
  18. }
  19. public void CreateConsole(uint codepage)
  20. {
  21. // On some Unity mono builds the SafeFileHandle overload for FileStream is missing
  22. // so we use the older but always included one instead
  23. #pragma warning disable 618
  24. ConsoleWindow.Attach();
  25. // Make sure of ConsoleEncoding helper class because on some Monos
  26. // Encoding.GetEncoding throws NotImplementedException on most codepages
  27. // NOTE: We don't set Console.OutputEncoding because it resets any existing Console.Out writers
  28. ConsoleEncoding.ConsoleCodePage = codepage;
  29. // If stdout exists, write to it, otherwise make it the same as console out
  30. // Not sure if this is needed? Does the original Console.Out still work?
  31. var stdout = ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero ? ConsoleWindow.OriginalStdoutHandle : ConsoleWindow.ConsoleOutHandle;
  32. var originalOutStream = new FileStream(stdout, FileAccess.Write);
  33. StandardOut = new StreamWriter(originalOutStream, new UTF8Encoding(false))
  34. {
  35. AutoFlush = true
  36. };
  37. var consoleOutStream = new FileStream(ConsoleWindow.ConsoleOutHandle, FileAccess.Write);
  38. // Can't use Console.OutputEncoding because it can be null (i.e. not preference by user)
  39. ConsoleOut = new StreamWriter(consoleOutStream, ConsoleEncoding.OutputEncoding)
  40. {
  41. AutoFlush = true
  42. };
  43. ConsoleActive = true;
  44. #pragma warning restore 618
  45. }
  46. public void DetachConsole()
  47. {
  48. ConsoleWindow.Detach();
  49. ConsoleOut.Close();
  50. ConsoleOut = null;
  51. ConsoleActive = false;
  52. }
  53. public void SetConsoleColor(ConsoleColor color)
  54. {
  55. SafeConsole.ForegroundColor = color;
  56. Kon.ForegroundColor = color;
  57. }
  58. public void SetConsoleTitle(string title)
  59. {
  60. ConsoleWindow.Title = title;
  61. }
  62. }
  63. }