MainWindow.cs 51 KB

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