MainWindow.cs 46 KB

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