MainWindow.cs 45 KB

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