LinuxConsoleDriver.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using BepInEx.Logging;
  5. using HarmonyLib;
  6. using UnityInjector.ConsoleUtil;
  7. namespace BepInEx.Unix
  8. {
  9. internal class LinuxConsoleDriver : IConsoleDriver
  10. {
  11. public TextWriter StandardOut { get; private set; }
  12. public TextWriter ConsoleOut { get; private set; }
  13. public bool ConsoleActive { get; private set; }
  14. public bool ConsoleIsExternal => false;
  15. public bool UseMonoTtyDriver { get; private set; }
  16. public bool StdoutRedirected { get; private set; }
  17. public TtyInfo TtyInfo { get; private set; }
  18. public void Initialize(bool alreadyActive)
  19. {
  20. // Console is always considered active on Unix
  21. ConsoleActive = true;
  22. UseMonoTtyDriver = typeof(Console).Assembly.GetType("System.ConsoleDriver") != null;
  23. var duplicateStream = UnixStreamHelper.CreateDuplicateStream(1);
  24. if (UseMonoTtyDriver)
  25. {
  26. // Mono implementation handles xterm for us
  27. var writer = ConsoleWriter.CreateConsoleStreamWriter(duplicateStream, Console.Out.Encoding, true);
  28. StandardOut = TextWriter.Synchronized(writer);
  29. var driver = AccessTools.Field(AccessTools.TypeByName("System.ConsoleDriver"), "driver").GetValue(null);
  30. AccessTools.Field(AccessTools.TypeByName("System.TermInfoDriver"), "stdout").SetValue(driver, writer);
  31. }
  32. else
  33. {
  34. // Handle TTY ourselves
  35. var writer = new StreamWriter(duplicateStream, Console.Out.Encoding);
  36. writer.AutoFlush = true;
  37. StandardOut = TextWriter.Synchronized(writer);
  38. TtyInfo = TtyHandler.GetTtyInfo();
  39. }
  40. ConsoleOut = StandardOut;
  41. }
  42. public void CreateConsole()
  43. {
  44. Logger.LogWarning("An external console currently cannot be spawned on a Unix platform.");
  45. }
  46. public void DetachConsole()
  47. {
  48. throw new PlatformNotSupportedException("Cannot detach console on a Unix platform");
  49. }
  50. public void SetConsoleColor(ConsoleColor color)
  51. {
  52. if (UseMonoTtyDriver)
  53. {
  54. // Use mono's inbuilt terminfo driver to set the foreground color for us
  55. SafeConsole.ForegroundColor = color;
  56. }
  57. else
  58. {
  59. ConsoleOut.Write(TtyInfo.GetAnsiCode(color));
  60. }
  61. }
  62. public void SetConsoleEncoding(Encoding encoding)
  63. {
  64. // We shouldn't be changing this on Unix
  65. }
  66. public void SetConsoleTitle(string title)
  67. {
  68. if (UseMonoTtyDriver)
  69. {
  70. SafeConsole.Title = title;
  71. }
  72. else
  73. {
  74. ConsoleOut.Write($"\u001B]2;{title.Replace("\\", "\\\\")}\u0007");
  75. }
  76. }
  77. }
  78. }