MainWindow.cs 41 KB

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