Program.cs 16 KB

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