Program.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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.SystemInterop;
  7. using Ryujinx.Modules;
  8. using Ryujinx.SDL2.Common;
  9. using Ryujinx.Ui;
  10. using Ryujinx.Ui.Common;
  11. using Ryujinx.Ui.Common.Configuration;
  12. using Ryujinx.Ui.Common.Helper;
  13. using Ryujinx.Ui.Common.SystemInfo;
  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. private const uint MbIconWarning = 0x30;
  38. static Program()
  39. {
  40. if (OperatingSystem.IsLinux())
  41. {
  42. NativeLibrary.SetDllImportResolver(typeof(Program).Assembly, (name, assembly, path) =>
  43. {
  44. if (name != X11LibraryName)
  45. {
  46. return IntPtr.Zero;
  47. }
  48. if (!NativeLibrary.TryLoad("libX11.so.6", assembly, path, out IntPtr result))
  49. {
  50. if (!NativeLibrary.TryLoad("libX11.so", assembly, path, out result))
  51. {
  52. return IntPtr.Zero;
  53. }
  54. }
  55. return result;
  56. });
  57. }
  58. }
  59. static void Main(string[] args)
  60. {
  61. Version = ReleaseInformation.GetVersion();
  62. if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134))
  63. {
  64. 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}", MbIconWarning);
  65. }
  66. // Parse arguments
  67. CommandLineState.ParseArguments(args);
  68. // Hook unhandled exception and process exit events.
  69. GLib.ExceptionManager.UnhandledException += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
  70. AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
  71. AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) => Exit();
  72. // Make process DPI aware for proper window sizing on high-res screens.
  73. ForceDpiAware.Windows();
  74. WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();
  75. // Delete backup files after updating.
  76. Task.Run(Updater.CleanupUpdate);
  77. Console.Title = $"Ryujinx Console {Version}";
  78. // NOTE: GTK3 doesn't init X11 in a multi threaded way.
  79. // This ends up causing race condition and abort of XCB when a context is created by SPB (even if SPB do call XInitThreads).
  80. if (OperatingSystem.IsLinux())
  81. {
  82. if (XInitThreads() == 0)
  83. {
  84. throw new NotSupportedException("Failed to initialize multi-threading support.");
  85. }
  86. Environment.SetEnvironmentVariable("GDK_BACKEND", "x11");
  87. setenv("GDK_BACKEND", "x11", 1);
  88. }
  89. if (OperatingSystem.IsMacOS())
  90. {
  91. string baseDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  92. string resourcesDataDir;
  93. if (Path.GetFileName(baseDirectory) == "MacOS")
  94. {
  95. resourcesDataDir = Path.Combine(Directory.GetParent(baseDirectory).FullName, "Resources");
  96. }
  97. else
  98. {
  99. resourcesDataDir = baseDirectory;
  100. }
  101. static void SetEnvironmentVariableNoCaching(string key, string value)
  102. {
  103. int res = setenv(key, value, 1);
  104. Debug.Assert(res != -1);
  105. }
  106. // On macOS, GTK3 needs XDG_DATA_DIRS to be set, otherwise it will try searching for "gschemas.compiled" in system directories.
  107. SetEnvironmentVariableNoCaching("XDG_DATA_DIRS", Path.Combine(resourcesDataDir, "share"));
  108. // On macOS, GTK3 needs GDK_PIXBUF_MODULE_FILE to be set, otherwise it will try searching for "loaders.cache" in system directories.
  109. SetEnvironmentVariableNoCaching("GDK_PIXBUF_MODULE_FILE", Path.Combine(resourcesDataDir, "lib", "gdk-pixbuf-2.0", "2.10.0", "loaders.cache"));
  110. SetEnvironmentVariableNoCaching("GTK_IM_MODULE_FILE", Path.Combine(resourcesDataDir, "lib", "gtk-3.0", "3.0.0", "immodules.cache"));
  111. }
  112. string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
  113. Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");
  114. // Setup base data directory.
  115. AppDataManager.Initialize(CommandLineState.BaseDirPathArg);
  116. // Initialize the configuration.
  117. ConfigurationState.Initialize();
  118. // Initialize the logger system.
  119. LoggerModule.Initialize();
  120. // Initialize Discord integration.
  121. DiscordIntegrationModule.Initialize();
  122. // Initialize SDL2 driver
  123. SDL2Driver.MainThreadDispatcher = action =>
  124. {
  125. Application.Invoke(delegate
  126. {
  127. action();
  128. });
  129. };
  130. // Sets ImageSharp Jpeg Encoder Quality.
  131. SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.SetEncoder(JpegFormat.Instance, new JpegEncoder()
  132. {
  133. Quality = 100,
  134. });
  135. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
  136. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");
  137. // Now load the configuration as the other subsystems are now registered
  138. ConfigurationPath = File.Exists(localConfigurationPath)
  139. ? localConfigurationPath
  140. : File.Exists(appDataConfigurationPath)
  141. ? appDataConfigurationPath
  142. : null;
  143. bool showVulkanPrompt = false;
  144. if (ConfigurationPath == null)
  145. {
  146. // No configuration, we load the default values and save it to disk
  147. ConfigurationPath = appDataConfigurationPath;
  148. ConfigurationState.Instance.LoadDefault();
  149. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  150. showVulkanPrompt = true;
  151. }
  152. else
  153. {
  154. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  155. {
  156. ConfigurationLoadResult result = ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  157. if ((result & ConfigurationLoadResult.MigratedFromPreVulkan) != 0)
  158. {
  159. showVulkanPrompt = true;
  160. }
  161. }
  162. else
  163. {
  164. ConfigurationState.Instance.LoadDefault();
  165. showVulkanPrompt = true;
  166. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
  167. }
  168. }
  169. // Check if graphics backend was overridden.
  170. if (CommandLineState.OverrideGraphicsBackend != null)
  171. {
  172. if (CommandLineState.OverrideGraphicsBackend.ToLower() == "opengl")
  173. {
  174. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;
  175. showVulkanPrompt = false;
  176. }
  177. else if (CommandLineState.OverrideGraphicsBackend.ToLower() == "vulkan")
  178. {
  179. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.Vulkan;
  180. showVulkanPrompt = false;
  181. }
  182. }
  183. // Check if HideCursor was overridden.
  184. if (CommandLineState.OverrideHideCursor is not null)
  185. {
  186. ConfigurationState.Instance.HideCursor.Value = CommandLineState.OverrideHideCursor!.ToLower() switch
  187. {
  188. "never" => HideCursorMode.Never,
  189. "onidle" => HideCursorMode.OnIdle,
  190. "always" => HideCursorMode.Always,
  191. _ => ConfigurationState.Instance.HideCursor.Value,
  192. };
  193. }
  194. // Check if docked mode was overridden.
  195. if (CommandLineState.OverrideDockedMode.HasValue)
  196. {
  197. ConfigurationState.Instance.System.EnableDockedMode.Value = CommandLineState.OverrideDockedMode.Value;
  198. }
  199. // Logging system information.
  200. PrintSystemInfo();
  201. // Enable OGL multithreading on the driver, when available.
  202. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  203. DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);
  204. // Initialize Gtk.
  205. Application.Init();
  206. // Check if keys exists.
  207. bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
  208. bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));
  209. if (!hasSystemProdKeys && !hasCommonProdKeys)
  210. {
  211. UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
  212. }
  213. // Show the main window UI.
  214. MainWindow mainWindow = new();
  215. mainWindow.Show();
  216. if (OperatingSystem.IsLinux())
  217. {
  218. int currentVmMaxMapCount = LinuxHelper.VmMaxMapCount;
  219. if (LinuxHelper.VmMaxMapCount < LinuxHelper.RecommendedVmMaxMapCount)
  220. {
  221. Logger.Warning?.Print(LogClass.Application, $"The value of vm.max_map_count is lower than {LinuxHelper.RecommendedVmMaxMapCount}. ({currentVmMaxMapCount})");
  222. if (LinuxHelper.PkExecPath is not null)
  223. {
  224. var buttonTexts = new Dictionary<int, string>()
  225. {
  226. { 0, "Yes, until the next restart" },
  227. { 1, "Yes, permanently" },
  228. { 2, "No" },
  229. };
  230. ResponseType response = GtkDialog.CreateCustomDialog(
  231. "Ryujinx - Low limit for memory mappings detected",
  232. $"Would you like to increase the value of vm.max_map_count to {LinuxHelper.RecommendedVmMaxMapCount}?",
  233. "Some games might try to create more memory mappings than currently allowed. " +
  234. "Ryujinx will crash as soon as this limit gets exceeded.",
  235. buttonTexts,
  236. MessageType.Question);
  237. int rc;
  238. switch ((int)response)
  239. {
  240. case 0:
  241. rc = LinuxHelper.RunPkExec($"echo {LinuxHelper.RecommendedVmMaxMapCount} > {LinuxHelper.VmMaxMapCountPath}");
  242. if (rc == 0)
  243. {
  244. Logger.Info?.Print(LogClass.Application, $"vm.max_map_count set to {LinuxHelper.VmMaxMapCount} until the next restart.");
  245. }
  246. else
  247. {
  248. Logger.Error?.Print(LogClass.Application, $"Unable to change vm.max_map_count. Process exited with code: {rc}");
  249. }
  250. break;
  251. case 1:
  252. rc = LinuxHelper.RunPkExec($"echo \"vm.max_map_count = {LinuxHelper.RecommendedVmMaxMapCount}\" > {LinuxHelper.SysCtlConfigPath} && sysctl -p {LinuxHelper.SysCtlConfigPath}");
  253. if (rc == 0)
  254. {
  255. Logger.Info?.Print(LogClass.Application, $"vm.max_map_count set to {LinuxHelper.VmMaxMapCount}. Written to config: {LinuxHelper.SysCtlConfigPath}");
  256. }
  257. else
  258. {
  259. Logger.Error?.Print(LogClass.Application, $"Unable to write new value for vm.max_map_count to config. Process exited with code: {rc}");
  260. }
  261. break;
  262. }
  263. }
  264. else
  265. {
  266. GtkDialog.CreateWarningDialog(
  267. "Max amount of memory mappings is lower than recommended.",
  268. $"The current value of vm.max_map_count ({currentVmMaxMapCount}) is lower than {LinuxHelper.RecommendedVmMaxMapCount}." +
  269. "Some games might try to create more memory mappings than currently allowed. " +
  270. "Ryujinx will crash as soon as this limit gets exceeded.\n\n" +
  271. "You might want to either manually increase the limit or install pkexec, which allows Ryujinx to assist with that.");
  272. }
  273. }
  274. }
  275. if (CommandLineState.LaunchPathArg != null)
  276. {
  277. mainWindow.RunApplication(CommandLineState.LaunchPathArg, CommandLineState.StartFullscreenArg);
  278. }
  279. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
  280. {
  281. Updater.BeginParse(mainWindow, false).ContinueWith(task =>
  282. {
  283. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  284. }, TaskContinuationOptions.OnlyOnFaulted);
  285. }
  286. if (showVulkanPrompt)
  287. {
  288. var buttonTexts = new Dictionary<int, string>()
  289. {
  290. { 0, "Yes (Vulkan)" },
  291. { 1, "No (OpenGL)" },
  292. };
  293. ResponseType response = GtkDialog.CreateCustomDialog(
  294. "Ryujinx - Default graphics backend",
  295. "Use Vulkan as default graphics backend?",
  296. "Ryujinx now supports the Vulkan API. " +
  297. "Vulkan greatly improves shader compilation performance, " +
  298. "and fixes some graphical glitches; however, since it is a new feature, " +
  299. "you may experience some issues that did not occur with OpenGL.\n\n" +
  300. "Note that you will also lose any existing shader cache the first time you start a game " +
  301. "on version 1.1.200 onwards, because Vulkan required changes to the shader cache that makes it incompatible with previous versions.\n\n" +
  302. "Would you like to set Vulkan as the default graphics backend? " +
  303. "You can change this at any time on the settings window.",
  304. buttonTexts,
  305. MessageType.Question);
  306. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = response == 0
  307. ? GraphicsBackend.Vulkan
  308. : GraphicsBackend.OpenGl;
  309. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  310. }
  311. Application.Run();
  312. }
  313. private static void PrintSystemInfo()
  314. {
  315. Logger.Notice.Print(LogClass.Application, $"Ryujinx Version: {Version}");
  316. SystemInfo.Gather().Print();
  317. var enabledLogs = Logger.GetEnabledLevels();
  318. Logger.Notice.Print(LogClass.Application, $"Logs Enabled: {(enabledLogs.Count == 0 ? "<None>" : string.Join(", ", enabledLogs))}");
  319. if (AppDataManager.Mode == AppDataManager.LaunchMode.Custom)
  320. {
  321. Logger.Notice.Print(LogClass.Application, $"Launch Mode: Custom Path {AppDataManager.BaseDirPath}");
  322. }
  323. else
  324. {
  325. Logger.Notice.Print(LogClass.Application, $"Launch Mode: {AppDataManager.Mode}");
  326. }
  327. }
  328. private static void ProcessUnhandledException(Exception ex, bool isTerminating)
  329. {
  330. string message = $"Unhandled exception caught: {ex}";
  331. Logger.Error?.PrintMsg(LogClass.Application, message);
  332. if (Logger.Error == null)
  333. {
  334. Logger.Notice.PrintMsg(LogClass.Application, message);
  335. }
  336. if (isTerminating)
  337. {
  338. Exit();
  339. }
  340. }
  341. public static void Exit()
  342. {
  343. DiscordIntegrationModule.Exit();
  344. Logger.Shutdown();
  345. }
  346. }
  347. }