MainWindow.cs 45 KB

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