MainWindow.cs 51 KB

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