MainWindow.cs 42 KB

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