MainWindow.cs 44 KB

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