Program.cs 12 KB

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