Program.cs 13 KB

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