MainWindow.cs 47 KB

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