MainWindow.cs 53 KB

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