LinuxConsoleDriver.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 void Initialize(bool alreadyActive)
  18. {
  19. // Console is always considered active on Unix
  20. ConsoleActive = true;
  21. var duplicateStream = UnixStreamHelper.CreateDuplicateStream(1);
  22. var writer = ConsoleWriter.CreateConsoleStreamWriter(duplicateStream, Console.Out.Encoding, true);
  23. StandardOut = TextWriter.Synchronized(writer);
  24. var driver = AccessTools.Field(AccessTools.TypeByName("System.ConsoleDriver"), "driver").GetValue(null);
  25. AccessTools.Field(AccessTools.TypeByName("System.TermInfoDriver"), "stdout").SetValue(driver, writer);
  26. ConsoleOut = StandardOut;
  27. }
  28. public void CreateConsole()
  29. {
  30. Logger.LogWarning("An external console currently cannot be spawned on a Unix platform.");
  31. }
  32. public void DetachConsole()
  33. {
  34. throw new PlatformNotSupportedException("Cannot detach console on a Unix platform");
  35. }
  36. public void SetConsoleColor(ConsoleColor color)
  37. {
  38. if (SafeConsole.ForegroundColorExists)
  39. {
  40. // Use mono's inbuilt terminfo driver to set the foreground color for us
  41. SafeConsole.ForegroundColor = color;
  42. }
  43. else
  44. {
  45. throw new PlatformNotSupportedException("Cannot set Unix TTY color as mono implementation is missing");
  46. }
  47. }
  48. public void SetConsoleEncoding(Encoding encoding)
  49. {
  50. // We shouldn't be changing this on Unix
  51. }
  52. public void SetConsoleTitle(string title)
  53. {
  54. Console.Title = title;
  55. }
  56. }
  57. }