Program.cs 11 KB

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