Program.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. using ARMeilleure.Translation.PTC;
  2. using Avalonia;
  3. using Avalonia.OpenGL;
  4. using Avalonia.Rendering;
  5. using Avalonia.Threading;
  6. using Ryujinx.Ava.Ui.Backend;
  7. using Ryujinx.Ava.Ui.Controls;
  8. using Ryujinx.Ava.Ui.Windows;
  9. using Ryujinx.Common;
  10. using Ryujinx.Common.Configuration;
  11. using Ryujinx.Common.GraphicsDriver;
  12. using Ryujinx.Common.Logging;
  13. using Ryujinx.Common.System;
  14. using Ryujinx.Common.SystemInfo;
  15. using Ryujinx.Graphics.Vulkan;
  16. using Ryujinx.Modules;
  17. using Ryujinx.Ui.Common;
  18. using Ryujinx.Ui.Common.Configuration;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.IO;
  22. using System.Runtime.InteropServices;
  23. using System.Threading.Tasks;
  24. namespace Ryujinx.Ava
  25. {
  26. internal class Program
  27. {
  28. public static double WindowScaleFactor { get; set; }
  29. public static double ActualScaleFactor { get; set; }
  30. public static string Version { get; private set; }
  31. public static string ConfigurationPath { get; private set; }
  32. public static string CommandLineProfile { get; set; }
  33. public static bool PreviewerDetached { get; private set; }
  34. public static RenderTimer RenderTimer { get; private set; }
  35. public static bool UseVulkan { get; private set; }
  36. [DllImport("user32.dll", SetLastError = true)]
  37. public static extern int MessageBoxA(IntPtr hWnd, string text, string caption, uint type);
  38. private const uint MB_ICONWARNING = 0x30;
  39. private const int BaseDpi = 96;
  40. public static void Main(string[] args)
  41. {
  42. Version = ReleaseInformations.GetVersion();
  43. if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134))
  44. {
  45. 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);
  46. }
  47. PreviewerDetached = true;
  48. Initialize(args);
  49. RenderTimer = new RenderTimer();
  50. BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
  51. RenderTimer.Dispose();
  52. }
  53. public static AppBuilder BuildAvaloniaApp()
  54. {
  55. return AppBuilder.Configure<App>()
  56. .UsePlatformDetect()
  57. .With(new X11PlatformOptions
  58. {
  59. EnableMultiTouch = true,
  60. EnableIme = true,
  61. UseEGL = false,
  62. UseGpu = !UseVulkan,
  63. GlProfiles = new List<GlVersion>()
  64. {
  65. new GlVersion(GlProfileType.OpenGL, 4, 3)
  66. }
  67. })
  68. .With(new Win32PlatformOptions
  69. {
  70. EnableMultitouch = true,
  71. UseWgl = !UseVulkan,
  72. WglProfiles = new List<GlVersion>()
  73. {
  74. new GlVersion(GlProfileType.OpenGL, 4, 3)
  75. },
  76. AllowEglInitialization = false,
  77. CompositionBackdropCornerRadius = 8f,
  78. })
  79. .UseSkia()
  80. .With(new Ui.Vulkan.VulkanOptions()
  81. {
  82. ApplicationName = "Ryujinx.Graphics.Vulkan",
  83. MaxQueueCount = 2,
  84. PreferDiscreteGpu = true,
  85. PreferredDevice = !PreviewerDetached ? "" : ConfigurationState.Instance.Graphics.PreferredGpu.Value,
  86. UseDebug = !PreviewerDetached ? false : ConfigurationState.Instance.Logger.GraphicsDebugLevel.Value != GraphicsDebugLevel.None,
  87. })
  88. .With(new SkiaOptions()
  89. {
  90. CustomGpuFactory = UseVulkan ? SkiaGpuFactory.CreateVulkanGpu : null
  91. })
  92. .AfterSetup(_ =>
  93. {
  94. AvaloniaLocator.CurrentMutable
  95. .Bind<IRenderTimer>().ToConstant(RenderTimer)
  96. .Bind<IRenderLoop>().ToConstant(new RenderLoop(RenderTimer, Dispatcher.UIThread));
  97. })
  98. .LogToTrace();
  99. }
  100. private static void Initialize(string[] args)
  101. {
  102. // Parse Arguments.
  103. string launchPathArg = null;
  104. string baseDirPathArg = null;
  105. bool startFullscreenArg = false;
  106. for (int i = 0; i < args.Length; ++i)
  107. {
  108. string arg = args[i];
  109. if (arg == "-r" || arg == "--root-data-dir")
  110. {
  111. if (i + 1 >= args.Length)
  112. {
  113. Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");
  114. continue;
  115. }
  116. baseDirPathArg = args[++i];
  117. }
  118. else if (arg == "-p" || arg == "--profile")
  119. {
  120. if (i + 1 >= args.Length)
  121. {
  122. Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");
  123. continue;
  124. }
  125. CommandLineProfile = args[++i];
  126. }
  127. else if (arg == "-f" || arg == "--fullscreen")
  128. {
  129. startFullscreenArg = true;
  130. }
  131. else
  132. {
  133. launchPathArg = arg;
  134. }
  135. }
  136. // Delete backup files after updating.
  137. Task.Run(Updater.CleanupUpdate);
  138. Console.Title = $"Ryujinx Console {Version}";
  139. // Hook unhandled exception and process exit events.
  140. AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
  141. AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) => Exit();
  142. // Setup base data directory.
  143. AppDataManager.Initialize(baseDirPathArg);
  144. // Initialize the configuration.
  145. ConfigurationState.Initialize();
  146. // Initialize the logger system.
  147. LoggerModule.Initialize();
  148. // Initialize Discord integration.
  149. DiscordIntegrationModule.Initialize();
  150. ReloadConfig();
  151. UseVulkan = PreviewerDetached ? ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan : false;
  152. if (UseVulkan)
  153. {
  154. if (VulkanRenderer.GetPhysicalDevices().Length == 0)
  155. {
  156. UseVulkan = false;
  157. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;
  158. Logger.Warning?.PrintMsg(LogClass.Application, "A suitable Vulkan physical device is not available. Falling back to OpenGL");
  159. }
  160. }
  161. if (UseVulkan)
  162. {
  163. // With a custom gpu backend, avalonia doesn't enable dpi awareness, so the backend must handle it. This isn't so for the opengl backed,
  164. // as that uses avalonia's gpu backend and it's enabled there.
  165. ForceDpiAware.Windows();
  166. }
  167. WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();
  168. ActualScaleFactor = ForceDpiAware.GetActualScaleFactor() / BaseDpi;
  169. // Logging system information.
  170. PrintSystemInfo();
  171. // Enable OGL multithreading on the driver, when available.
  172. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  173. DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);
  174. // Check if keys exists.
  175. bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
  176. if (!hasSystemProdKeys)
  177. {
  178. if (!(AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"))))
  179. {
  180. MainWindow.ShowKeyErrorOnLoad = true;
  181. }
  182. }
  183. if (launchPathArg != null)
  184. {
  185. MainWindow.DeferLoadApplication(launchPathArg, startFullscreenArg);
  186. }
  187. }
  188. public static void ReloadConfig()
  189. {
  190. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
  191. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");
  192. // Now load the configuration as the other subsystems are now registered
  193. if (File.Exists(localConfigurationPath))
  194. {
  195. ConfigurationPath = localConfigurationPath;
  196. }
  197. else if (File.Exists(appDataConfigurationPath))
  198. {
  199. ConfigurationPath = appDataConfigurationPath;
  200. }
  201. if (ConfigurationPath == null)
  202. {
  203. // No configuration, we load the default values and save it to disk
  204. ConfigurationPath = appDataConfigurationPath;
  205. ConfigurationState.Instance.LoadDefault();
  206. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  207. }
  208. else
  209. {
  210. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  211. {
  212. ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  213. }
  214. else
  215. {
  216. ConfigurationState.Instance.LoadDefault();
  217. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
  218. }
  219. }
  220. }
  221. private static void PrintSystemInfo()
  222. {
  223. Logger.Notice.Print(LogClass.Application, $"Ryujinx Version: {Version}");
  224. SystemInfo.Gather().Print();
  225. var enabledLogs = Logger.GetEnabledLevels();
  226. Logger.Notice.Print(LogClass.Application, $"Logs Enabled: {(enabledLogs.Count == 0 ? "<None>" : string.Join(", ", enabledLogs))}");
  227. if (AppDataManager.Mode == AppDataManager.LaunchMode.Custom)
  228. {
  229. Logger.Notice.Print(LogClass.Application, $"Launch Mode: Custom Path {AppDataManager.BaseDirPath}");
  230. }
  231. else
  232. {
  233. Logger.Notice.Print(LogClass.Application, $"Launch Mode: {AppDataManager.Mode}");
  234. }
  235. }
  236. private static void ProcessUnhandledException(Exception ex, bool isTerminating)
  237. {
  238. Ptc.Close();
  239. PtcProfiler.Stop();
  240. string message = $"Unhandled exception caught: {ex}";
  241. Logger.Error?.PrintMsg(LogClass.Application, message);
  242. if (Logger.Error == null)
  243. {
  244. Logger.Notice.PrintMsg(LogClass.Application, message);
  245. }
  246. if (isTerminating)
  247. {
  248. Exit();
  249. }
  250. }
  251. public static void Exit()
  252. {
  253. DiscordIntegrationModule.Exit();
  254. Ptc.Dispose();
  255. PtcProfiler.Dispose();
  256. Logger.Shutdown();
  257. }
  258. }
  259. }