MainWindow.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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, trying to fall back to SoundIO.");
  554. if (SoundIoAudioOut.IsSupported)
  555. {
  556. Logger.PrintWarning(LogClass.Audio, "Found SoundIO, changing configuration.");
  557. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  558. SaveConfig();
  559. return new SoundIoAudioOut();
  560. }
  561. else
  562. {
  563. Logger.PrintWarning(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  564. }
  565. }
  566. }
  567. return new DummyAudioOut();
  568. }
  569. //Events
  570. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  571. {
  572. Application.Invoke(delegate
  573. {
  574. _tableStore.AppendValues(
  575. args.AppData.Favorite,
  576. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  577. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  578. args.AppData.Developer,
  579. args.AppData.Version,
  580. args.AppData.TimePlayed,
  581. args.AppData.LastPlayed,
  582. args.AppData.FileExtension,
  583. args.AppData.FileSize,
  584. args.AppData.Path,
  585. args.AppData.ControlHolder);
  586. });
  587. }
  588. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  589. {
  590. Application.Invoke(delegate
  591. {
  592. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  593. float barValue = 0;
  594. if (args.NumAppsFound != 0)
  595. {
  596. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  597. }
  598. _progressBar.Value = barValue;
  599. if (args.NumAppsLoaded == args.NumAppsFound) // Reset the vertical scrollbar to the top when titles finish loading
  600. {
  601. _gameTableWindow.Vadjustment.Value = 0;
  602. }
  603. });
  604. }
  605. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  606. {
  607. Application.Invoke(delegate
  608. {
  609. _hostStatus.Text = args.HostStatus;
  610. _gameStatus.Text = args.GameStatus;
  611. _gpuName.Text = args.GpuName;
  612. _dockedMode.Text = args.DockedMode;
  613. if (args.VSyncEnabled)
  614. {
  615. _vSyncStatus.Attributes = new Pango.AttrList();
  616. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  617. }
  618. else
  619. {
  620. _vSyncStatus.Attributes = new Pango.AttrList();
  621. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  622. }
  623. });
  624. }
  625. private void FavToggle_Toggled(object sender, ToggledArgs args)
  626. {
  627. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  628. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  629. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  630. _tableStore.SetValue(treeIter, 0, newToggleValue);
  631. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  632. {
  633. appMetadata.Favorite = newToggleValue;
  634. });
  635. }
  636. private void Column_Clicked(object sender, EventArgs args)
  637. {
  638. TreeViewColumn column = (TreeViewColumn)sender;
  639. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  640. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  641. SaveConfig();
  642. }
  643. private void Row_Activated(object sender, RowActivatedArgs args)
  644. {
  645. _gameTableSelection.GetSelected(out TreeIter treeIter);
  646. string path = (string)_tableStore.GetValue(treeIter, 9);
  647. LoadApplication(path);
  648. }
  649. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  650. {
  651. if (args.Event.Button != 3) return;
  652. _gameTableSelection.GetSelected(out TreeIter treeIter);
  653. if (treeIter.UserData == IntPtr.Zero) return;
  654. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  655. GameTableContextMenu contextMenu = new GameTableContextMenu(_tableStore, controlData, treeIter, _virtualFileSystem);
  656. contextMenu.ShowAll();
  657. contextMenu.PopupAtPointer(null);
  658. }
  659. private void Load_Application_File(object sender, EventArgs args)
  660. {
  661. FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  662. fileChooser.Filter = new FileFilter();
  663. fileChooser.Filter.AddPattern("*.nsp" );
  664. fileChooser.Filter.AddPattern("*.pfs0");
  665. fileChooser.Filter.AddPattern("*.xci" );
  666. fileChooser.Filter.AddPattern("*.nca" );
  667. fileChooser.Filter.AddPattern("*.nro" );
  668. fileChooser.Filter.AddPattern("*.nso" );
  669. if (fileChooser.Run() == (int)ResponseType.Accept)
  670. {
  671. LoadApplication(fileChooser.Filename);
  672. }
  673. fileChooser.Dispose();
  674. }
  675. private void Load_Application_Folder(object sender, EventArgs args)
  676. {
  677. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  678. if (fileChooser.Run() == (int)ResponseType.Accept)
  679. {
  680. LoadApplication(fileChooser.Filename);
  681. }
  682. fileChooser.Dispose();
  683. }
  684. private void Open_Ryu_Folder(object sender, EventArgs args)
  685. {
  686. Process.Start(new ProcessStartInfo()
  687. {
  688. FileName = _virtualFileSystem.GetBasePath(),
  689. UseShellExecute = true,
  690. Verb = "open"
  691. });
  692. }
  693. private void Exit_Pressed(object sender, EventArgs args)
  694. {
  695. End(_emulationContext);
  696. }
  697. private void Window_Close(object sender, DeleteEventArgs args)
  698. {
  699. End(_emulationContext);
  700. }
  701. private void StopEmulation_Pressed(object sender, EventArgs args)
  702. {
  703. _glWidget?.Exit();
  704. }
  705. private void Installer_File_Pressed(object o, EventArgs args)
  706. {
  707. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open",
  708. this,
  709. FileChooserAction.Open,
  710. "Cancel",
  711. ResponseType.Cancel,
  712. "Open",
  713. ResponseType.Accept);
  714. fileChooser.Filter = new FileFilter();
  715. fileChooser.Filter.AddPattern("*.zip");
  716. fileChooser.Filter.AddPattern("*.xci");
  717. HandleInstallerDialog(fileChooser);
  718. }
  719. private void Installer_Directory_Pressed(object o, EventArgs args)
  720. {
  721. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open",
  722. this,
  723. FileChooserAction.SelectFolder,
  724. "Cancel",
  725. ResponseType.Cancel,
  726. "Open",
  727. ResponseType.Accept);
  728. HandleInstallerDialog(directoryChooser);
  729. }
  730. private void RefreshFirmwareLabel()
  731. {
  732. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  733. GLib.Idle.Add(new GLib.IdleHandler(() =>
  734. {
  735. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  736. return false;
  737. }));
  738. }
  739. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  740. {
  741. if (fileChooser.Run() == (int)ResponseType.Accept)
  742. {
  743. MessageDialog dialog = null;
  744. try
  745. {
  746. string filename = fileChooser.Filename;
  747. fileChooser.Dispose();
  748. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  749. if (firmwareVersion == null)
  750. {
  751. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  752. dialog.Text = "Firmware not found.";
  753. dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";
  754. Logger.PrintError(LogClass.Application, $"A valid system firmware was not found in {filename}.");
  755. dialog.Run();
  756. dialog.Hide();
  757. dialog.Dispose();
  758. return;
  759. }
  760. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  761. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  762. if (currentVersion != null)
  763. {
  764. dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
  765. }
  766. dialogMessage += "Do you want to continue?";
  767. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");
  768. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  769. dialog.SecondaryText = dialogMessage;
  770. int response = dialog.Run();
  771. dialog.Dispose();
  772. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");
  773. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  774. dialog.SecondaryText = "Installing firmware...";
  775. if (response == (int)ResponseType.Yes)
  776. {
  777. Logger.PrintInfo(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  778. Thread thread = new Thread(() =>
  779. {
  780. GLib.Idle.Add(new GLib.IdleHandler(() =>
  781. {
  782. dialog.Run();
  783. return false;
  784. }));
  785. try
  786. {
  787. _contentManager.InstallFirmware(filename);
  788. GLib.Idle.Add(new GLib.IdleHandler(() =>
  789. {
  790. dialog.Dispose();
  791. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  792. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  793. dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";
  794. Logger.PrintInfo(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");
  795. dialog.Run();
  796. dialog.Dispose();
  797. return false;
  798. }));
  799. }
  800. catch (Exception ex)
  801. {
  802. GLib.Idle.Add(new GLib.IdleHandler(() =>
  803. {
  804. dialog.Dispose();
  805. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  806. dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";
  807. dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
  808. " Please check logs for more info.";
  809. Logger.PrintError(LogClass.Application, ex.Message);
  810. dialog.Run();
  811. dialog.Dispose();
  812. return false;
  813. }));
  814. }
  815. finally
  816. {
  817. RefreshFirmwareLabel();
  818. }
  819. });
  820. thread.Name = "GUI.FirmwareInstallerThread";
  821. thread.Start();
  822. }
  823. else
  824. {
  825. dialog.Dispose();
  826. }
  827. }
  828. catch (Exception ex)
  829. {
  830. if (dialog != null)
  831. {
  832. dialog.Dispose();
  833. }
  834. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  835. dialog.Text = "Parsing Firmware Failed.";
  836. dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";
  837. Logger.PrintError(LogClass.Application, ex.Message);
  838. dialog.Run();
  839. dialog.Dispose();
  840. }
  841. }
  842. else
  843. {
  844. fileChooser.Dispose();
  845. }
  846. }
  847. private void FullScreen_Toggled(object o, EventArgs args)
  848. {
  849. bool fullScreenToggled = this.Window.State.HasFlag(Gdk.WindowState.Fullscreen);
  850. if (!fullScreenToggled)
  851. {
  852. Fullscreen();
  853. ToggleExtraWidgets(false);
  854. }
  855. else
  856. {
  857. Unfullscreen();
  858. ToggleExtraWidgets(true);
  859. }
  860. }
  861. private void Settings_Pressed(object sender, EventArgs args)
  862. {
  863. SettingsWindow settingsWin = new SettingsWindow(_virtualFileSystem, _contentManager);
  864. settingsWin.Show();
  865. }
  866. private void Update_Pressed(object sender, EventArgs args)
  867. {
  868. string ryuUpdater = System.IO.Path.Combine(_virtualFileSystem.GetBasePath(), "RyuUpdater.exe");
  869. try
  870. {
  871. Process.Start(new ProcessStartInfo(ryuUpdater, "/U") { UseShellExecute = true });
  872. }
  873. catch(System.ComponentModel.Win32Exception)
  874. {
  875. GtkDialog.CreateErrorDialog("Update canceled by user or updater was not found");
  876. }
  877. }
  878. private void About_Pressed(object sender, EventArgs args)
  879. {
  880. AboutWindow aboutWin = new AboutWindow();
  881. aboutWin.Show();
  882. }
  883. private void Fav_Toggled(object sender, EventArgs args)
  884. {
  885. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  886. SaveConfig();
  887. UpdateColumns();
  888. }
  889. private void Icon_Toggled(object sender, EventArgs args)
  890. {
  891. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  892. SaveConfig();
  893. UpdateColumns();
  894. }
  895. private void Title_Toggled(object sender, EventArgs args)
  896. {
  897. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  898. SaveConfig();
  899. UpdateColumns();
  900. }
  901. private void Developer_Toggled(object sender, EventArgs args)
  902. {
  903. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  904. SaveConfig();
  905. UpdateColumns();
  906. }
  907. private void Version_Toggled(object sender, EventArgs args)
  908. {
  909. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  910. SaveConfig();
  911. UpdateColumns();
  912. }
  913. private void TimePlayed_Toggled(object sender, EventArgs args)
  914. {
  915. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  916. SaveConfig();
  917. UpdateColumns();
  918. }
  919. private void LastPlayed_Toggled(object sender, EventArgs args)
  920. {
  921. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  922. SaveConfig();
  923. UpdateColumns();
  924. }
  925. private void FileExt_Toggled(object sender, EventArgs args)
  926. {
  927. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  928. SaveConfig();
  929. UpdateColumns();
  930. }
  931. private void FileSize_Toggled(object sender, EventArgs args)
  932. {
  933. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  934. SaveConfig();
  935. UpdateColumns();
  936. }
  937. private void Path_Toggled(object sender, EventArgs args)
  938. {
  939. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  940. SaveConfig();
  941. UpdateColumns();
  942. }
  943. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  944. {
  945. UpdateGameTable();
  946. }
  947. private static int TimePlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  948. {
  949. string aValue = model.GetValue(a, 5).ToString();
  950. string bValue = model.GetValue(b, 5).ToString();
  951. if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "mins")
  952. {
  953. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 60).ToString();
  954. }
  955. else if (aValue.Length > 3 && aValue.Substring(aValue.Length - 3) == "hrs")
  956. {
  957. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 4)) * 3600).ToString();
  958. }
  959. else if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "days")
  960. {
  961. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 86400).ToString();
  962. }
  963. else
  964. {
  965. aValue = aValue.Substring(0, aValue.Length - 1);
  966. }
  967. if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "mins")
  968. {
  969. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 60).ToString();
  970. }
  971. else if (bValue.Length > 3 && bValue.Substring(bValue.Length - 3) == "hrs")
  972. {
  973. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 4)) * 3600).ToString();
  974. }
  975. else if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "days")
  976. {
  977. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 86400).ToString();
  978. }
  979. else
  980. {
  981. bValue = bValue.Substring(0, bValue.Length - 1);
  982. }
  983. if (float.Parse(aValue) > float.Parse(bValue))
  984. {
  985. return -1;
  986. }
  987. else if (float.Parse(bValue) > float.Parse(aValue))
  988. {
  989. return 1;
  990. }
  991. else
  992. {
  993. return 0;
  994. }
  995. }
  996. private static int LastPlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  997. {
  998. string aValue = model.GetValue(a, 6).ToString();
  999. string bValue = model.GetValue(b, 6).ToString();
  1000. if (aValue == "Never")
  1001. {
  1002. aValue = DateTime.UnixEpoch.ToString();
  1003. }
  1004. if (bValue == "Never")
  1005. {
  1006. bValue = DateTime.UnixEpoch.ToString();
  1007. }
  1008. return DateTime.Compare(DateTime.Parse(bValue), DateTime.Parse(aValue));
  1009. }
  1010. private static int FileSizeSort(ITreeModel model, TreeIter a, TreeIter b)
  1011. {
  1012. string aValue = model.GetValue(a, 8).ToString();
  1013. string bValue = model.GetValue(b, 8).ToString();
  1014. if (aValue.Substring(aValue.Length - 2) == "GB")
  1015. {
  1016. aValue = (float.Parse(aValue[0..^2]) * 1024).ToString();
  1017. }
  1018. else
  1019. {
  1020. aValue = aValue[0..^2];
  1021. }
  1022. if (bValue.Substring(bValue.Length - 2) == "GB")
  1023. {
  1024. bValue = (float.Parse(bValue[0..^2]) * 1024).ToString();
  1025. }
  1026. else
  1027. {
  1028. bValue = bValue[0..^2];
  1029. }
  1030. if (float.Parse(aValue) > float.Parse(bValue))
  1031. {
  1032. return -1;
  1033. }
  1034. else if (float.Parse(bValue) > float.Parse(aValue))
  1035. {
  1036. return 1;
  1037. }
  1038. else
  1039. {
  1040. return 0;
  1041. }
  1042. }
  1043. }
  1044. }