MainWindow.cs 44 KB

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