MainWindow.cs 40 KB

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