MainWindow.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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 _screenExitStatus = 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. _screenExitStatus.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?.Exit();
  322. _gLWidget?.Dispose();
  323. _gLWidget = new GLRenderer(_emulationContext);
  324. Application.Invoke(delegate
  325. {
  326. _viewBox.Remove(_gameTableWindow);
  327. _gLWidget.Expand = true;
  328. _viewBox.Child = _gLWidget;
  329. _gLWidget.ShowAll();
  330. _listStatusBox.Hide();
  331. });
  332. _gLWidget.WaitEvent.WaitOne();
  333. _gLWidget.Start();
  334. Application.Invoke(delegate
  335. {
  336. _viewBox.Remove(_gLWidget);
  337. _gLWidget.Exit();
  338. if(_gLWidget.Window != this.Window && _gLWidget.Window != null)
  339. {
  340. _gLWidget.Window.Dispose();
  341. }
  342. _viewBox.Add(_gameTableWindow);
  343. _gameTableWindow.Expand = true;
  344. this.Window.Title = "Ryujinx";
  345. _listStatusBox.ShowAll();
  346. UpdateColumns();
  347. UpdateGameTable();
  348. Task.Run(RefreshFirmwareLabel);
  349. });
  350. device.Dispose();
  351. _emulationContext = null;
  352. _gameLoaded = false;
  353. _gLWidget = null;
  354. DiscordIntegrationModule.SwitchToMainMenu();
  355. Application.Invoke(delegate
  356. {
  357. _stopEmulation.Sensitive = false;
  358. _firmwareInstallFile.Sensitive = true;
  359. _firmwareInstallDirectory.Sensitive = true;
  360. });
  361. _screenExitStatus.Set();
  362. }
  363. public void ToggleExtraWidgets(bool show)
  364. {
  365. if (_gLWidget != null)
  366. {
  367. if (show)
  368. {
  369. _menuBar.ShowAll();
  370. _footerBox.ShowAll();
  371. }
  372. else
  373. {
  374. _menuBar.Hide();
  375. _footerBox.Hide();
  376. }
  377. }
  378. bool fullScreenToggled = this.Window.State.HasFlag(Gdk.WindowState.Fullscreen);
  379. _fullScreen.Label = !fullScreenToggled ? "Exit Fullscreen" : "Enter Fullscreen";
  380. }
  381. private static void UpdateGameMetadata(string titleId)
  382. {
  383. if (_gameLoaded)
  384. {
  385. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  386. {
  387. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  388. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  389. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  390. });
  391. }
  392. }
  393. private void End(HLE.Switch device)
  394. {
  395. #if USE_DEBUGGING
  396. _debugger.Dispose();
  397. #endif
  398. if (_ending)
  399. {
  400. return;
  401. }
  402. _ending = true;
  403. if (device != null)
  404. {
  405. UpdateGameMetadata(device.System.TitleIdText);
  406. if (_gLWidget != null)
  407. {
  408. _gLWidget.Exit();
  409. _screenExitStatus.WaitOne();
  410. }
  411. }
  412. Dispose();
  413. Profile.FinishProfiling();
  414. DiscordIntegrationModule.Exit();
  415. Logger.Shutdown();
  416. Application.Quit();
  417. }
  418. private static IRenderer InitializeRenderer()
  419. {
  420. return new Renderer();
  421. }
  422. /// <summary>
  423. /// Picks an <see cref="IAalOutput"/> audio output renderer supported on this machine
  424. /// </summary>
  425. /// <returns>An <see cref="IAalOutput"/> supported by this machine</returns>
  426. private static IAalOutput InitializeAudioEngine()
  427. {
  428. if (OpenALAudioOut.IsSupported)
  429. {
  430. return new OpenALAudioOut();
  431. }
  432. else if (SoundIoAudioOut.IsSupported)
  433. {
  434. return new SoundIoAudioOut();
  435. }
  436. else
  437. {
  438. return new DummyAudioOut();
  439. }
  440. }
  441. //Events
  442. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  443. {
  444. Application.Invoke(delegate
  445. {
  446. _tableStore.AppendValues(
  447. args.AppData.Favorite,
  448. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  449. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  450. args.AppData.Developer,
  451. args.AppData.Version,
  452. args.AppData.TimePlayed,
  453. args.AppData.LastPlayed,
  454. args.AppData.FileExtension,
  455. args.AppData.FileSize,
  456. args.AppData.Path);
  457. });
  458. }
  459. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  460. {
  461. Application.Invoke(delegate
  462. {
  463. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  464. float barValue = 0;
  465. if (args.NumAppsFound != 0)
  466. {
  467. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  468. }
  469. _progressBar.Value = barValue;
  470. });
  471. }
  472. private void FavToggle_Toggled(object sender, ToggledArgs args)
  473. {
  474. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  475. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  476. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  477. _tableStore.SetValue(treeIter, 0, newToggleValue);
  478. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  479. {
  480. appMetadata.Favorite = newToggleValue;
  481. });
  482. }
  483. private void Row_Activated(object sender, RowActivatedArgs args)
  484. {
  485. _gameTableSelection.GetSelected(out TreeIter treeIter);
  486. string path = (string)_tableStore.GetValue(treeIter, 9);
  487. LoadApplication(path);
  488. }
  489. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  490. {
  491. if (args.Event.Button != 3) return;
  492. _gameTableSelection.GetSelected(out TreeIter treeIter);
  493. if (treeIter.UserData == IntPtr.Zero) return;
  494. GameTableContextMenu contextMenu = new GameTableContextMenu(_tableStore, treeIter, _virtualFileSystem);
  495. contextMenu.ShowAll();
  496. contextMenu.PopupAtPointer(null);
  497. }
  498. private void Load_Application_File(object sender, EventArgs args)
  499. {
  500. FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  501. fileChooser.Filter = new FileFilter();
  502. fileChooser.Filter.AddPattern("*.nsp" );
  503. fileChooser.Filter.AddPattern("*.pfs0");
  504. fileChooser.Filter.AddPattern("*.xci" );
  505. fileChooser.Filter.AddPattern("*.nca" );
  506. fileChooser.Filter.AddPattern("*.nro" );
  507. fileChooser.Filter.AddPattern("*.nso" );
  508. if (fileChooser.Run() == (int)ResponseType.Accept)
  509. {
  510. LoadApplication(fileChooser.Filename);
  511. }
  512. fileChooser.Dispose();
  513. }
  514. private void Load_Application_Folder(object sender, EventArgs args)
  515. {
  516. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  517. if (fileChooser.Run() == (int)ResponseType.Accept)
  518. {
  519. LoadApplication(fileChooser.Filename);
  520. }
  521. fileChooser.Dispose();
  522. }
  523. private void Open_Ryu_Folder(object sender, EventArgs args)
  524. {
  525. Process.Start(new ProcessStartInfo()
  526. {
  527. FileName = _virtualFileSystem.GetBasePath(),
  528. UseShellExecute = true,
  529. Verb = "open"
  530. });
  531. }
  532. private void Exit_Pressed(object sender, EventArgs args)
  533. {
  534. End(_emulationContext);
  535. }
  536. private void Window_Close(object sender, DeleteEventArgs args)
  537. {
  538. End(_emulationContext);
  539. }
  540. private void StopEmulation_Pressed(object sender, EventArgs args)
  541. {
  542. _gLWidget?.Exit();
  543. }
  544. private void Installer_File_Pressed(object o, EventArgs args)
  545. {
  546. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open",
  547. this,
  548. FileChooserAction.Open,
  549. "Cancel",
  550. ResponseType.Cancel,
  551. "Open",
  552. ResponseType.Accept);
  553. fileChooser.Filter = new FileFilter();
  554. fileChooser.Filter.AddPattern("*.zip");
  555. fileChooser.Filter.AddPattern("*.xci");
  556. HandleInstallerDialog(fileChooser);
  557. }
  558. private void Installer_Directory_Pressed(object o, EventArgs args)
  559. {
  560. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open",
  561. this,
  562. FileChooserAction.SelectFolder,
  563. "Cancel",
  564. ResponseType.Cancel,
  565. "Open",
  566. ResponseType.Accept);
  567. HandleInstallerDialog(directoryChooser);
  568. }
  569. private void RefreshFirmwareLabel()
  570. {
  571. var currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  572. GLib.Idle.Add(new GLib.IdleHandler(() =>
  573. {
  574. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  575. return false;
  576. }));
  577. }
  578. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  579. {
  580. if (fileChooser.Run() == (int)ResponseType.Accept)
  581. {
  582. MessageDialog dialog = null;
  583. try
  584. {
  585. string filename = fileChooser.Filename;
  586. fileChooser.Dispose();
  587. var firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  588. if (firmwareVersion == null)
  589. {
  590. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  591. dialog.Text = "Firmware not found.";
  592. dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";
  593. Logger.PrintError(LogClass.Application, $"A valid system firmware was not found in {filename}.");
  594. dialog.Run();
  595. dialog.Hide();
  596. dialog.Dispose();
  597. return;
  598. }
  599. var currentVersion = _contentManager.GetCurrentFirmwareVersion();
  600. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  601. if (currentVersion != null)
  602. {
  603. dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
  604. }
  605. dialogMessage += "Do you want to continue?";
  606. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");
  607. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  608. dialog.SecondaryText = dialogMessage;
  609. int response = dialog.Run();
  610. dialog.Dispose();
  611. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");
  612. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  613. dialog.SecondaryText = "Installing firmware...";
  614. if (response == (int)ResponseType.Yes)
  615. {
  616. Logger.PrintInfo(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  617. Thread thread = new Thread(() =>
  618. {
  619. GLib.Idle.Add(new GLib.IdleHandler(() =>
  620. {
  621. dialog.Run();
  622. return false;
  623. }));
  624. try
  625. {
  626. _contentManager.InstallFirmware(filename);
  627. GLib.Idle.Add(new GLib.IdleHandler(() =>
  628. {
  629. dialog.Dispose();
  630. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  631. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  632. dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";
  633. Logger.PrintInfo(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");
  634. dialog.Run();
  635. dialog.Dispose();
  636. return false;
  637. }));
  638. }
  639. catch (Exception ex)
  640. {
  641. GLib.Idle.Add(new GLib.IdleHandler(() =>
  642. {
  643. dialog.Dispose();
  644. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  645. dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";
  646. dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
  647. " Please check logs for more info.";
  648. Logger.PrintError(LogClass.Application, ex.Message);
  649. dialog.Run();
  650. dialog.Dispose();
  651. return false;
  652. }));
  653. }
  654. finally
  655. {
  656. RefreshFirmwareLabel();
  657. }
  658. });
  659. thread.Name = "GUI.FirmwareInstallerThread";
  660. thread.Start();
  661. }
  662. else
  663. {
  664. dialog.Dispose();
  665. }
  666. }
  667. catch (Exception ex)
  668. {
  669. if (dialog != null)
  670. {
  671. dialog.Dispose();
  672. }
  673. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  674. dialog.Text = "Parsing Firmware Failed.";
  675. dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";
  676. Logger.PrintError(LogClass.Application, ex.Message);
  677. dialog.Run();
  678. dialog.Dispose();
  679. }
  680. }
  681. else
  682. {
  683. fileChooser.Dispose();
  684. }
  685. }
  686. private void FullScreen_Toggled(object o, EventArgs args)
  687. {
  688. bool fullScreenToggled = this.Window.State.HasFlag(Gdk.WindowState.Fullscreen);
  689. if (!fullScreenToggled)
  690. {
  691. Fullscreen();
  692. _fullScreen.Label = "Exit Fullscreen";
  693. ToggleExtraWidgets(false);
  694. }
  695. else
  696. {
  697. Unfullscreen();
  698. _fullScreen.Label = "Enter Fullscreen";
  699. ToggleExtraWidgets(true);
  700. }
  701. }
  702. private void Settings_Pressed(object sender, EventArgs args)
  703. {
  704. SwitchSettings settingsWin = new SwitchSettings();
  705. settingsWin.Show();
  706. }
  707. private void Update_Pressed(object sender, EventArgs args)
  708. {
  709. string ryuUpdater = System.IO.Path.Combine(_virtualFileSystem.GetBasePath(), "RyuUpdater.exe");
  710. try
  711. {
  712. Process.Start(new ProcessStartInfo(ryuUpdater, "/U") { UseShellExecute = true });
  713. }
  714. catch(System.ComponentModel.Win32Exception)
  715. {
  716. GtkDialog.CreateErrorDialog("Update canceled by user or updater was not found");
  717. }
  718. }
  719. private void About_Pressed(object sender, EventArgs args)
  720. {
  721. AboutWindow aboutWin = new AboutWindow();
  722. aboutWin.Show();
  723. }
  724. private void Fav_Toggled(object sender, EventArgs args)
  725. {
  726. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  727. SaveConfig();
  728. UpdateColumns();
  729. }
  730. private void Icon_Toggled(object sender, EventArgs args)
  731. {
  732. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  733. SaveConfig();
  734. UpdateColumns();
  735. }
  736. private void Title_Toggled(object sender, EventArgs args)
  737. {
  738. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  739. SaveConfig();
  740. UpdateColumns();
  741. }
  742. private void Developer_Toggled(object sender, EventArgs args)
  743. {
  744. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  745. SaveConfig();
  746. UpdateColumns();
  747. }
  748. private void Version_Toggled(object sender, EventArgs args)
  749. {
  750. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  751. SaveConfig();
  752. UpdateColumns();
  753. }
  754. private void TimePlayed_Toggled(object sender, EventArgs args)
  755. {
  756. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  757. SaveConfig();
  758. UpdateColumns();
  759. }
  760. private void LastPlayed_Toggled(object sender, EventArgs args)
  761. {
  762. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  763. SaveConfig();
  764. UpdateColumns();
  765. }
  766. private void FileExt_Toggled(object sender, EventArgs args)
  767. {
  768. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  769. SaveConfig();
  770. UpdateColumns();
  771. }
  772. private void FileSize_Toggled(object sender, EventArgs args)
  773. {
  774. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  775. SaveConfig();
  776. UpdateColumns();
  777. }
  778. private void Path_Toggled(object sender, EventArgs args)
  779. {
  780. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  781. SaveConfig();
  782. UpdateColumns();
  783. }
  784. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  785. {
  786. UpdateGameTable();
  787. }
  788. private static int TimePlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  789. {
  790. string aValue = model.GetValue(a, 5).ToString();
  791. string bValue = model.GetValue(b, 5).ToString();
  792. if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "mins")
  793. {
  794. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 60).ToString();
  795. }
  796. else if (aValue.Length > 3 && aValue.Substring(aValue.Length - 3) == "hrs")
  797. {
  798. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 4)) * 3600).ToString();
  799. }
  800. else if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "days")
  801. {
  802. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 86400).ToString();
  803. }
  804. else
  805. {
  806. aValue = aValue.Substring(0, aValue.Length - 1);
  807. }
  808. if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "mins")
  809. {
  810. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 60).ToString();
  811. }
  812. else if (bValue.Length > 3 && bValue.Substring(bValue.Length - 3) == "hrs")
  813. {
  814. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 4)) * 3600).ToString();
  815. }
  816. else if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "days")
  817. {
  818. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 86400).ToString();
  819. }
  820. else
  821. {
  822. bValue = bValue.Substring(0, bValue.Length - 1);
  823. }
  824. if (float.Parse(aValue) > float.Parse(bValue))
  825. {
  826. return -1;
  827. }
  828. else if (float.Parse(bValue) > float.Parse(aValue))
  829. {
  830. return 1;
  831. }
  832. else
  833. {
  834. return 0;
  835. }
  836. }
  837. private static int LastPlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  838. {
  839. string aValue = model.GetValue(a, 6).ToString();
  840. string bValue = model.GetValue(b, 6).ToString();
  841. if (aValue == "Never")
  842. {
  843. aValue = DateTime.UnixEpoch.ToString();
  844. }
  845. if (bValue == "Never")
  846. {
  847. bValue = DateTime.UnixEpoch.ToString();
  848. }
  849. return DateTime.Compare(DateTime.Parse(bValue), DateTime.Parse(aValue));
  850. }
  851. private static int FileSizeSort(ITreeModel model, TreeIter a, TreeIter b)
  852. {
  853. string aValue = model.GetValue(a, 8).ToString();
  854. string bValue = model.GetValue(b, 8).ToString();
  855. if (aValue.Substring(aValue.Length - 2) == "GB")
  856. {
  857. aValue = (float.Parse(aValue[0..^2]) * 1024).ToString();
  858. }
  859. else
  860. {
  861. aValue = aValue[0..^2];
  862. }
  863. if (bValue.Substring(bValue.Length - 2) == "GB")
  864. {
  865. bValue = (float.Parse(bValue[0..^2]) * 1024).ToString();
  866. }
  867. else
  868. {
  869. bValue = bValue[0..^2];
  870. }
  871. if (float.Parse(aValue) > float.Parse(bValue))
  872. {
  873. return -1;
  874. }
  875. else if (float.Parse(bValue) > float.Parse(aValue))
  876. {
  877. return 1;
  878. }
  879. else
  880. {
  881. return 0;
  882. }
  883. }
  884. public static void SaveConfig()
  885. {
  886. ConfigurationState.Instance.ToFileFormat().SaveConfig(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json"));
  887. }
  888. }
  889. }