MainWindow.cs 51 KB

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