MainWindow.cs 46 KB

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