Program.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. Console.Title = $"Ryujinx Console {Version}";
  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. Environment.SetEnvironmentVariable("GDK_BACKEND", "x11");
  86. setenv("GDK_BACKEND", "x11", 1);
  87. }
  88. if (OperatingSystem.IsMacOS())
  89. {
  90. string baseDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  91. string resourcesDataDir;
  92. if (Path.GetFileName(baseDirectory) == "MacOS")
  93. {
  94. resourcesDataDir = Path.Combine(Directory.GetParent(baseDirectory).FullName, "Resources");
  95. }
  96. else
  97. {
  98. resourcesDataDir = baseDirectory;
  99. }
  100. void SetEnvironmentVariableNoCaching(string key, string value)
  101. {
  102. int res = setenv(key, value, 1);
  103. Debug.Assert(res != -1);
  104. }
  105. // On macOS, GTK3 needs XDG_DATA_DIRS to be set, otherwise it will try searching for "gschemas.compiled" in system directories.
  106. SetEnvironmentVariableNoCaching("XDG_DATA_DIRS", Path.Combine(resourcesDataDir, "share"));
  107. // On macOS, GTK3 needs GDK_PIXBUF_MODULE_FILE to be set, otherwise it will try searching for "loaders.cache" in system directories.
  108. SetEnvironmentVariableNoCaching("GDK_PIXBUF_MODULE_FILE", Path.Combine(resourcesDataDir, "lib", "gdk-pixbuf-2.0", "2.10.0", "loaders.cache"));
  109. SetEnvironmentVariableNoCaching("GTK_IM_MODULE_FILE", Path.Combine(resourcesDataDir, "lib", "gtk-3.0", "3.0.0", "immodules.cache"));
  110. }
  111. string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
  112. Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");
  113. // Setup base data directory.
  114. AppDataManager.Initialize(CommandLineState.BaseDirPathArg);
  115. // Initialize the configuration.
  116. ConfigurationState.Initialize();
  117. // Initialize the logger system.
  118. LoggerModule.Initialize();
  119. // Initialize Discord integration.
  120. DiscordIntegrationModule.Initialize();
  121. // Initialize SDL2 driver
  122. SDL2Driver.MainThreadDispatcher = action =>
  123. {
  124. Application.Invoke(delegate
  125. {
  126. action();
  127. });
  128. };
  129. // Sets ImageSharp Jpeg Encoder Quality.
  130. SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.SetEncoder(JpegFormat.Instance, new JpegEncoder()
  131. {
  132. Quality = 100
  133. });
  134. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
  135. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");
  136. // Now load the configuration as the other subsystems are now registered
  137. ConfigurationPath = File.Exists(localConfigurationPath)
  138. ? localConfigurationPath
  139. : File.Exists(appDataConfigurationPath)
  140. ? appDataConfigurationPath
  141. : null;
  142. bool showVulkanPrompt = false;
  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. showVulkanPrompt = true;
  150. }
  151. else
  152. {
  153. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  154. {
  155. ConfigurationLoadResult result = ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  156. if ((result & ConfigurationLoadResult.MigratedFromPreVulkan) != 0)
  157. {
  158. showVulkanPrompt = true;
  159. }
  160. }
  161. else
  162. {
  163. ConfigurationState.Instance.LoadDefault();
  164. showVulkanPrompt = true;
  165. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
  166. }
  167. }
  168. // Check if graphics backend was overridden
  169. if (CommandLineState.OverrideGraphicsBackend != null)
  170. {
  171. if (CommandLineState.OverrideGraphicsBackend.ToLower() == "opengl")
  172. {
  173. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;
  174. showVulkanPrompt = false;
  175. }
  176. else if (CommandLineState.OverrideGraphicsBackend.ToLower() == "vulkan")
  177. {
  178. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.Vulkan;
  179. showVulkanPrompt = false;
  180. }
  181. }
  182. // Check if docked mode was overriden.
  183. if (CommandLineState.OverrideDockedMode.HasValue)
  184. {
  185. ConfigurationState.Instance.System.EnableDockedMode.Value = CommandLineState.OverrideDockedMode.Value;
  186. }
  187. // Logging system information.
  188. PrintSystemInfo();
  189. // Enable OGL multithreading on the driver, when available.
  190. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  191. DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);
  192. // Initialize Gtk.
  193. Application.Init();
  194. // Check if keys exists.
  195. bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
  196. bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));
  197. if (!hasSystemProdKeys && !hasCommonProdKeys)
  198. {
  199. UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
  200. }
  201. // Show the main window UI.
  202. MainWindow mainWindow = new MainWindow();
  203. mainWindow.Show();
  204. if (CommandLineState.LaunchPathArg != null)
  205. {
  206. mainWindow.RunApplication(CommandLineState.LaunchPathArg, CommandLineState.StartFullscreenArg);
  207. }
  208. if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
  209. {
  210. Updater.BeginParse(mainWindow, false).ContinueWith(task =>
  211. {
  212. Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
  213. }, TaskContinuationOptions.OnlyOnFaulted);
  214. }
  215. if (showVulkanPrompt)
  216. {
  217. var buttonTexts = new Dictionary<int, string>()
  218. {
  219. { 0, "Yes (Vulkan)" },
  220. { 1, "No (OpenGL)" }
  221. };
  222. ResponseType response = GtkDialog.CreateCustomDialog(
  223. "Ryujinx - Default graphics backend",
  224. "Use Vulkan as default graphics backend?",
  225. "Ryujinx now supports the Vulkan API. " +
  226. "Vulkan greatly improves shader compilation performance, " +
  227. "and fixes some graphical glitches; however, since it is a new feature, " +
  228. "you may experience some issues that did not occur with OpenGL.\n\n" +
  229. "Note that you will also lose any existing shader cache the first time you start a game " +
  230. "on version 1.1.200 onwards, because Vulkan required changes to the shader cache that makes it incompatible with previous versions.\n\n" +
  231. "Would you like to set Vulkan as the default graphics backend? " +
  232. "You can change this at any time on the settings window.",
  233. buttonTexts,
  234. MessageType.Question);
  235. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = response == 0
  236. ? GraphicsBackend.Vulkan
  237. : GraphicsBackend.OpenGl;
  238. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  239. }
  240. Application.Run();
  241. }
  242. private static void PrintSystemInfo()
  243. {
  244. Logger.Notice.Print(LogClass.Application, $"Ryujinx Version: {Version}");
  245. SystemInfo.Gather().Print();
  246. var enabledLogs = Logger.GetEnabledLevels();
  247. Logger.Notice.Print(LogClass.Application, $"Logs Enabled: {(enabledLogs.Count == 0 ? "<None>" : string.Join(", ", enabledLogs))}");
  248. if (AppDataManager.Mode == AppDataManager.LaunchMode.Custom)
  249. {
  250. Logger.Notice.Print(LogClass.Application, $"Launch Mode: Custom Path {AppDataManager.BaseDirPath}");
  251. }
  252. else
  253. {
  254. Logger.Notice.Print(LogClass.Application, $"Launch Mode: {AppDataManager.Mode}");
  255. }
  256. }
  257. private static void ProcessUnhandledException(Exception ex, bool isTerminating)
  258. {
  259. string message = $"Unhandled exception caught: {ex}";
  260. Logger.Error?.PrintMsg(LogClass.Application, message);
  261. if (Logger.Error == null)
  262. {
  263. Logger.Notice.PrintMsg(LogClass.Application, message);
  264. }
  265. if (isTerminating)
  266. {
  267. Exit();
  268. }
  269. }
  270. public static void Exit()
  271. {
  272. DiscordIntegrationModule.Exit();
  273. Logger.Shutdown();
  274. }
  275. }
  276. }