Program.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using Avalonia;
  2. using Avalonia.Threading;
  3. using DiscordRPC;
  4. using Gommon;
  5. using Projektanker.Icons.Avalonia;
  6. using Projektanker.Icons.Avalonia.FontAwesome;
  7. using Projektanker.Icons.Avalonia.MaterialDesign;
  8. using Ryujinx.Ava.UI.Helpers;
  9. using Ryujinx.Ava.UI.Windows;
  10. using Ryujinx.Ava.Utilities;
  11. using Ryujinx.Ava.Utilities.Configuration;
  12. using Ryujinx.Ava.Utilities.SystemInfo;
  13. using Ryujinx.Common;
  14. using Ryujinx.Common.Configuration;
  15. using Ryujinx.Common.GraphicsDriver;
  16. using Ryujinx.Common.Logging;
  17. using Ryujinx.Common.SystemInterop;
  18. using Ryujinx.Graphics.Vulkan.MoltenVK;
  19. using Ryujinx.Headless;
  20. using Ryujinx.SDL2.Common;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.IO;
  24. using System.Runtime.InteropServices;
  25. using System.Threading.Tasks;
  26. namespace Ryujinx.Ava
  27. {
  28. internal partial class Program
  29. {
  30. public static double WindowScaleFactor { get; set; }
  31. public static double DesktopScaleFactor { get; set; } = 1.0;
  32. public static string Version { get; private set; }
  33. public static string ConfigurationPath { get; private set; }
  34. public static bool PreviewerDetached { get; private set; }
  35. public static bool UseHardwareAcceleration { get; private set; }
  36. [LibraryImport("user32.dll", SetLastError = true)]
  37. public static partial int MessageBoxA(nint hWnd, [MarshalAs(UnmanagedType.LPStr)] string text, [MarshalAs(UnmanagedType.LPStr)] string caption, uint type);
  38. private const uint MbIconwarning = 0x30;
  39. public static int Main(string[] args)
  40. {
  41. Version = ReleaseInformation.Version;
  42. if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 19041))
  43. {
  44. _ = MessageBoxA(nint.Zero, "You are running an outdated version of Windows.\n\nRyujinx supports Windows 10 version 20H1 and newer.\n", $"Ryujinx {Version}", MbIconwarning);
  45. return 0;
  46. }
  47. PreviewerDetached = true;
  48. if (args.Length > 0 && args[0] is "--no-gui" or "nogui")
  49. {
  50. HeadlessRyujinx.Entrypoint(args[1..]);
  51. return 0;
  52. }
  53. Initialize(args);
  54. LoggerAdapter.Register();
  55. IconProvider.Current
  56. .Register<FontAwesomeIconProvider>()
  57. .Register<MaterialDesignIconProvider>();
  58. return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
  59. }
  60. public static AppBuilder BuildAvaloniaApp() =>
  61. AppBuilder.Configure<RyujinxApp>()
  62. .UsePlatformDetect()
  63. .With(new X11PlatformOptions
  64. {
  65. EnableMultiTouch = true,
  66. EnableIme = true,
  67. EnableInputFocusProxy = Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP") == "gamescope",
  68. RenderingMode = UseHardwareAcceleration
  69. ? [X11RenderingMode.Glx, X11RenderingMode.Software]
  70. : [X11RenderingMode.Software]
  71. })
  72. .With(new Win32PlatformOptions
  73. {
  74. WinUICompositionBackdropCornerRadius = 8.0f,
  75. RenderingMode = UseHardwareAcceleration
  76. ? [Win32RenderingMode.AngleEgl, Win32RenderingMode.Software]
  77. : [Win32RenderingMode.Software]
  78. });
  79. private static void Initialize(string[] args)
  80. {
  81. // Ensure Discord presence timestamp begins at the absolute start of when Ryujinx is launched
  82. DiscordIntegrationModule.EmulatorStartedAt = Timestamps.Now;
  83. // Parse arguments
  84. CommandLineState.ParseArguments(args);
  85. if (OperatingSystem.IsMacOS())
  86. {
  87. MVKInitialization.InitializeResolver();
  88. }
  89. // Delete backup files after updating.
  90. Task.Run(Updater.CleanupUpdate);
  91. Console.Title = $"{RyujinxApp.FullAppName} Console {Version}";
  92. // Hook unhandled exception and process exit events.
  93. AppDomain.CurrentDomain.UnhandledException += (sender, e)
  94. => ProcessUnhandledException(sender, e.ExceptionObject as Exception, e.IsTerminating);
  95. TaskScheduler.UnobservedTaskException += (sender, e)
  96. => ProcessUnhandledException(sender, e.Exception, false);
  97. AppDomain.CurrentDomain.ProcessExit += (_, _) => Exit();
  98. // Setup base data directory.
  99. AppDataManager.Initialize(CommandLineState.BaseDirPathArg);
  100. // Initialize the configuration.
  101. ConfigurationState.Initialize();
  102. // Initialize the logger system.
  103. LoggerModule.Initialize();
  104. // Initialize Discord integration.
  105. DiscordIntegrationModule.Initialize();
  106. // Initialize SDL2 driver
  107. SDL2Driver.MainThreadDispatcher = action => Dispatcher.UIThread.InvokeAsync(action, DispatcherPriority.Input);
  108. ReloadConfig();
  109. WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();
  110. // Logging system information.
  111. PrintSystemInfo();
  112. // Enable OGL multithreading on the driver, and some other flags.
  113. DriverUtilities.InitDriverConfig(ConfigurationState.Instance.Graphics.BackendThreading == BackendThreading.Off);
  114. // Check if keys exists.
  115. if (!File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys")))
  116. {
  117. if (!(AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"))))
  118. {
  119. MainWindow.ShowKeyErrorOnLoad = true;
  120. }
  121. }
  122. if (CommandLineState.LaunchPathArg != null)
  123. {
  124. MainWindow.DeferLoadApplication(CommandLineState.LaunchPathArg, CommandLineState.LaunchApplicationId, CommandLineState.StartFullscreenArg);
  125. }
  126. }
  127. public static void ReloadConfig()
  128. {
  129. string localConfigurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ReleaseInformation.ConfigName);
  130. string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, ReleaseInformation.ConfigName);
  131. // Now load the configuration as the other subsystems are now registered
  132. if (File.Exists(localConfigurationPath))
  133. {
  134. ConfigurationPath = localConfigurationPath;
  135. }
  136. else if (File.Exists(appDataConfigurationPath))
  137. {
  138. ConfigurationPath = appDataConfigurationPath;
  139. }
  140. if (ConfigurationPath == null)
  141. {
  142. // No configuration, we load the default values and save it to disk
  143. ConfigurationPath = appDataConfigurationPath;
  144. Logger.Notice.Print(LogClass.Application, $"No configuration file found. Saving default configuration to: {ConfigurationPath}");
  145. ConfigurationState.Instance.LoadDefault();
  146. ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
  147. }
  148. else
  149. {
  150. Logger.Notice.Print(LogClass.Application, $"Loading configuration from: {ConfigurationPath}");
  151. if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
  152. {
  153. ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
  154. }
  155. else
  156. {
  157. Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location: {ConfigurationPath}");
  158. ConfigurationState.Instance.LoadDefault();
  159. }
  160. }
  161. UseHardwareAcceleration = ConfigurationState.Instance.EnableHardwareAcceleration;
  162. // Check if graphics backend was overridden
  163. if (CommandLineState.OverrideGraphicsBackend is not null)
  164. ConfigurationState.Instance.Graphics.GraphicsBackend.Value = CommandLineState.OverrideGraphicsBackend.ToLower() switch
  165. {
  166. "opengl" => GraphicsBackend.OpenGl,
  167. "vulkan" => GraphicsBackend.Vulkan,
  168. "metal" => GraphicsBackend.Metal,
  169. _ => ConfigurationState.Instance.Graphics.GraphicsBackend
  170. };
  171. // Check if backend threading was overridden
  172. if (CommandLineState.OverrideBackendThreading is not null)
  173. ConfigurationState.Instance.Graphics.BackendThreading.Value = CommandLineState.OverrideBackendThreading.ToLower() switch
  174. {
  175. "auto" => BackendThreading.Auto,
  176. "off" => BackendThreading.Off,
  177. "on" => BackendThreading.On,
  178. _ => ConfigurationState.Instance.Graphics.BackendThreading
  179. };
  180. // Check if docked mode was overriden.
  181. if (CommandLineState.OverrideDockedMode.HasValue)
  182. ConfigurationState.Instance.System.EnableDockedMode.Value = CommandLineState.OverrideDockedMode.Value;
  183. // Check if HideCursor was overridden.
  184. if (CommandLineState.OverrideHideCursor is not null)
  185. ConfigurationState.Instance.HideCursor.Value = CommandLineState.OverrideHideCursor.ToLower() switch
  186. {
  187. "never" => HideCursorMode.Never,
  188. "onidle" => HideCursorMode.OnIdle,
  189. "always" => HideCursorMode.Always,
  190. _ => ConfigurationState.Instance.HideCursor,
  191. };
  192. // Check if hardware-acceleration was overridden.
  193. if (CommandLineState.OverrideHardwareAcceleration != null)
  194. UseHardwareAcceleration = CommandLineState.OverrideHardwareAcceleration.Value;
  195. }
  196. internal static void PrintSystemInfo()
  197. {
  198. Logger.Notice.Print(LogClass.Application, $"{RyujinxApp.FullAppName} Version: {Version}");
  199. Logger.Notice.Print(LogClass.Application, $".NET Runtime: {RuntimeInformation.FrameworkDescription}");
  200. SystemInfo.Gather().Print();
  201. Logger.Notice.Print(LogClass.Application, $"Logs Enabled: {
  202. Logger.GetEnabledLevels()
  203. .FormatCollection(
  204. x => x.ToString(),
  205. separator: ", ",
  206. emptyCollectionFallback: "<None>")
  207. }");
  208. Logger.Notice.Print(LogClass.Application,
  209. AppDataManager.Mode == AppDataManager.LaunchMode.Custom
  210. ? $"Launch Mode: Custom Path {AppDataManager.BaseDirPath}"
  211. : $"Launch Mode: {AppDataManager.Mode}");
  212. }
  213. internal static void ProcessUnhandledException(object sender, Exception initialException, bool isTerminating)
  214. {
  215. Logger.Log log = Logger.Error ?? Logger.Notice;
  216. List<Exception> exceptions = [];
  217. if (initialException is AggregateException ae)
  218. {
  219. exceptions.AddRange(ae.InnerExceptions);
  220. }
  221. else
  222. {
  223. exceptions.Add(initialException);
  224. }
  225. foreach (Exception e in exceptions)
  226. {
  227. string message = $"Unhandled exception caught: {e}";
  228. // ReSharper disable once ConstantConditionalAccessQualifier
  229. if (sender?.GetType()?.AsPrettyString() is { } senderName)
  230. log.Print(LogClass.Application, message, senderName);
  231. else
  232. log.PrintMsg(LogClass.Application, message);
  233. }
  234. if (isTerminating)
  235. Exit();
  236. }
  237. internal static void Exit()
  238. {
  239. DiscordIntegrationModule.Exit();
  240. Logger.Shutdown();
  241. }
  242. }
  243. }