MainWindow.cs 45 KB

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