Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using ARMeilleure.Translation.PTC;
  2. using Gtk;
  3. using Ryujinx.Common;
  4. using Ryujinx.Common.Configuration;
  5. using Ryujinx.Common.GraphicsDriver;
  6. using Ryujinx.Common.Logging;
  7. using Ryujinx.Common.System;
  8. using Ryujinx.Common.SystemInfo;
  9. using Ryujinx.Modules;
  10. using Ryujinx.Ui;
  11. using Ryujinx.Ui.Common;
  12. using Ryujinx.Ui.Common.Configuration;
  13. using Ryujinx.Ui.Common.Helper;
  14. using Ryujinx.Ui.Widgets;
  15. using SixLabors.ImageSharp.Formats.Jpeg;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Runtime.InteropServices;
  20. using System.Threading.Tasks;
  21. namespace Ryujinx
  22. {
  23. class Program
  24. {
  25. public static double WindowScaleFactor { get; private set; }
  26. public static string Version { get; private set; }
  27. public static string ConfigurationPath { get; set; }
  28. [DllImport("libX11")]
  29. private extern static int XInitThreads();
  30. [DllImport("user32.dll", SetLastError = true)]
  31. public static extern int MessageBoxA(IntPtr hWnd, string text, string caption, uint type);
  32. private const uint MB_ICONWARNING = 0x30;
  33. static void Main(string[] args)
  34. {
  35. Version = ReleaseInformations.GetVersion();
  36. if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134))
  37. {
  38. MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MB_ICONWARNING);
  39. }
  40. // Parse arguments
  41. CommandLineState.ParseArguments(args);
  42. // Hook unhandled exception and process exit events.
  43. GLib.ExceptionManager.UnhandledException += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
  44. AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
  45. AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) => Exit();
  46. // Make process DPI aware for proper window sizing on high-res screens.
  47. ForceDpiAware.Windows();
  48. WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();
  49. // Delete backup files after updating.
  50. Task.Run(Updater.CleanupUpdate);
  51. // NOTE: GTK3 doesn't init X11 in a multi threaded way.
  52. // This ends up causing race condition and abort of XCB when a context is created by SPB (even if SPB do call XInitThreads).
  53. if (OperatingSystem.IsLinux())
  54. {
  55. XInitThreads();
  56. }
  57. string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
  58. Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");
  59. // Setup base data directory.
  60. AppDataManager.Initialize(CommandLineState.BaseDirPathArg);
  61. // Initialize the configuration.
  62. ConfigurationState.Initialize();
  63. // Initialize the logger system.
  64. LoggerModule.Initialize();
  65. // Initialize Discord integration.
  66. DiscordIntegrationModule.Initialize();
  67. // Sets ImageSharp Jpeg Encoder Quality.
  68. SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.SetEncoder(JpegFormat.Instance, new JpegEncoder()
  69. {
  70. Quality = 100
  71. });
  72. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
  73. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");
  74. // Now load the configuration as the other subsystems are now registered
  75. ConfigurationPath = File.Exists(localConfigurationPath)
  76. ? localConfigurationPath
  77. : File.Exists(appDataConfigurationPath)
  78. ? appDataConfigurationPath
  79. : null;
  80. bool showVulkanPrompt = false;
  81. if (ConfigurationPath == null)
  82. {
  83. // No configuration, we load the default values and save it to disk
  84. ConfigurationPath = appDataConfigurationPath;
  85. ConfigurationState.Instance.LoadDefault();
  86. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  87. showVulkanPrompt = true;
  88. }
  89. else
  90. {
  91. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  92. {
  93. ConfigurationLoadResult result = ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  94. if ((result & ConfigurationLoadResult.MigratedFromPreVulkan) != 0)
  95. {
  96. showVulkanPrompt = true;
  97. }
  98. }
  99. else
  100. {
  101. ConfigurationState.Instance.LoadDefault();
  102. showVulkanPrompt = true;
  103. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
  104. }
  105. }
  106. // Check if graphics backend was overridden
  107. if (CommandLineState.OverrideGraphicsBackend != null)
  108. {
  109. if (CommandLineState.OverrideGraphicsBackend.ToLower() == "opengl")
  110. {
  111. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;
  112. showVulkanPrompt = false;
  113. }
  114. else if (CommandLineState.OverrideGraphicsBackend.ToLower() == "vulkan")
  115. {
  116. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.Vulkan;
  117. showVulkanPrompt = false;
  118. }
  119. }
  120. // Logging system information.
  121. PrintSystemInfo();
  122. // Enable OGL multithreading on the driver, when available.
  123. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  124. DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);
  125. // Initialize Gtk.
  126. Application.Init();
  127. // Check if keys exists.
  128. bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
  129. bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));
  130. if (!hasSystemProdKeys && !hasCommonProdKeys)
  131. {
  132. UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
  133. }
  134. // Show the main window UI.
  135. MainWindow mainWindow = new MainWindow();
  136. mainWindow.Show();
  137. if (CommandLineState.LaunchPathArg != null)
  138. {
  139. mainWindow.LoadApplication(CommandLineState.LaunchPathArg, CommandLineState.StartFullscreenArg);
  140. }
  141. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
  142. {
  143. Updater.BeginParse(mainWindow, false).ContinueWith(task =>
  144. {
  145. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  146. }, TaskContinuationOptions.OnlyOnFaulted);
  147. }
  148. if (showVulkanPrompt)
  149. {
  150. var buttonTexts = new Dictionary<int, string>()
  151. {
  152. { 0, "Yes (Vulkan)" },
  153. { 1, "No (OpenGL)" }
  154. };
  155. ResponseType response = GtkDialog.CreateCustomDialog(
  156. "Ryujinx - Default graphics backend",
  157. "Use Vulkan as default graphics backend?",
  158. "Ryujinx now supports the Vulkan API. " +
  159. "Vulkan greatly improves shader compilation performance, " +
  160. "and fixes some graphical glitches; however, since it is a new feature, " +
  161. "you may experience some issues that did not occur with OpenGL.\n\n" +
  162. "Note that you will also lose any existing shader cache the first time you start a game " +
  163. "on version 1.1.200 onwards, because Vulkan required changes to the shader cache that makes it incompatible with previous versions.\n\n" +
  164. "Would you like to set Vulkan as the default graphics backend? " +
  165. "You can change this at any time on the settings window.",
  166. buttonTexts,
  167. MessageType.Question);
  168. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = response == 0
  169. ? GraphicsBackend.Vulkan
  170. : GraphicsBackend.OpenGl;
  171. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  172. }
  173. Application.Run();
  174. }
  175. private static void PrintSystemInfo()
  176. {
  177. Logger.Notice.Print(LogClass.Application, $"Ryujinx Version: {Version}");
  178. SystemInfo.Gather().Print();
  179. var enabledLogs = Logger.GetEnabledLevels();
  180. Logger.Notice.Print(LogClass.Application, $"Logs Enabled: {(enabledLogs.Count == 0 ? "<None>" : string.Join(", ", enabledLogs))}");
  181. if (AppDataManager.Mode == AppDataManager.LaunchMode.Custom)
  182. {
  183. Logger.Notice.Print(LogClass.Application, $"Launch Mode: Custom Path {AppDataManager.BaseDirPath}");
  184. }
  185. else
  186. {
  187. Logger.Notice.Print(LogClass.Application, $"Launch Mode: {AppDataManager.Mode}");
  188. }
  189. }
  190. private static void ProcessUnhandledException(Exception ex, bool isTerminating)
  191. {
  192. Ptc.Close();
  193. PtcProfiler.Stop();
  194. string message = $"Unhandled exception caught: {ex}";
  195. Logger.Error?.PrintMsg(LogClass.Application, message);
  196. if (Logger.Error == null)
  197. {
  198. Logger.Notice.PrintMsg(LogClass.Application, message);
  199. }
  200. if (isTerminating)
  201. {
  202. Exit();
  203. }
  204. }
  205. public static void Exit()
  206. {
  207. DiscordIntegrationModule.Exit();
  208. Ptc.Dispose();
  209. PtcProfiler.Dispose();
  210. Logger.Shutdown();
  211. }
  212. }
  213. }