Program.cs 14 KB

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