MainWindow.cs 52 KB

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