MainWindow.cs 41 KB

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