MainWindow.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. using Gtk;
  2. using LibHac.Common;
  3. using LibHac.Ns;
  4. using Ryujinx.Audio;
  5. using Ryujinx.Common.Logging;
  6. using Ryujinx.Configuration;
  7. using Ryujinx.Debugger.Profiler;
  8. using Ryujinx.Graphics.GAL;
  9. using Ryujinx.Graphics.OpenGL;
  10. using Ryujinx.HLE.FileSystem;
  11. using Ryujinx.HLE.FileSystem.Content;
  12. using Ryujinx.HLE.HOS.Services.Hid;
  13. using System;
  14. using System.Diagnostics;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Reflection;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using GUI = Gtk.Builder.ObjectAttribute;
  21. namespace Ryujinx.Ui
  22. {
  23. public class MainWindow : Window
  24. {
  25. private static VirtualFileSystem _virtualFileSystem;
  26. private static ContentManager _contentManager;
  27. private static HLE.Switch _emulationContext;
  28. private static GlRenderer _glWidget;
  29. private static AutoResetEvent _deviceExitStatus = new AutoResetEvent(false);
  30. private static ListStore _tableStore;
  31. private static bool _updatingGameTable;
  32. private static bool _gameLoaded;
  33. private static bool _ending;
  34. #pragma warning disable CS0169
  35. private static bool _debuggerOpened;
  36. private static Debugger.Debugger _debugger;
  37. #pragma warning restore CS0169
  38. #pragma warning disable CS0169, CS0649, IDE0044
  39. [GUI] MenuBar _menuBar;
  40. [GUI] Box _footerBox;
  41. [GUI] Box _statusBar;
  42. [GUI] MenuItem _stopEmulation;
  43. [GUI] MenuItem _fullScreen;
  44. [GUI] CheckMenuItem _favToggle;
  45. [GUI] MenuItem _firmwareInstallDirectory;
  46. [GUI] MenuItem _firmwareInstallFile;
  47. [GUI] Label _hostStatus;
  48. [GUI] MenuItem _openDebugger;
  49. [GUI] CheckMenuItem _iconToggle;
  50. [GUI] CheckMenuItem _developerToggle;
  51. [GUI] CheckMenuItem _appToggle;
  52. [GUI] CheckMenuItem _timePlayedToggle;
  53. [GUI] CheckMenuItem _versionToggle;
  54. [GUI] CheckMenuItem _lastPlayedToggle;
  55. [GUI] CheckMenuItem _fileExtToggle;
  56. [GUI] CheckMenuItem _pathToggle;
  57. [GUI] CheckMenuItem _fileSizeToggle;
  58. [GUI] Label _dockedMode;
  59. [GUI] Label _gameStatus;
  60. [GUI] TreeView _gameTable;
  61. [GUI] TreeSelection _gameTableSelection;
  62. [GUI] ScrolledWindow _gameTableWindow;
  63. [GUI] Label _gpuName;
  64. [GUI] Label _progressLabel;
  65. [GUI] Label _firmwareVersionLabel;
  66. [GUI] LevelBar _progressBar;
  67. [GUI] Box _viewBox;
  68. [GUI] Label _vSyncStatus;
  69. [GUI] Box _listStatusBox;
  70. #pragma warning restore CS0649, IDE0044, CS0169
  71. public MainWindow() : this(new Builder("Ryujinx.Ui.MainWindow.glade")) { }
  72. private MainWindow(Builder builder) : base(builder.GetObject("_mainWin").Handle)
  73. {
  74. builder.Autoconnect(this);
  75. int monitorWidth = Display.PrimaryMonitor.Geometry.Width * Display.PrimaryMonitor.ScaleFactor;
  76. int monitorHeight = Display.PrimaryMonitor.Geometry.Height * Display.PrimaryMonitor.ScaleFactor;
  77. this.DefaultWidth = monitorWidth < 1280 ? monitorWidth : 1280;
  78. this.DefaultHeight = monitorHeight < 760 ? monitorHeight : 760;
  79. this.DeleteEvent += Window_Close;
  80. _fullScreen.Activated += FullScreen_Toggled;
  81. this.Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png");
  82. this.Title = $"Ryujinx {Program.Version}";
  83. ApplicationLibrary.ApplicationAdded += Application_Added;
  84. ApplicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated;
  85. GlRenderer.StatusUpdatedEvent += Update_StatusBar;
  86. _gameTable.ButtonReleaseEvent += Row_Clicked;
  87. // First we check that a migration isn't needed. (because VirtualFileSystem will create the new directory otherwise)
  88. bool continueWithStartup = Migration.PromptIfMigrationNeededForStartup(this, out bool migrationNeeded);
  89. if (!continueWithStartup)
  90. {
  91. End(null);
  92. }
  93. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  94. _contentManager = new ContentManager(_virtualFileSystem);
  95. if (migrationNeeded)
  96. {
  97. bool migrationSuccessful = Migration.DoMigrationForStartup(this, _virtualFileSystem);
  98. if (!migrationSuccessful)
  99. {
  100. End(null);
  101. }
  102. }
  103. // Make sure that everything is loaded.
  104. _virtualFileSystem.Reload();
  105. ApplyTheme();
  106. _stopEmulation.Sensitive = false;
  107. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true;
  108. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true;
  109. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true;
  110. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true;
  111. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true;
  112. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true;
  113. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true;
  114. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true;
  115. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true;
  116. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true;
  117. #if USE_DEBUGGING
  118. _debugger = new Debugger.Debugger();
  119. _openDebugger.Activated += _openDebugger_Opened;
  120. #else
  121. _openDebugger.Hide();
  122. #endif
  123. _gameTable.Model = _tableStore = new ListStore(
  124. typeof(bool),
  125. typeof(Gdk.Pixbuf),
  126. typeof(string),
  127. typeof(string),
  128. typeof(string),
  129. typeof(string),
  130. typeof(string),
  131. typeof(string),
  132. typeof(string),
  133. typeof(string),
  134. typeof(BlitStruct<ApplicationControlProperty>));
  135. _tableStore.SetSortFunc(5, TimePlayedSort);
  136. _tableStore.SetSortFunc(6, LastPlayedSort);
  137. _tableStore.SetSortFunc(8, FileSizeSort);
  138. _tableStore.SetSortColumnId(0, SortType.Descending);
  139. _gameTable.EnableSearch = true;
  140. _gameTable.SearchColumn = 2;
  141. UpdateColumns();
  142. UpdateGameTable();
  143. Task.Run(RefreshFirmwareLabel);
  144. _statusBar.Hide();
  145. }
  146. #if USE_DEBUGGING
  147. private void _openDebugger_Opened(object sender, EventArgs e)
  148. {
  149. if (_debuggerOpened)
  150. {
  151. return;
  152. }
  153. Window debugWindow = new Window("Debugger");
  154. debugWindow.SetSizeRequest(1280, 640);
  155. debugWindow.Child = _debugger.Widget;
  156. debugWindow.DeleteEvent += DebugWindow_DeleteEvent;
  157. debugWindow.ShowAll();
  158. _debugger.Enable();
  159. _debuggerOpened = true;
  160. }
  161. private void DebugWindow_DeleteEvent(object o, DeleteEventArgs args)
  162. {
  163. _debuggerOpened = false;
  164. _debugger.Disable();
  165. (_debugger.Widget.Parent as Window)?.Remove(_debugger.Widget);
  166. }
  167. #endif
  168. internal static void ApplyTheme()
  169. {
  170. if (!ConfigurationState.Instance.Ui.EnableCustomTheme)
  171. {
  172. return;
  173. }
  174. if (File.Exists(ConfigurationState.Instance.Ui.CustomThemePath) && (System.IO.Path.GetExtension(ConfigurationState.Instance.Ui.CustomThemePath) == ".css"))
  175. {
  176. CssProvider cssProvider = new CssProvider();
  177. cssProvider.LoadFromPath(ConfigurationState.Instance.Ui.CustomThemePath);
  178. StyleContext.AddProviderForScreen(Gdk.Screen.Default, cssProvider, 800);
  179. }
  180. else
  181. {
  182. Logger.PrintWarning(LogClass.Application, $"The \"custom_theme_path\" section in \"Config.json\" contains an invalid path: \"{ConfigurationState.Instance.Ui.CustomThemePath}\".");
  183. }
  184. }
  185. private void UpdateColumns()
  186. {
  187. foreach (TreeViewColumn column in _gameTable.Columns)
  188. {
  189. _gameTable.RemoveColumn(column);
  190. }
  191. CellRendererToggle favToggle = new CellRendererToggle();
  192. favToggle.Toggled += FavToggle_Toggled;
  193. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0);
  194. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
  195. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
  196. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
  197. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
  198. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
  199. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
  200. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
  201. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
  202. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
  203. foreach (TreeViewColumn column in _gameTable.Columns)
  204. {
  205. if (column.Title == "Fav" && ConfigurationState.Instance.Ui.GuiColumns.FavColumn) column.SortColumnId = 0;
  206. else if (column.Title == "Application" && ConfigurationState.Instance.Ui.GuiColumns.AppColumn) column.SortColumnId = 2;
  207. else if (column.Title == "Developer" && ConfigurationState.Instance.Ui.GuiColumns.DevColumn) column.SortColumnId = 3;
  208. else if (column.Title == "Version" && ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) column.SortColumnId = 4;
  209. else if (column.Title == "Time Played" && ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) column.SortColumnId = 5;
  210. else if (column.Title == "Last Played" && ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) column.SortColumnId = 6;
  211. else if (column.Title == "File Ext" && ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) column.SortColumnId = 7;
  212. else if (column.Title == "File Size" && ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) column.SortColumnId = 8;
  213. else if (column.Title == "Path" && ConfigurationState.Instance.Ui.GuiColumns.PathColumn) column.SortColumnId = 9;
  214. }
  215. }
  216. private HLE.Switch InitializeSwitchInstance()
  217. {
  218. _virtualFileSystem.Reload();
  219. HLE.Switch instance = new HLE.Switch(_virtualFileSystem, _contentManager, InitializeRenderer(), InitializeAudioEngine());
  220. instance.Initialize();
  221. return instance;
  222. }
  223. internal static void UpdateGameTable()
  224. {
  225. if (_updatingGameTable)
  226. {
  227. return;
  228. }
  229. _updatingGameTable = true;
  230. _tableStore.Clear();
  231. Thread applicationLibraryThread = new Thread(() =>
  232. {
  233. ApplicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs,
  234. _virtualFileSystem, ConfigurationState.Instance.System.Language);
  235. _updatingGameTable = false;
  236. });
  237. applicationLibraryThread.Name = "GUI.ApplicationLibraryThread";
  238. applicationLibraryThread.IsBackground = true;
  239. applicationLibraryThread.Start();
  240. }
  241. internal void LoadApplication(string path)
  242. {
  243. if (_gameLoaded)
  244. {
  245. GtkDialog.CreateInfoDialog("Ryujinx", "A game has already been loaded", "Please close it first and try again.");
  246. }
  247. else
  248. {
  249. if (ConfigurationState.Instance.Logger.EnableDebug.Value)
  250. {
  251. MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  252. {
  253. Title = "Ryujinx - Warning",
  254. Text = "You have debug logging enabled, which is designed to be used by developers only.",
  255. SecondaryText = "For optimal performance, it's recommended to disable debug logging. Would you like to disable debug logging now?"
  256. };
  257. if (debugWarningDialog.Run() == (int)ResponseType.Yes)
  258. {
  259. ConfigurationState.Instance.Logger.EnableDebug.Value = false;
  260. SaveConfig();
  261. }
  262. debugWarningDialog.Dispose();
  263. }
  264. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  265. {
  266. MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  267. {
  268. Title = "Ryujinx - Warning",
  269. Text = "You have shader dumping enabled, which is designed to be used by developers only.",
  270. SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
  271. };
  272. if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
  273. {
  274. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  275. SaveConfig();
  276. }
  277. shadersDumpWarningDialog.Dispose();
  278. }
  279. Logger.RestartTime();
  280. HLE.Switch device = InitializeSwitchInstance();
  281. // TODO: Move this somewhere else + reloadable?
  282. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  283. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  284. Logger.PrintInfo(LogClass.Application, $"Using Firmware Version: {_contentManager.GetCurrentFirmwareVersion()?.VersionString}");
  285. if (Directory.Exists(path))
  286. {
  287. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  288. if (romFsFiles.Length == 0)
  289. {
  290. romFsFiles = Directory.GetFiles(path, "*.romfs");
  291. }
  292. if (romFsFiles.Length > 0)
  293. {
  294. Logger.PrintInfo(LogClass.Application, "Loading as cart with RomFS.");
  295. device.LoadCart(path, romFsFiles[0]);
  296. }
  297. else
  298. {
  299. Logger.PrintInfo(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  300. device.LoadCart(path);
  301. }
  302. }
  303. else if (File.Exists(path))
  304. {
  305. switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
  306. {
  307. case ".xci":
  308. Logger.PrintInfo(LogClass.Application, "Loading as XCI.");
  309. device.LoadXci(path);
  310. break;
  311. case ".nca":
  312. Logger.PrintInfo(LogClass.Application, "Loading as NCA.");
  313. device.LoadNca(path);
  314. break;
  315. case ".nsp":
  316. case ".pfs0":
  317. Logger.PrintInfo(LogClass.Application, "Loading as NSP.");
  318. device.LoadNsp(path);
  319. break;
  320. default:
  321. Logger.PrintInfo(LogClass.Application, "Loading as homebrew.");
  322. try
  323. {
  324. device.LoadProgram(path);
  325. }
  326. catch (ArgumentOutOfRangeException)
  327. {
  328. Logger.PrintError(LogClass.Application, "The file which you have specified is unsupported by Ryujinx.");
  329. }
  330. break;
  331. }
  332. }
  333. else
  334. {
  335. Logger.PrintWarning(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  336. device.Dispose();
  337. return;
  338. }
  339. _emulationContext = device;
  340. _deviceExitStatus.Reset();
  341. #if MACOS_BUILD
  342. CreateGameWindow(device);
  343. #else
  344. Thread windowThread = new Thread(() =>
  345. {
  346. CreateGameWindow(device);
  347. })
  348. {
  349. Name = "GUI.WindowThread"
  350. };
  351. windowThread.Start();
  352. #endif
  353. _gameLoaded = true;
  354. _stopEmulation.Sensitive = true;
  355. _firmwareInstallFile.Sensitive = false;
  356. _firmwareInstallDirectory.Sensitive = false;
  357. DiscordIntegrationModule.SwitchToPlayingState(device.Application.TitleIdText, device.Application.TitleName);
  358. ApplicationLibrary.LoadAndSaveMetaData(device.Application.TitleIdText, appMetadata =>
  359. {
  360. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  361. });
  362. }
  363. }
  364. private void CreateGameWindow(HLE.Switch device)
  365. {
  366. device.Hid.Npads.AddControllers(ConfigurationState.Instance.Hid.InputConfig.Value.Select(inputConfig =>
  367. new HLE.HOS.Services.Hid.ControllerConfig
  368. {
  369. Player = (PlayerIndex)inputConfig.PlayerIndex,
  370. Type = (ControllerType)inputConfig.ControllerType
  371. }
  372. ).ToArray());
  373. _glWidget = new GlRenderer(_emulationContext);
  374. Application.Invoke(delegate
  375. {
  376. _viewBox.Remove(_gameTableWindow);
  377. _glWidget.Expand = true;
  378. _viewBox.Child = _glWidget;
  379. _glWidget.ShowAll();
  380. EditFooterForGameRender();
  381. });
  382. _glWidget.WaitEvent.WaitOne();
  383. _glWidget.Start();
  384. device.Dispose();
  385. _deviceExitStatus.Set();
  386. // NOTE: Everything that is here will not be executed when you close the UI.
  387. Application.Invoke(delegate
  388. {
  389. _viewBox.Remove(_glWidget);
  390. _glWidget.Exit();
  391. if(_glWidget.Window != this.Window && _glWidget.Window != null)
  392. {
  393. _glWidget.Window.Dispose();
  394. }
  395. _glWidget.Dispose();
  396. _viewBox.Add(_gameTableWindow);
  397. _gameTableWindow.Expand = true;
  398. this.Window.Title = $"Ryujinx {Program.Version}";
  399. _emulationContext = null;
  400. _gameLoaded = false;
  401. _glWidget = null;
  402. DiscordIntegrationModule.SwitchToMainMenu();
  403. RecreateFooterForMenu();
  404. UpdateColumns();
  405. UpdateGameTable();
  406. Task.Run(RefreshFirmwareLabel);
  407. _stopEmulation.Sensitive = false;
  408. _firmwareInstallFile.Sensitive = true;
  409. _firmwareInstallDirectory.Sensitive = true;
  410. });
  411. }
  412. private void RecreateFooterForMenu()
  413. {
  414. _listStatusBox.Show();
  415. _statusBar.Hide();
  416. }
  417. private void EditFooterForGameRender()
  418. {
  419. _listStatusBox.Hide();
  420. _statusBar.Show();
  421. }
  422. public void ToggleExtraWidgets(bool show)
  423. {
  424. if (_glWidget != null)
  425. {
  426. if (show)
  427. {
  428. _menuBar.ShowAll();
  429. _footerBox.Show();
  430. _statusBar.Show();
  431. }
  432. else
  433. {
  434. _menuBar.Hide();
  435. _footerBox.Hide();
  436. }
  437. }
  438. bool fullScreenToggled = this.Window.State.HasFlag(Gdk.WindowState.Fullscreen);
  439. _fullScreen.Label = fullScreenToggled ? "Exit Fullscreen" : "Enter Fullscreen";
  440. }
  441. private static void UpdateGameMetadata(string titleId)
  442. {
  443. if (_gameLoaded)
  444. {
  445. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  446. {
  447. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  448. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  449. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  450. });
  451. }
  452. }
  453. public static void SaveConfig()
  454. {
  455. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  456. }
  457. private void End(HLE.Switch device)
  458. {
  459. #if USE_DEBUGGING
  460. _debugger.Dispose();
  461. #endif
  462. if (_ending)
  463. {
  464. return;
  465. }
  466. _ending = true;
  467. if (device != null)
  468. {
  469. UpdateGameMetadata(device.Application.TitleIdText);
  470. if (_glWidget != null)
  471. {
  472. // We tell the widget that we are exiting
  473. _glWidget.Exit();
  474. // Wait for the other thread to dispose the HLE context before exiting.
  475. _deviceExitStatus.WaitOne();
  476. }
  477. }
  478. Dispose();
  479. Profile.FinishProfiling();
  480. DiscordIntegrationModule.Exit();
  481. Logger.Shutdown();
  482. Application.Quit();
  483. }
  484. private static IRenderer InitializeRenderer()
  485. {
  486. return new Renderer();
  487. }
  488. /// <summary>
  489. /// Picks an <see cref="IAalOutput"/> audio output renderer supported on this machine
  490. /// </summary>
  491. /// <returns>An <see cref="IAalOutput"/> supported by this machine</returns>
  492. private static IAalOutput InitializeAudioEngine()
  493. {
  494. if (OpenALAudioOut.IsSupported)
  495. {
  496. return new OpenALAudioOut();
  497. }
  498. else if (SoundIoAudioOut.IsSupported)
  499. {
  500. return new SoundIoAudioOut();
  501. }
  502. else
  503. {
  504. return new DummyAudioOut();
  505. }
  506. }
  507. //Events
  508. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  509. {
  510. Application.Invoke(delegate
  511. {
  512. _tableStore.AppendValues(
  513. args.AppData.Favorite,
  514. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  515. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  516. args.AppData.Developer,
  517. args.AppData.Version,
  518. args.AppData.TimePlayed,
  519. args.AppData.LastPlayed,
  520. args.AppData.FileExtension,
  521. args.AppData.FileSize,
  522. args.AppData.Path,
  523. args.AppData.ControlHolder);
  524. });
  525. }
  526. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  527. {
  528. Application.Invoke(delegate
  529. {
  530. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  531. float barValue = 0;
  532. if (args.NumAppsFound != 0)
  533. {
  534. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  535. }
  536. _progressBar.Value = barValue;
  537. });
  538. }
  539. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  540. {
  541. Application.Invoke(delegate
  542. {
  543. _hostStatus.Text = args.HostStatus;
  544. _gameStatus.Text = args.GameStatus;
  545. _gpuName.Text = args.GpuName;
  546. _dockedMode.Text = args.DockedMode;
  547. if (args.VSyncEnabled)
  548. {
  549. _vSyncStatus.Attributes = new Pango.AttrList();
  550. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  551. }
  552. else
  553. {
  554. _vSyncStatus.Attributes = new Pango.AttrList();
  555. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  556. }
  557. });
  558. }
  559. private void FavToggle_Toggled(object sender, ToggledArgs args)
  560. {
  561. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  562. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  563. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  564. _tableStore.SetValue(treeIter, 0, newToggleValue);
  565. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  566. {
  567. appMetadata.Favorite = newToggleValue;
  568. });
  569. }
  570. private void Row_Activated(object sender, RowActivatedArgs args)
  571. {
  572. _gameTableSelection.GetSelected(out TreeIter treeIter);
  573. string path = (string)_tableStore.GetValue(treeIter, 9);
  574. LoadApplication(path);
  575. }
  576. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  577. {
  578. if (args.Event.Button != 3) return;
  579. _gameTableSelection.GetSelected(out TreeIter treeIter);
  580. if (treeIter.UserData == IntPtr.Zero) return;
  581. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  582. GameTableContextMenu contextMenu = new GameTableContextMenu(_tableStore, controlData, treeIter, _virtualFileSystem);
  583. contextMenu.ShowAll();
  584. contextMenu.PopupAtPointer(null);
  585. }
  586. private void Load_Application_File(object sender, EventArgs args)
  587. {
  588. FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  589. fileChooser.Filter = new FileFilter();
  590. fileChooser.Filter.AddPattern("*.nsp" );
  591. fileChooser.Filter.AddPattern("*.pfs0");
  592. fileChooser.Filter.AddPattern("*.xci" );
  593. fileChooser.Filter.AddPattern("*.nca" );
  594. fileChooser.Filter.AddPattern("*.nro" );
  595. fileChooser.Filter.AddPattern("*.nso" );
  596. if (fileChooser.Run() == (int)ResponseType.Accept)
  597. {
  598. LoadApplication(fileChooser.Filename);
  599. }
  600. fileChooser.Dispose();
  601. }
  602. private void Load_Application_Folder(object sender, EventArgs args)
  603. {
  604. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  605. if (fileChooser.Run() == (int)ResponseType.Accept)
  606. {
  607. LoadApplication(fileChooser.Filename);
  608. }
  609. fileChooser.Dispose();
  610. }
  611. private void Open_Ryu_Folder(object sender, EventArgs args)
  612. {
  613. Process.Start(new ProcessStartInfo()
  614. {
  615. FileName = _virtualFileSystem.GetBasePath(),
  616. UseShellExecute = true,
  617. Verb = "open"
  618. });
  619. }
  620. private void Exit_Pressed(object sender, EventArgs args)
  621. {
  622. End(_emulationContext);
  623. }
  624. private void Window_Close(object sender, DeleteEventArgs args)
  625. {
  626. End(_emulationContext);
  627. }
  628. private void StopEmulation_Pressed(object sender, EventArgs args)
  629. {
  630. _glWidget?.Exit();
  631. }
  632. private void Installer_File_Pressed(object o, EventArgs args)
  633. {
  634. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open",
  635. this,
  636. FileChooserAction.Open,
  637. "Cancel",
  638. ResponseType.Cancel,
  639. "Open",
  640. ResponseType.Accept);
  641. fileChooser.Filter = new FileFilter();
  642. fileChooser.Filter.AddPattern("*.zip");
  643. fileChooser.Filter.AddPattern("*.xci");
  644. HandleInstallerDialog(fileChooser);
  645. }
  646. private void Installer_Directory_Pressed(object o, EventArgs args)
  647. {
  648. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open",
  649. this,
  650. FileChooserAction.SelectFolder,
  651. "Cancel",
  652. ResponseType.Cancel,
  653. "Open",
  654. ResponseType.Accept);
  655. HandleInstallerDialog(directoryChooser);
  656. }
  657. private void RefreshFirmwareLabel()
  658. {
  659. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  660. GLib.Idle.Add(new GLib.IdleHandler(() =>
  661. {
  662. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  663. return false;
  664. }));
  665. }
  666. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  667. {
  668. if (fileChooser.Run() == (int)ResponseType.Accept)
  669. {
  670. MessageDialog dialog = null;
  671. try
  672. {
  673. string filename = fileChooser.Filename;
  674. fileChooser.Dispose();
  675. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  676. if (firmwareVersion == null)
  677. {
  678. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  679. dialog.Text = "Firmware not found.";
  680. dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";
  681. Logger.PrintError(LogClass.Application, $"A valid system firmware was not found in {filename}.");
  682. dialog.Run();
  683. dialog.Hide();
  684. dialog.Dispose();
  685. return;
  686. }
  687. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  688. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  689. if (currentVersion != null)
  690. {
  691. dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
  692. }
  693. dialogMessage += "Do you want to continue?";
  694. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");
  695. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  696. dialog.SecondaryText = dialogMessage;
  697. int response = dialog.Run();
  698. dialog.Dispose();
  699. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");
  700. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  701. dialog.SecondaryText = "Installing firmware...";
  702. if (response == (int)ResponseType.Yes)
  703. {
  704. Logger.PrintInfo(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  705. Thread thread = new Thread(() =>
  706. {
  707. GLib.Idle.Add(new GLib.IdleHandler(() =>
  708. {
  709. dialog.Run();
  710. return false;
  711. }));
  712. try
  713. {
  714. _contentManager.InstallFirmware(filename);
  715. GLib.Idle.Add(new GLib.IdleHandler(() =>
  716. {
  717. dialog.Dispose();
  718. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  719. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  720. dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";
  721. Logger.PrintInfo(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");
  722. dialog.Run();
  723. dialog.Dispose();
  724. return false;
  725. }));
  726. }
  727. catch (Exception ex)
  728. {
  729. GLib.Idle.Add(new GLib.IdleHandler(() =>
  730. {
  731. dialog.Dispose();
  732. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  733. dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";
  734. dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
  735. " Please check logs for more info.";
  736. Logger.PrintError(LogClass.Application, ex.Message);
  737. dialog.Run();
  738. dialog.Dispose();
  739. return false;
  740. }));
  741. }
  742. finally
  743. {
  744. RefreshFirmwareLabel();
  745. }
  746. });
  747. thread.Name = "GUI.FirmwareInstallerThread";
  748. thread.Start();
  749. }
  750. else
  751. {
  752. dialog.Dispose();
  753. }
  754. }
  755. catch (Exception ex)
  756. {
  757. if (dialog != null)
  758. {
  759. dialog.Dispose();
  760. }
  761. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  762. dialog.Text = "Parsing Firmware Failed.";
  763. dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";
  764. Logger.PrintError(LogClass.Application, ex.Message);
  765. dialog.Run();
  766. dialog.Dispose();
  767. }
  768. }
  769. else
  770. {
  771. fileChooser.Dispose();
  772. }
  773. }
  774. private void FullScreen_Toggled(object o, EventArgs args)
  775. {
  776. bool fullScreenToggled = this.Window.State.HasFlag(Gdk.WindowState.Fullscreen);
  777. if (!fullScreenToggled)
  778. {
  779. Fullscreen();
  780. ToggleExtraWidgets(false);
  781. }
  782. else
  783. {
  784. Unfullscreen();
  785. ToggleExtraWidgets(true);
  786. }
  787. }
  788. private void Settings_Pressed(object sender, EventArgs args)
  789. {
  790. SettingsWindow settingsWin = new SettingsWindow(_virtualFileSystem, _contentManager);
  791. settingsWin.Show();
  792. }
  793. private void Update_Pressed(object sender, EventArgs args)
  794. {
  795. string ryuUpdater = System.IO.Path.Combine(_virtualFileSystem.GetBasePath(), "RyuUpdater.exe");
  796. try
  797. {
  798. Process.Start(new ProcessStartInfo(ryuUpdater, "/U") { UseShellExecute = true });
  799. }
  800. catch(System.ComponentModel.Win32Exception)
  801. {
  802. GtkDialog.CreateErrorDialog("Update canceled by user or updater was not found");
  803. }
  804. }
  805. private void About_Pressed(object sender, EventArgs args)
  806. {
  807. AboutWindow aboutWin = new AboutWindow();
  808. aboutWin.Show();
  809. }
  810. private void Fav_Toggled(object sender, EventArgs args)
  811. {
  812. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  813. SaveConfig();
  814. UpdateColumns();
  815. }
  816. private void Icon_Toggled(object sender, EventArgs args)
  817. {
  818. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  819. SaveConfig();
  820. UpdateColumns();
  821. }
  822. private void Title_Toggled(object sender, EventArgs args)
  823. {
  824. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  825. SaveConfig();
  826. UpdateColumns();
  827. }
  828. private void Developer_Toggled(object sender, EventArgs args)
  829. {
  830. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  831. SaveConfig();
  832. UpdateColumns();
  833. }
  834. private void Version_Toggled(object sender, EventArgs args)
  835. {
  836. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  837. SaveConfig();
  838. UpdateColumns();
  839. }
  840. private void TimePlayed_Toggled(object sender, EventArgs args)
  841. {
  842. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  843. SaveConfig();
  844. UpdateColumns();
  845. }
  846. private void LastPlayed_Toggled(object sender, EventArgs args)
  847. {
  848. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  849. SaveConfig();
  850. UpdateColumns();
  851. }
  852. private void FileExt_Toggled(object sender, EventArgs args)
  853. {
  854. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  855. SaveConfig();
  856. UpdateColumns();
  857. }
  858. private void FileSize_Toggled(object sender, EventArgs args)
  859. {
  860. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  861. SaveConfig();
  862. UpdateColumns();
  863. }
  864. private void Path_Toggled(object sender, EventArgs args)
  865. {
  866. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  867. SaveConfig();
  868. UpdateColumns();
  869. }
  870. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  871. {
  872. UpdateGameTable();
  873. }
  874. private static int TimePlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  875. {
  876. string aValue = model.GetValue(a, 5).ToString();
  877. string bValue = model.GetValue(b, 5).ToString();
  878. if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "mins")
  879. {
  880. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 60).ToString();
  881. }
  882. else if (aValue.Length > 3 && aValue.Substring(aValue.Length - 3) == "hrs")
  883. {
  884. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 4)) * 3600).ToString();
  885. }
  886. else if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "days")
  887. {
  888. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 86400).ToString();
  889. }
  890. else
  891. {
  892. aValue = aValue.Substring(0, aValue.Length - 1);
  893. }
  894. if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "mins")
  895. {
  896. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 60).ToString();
  897. }
  898. else if (bValue.Length > 3 && bValue.Substring(bValue.Length - 3) == "hrs")
  899. {
  900. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 4)) * 3600).ToString();
  901. }
  902. else if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "days")
  903. {
  904. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 86400).ToString();
  905. }
  906. else
  907. {
  908. bValue = bValue.Substring(0, bValue.Length - 1);
  909. }
  910. if (float.Parse(aValue) > float.Parse(bValue))
  911. {
  912. return -1;
  913. }
  914. else if (float.Parse(bValue) > float.Parse(aValue))
  915. {
  916. return 1;
  917. }
  918. else
  919. {
  920. return 0;
  921. }
  922. }
  923. private static int LastPlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  924. {
  925. string aValue = model.GetValue(a, 6).ToString();
  926. string bValue = model.GetValue(b, 6).ToString();
  927. if (aValue == "Never")
  928. {
  929. aValue = DateTime.UnixEpoch.ToString();
  930. }
  931. if (bValue == "Never")
  932. {
  933. bValue = DateTime.UnixEpoch.ToString();
  934. }
  935. return DateTime.Compare(DateTime.Parse(bValue), DateTime.Parse(aValue));
  936. }
  937. private static int FileSizeSort(ITreeModel model, TreeIter a, TreeIter b)
  938. {
  939. string aValue = model.GetValue(a, 8).ToString();
  940. string bValue = model.GetValue(b, 8).ToString();
  941. if (aValue.Substring(aValue.Length - 2) == "GB")
  942. {
  943. aValue = (float.Parse(aValue[0..^2]) * 1024).ToString();
  944. }
  945. else
  946. {
  947. aValue = aValue[0..^2];
  948. }
  949. if (bValue.Substring(bValue.Length - 2) == "GB")
  950. {
  951. bValue = (float.Parse(bValue[0..^2]) * 1024).ToString();
  952. }
  953. else
  954. {
  955. bValue = bValue[0..^2];
  956. }
  957. if (float.Parse(aValue) > float.Parse(bValue))
  958. {
  959. return -1;
  960. }
  961. else if (float.Parse(bValue) > float.Parse(aValue))
  962. {
  963. return 1;
  964. }
  965. else
  966. {
  967. return 0;
  968. }
  969. }
  970. }
  971. }