MainWindow.cs 42 KB

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