MainWindow.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. using Gtk;
  2. using JsonPrettyPrinterPlus;
  3. using Ryujinx.Audio;
  4. using Ryujinx.Common.Logging;
  5. using Ryujinx.Configuration;
  6. using Ryujinx.Graphics.OpenGL;
  7. using Ryujinx.HLE.FileSystem;
  8. using Ryujinx.Profiler;
  9. using System;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Reflection;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using Utf8Json;
  17. using Utf8Json.Resolvers;
  18. using GUI = Gtk.Builder.ObjectAttribute;
  19. namespace Ryujinx.Ui
  20. {
  21. public class MainWindow : Window
  22. {
  23. private static HLE.Switch _device;
  24. private static Renderer _renderer;
  25. private static IAalOutput _audioOut;
  26. private static GlScreen _screen;
  27. private static ListStore _tableStore;
  28. private static bool _updatingGameTable;
  29. private static bool _gameLoaded;
  30. private static bool _ending;
  31. private static TreeView _treeView;
  32. #pragma warning disable CS0649
  33. #pragma warning disable IDE0044
  34. [GUI] Window _mainWin;
  35. [GUI] CheckMenuItem _fullScreen;
  36. [GUI] MenuItem _stopEmulation;
  37. [GUI] CheckMenuItem _favToggle;
  38. [GUI] MenuItem _firmwareInstallFile;
  39. [GUI] MenuItem _firmwareInstallDirectory;
  40. [GUI] CheckMenuItem _iconToggle;
  41. [GUI] CheckMenuItem _appToggle;
  42. [GUI] CheckMenuItem _developerToggle;
  43. [GUI] CheckMenuItem _versionToggle;
  44. [GUI] CheckMenuItem _timePlayedToggle;
  45. [GUI] CheckMenuItem _lastPlayedToggle;
  46. [GUI] CheckMenuItem _fileExtToggle;
  47. [GUI] CheckMenuItem _fileSizeToggle;
  48. [GUI] CheckMenuItem _pathToggle;
  49. [GUI] TreeView _gameTable;
  50. [GUI] TreeSelection _gameTableSelection;
  51. [GUI] Label _progressLabel;
  52. [GUI] Label _firmwareVersionLabel;
  53. [GUI] LevelBar _progressBar;
  54. #pragma warning restore CS0649
  55. #pragma warning restore IDE0044
  56. public MainWindow() : this(new Builder("Ryujinx.Ui.MainWindow.glade")) { }
  57. private MainWindow(Builder builder) : base(builder.GetObject("_mainWin").Handle)
  58. {
  59. builder.Autoconnect(this);
  60. DeleteEvent += Window_Close;
  61. ApplicationLibrary.ApplicationAdded += Application_Added;
  62. _gameTable.ButtonReleaseEvent += Row_Clicked;
  63. bool continueWithStartup = Migration.PromptIfMigrationNeededForStartup(this, out bool migrationNeeded);
  64. if (!continueWithStartup)
  65. {
  66. End();
  67. }
  68. _renderer = new Renderer();
  69. _audioOut = InitializeAudioEngine();
  70. // TODO: Initialization and dispose of HLE.Switch when starting/stoping emulation.
  71. _device = InitializeSwitchInstance();
  72. if (migrationNeeded)
  73. {
  74. bool migrationSuccessful = Migration.DoMigrationForStartup(this, _device);
  75. if (!migrationSuccessful)
  76. {
  77. End();
  78. }
  79. }
  80. _treeView = _gameTable;
  81. ApplyTheme();
  82. _mainWin.Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png");
  83. _stopEmulation.Sensitive = false;
  84. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true;
  85. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true;
  86. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true;
  87. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true;
  88. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true;
  89. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true;
  90. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true;
  91. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true;
  92. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true;
  93. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true;
  94. _gameTable.Model = _tableStore = new ListStore(
  95. typeof(bool),
  96. typeof(Gdk.Pixbuf),
  97. typeof(string),
  98. typeof(string),
  99. typeof(string),
  100. typeof(string),
  101. typeof(string),
  102. typeof(string),
  103. typeof(string),
  104. typeof(string));
  105. _tableStore.SetSortFunc(5, TimePlayedSort);
  106. _tableStore.SetSortFunc(6, LastPlayedSort);
  107. _tableStore.SetSortFunc(8, FileSizeSort);
  108. _tableStore.SetSortColumnId(0, SortType.Descending);
  109. UpdateColumns();
  110. #pragma warning disable CS4014
  111. UpdateGameTable();
  112. #pragma warning restore CS4014
  113. Task.Run(RefreshFirmwareLabel);
  114. }
  115. internal static void ApplyTheme()
  116. {
  117. if (!ConfigurationState.Instance.Ui.EnableCustomTheme)
  118. {
  119. return;
  120. }
  121. if (File.Exists(ConfigurationState.Instance.Ui.CustomThemePath) && (System.IO.Path.GetExtension(ConfigurationState.Instance.Ui.CustomThemePath) == ".css"))
  122. {
  123. CssProvider cssProvider = new CssProvider();
  124. cssProvider.LoadFromPath(ConfigurationState.Instance.Ui.CustomThemePath);
  125. StyleContext.AddProviderForScreen(Gdk.Screen.Default, cssProvider, 800);
  126. }
  127. else
  128. {
  129. Logger.PrintWarning(LogClass.Application, $"The \"custom_theme_path\" section in \"Config.json\" contains an invalid path: \"{ConfigurationState.Instance.Ui.CustomThemePath}\".");
  130. }
  131. }
  132. private void UpdateColumns()
  133. {
  134. foreach (TreeViewColumn column in _gameTable.Columns)
  135. {
  136. _gameTable.RemoveColumn(column);
  137. }
  138. CellRendererToggle favToggle = new CellRendererToggle();
  139. favToggle.Toggled += FavToggle_Toggled;
  140. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0);
  141. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
  142. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
  143. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
  144. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
  145. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
  146. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
  147. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
  148. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
  149. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
  150. foreach (TreeViewColumn column in _gameTable.Columns)
  151. {
  152. if (column.Title == "Fav" && ConfigurationState.Instance.Ui.GuiColumns.FavColumn) column.SortColumnId = 0;
  153. else if (column.Title == "Application" && ConfigurationState.Instance.Ui.GuiColumns.AppColumn) column.SortColumnId = 2;
  154. else if (column.Title == "Developer" && ConfigurationState.Instance.Ui.GuiColumns.DevColumn) column.SortColumnId = 3;
  155. else if (column.Title == "Version" && ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) column.SortColumnId = 4;
  156. else if (column.Title == "Time Played" && ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) column.SortColumnId = 5;
  157. else if (column.Title == "Last Played" && ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) column.SortColumnId = 6;
  158. else if (column.Title == "File Ext" && ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) column.SortColumnId = 7;
  159. else if (column.Title == "File Size" && ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) column.SortColumnId = 8;
  160. else if (column.Title == "Path" && ConfigurationState.Instance.Ui.GuiColumns.PathColumn) column.SortColumnId = 9;
  161. }
  162. }
  163. private HLE.Switch InitializeSwitchInstance()
  164. {
  165. HLE.Switch instance = new HLE.Switch(_renderer, _audioOut);
  166. instance.Initialize();
  167. return instance;
  168. }
  169. internal static async Task UpdateGameTable()
  170. {
  171. if (_updatingGameTable)
  172. {
  173. return;
  174. }
  175. _updatingGameTable = true;
  176. _tableStore.Clear();
  177. await Task.Run(() => ApplicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs,
  178. _device.System.KeySet, _device.System.State.DesiredTitleLanguage, _device.System.FsClient,
  179. _device.FileSystem));
  180. _updatingGameTable = false;
  181. }
  182. internal void LoadApplication(string path)
  183. {
  184. if (_gameLoaded)
  185. {
  186. GtkDialog.CreateErrorDialog("A game has already been loaded. Please close the emulator and try again");
  187. }
  188. else
  189. {
  190. Logger.RestartTime();
  191. // TODO: Move this somewhere else + reloadable?
  192. Ryujinx.Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  193. if (Directory.Exists(path))
  194. {
  195. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  196. if (romFsFiles.Length == 0)
  197. {
  198. romFsFiles = Directory.GetFiles(path, "*.romfs");
  199. }
  200. if (romFsFiles.Length > 0)
  201. {
  202. Logger.PrintInfo(LogClass.Application, "Loading as cart with RomFS.");
  203. _device.LoadCart(path, romFsFiles[0]);
  204. }
  205. else
  206. {
  207. Logger.PrintInfo(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  208. _device.LoadCart(path);
  209. }
  210. }
  211. else if (File.Exists(path))
  212. {
  213. switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
  214. {
  215. case ".xci":
  216. Logger.PrintInfo(LogClass.Application, "Loading as XCI.");
  217. _device.LoadXci(path);
  218. break;
  219. case ".nca":
  220. Logger.PrintInfo(LogClass.Application, "Loading as NCA.");
  221. _device.LoadNca(path);
  222. break;
  223. case ".nsp":
  224. case ".pfs0":
  225. Logger.PrintInfo(LogClass.Application, "Loading as NSP.");
  226. _device.LoadNsp(path);
  227. break;
  228. default:
  229. Logger.PrintInfo(LogClass.Application, "Loading as homebrew.");
  230. try
  231. {
  232. _device.LoadProgram(path);
  233. }
  234. catch (ArgumentOutOfRangeException)
  235. {
  236. Logger.PrintError(LogClass.Application, "The file which you have specified is unsupported by Ryujinx.");
  237. }
  238. break;
  239. }
  240. }
  241. else
  242. {
  243. Logger.PrintWarning(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  244. End();
  245. }
  246. #if MACOS_BUILD
  247. CreateGameWindow();
  248. #else
  249. new Thread(CreateGameWindow).Start();
  250. #endif
  251. _gameLoaded = true;
  252. _stopEmulation.Sensitive = true;
  253. _firmwareInstallFile.Sensitive = false;
  254. _firmwareInstallDirectory.Sensitive = false;
  255. DiscordIntegrationModule.SwitchToPlayingState(_device.System.TitleId, _device.System.TitleName);
  256. string metadataFolder = System.IO.Path.Combine(new VirtualFileSystem().GetBasePath(), "games", _device.System.TitleId, "gui");
  257. string metadataFile = System.IO.Path.Combine(metadataFolder, "metadata.json");
  258. IJsonFormatterResolver resolver = CompositeResolver.Create(new[] { StandardResolver.AllowPrivateSnakeCase });
  259. ApplicationMetadata appMetadata;
  260. if (!File.Exists(metadataFile))
  261. {
  262. Directory.CreateDirectory(metadataFolder);
  263. appMetadata = new ApplicationMetadata
  264. {
  265. Favorite = false,
  266. TimePlayed = 0,
  267. LastPlayed = "Never"
  268. };
  269. byte[] data = JsonSerializer.Serialize(appMetadata, resolver);
  270. File.WriteAllText(metadataFile, Encoding.UTF8.GetString(data, 0, data.Length).PrettyPrintJson());
  271. }
  272. using (Stream stream = File.OpenRead(metadataFile))
  273. {
  274. appMetadata = JsonSerializer.Deserialize<ApplicationMetadata>(stream, resolver);
  275. }
  276. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  277. byte[] saveData = JsonSerializer.Serialize(appMetadata, resolver);
  278. File.WriteAllText(metadataFile, Encoding.UTF8.GetString(saveData, 0, saveData.Length).PrettyPrintJson());
  279. }
  280. }
  281. private static void CreateGameWindow()
  282. {
  283. _device.Hid.InitializePrimaryController(ConfigurationState.Instance.Hid.ControllerType);
  284. using (_screen = new GlScreen(_device, _renderer))
  285. {
  286. _screen.MainLoop();
  287. End();
  288. }
  289. }
  290. private static void End()
  291. {
  292. if (_ending)
  293. {
  294. return;
  295. }
  296. _ending = true;
  297. if (_gameLoaded)
  298. {
  299. string metadataFolder = System.IO.Path.Combine(new VirtualFileSystem().GetBasePath(), "games", _device.System.TitleId, "gui");
  300. string metadataFile = System.IO.Path.Combine(metadataFolder, "metadata.json");
  301. IJsonFormatterResolver resolver = CompositeResolver.Create(new[] { StandardResolver.AllowPrivateSnakeCase });
  302. ApplicationMetadata appMetadata;
  303. if (!File.Exists(metadataFile))
  304. {
  305. Directory.CreateDirectory(metadataFolder);
  306. appMetadata = new ApplicationMetadata
  307. {
  308. Favorite = false,
  309. TimePlayed = 0,
  310. LastPlayed = "Never"
  311. };
  312. byte[] data = JsonSerializer.Serialize(appMetadata, resolver);
  313. File.WriteAllText(metadataFile, Encoding.UTF8.GetString(data, 0, data.Length).PrettyPrintJson());
  314. }
  315. using (Stream stream = File.OpenRead(metadataFile))
  316. {
  317. appMetadata = JsonSerializer.Deserialize<ApplicationMetadata>(stream, resolver);
  318. }
  319. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  320. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  321. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  322. byte[] saveData = JsonSerializer.Serialize(appMetadata, resolver);
  323. File.WriteAllText(metadataFile, Encoding.UTF8.GetString(saveData, 0, saveData.Length).PrettyPrintJson());
  324. }
  325. Profile.FinishProfiling();
  326. _device?.Dispose();
  327. _audioOut?.Dispose();
  328. Logger.Shutdown();
  329. Environment.Exit(0);
  330. }
  331. /// <summary>
  332. /// Picks an <see cref="IAalOutput"/> audio output renderer supported on this machine
  333. /// </summary>
  334. /// <returns>An <see cref="IAalOutput"/> supported by this machine</returns>
  335. private static IAalOutput InitializeAudioEngine()
  336. {
  337. if (OpenALAudioOut.IsSupported)
  338. {
  339. return new OpenALAudioOut();
  340. }
  341. else if (SoundIoAudioOut.IsSupported)
  342. {
  343. return new SoundIoAudioOut();
  344. }
  345. else
  346. {
  347. return new DummyAudioOut();
  348. }
  349. }
  350. //Events
  351. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  352. {
  353. Application.Invoke(delegate
  354. {
  355. _tableStore.AppendValues(
  356. args.AppData.Favorite,
  357. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  358. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  359. args.AppData.Developer,
  360. args.AppData.Version,
  361. args.AppData.TimePlayed,
  362. args.AppData.LastPlayed,
  363. args.AppData.FileExtension,
  364. args.AppData.FileSize,
  365. args.AppData.Path);
  366. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  367. _progressBar.Value = (float)args.NumAppsLoaded / args.NumAppsFound;
  368. });
  369. }
  370. private void FavToggle_Toggled(object sender, ToggledArgs args)
  371. {
  372. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  373. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  374. string metadataPath = System.IO.Path.Combine(new VirtualFileSystem().GetBasePath(), "games", titleId, "gui", "metadata.json");
  375. IJsonFormatterResolver resolver = CompositeResolver.Create(new[] { StandardResolver.AllowPrivateSnakeCase });
  376. ApplicationMetadata appMetadata;
  377. using (Stream stream = File.OpenRead(metadataPath))
  378. {
  379. appMetadata = JsonSerializer.Deserialize<ApplicationMetadata>(stream, resolver);
  380. }
  381. if ((bool)_tableStore.GetValue(treeIter, 0))
  382. {
  383. _tableStore.SetValue(treeIter, 0, false);
  384. appMetadata.Favorite = false;
  385. }
  386. else
  387. {
  388. _tableStore.SetValue(treeIter, 0, true);
  389. appMetadata.Favorite = true;
  390. }
  391. byte[] saveData = JsonSerializer.Serialize(appMetadata, resolver);
  392. File.WriteAllText(metadataPath, Encoding.UTF8.GetString(saveData, 0, saveData.Length).PrettyPrintJson());
  393. }
  394. private void Row_Activated(object sender, RowActivatedArgs args)
  395. {
  396. _gameTableSelection.GetSelected(out TreeIter treeIter);
  397. string path = (string)_tableStore.GetValue(treeIter, 9);
  398. LoadApplication(path);
  399. }
  400. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  401. {
  402. if (args.Event.Button != 3) return;
  403. _gameTableSelection.GetSelected(out TreeIter treeIter);
  404. if (treeIter.UserData == IntPtr.Zero) return;
  405. GameTableContextMenu contextMenu = new GameTableContextMenu(_tableStore, treeIter, _device.System.FsClient);
  406. contextMenu.ShowAll();
  407. contextMenu.PopupAtPointer(null);
  408. }
  409. private void Load_Application_File(object sender, EventArgs args)
  410. {
  411. FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  412. fileChooser.Filter = new FileFilter();
  413. fileChooser.Filter.AddPattern("*.nsp" );
  414. fileChooser.Filter.AddPattern("*.pfs0");
  415. fileChooser.Filter.AddPattern("*.xci" );
  416. fileChooser.Filter.AddPattern("*.nca" );
  417. fileChooser.Filter.AddPattern("*.nro" );
  418. fileChooser.Filter.AddPattern("*.nso" );
  419. if (fileChooser.Run() == (int)ResponseType.Accept)
  420. {
  421. LoadApplication(fileChooser.Filename);
  422. }
  423. fileChooser.Dispose();
  424. }
  425. private void Load_Application_Folder(object sender, EventArgs args)
  426. {
  427. FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  428. if (fileChooser.Run() == (int)ResponseType.Accept)
  429. {
  430. LoadApplication(fileChooser.Filename);
  431. }
  432. fileChooser.Dispose();
  433. }
  434. private void Open_Ryu_Folder(object sender, EventArgs args)
  435. {
  436. Process.Start(new ProcessStartInfo()
  437. {
  438. FileName = new VirtualFileSystem().GetBasePath(),
  439. UseShellExecute = true,
  440. Verb = "open"
  441. });
  442. }
  443. private void Exit_Pressed(object sender, EventArgs args)
  444. {
  445. _screen?.Exit();
  446. End();
  447. }
  448. private void Window_Close(object sender, DeleteEventArgs args)
  449. {
  450. _screen?.Exit();
  451. End();
  452. }
  453. private void StopEmulation_Pressed(object sender, EventArgs args)
  454. {
  455. // TODO: Write logic to kill running game
  456. _gameLoaded = false;
  457. }
  458. private void Installer_File_Pressed(object o, EventArgs args)
  459. {
  460. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open",
  461. this,
  462. FileChooserAction.Open,
  463. "Cancel",
  464. ResponseType.Cancel,
  465. "Open",
  466. ResponseType.Accept);
  467. fileChooser.Filter = new FileFilter();
  468. fileChooser.Filter.AddPattern("*.zip");
  469. fileChooser.Filter.AddPattern("*.xci");
  470. HandleInstallerDialog(fileChooser);
  471. }
  472. private void Installer_Directory_Pressed(object o, EventArgs args)
  473. {
  474. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open",
  475. this,
  476. FileChooserAction.SelectFolder,
  477. "Cancel",
  478. ResponseType.Cancel,
  479. "Open",
  480. ResponseType.Accept);
  481. HandleInstallerDialog(directoryChooser);
  482. }
  483. private void RefreshFirmwareLabel()
  484. {
  485. var currentFirmware = _device.System.GetCurrentFirmwareVersion();
  486. GLib.Idle.Add(new GLib.IdleHandler(() =>
  487. {
  488. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  489. return false;
  490. }));
  491. }
  492. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  493. {
  494. if (fileChooser.Run() == (int)ResponseType.Accept)
  495. {
  496. MessageDialog dialog = null;
  497. try
  498. {
  499. string filename = fileChooser.Filename;
  500. fileChooser.Dispose();
  501. var firmwareVersion = _device.System.VerifyFirmwarePackage(filename);
  502. if (firmwareVersion == null)
  503. {
  504. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  505. dialog.Text = "Firmware not found.";
  506. dialog.SecondaryText = $"A valid system firmware was not found in {filename}.";
  507. Logger.PrintError(LogClass.Application, $"A valid system firmware was not found in {filename}.");
  508. dialog.Run();
  509. dialog.Hide();
  510. dialog.Dispose();
  511. return;
  512. }
  513. var currentVersion = _device.System.GetCurrentFirmwareVersion();
  514. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  515. if (currentVersion != null)
  516. {
  517. dialogMessage += $"This will replace the current system version {currentVersion.VersionString}. ";
  518. }
  519. dialogMessage += "Do you want to continue?";
  520. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, false, "");
  521. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  522. dialog.SecondaryText = dialogMessage;
  523. int response = dialog.Run();
  524. dialog.Dispose();
  525. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, false, "");
  526. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  527. dialog.SecondaryText = "Installing firmware...";
  528. if (response == (int)ResponseType.Yes)
  529. {
  530. Logger.PrintInfo(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  531. Thread thread = new Thread(() =>
  532. {
  533. GLib.Idle.Add(new GLib.IdleHandler(() =>
  534. {
  535. dialog.Run();
  536. return false;
  537. }));
  538. try
  539. {
  540. _device.System.InstallFirmware(filename);
  541. GLib.Idle.Add(new GLib.IdleHandler(() =>
  542. {
  543. dialog.Dispose();
  544. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  545. dialog.Text = $"Install Firmware {firmwareVersion.VersionString}";
  546. dialog.SecondaryText = $"System version {firmwareVersion.VersionString} successfully installed.";
  547. Logger.PrintInfo(LogClass.Application, $"System version {firmwareVersion.VersionString} successfully installed.");
  548. dialog.Run();
  549. dialog.Dispose();
  550. return false;
  551. }));
  552. }
  553. catch (Exception ex)
  554. {
  555. GLib.Idle.Add(new GLib.IdleHandler(() =>
  556. {
  557. dialog.Dispose();
  558. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  559. dialog.Text = $"Install Firmware {firmwareVersion.VersionString} Failed.";
  560. dialog.SecondaryText = $"An error occured while installing system version {firmwareVersion.VersionString}." +
  561. " Please check logs for more info.";
  562. Logger.PrintError(LogClass.Application, ex.Message);
  563. dialog.Run();
  564. dialog.Dispose();
  565. return false;
  566. }));
  567. }
  568. finally
  569. {
  570. RefreshFirmwareLabel();
  571. }
  572. });
  573. thread.Start();
  574. }
  575. else
  576. {
  577. dialog.Dispose();
  578. }
  579. }
  580. catch (Exception ex)
  581. {
  582. if (dialog != null)
  583. {
  584. dialog.Dispose();
  585. }
  586. dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, false, "");
  587. dialog.Text = "Parsing Firmware Failed.";
  588. dialog.SecondaryText = "An error occured while parsing firmware. Please check the logs for more info.";
  589. Logger.PrintError(LogClass.Application, ex.Message);
  590. dialog.Run();
  591. dialog.Dispose();
  592. }
  593. }
  594. else
  595. {
  596. fileChooser.Dispose();
  597. }
  598. }
  599. private void FullScreen_Toggled(object o, EventArgs args)
  600. {
  601. if (_fullScreen.Active)
  602. {
  603. Fullscreen();
  604. }
  605. else
  606. {
  607. Unfullscreen();
  608. }
  609. }
  610. private void Settings_Pressed(object sender, EventArgs args)
  611. {
  612. SwitchSettings settingsWin = new SwitchSettings();
  613. settingsWin.Show();
  614. }
  615. private void Update_Pressed(object sender, EventArgs args)
  616. {
  617. string ryuUpdater = System.IO.Path.Combine(new VirtualFileSystem().GetBasePath(), "RyuUpdater.exe");
  618. try
  619. {
  620. Process.Start(new ProcessStartInfo(ryuUpdater, "/U") { UseShellExecute = true });
  621. }
  622. catch(System.ComponentModel.Win32Exception)
  623. {
  624. GtkDialog.CreateErrorDialog("Update canceled by user or updater was not found");
  625. }
  626. }
  627. private void About_Pressed(object sender, EventArgs args)
  628. {
  629. AboutWindow aboutWin = new AboutWindow();
  630. aboutWin.Show();
  631. }
  632. private void Fav_Toggled(object sender, EventArgs args)
  633. {
  634. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  635. SaveConfig();
  636. UpdateColumns();
  637. }
  638. private void Icon_Toggled(object sender, EventArgs args)
  639. {
  640. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  641. SaveConfig();
  642. UpdateColumns();
  643. }
  644. private void Title_Toggled(object sender, EventArgs args)
  645. {
  646. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  647. SaveConfig();
  648. UpdateColumns();
  649. }
  650. private void Developer_Toggled(object sender, EventArgs args)
  651. {
  652. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  653. SaveConfig();
  654. UpdateColumns();
  655. }
  656. private void Version_Toggled(object sender, EventArgs args)
  657. {
  658. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  659. SaveConfig();
  660. UpdateColumns();
  661. }
  662. private void TimePlayed_Toggled(object sender, EventArgs args)
  663. {
  664. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  665. SaveConfig();
  666. UpdateColumns();
  667. }
  668. private void LastPlayed_Toggled(object sender, EventArgs args)
  669. {
  670. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  671. SaveConfig();
  672. UpdateColumns();
  673. }
  674. private void FileExt_Toggled(object sender, EventArgs args)
  675. {
  676. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  677. SaveConfig();
  678. UpdateColumns();
  679. }
  680. private void FileSize_Toggled(object sender, EventArgs args)
  681. {
  682. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  683. SaveConfig();
  684. UpdateColumns();
  685. }
  686. private void Path_Toggled(object sender, EventArgs args)
  687. {
  688. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  689. SaveConfig();
  690. UpdateColumns();
  691. }
  692. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  693. {
  694. #pragma warning disable CS4014
  695. UpdateGameTable();
  696. #pragma warning restore CS4014
  697. }
  698. private static int TimePlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  699. {
  700. string aValue = model.GetValue(a, 5).ToString();
  701. string bValue = model.GetValue(b, 5).ToString();
  702. if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "mins")
  703. {
  704. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 60).ToString();
  705. }
  706. else if (aValue.Length > 3 && aValue.Substring(aValue.Length - 3) == "hrs")
  707. {
  708. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 4)) * 3600).ToString();
  709. }
  710. else if (aValue.Length > 4 && aValue.Substring(aValue.Length - 4) == "days")
  711. {
  712. aValue = (float.Parse(aValue.Substring(0, aValue.Length - 5)) * 86400).ToString();
  713. }
  714. else
  715. {
  716. aValue = aValue.Substring(0, aValue.Length - 1);
  717. }
  718. if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "mins")
  719. {
  720. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 60).ToString();
  721. }
  722. else if (bValue.Length > 3 && bValue.Substring(bValue.Length - 3) == "hrs")
  723. {
  724. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 4)) * 3600).ToString();
  725. }
  726. else if (bValue.Length > 4 && bValue.Substring(bValue.Length - 4) == "days")
  727. {
  728. bValue = (float.Parse(bValue.Substring(0, bValue.Length - 5)) * 86400).ToString();
  729. }
  730. else
  731. {
  732. bValue = bValue.Substring(0, bValue.Length - 1);
  733. }
  734. if (float.Parse(aValue) > float.Parse(bValue))
  735. {
  736. return -1;
  737. }
  738. else if (float.Parse(bValue) > float.Parse(aValue))
  739. {
  740. return 1;
  741. }
  742. else
  743. {
  744. return 0;
  745. }
  746. }
  747. private static int LastPlayedSort(ITreeModel model, TreeIter a, TreeIter b)
  748. {
  749. string aValue = model.GetValue(a, 6).ToString();
  750. string bValue = model.GetValue(b, 6).ToString();
  751. if (aValue == "Never")
  752. {
  753. aValue = DateTime.UnixEpoch.ToString();
  754. }
  755. if (bValue == "Never")
  756. {
  757. bValue = DateTime.UnixEpoch.ToString();
  758. }
  759. return DateTime.Compare(DateTime.Parse(bValue), DateTime.Parse(aValue));
  760. }
  761. private static int FileSizeSort(ITreeModel model, TreeIter a, TreeIter b)
  762. {
  763. string aValue = model.GetValue(a, 8).ToString();
  764. string bValue = model.GetValue(b, 8).ToString();
  765. if (aValue.Substring(aValue.Length - 2) == "GB")
  766. {
  767. aValue = (float.Parse(aValue[0..^2]) * 1024).ToString();
  768. }
  769. else
  770. {
  771. aValue = aValue[0..^2];
  772. }
  773. if (bValue.Substring(bValue.Length - 2) == "GB")
  774. {
  775. bValue = (float.Parse(bValue[0..^2]) * 1024).ToString();
  776. }
  777. else
  778. {
  779. bValue = bValue[0..^2];
  780. }
  781. if (float.Parse(aValue) > float.Parse(bValue))
  782. {
  783. return -1;
  784. }
  785. else if (float.Parse(bValue) > float.Parse(aValue))
  786. {
  787. return 1;
  788. }
  789. else
  790. {
  791. return 0;
  792. }
  793. }
  794. public static void SaveConfig()
  795. {
  796. ConfigurationState.Instance.ToFileFormat().SaveConfig(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json"));
  797. }
  798. }
  799. }