Program.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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.Version;
  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, ReleaseInformation.ConfigName);
  136. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, ReleaseInformation.ConfigName);
  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. if (ConfigurationPath == null)
  144. {
  145. // No configuration, we load the default values and save it to disk
  146. ConfigurationPath = appDataConfigurationPath;
  147. ConfigurationState.Instance.LoadDefault();
  148. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  149. }
  150. else
  151. {
  152. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  153. {
  154. ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  155. }
  156. else
  157. {
  158. ConfigurationState.Instance.LoadDefault();
  159. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
  160. }
  161. }
  162. // Check if graphics backend was overridden.
  163. if (CommandLineState.OverrideGraphicsBackend != null)
  164. {
  165. if (CommandLineState.OverrideGraphicsBackend.ToLower() == "opengl")
  166. {
  167. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;
  168. }
  169. else if (CommandLineState.OverrideGraphicsBackend.ToLower() == "vulkan")
  170. {
  171. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.Vulkan;
  172. }
  173. }
  174. // Check if HideCursor was overridden.
  175. if (CommandLineState.OverrideHideCursor is not null)
  176. {
  177. ConfigurationState.Instance.HideCursor.Value = CommandLineState.OverrideHideCursor!.ToLower() switch
  178. {
  179. "never" => HideCursorMode.Never,
  180. "onidle" => HideCursorMode.OnIdle,
  181. "always" => HideCursorMode.Always,
  182. _ => ConfigurationState.Instance.HideCursor.Value,
  183. };
  184. }
  185. // Check if docked mode was overridden.
  186. if (CommandLineState.OverrideDockedMode.HasValue)
  187. {
  188. ConfigurationState.Instance.System.EnableDockedMode.Value = CommandLineState.OverrideDockedMode.Value;
  189. }
  190. // Logging system information.
  191. PrintSystemInfo();
  192. // Enable OGL multithreading on the driver, when available.
  193. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  194. DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);
  195. // Initialize Gtk.
  196. Application.Init();
  197. // Check if keys exists.
  198. bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
  199. bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));
  200. if (!hasSystemProdKeys && !hasCommonProdKeys)
  201. {
  202. UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
  203. }
  204. // Show the main window UI.
  205. MainWindow mainWindow = new();
  206. mainWindow.Show();
  207. if (OperatingSystem.IsLinux())
  208. {
  209. int currentVmMaxMapCount = LinuxHelper.VmMaxMapCount;
  210. if (LinuxHelper.VmMaxMapCount < LinuxHelper.RecommendedVmMaxMapCount)
  211. {
  212. Logger.Warning?.Print(LogClass.Application, $"The value of vm.max_map_count is lower than {LinuxHelper.RecommendedVmMaxMapCount}. ({currentVmMaxMapCount})");
  213. if (LinuxHelper.PkExecPath is not null)
  214. {
  215. var buttonTexts = new Dictionary<int, string>()
  216. {
  217. { 0, "Yes, until the next restart" },
  218. { 1, "Yes, permanently" },
  219. { 2, "No" },
  220. };
  221. ResponseType response = GtkDialog.CreateCustomDialog(
  222. "Ryujinx - Low limit for memory mappings detected",
  223. $"Would you like to increase the value of vm.max_map_count to {LinuxHelper.RecommendedVmMaxMapCount}?",
  224. "Some games might try to create more memory mappings than currently allowed. " +
  225. "Ryujinx will crash as soon as this limit gets exceeded.",
  226. buttonTexts,
  227. MessageType.Question);
  228. int rc;
  229. switch ((int)response)
  230. {
  231. case 0:
  232. rc = LinuxHelper.RunPkExec($"echo {LinuxHelper.RecommendedVmMaxMapCount} > {LinuxHelper.VmMaxMapCountPath}");
  233. if (rc == 0)
  234. {
  235. Logger.Info?.Print(LogClass.Application, $"vm.max_map_count set to {LinuxHelper.VmMaxMapCount} until the next restart.");
  236. }
  237. else
  238. {
  239. Logger.Error?.Print(LogClass.Application, $"Unable to change vm.max_map_count. Process exited with code: {rc}");
  240. }
  241. break;
  242. case 1:
  243. rc = LinuxHelper.RunPkExec($"echo \"vm.max_map_count = {LinuxHelper.RecommendedVmMaxMapCount}\" > {LinuxHelper.SysCtlConfigPath} && sysctl -p {LinuxHelper.SysCtlConfigPath}");
  244. if (rc == 0)
  245. {
  246. Logger.Info?.Print(LogClass.Application, $"vm.max_map_count set to {LinuxHelper.VmMaxMapCount}. Written to config: {LinuxHelper.SysCtlConfigPath}");
  247. }
  248. else
  249. {
  250. Logger.Error?.Print(LogClass.Application, $"Unable to write new value for vm.max_map_count to config. Process exited with code: {rc}");
  251. }
  252. break;
  253. }
  254. }
  255. else
  256. {
  257. GtkDialog.CreateWarningDialog(
  258. "Max amount of memory mappings is lower than recommended.",
  259. $"The current value of vm.max_map_count ({currentVmMaxMapCount}) is lower than {LinuxHelper.RecommendedVmMaxMapCount}." +
  260. "Some games might try to create more memory mappings than currently allowed. " +
  261. "Ryujinx will crash as soon as this limit gets exceeded.\n\n" +
  262. "You might want to either manually increase the limit or install pkexec, which allows Ryujinx to assist with that.");
  263. }
  264. }
  265. }
  266. if (CommandLineState.LaunchPathArg != null)
  267. {
  268. mainWindow.RunApplication(CommandLineState.LaunchPathArg, CommandLineState.StartFullscreenArg);
  269. }
  270. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
  271. {
  272. Updater.BeginParse(mainWindow, false).ContinueWith(task =>
  273. {
  274. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  275. }, TaskContinuationOptions.OnlyOnFaulted);
  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. }