Program.cs 12 KB

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