MainWindow.cs 40 KB

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