Program.cs 13 KB

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