MainWindow.cs 51 KB

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