MainWindow.cs 47 KB

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