MainWindowViewModel.cs 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  1. using Avalonia.Controls;
  2. using Avalonia.Controls.ApplicationLifetimes;
  3. using Avalonia.Input;
  4. using Avalonia.Media;
  5. using Avalonia.Threading;
  6. using DynamicData;
  7. using DynamicData.Binding;
  8. using LibHac.Fs;
  9. using LibHac.FsSystem;
  10. using Ryujinx.Ava.Common;
  11. using Ryujinx.Ava.Common.Locale;
  12. using Ryujinx.Ava.Input;
  13. using Ryujinx.Ava.UI.Controls;
  14. using Ryujinx.Ava.UI.Helpers;
  15. using Ryujinx.Ava.UI.Models;
  16. using Ryujinx.Ava.UI.Windows;
  17. using Ryujinx.Common;
  18. using Ryujinx.Common.Configuration;
  19. using Ryujinx.Common.Logging;
  20. using Ryujinx.Cpu;
  21. using Ryujinx.HLE;
  22. using Ryujinx.HLE.FileSystem;
  23. using Ryujinx.HLE.HOS;
  24. using Ryujinx.HLE.HOS.Services.Account.Acc;
  25. using Ryujinx.HLE.Ui;
  26. using Ryujinx.Ui.App.Common;
  27. using Ryujinx.Ui.Common;
  28. using Ryujinx.Ui.Common.Configuration;
  29. using Ryujinx.Ui.Common.Helper;
  30. using SixLabors.ImageSharp.PixelFormats;
  31. using System;
  32. using System.Collections.Generic;
  33. using System.Collections.ObjectModel;
  34. using System.Globalization;
  35. using System.IO;
  36. using System.Threading;
  37. using System.Threading.Tasks;
  38. using Path = System.IO.Path;
  39. using ShaderCacheLoadingState = Ryujinx.Graphics.Gpu.Shader.ShaderCacheState;
  40. using UserId = LibHac.Fs.UserId;
  41. namespace Ryujinx.Ava.UI.ViewModels
  42. {
  43. public class MainWindowViewModel : BaseModel
  44. {
  45. private const int HotKeyPressDelayMs = 500;
  46. private ObservableCollection<ApplicationData> _applications;
  47. private string _aspectStatusText;
  48. private string _loadHeading;
  49. private string _cacheLoadStatus;
  50. private string _searchText;
  51. private Timer _searchTimer;
  52. private string _dockedStatusText;
  53. private string _fifoStatusText;
  54. private string _gameStatusText;
  55. private string _volumeStatusText;
  56. private string _gpuStatusText;
  57. private bool _isAmiiboRequested;
  58. private bool _isGameRunning;
  59. private bool _isFullScreen;
  60. private int _progressMaximum;
  61. private int _progressValue;
  62. private long _lastFullscreenToggle = Environment.TickCount64;
  63. private bool _showLoadProgress;
  64. private bool _showMenuAndStatusBar = true;
  65. private bool _showStatusSeparator;
  66. private Brush _progressBarForegroundColor;
  67. private Brush _progressBarBackgroundColor;
  68. private Brush _vsyncColor;
  69. private byte[] _selectedIcon;
  70. private bool _isAppletMenuActive;
  71. private int _statusBarProgressMaximum;
  72. private int _statusBarProgressValue;
  73. private bool _isPaused;
  74. private bool _showContent = true;
  75. private bool _isLoadingIndeterminate = true;
  76. private bool _showAll;
  77. private string _lastScannedAmiiboId;
  78. private bool _statusBarVisible;
  79. private ReadOnlyObservableCollection<ApplicationData> _appsObservableList;
  80. private string _showUiKey = "F4";
  81. private string _pauseKey = "F5";
  82. private string _screenshotKey = "F8";
  83. private float _volume;
  84. private string _backendText;
  85. private bool _canUpdate;
  86. private Cursor _cursor;
  87. private string _title;
  88. private string _currentEmulatedGamePath;
  89. private AutoResetEvent _rendererWaitEvent;
  90. private WindowState _windowState;
  91. private bool _isActive;
  92. public ApplicationData ListSelectedApplication;
  93. public ApplicationData GridSelectedApplication;
  94. public event Action ReloadGameList;
  95. private string TitleName { get; set; }
  96. internal AppHost AppHost { get; set; }
  97. public MainWindowViewModel()
  98. {
  99. Applications = new ObservableCollection<ApplicationData>();
  100. Applications.ToObservableChangeSet()
  101. .Filter(Filter)
  102. .Sort(GetComparer())
  103. .Bind(out _appsObservableList).AsObservableList();
  104. _rendererWaitEvent = new AutoResetEvent(false);
  105. if (Program.PreviewerDetached)
  106. {
  107. LoadConfigurableHotKeys();
  108. Volume = ConfigurationState.Instance.System.AudioVolume;
  109. }
  110. }
  111. public void Initialize(
  112. ContentManager contentManager,
  113. ApplicationLibrary applicationLibrary,
  114. VirtualFileSystem virtualFileSystem,
  115. AccountManager accountManager,
  116. Ryujinx.Input.HLE.InputManager inputManager,
  117. UserChannelPersistence userChannelPersistence,
  118. LibHacHorizonManager libHacHorizonManager,
  119. IHostUiHandler uiHandler,
  120. Action<bool> showLoading,
  121. Action<bool> switchToGameControl,
  122. Action<Control> setMainContent,
  123. TopLevel topLevel)
  124. {
  125. ContentManager = contentManager;
  126. ApplicationLibrary = applicationLibrary;
  127. VirtualFileSystem = virtualFileSystem;
  128. AccountManager = accountManager;
  129. InputManager = inputManager;
  130. UserChannelPersistence = userChannelPersistence;
  131. LibHacHorizonManager = libHacHorizonManager;
  132. UiHandler = uiHandler;
  133. ShowLoading = showLoading;
  134. SwitchToGameControl = switchToGameControl;
  135. SetMainContent = setMainContent;
  136. TopLevel = topLevel;
  137. }
  138. #region Properties
  139. public string SearchText
  140. {
  141. get => _searchText;
  142. set
  143. {
  144. _searchText = value;
  145. _searchTimer?.Dispose();
  146. _searchTimer = new Timer(TimerCallback, null, 1000, 0);
  147. }
  148. }
  149. private void TimerCallback(object obj)
  150. {
  151. RefreshView();
  152. _searchTimer.Dispose();
  153. _searchTimer = null;
  154. }
  155. public bool CanUpdate
  156. {
  157. get => _canUpdate;
  158. set
  159. {
  160. _canUpdate = value;
  161. OnPropertyChanged();
  162. }
  163. }
  164. public Cursor Cursor
  165. {
  166. get => _cursor;
  167. set
  168. {
  169. _cursor = value;
  170. OnPropertyChanged();
  171. }
  172. }
  173. public ReadOnlyObservableCollection<ApplicationData> AppsObservableList
  174. {
  175. get => _appsObservableList;
  176. set
  177. {
  178. _appsObservableList = value;
  179. OnPropertyChanged();
  180. }
  181. }
  182. public bool IsPaused
  183. {
  184. get => _isPaused;
  185. set
  186. {
  187. _isPaused = value;
  188. OnPropertyChanged();
  189. }
  190. }
  191. public long LastFullscreenToggle
  192. {
  193. get => _lastFullscreenToggle;
  194. set
  195. {
  196. _lastFullscreenToggle = value;
  197. OnPropertyChanged();
  198. }
  199. }
  200. public bool StatusBarVisible
  201. {
  202. get => _statusBarVisible && EnableNonGameRunningControls;
  203. set
  204. {
  205. _statusBarVisible = value;
  206. OnPropertyChanged();
  207. }
  208. }
  209. public bool EnableNonGameRunningControls => !IsGameRunning;
  210. public bool ShowFirmwareStatus => !ShowLoadProgress;
  211. public bool IsGameRunning
  212. {
  213. get => _isGameRunning;
  214. set
  215. {
  216. _isGameRunning = value;
  217. if (!value)
  218. {
  219. ShowMenuAndStatusBar = false;
  220. }
  221. OnPropertyChanged();
  222. OnPropertyChanged(nameof(EnableNonGameRunningControls));
  223. OnPropertyChanged(nameof(StatusBarVisible));
  224. OnPropertyChanged(nameof(ShowFirmwareStatus));
  225. }
  226. }
  227. public bool IsAmiiboRequested
  228. {
  229. get => _isAmiiboRequested && _isGameRunning;
  230. set
  231. {
  232. _isAmiiboRequested = value;
  233. OnPropertyChanged();
  234. }
  235. }
  236. public bool ShowLoadProgress
  237. {
  238. get => _showLoadProgress;
  239. set
  240. {
  241. _showLoadProgress = value;
  242. OnPropertyChanged();
  243. OnPropertyChanged(nameof(ShowFirmwareStatus));
  244. }
  245. }
  246. public string GameStatusText
  247. {
  248. get => _gameStatusText;
  249. set
  250. {
  251. _gameStatusText = value;
  252. OnPropertyChanged();
  253. }
  254. }
  255. public bool IsFullScreen
  256. {
  257. get => _isFullScreen;
  258. set
  259. {
  260. _isFullScreen = value;
  261. OnPropertyChanged();
  262. }
  263. }
  264. public bool ShowAll
  265. {
  266. get => _showAll;
  267. set
  268. {
  269. _showAll = value;
  270. OnPropertyChanged();
  271. }
  272. }
  273. public string LastScannedAmiiboId
  274. {
  275. get => _lastScannedAmiiboId;
  276. set
  277. {
  278. _lastScannedAmiiboId = value;
  279. OnPropertyChanged();
  280. }
  281. }
  282. public ApplicationData SelectedApplication
  283. {
  284. get
  285. {
  286. return Glyph switch
  287. {
  288. Glyph.List => ListSelectedApplication,
  289. Glyph.Grid => GridSelectedApplication,
  290. _ => null,
  291. };
  292. }
  293. }
  294. public string LoadHeading
  295. {
  296. get => _loadHeading;
  297. set
  298. {
  299. _loadHeading = value;
  300. OnPropertyChanged();
  301. }
  302. }
  303. public string CacheLoadStatus
  304. {
  305. get => _cacheLoadStatus;
  306. set
  307. {
  308. _cacheLoadStatus = value;
  309. OnPropertyChanged();
  310. }
  311. }
  312. public Brush ProgressBarBackgroundColor
  313. {
  314. get => _progressBarBackgroundColor;
  315. set
  316. {
  317. _progressBarBackgroundColor = value;
  318. OnPropertyChanged();
  319. }
  320. }
  321. public Brush ProgressBarForegroundColor
  322. {
  323. get => _progressBarForegroundColor;
  324. set
  325. {
  326. _progressBarForegroundColor = value;
  327. OnPropertyChanged();
  328. }
  329. }
  330. public Brush VsyncColor
  331. {
  332. get => _vsyncColor;
  333. set
  334. {
  335. _vsyncColor = value;
  336. OnPropertyChanged();
  337. }
  338. }
  339. public byte[] SelectedIcon
  340. {
  341. get => _selectedIcon;
  342. set
  343. {
  344. _selectedIcon = value;
  345. OnPropertyChanged();
  346. }
  347. }
  348. public int ProgressMaximum
  349. {
  350. get => _progressMaximum;
  351. set
  352. {
  353. _progressMaximum = value;
  354. OnPropertyChanged();
  355. }
  356. }
  357. public int ProgressValue
  358. {
  359. get => _progressValue;
  360. set
  361. {
  362. _progressValue = value;
  363. OnPropertyChanged();
  364. }
  365. }
  366. public int StatusBarProgressMaximum
  367. {
  368. get => _statusBarProgressMaximum;
  369. set
  370. {
  371. _statusBarProgressMaximum = value;
  372. OnPropertyChanged();
  373. }
  374. }
  375. public int StatusBarProgressValue
  376. {
  377. get => _statusBarProgressValue;
  378. set
  379. {
  380. _statusBarProgressValue = value;
  381. OnPropertyChanged();
  382. }
  383. }
  384. public string FifoStatusText
  385. {
  386. get => _fifoStatusText;
  387. set
  388. {
  389. _fifoStatusText = value;
  390. OnPropertyChanged();
  391. }
  392. }
  393. public string GpuNameText
  394. {
  395. get => _gpuStatusText;
  396. set
  397. {
  398. _gpuStatusText = value;
  399. OnPropertyChanged();
  400. }
  401. }
  402. public string BackendText
  403. {
  404. get => _backendText;
  405. set
  406. {
  407. _backendText = value;
  408. OnPropertyChanged();
  409. }
  410. }
  411. public string DockedStatusText
  412. {
  413. get => _dockedStatusText;
  414. set
  415. {
  416. _dockedStatusText = value;
  417. OnPropertyChanged();
  418. }
  419. }
  420. public string AspectRatioStatusText
  421. {
  422. get => _aspectStatusText;
  423. set
  424. {
  425. _aspectStatusText = value;
  426. OnPropertyChanged();
  427. }
  428. }
  429. public string VolumeStatusText
  430. {
  431. get => _volumeStatusText;
  432. set
  433. {
  434. _volumeStatusText = value;
  435. OnPropertyChanged();
  436. }
  437. }
  438. public bool VolumeMuted => _volume == 0;
  439. public float Volume
  440. {
  441. get => _volume;
  442. set
  443. {
  444. _volume = value;
  445. if (_isGameRunning)
  446. {
  447. AppHost.Device.SetVolume(_volume);
  448. }
  449. OnPropertyChanged(nameof(VolumeStatusText));
  450. OnPropertyChanged(nameof(VolumeMuted));
  451. OnPropertyChanged();
  452. }
  453. }
  454. public bool ShowStatusSeparator
  455. {
  456. get => _showStatusSeparator;
  457. set
  458. {
  459. _showStatusSeparator = value;
  460. OnPropertyChanged();
  461. }
  462. }
  463. public bool ShowMenuAndStatusBar
  464. {
  465. get => _showMenuAndStatusBar;
  466. set
  467. {
  468. _showMenuAndStatusBar = value;
  469. OnPropertyChanged();
  470. }
  471. }
  472. public bool IsLoadingIndeterminate
  473. {
  474. get => _isLoadingIndeterminate;
  475. set
  476. {
  477. _isLoadingIndeterminate = value;
  478. OnPropertyChanged();
  479. }
  480. }
  481. public bool IsActive
  482. {
  483. get => _isActive;
  484. set
  485. {
  486. _isActive = value;
  487. OnPropertyChanged();
  488. }
  489. }
  490. public bool ShowContent
  491. {
  492. get => _showContent;
  493. set
  494. {
  495. _showContent = value;
  496. OnPropertyChanged();
  497. }
  498. }
  499. public bool IsAppletMenuActive
  500. {
  501. get => _isAppletMenuActive && EnableNonGameRunningControls;
  502. set
  503. {
  504. _isAppletMenuActive = value;
  505. OnPropertyChanged();
  506. }
  507. }
  508. public WindowState WindowState
  509. {
  510. get => _windowState;
  511. internal set
  512. {
  513. _windowState = value;
  514. OnPropertyChanged();
  515. }
  516. }
  517. public bool IsGrid => Glyph == Glyph.Grid;
  518. public bool IsList => Glyph == Glyph.List;
  519. internal void Sort(bool isAscending)
  520. {
  521. IsAscending = isAscending;
  522. RefreshView();
  523. }
  524. internal void Sort(ApplicationSort sort)
  525. {
  526. SortMode = sort;
  527. RefreshView();
  528. }
  529. public bool StartGamesInFullscreen
  530. {
  531. get => ConfigurationState.Instance.Ui.StartFullscreen;
  532. set
  533. {
  534. ConfigurationState.Instance.Ui.StartFullscreen.Value = value;
  535. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  536. OnPropertyChanged();
  537. }
  538. }
  539. public bool ShowConsole
  540. {
  541. get => ConfigurationState.Instance.Ui.ShowConsole;
  542. set
  543. {
  544. ConfigurationState.Instance.Ui.ShowConsole.Value = value;
  545. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  546. OnPropertyChanged();
  547. }
  548. }
  549. public string Title
  550. {
  551. get => _title;
  552. set
  553. {
  554. _title = value;
  555. OnPropertyChanged();
  556. }
  557. }
  558. public bool ShowConsoleVisible
  559. {
  560. get => ConsoleHelper.SetConsoleWindowStateSupported;
  561. }
  562. public ObservableCollection<ApplicationData> Applications
  563. {
  564. get => _applications;
  565. set
  566. {
  567. _applications = value;
  568. OnPropertyChanged();
  569. }
  570. }
  571. public Glyph Glyph
  572. {
  573. get => (Glyph)ConfigurationState.Instance.Ui.GameListViewMode.Value;
  574. set
  575. {
  576. ConfigurationState.Instance.Ui.GameListViewMode.Value = (int)value;
  577. OnPropertyChanged();
  578. OnPropertyChanged(nameof(IsGrid));
  579. OnPropertyChanged(nameof(IsList));
  580. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  581. }
  582. }
  583. public bool ShowNames
  584. {
  585. get => ConfigurationState.Instance.Ui.ShowNames && ConfigurationState.Instance.Ui.GridSize > 1; set
  586. {
  587. ConfigurationState.Instance.Ui.ShowNames.Value = value;
  588. OnPropertyChanged();
  589. OnPropertyChanged(nameof(GridSizeScale));
  590. OnPropertyChanged(nameof(GridItemSelectorSize));
  591. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  592. }
  593. }
  594. internal ApplicationSort SortMode
  595. {
  596. get => (ApplicationSort)ConfigurationState.Instance.Ui.ApplicationSort.Value;
  597. private set
  598. {
  599. ConfigurationState.Instance.Ui.ApplicationSort.Value = (int)value;
  600. OnPropertyChanged();
  601. OnPropertyChanged(nameof(SortName));
  602. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  603. }
  604. }
  605. public int ListItemSelectorSize
  606. {
  607. get
  608. {
  609. switch (ConfigurationState.Instance.Ui.GridSize)
  610. {
  611. case 1:
  612. return 78;
  613. case 2:
  614. return 100;
  615. case 3:
  616. return 120;
  617. case 4:
  618. return 140;
  619. default:
  620. return 16;
  621. }
  622. }
  623. }
  624. public int GridItemSelectorSize
  625. {
  626. get
  627. {
  628. switch (ConfigurationState.Instance.Ui.GridSize)
  629. {
  630. case 1:
  631. return 120;
  632. case 2:
  633. return ShowNames ? 210 : 150;
  634. case 3:
  635. return ShowNames ? 240 : 180;
  636. case 4:
  637. return ShowNames ? 280 : 220;
  638. default:
  639. return 16;
  640. }
  641. }
  642. }
  643. public int GridSizeScale
  644. {
  645. get => ConfigurationState.Instance.Ui.GridSize;
  646. set
  647. {
  648. ConfigurationState.Instance.Ui.GridSize.Value = value;
  649. if (value < 2)
  650. {
  651. ShowNames = false;
  652. }
  653. OnPropertyChanged();
  654. OnPropertyChanged(nameof(IsGridSmall));
  655. OnPropertyChanged(nameof(IsGridMedium));
  656. OnPropertyChanged(nameof(IsGridLarge));
  657. OnPropertyChanged(nameof(IsGridHuge));
  658. OnPropertyChanged(nameof(ListItemSelectorSize));
  659. OnPropertyChanged(nameof(GridItemSelectorSize));
  660. OnPropertyChanged(nameof(ShowNames));
  661. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  662. }
  663. }
  664. public string SortName
  665. {
  666. get
  667. {
  668. return SortMode switch
  669. {
  670. ApplicationSort.Title => LocaleManager.Instance[LocaleKeys.GameListHeaderApplication],
  671. ApplicationSort.Developer => LocaleManager.Instance[LocaleKeys.GameListHeaderDeveloper],
  672. ApplicationSort.LastPlayed => LocaleManager.Instance[LocaleKeys.GameListHeaderLastPlayed],
  673. ApplicationSort.TotalTimePlayed => LocaleManager.Instance[LocaleKeys.GameListHeaderTimePlayed],
  674. ApplicationSort.FileType => LocaleManager.Instance[LocaleKeys.GameListHeaderFileExtension],
  675. ApplicationSort.FileSize => LocaleManager.Instance[LocaleKeys.GameListHeaderFileSize],
  676. ApplicationSort.Path => LocaleManager.Instance[LocaleKeys.GameListHeaderPath],
  677. ApplicationSort.Favorite => LocaleManager.Instance[LocaleKeys.CommonFavorite],
  678. _ => string.Empty,
  679. };
  680. }
  681. }
  682. public bool IsAscending
  683. {
  684. get => ConfigurationState.Instance.Ui.IsAscendingOrder;
  685. private set
  686. {
  687. ConfigurationState.Instance.Ui.IsAscendingOrder.Value = value;
  688. OnPropertyChanged();
  689. OnPropertyChanged(nameof(SortMode));
  690. OnPropertyChanged(nameof(SortName));
  691. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  692. }
  693. }
  694. public KeyGesture ShowUiKey
  695. {
  696. get => KeyGesture.Parse(_showUiKey);
  697. set
  698. {
  699. _showUiKey = value.ToString();
  700. OnPropertyChanged();
  701. }
  702. }
  703. public KeyGesture ScreenshotKey
  704. {
  705. get => KeyGesture.Parse(_screenshotKey);
  706. set
  707. {
  708. _screenshotKey = value.ToString();
  709. OnPropertyChanged();
  710. }
  711. }
  712. public KeyGesture PauseKey
  713. {
  714. get => KeyGesture.Parse(_pauseKey); set
  715. {
  716. _pauseKey = value.ToString();
  717. OnPropertyChanged();
  718. }
  719. }
  720. public ContentManager ContentManager { get; private set; }
  721. public ApplicationLibrary ApplicationLibrary { get; private set; }
  722. public VirtualFileSystem VirtualFileSystem { get; private set; }
  723. public AccountManager AccountManager { get; private set; }
  724. public Ryujinx.Input.HLE.InputManager InputManager { get; private set; }
  725. public UserChannelPersistence UserChannelPersistence { get; private set; }
  726. public Action<bool> ShowLoading { get; private set; }
  727. public Action<bool> SwitchToGameControl { get; private set; }
  728. public Action<Control> SetMainContent { get; private set; }
  729. public TopLevel TopLevel { get; private set; }
  730. public RendererHost RendererControl { get; private set; }
  731. public bool IsClosing { get; set; }
  732. public LibHacHorizonManager LibHacHorizonManager { get; internal set; }
  733. public IHostUiHandler UiHandler { get; internal set; }
  734. public bool IsSortedByFavorite => SortMode == ApplicationSort.Favorite;
  735. public bool IsSortedByTitle => SortMode == ApplicationSort.Title;
  736. public bool IsSortedByDeveloper => SortMode == ApplicationSort.Developer;
  737. public bool IsSortedByLastPlayed => SortMode == ApplicationSort.LastPlayed;
  738. public bool IsSortedByTimePlayed => SortMode == ApplicationSort.TotalTimePlayed;
  739. public bool IsSortedByType => SortMode == ApplicationSort.FileType;
  740. public bool IsSortedBySize => SortMode == ApplicationSort.FileSize;
  741. public bool IsSortedByPath => SortMode == ApplicationSort.Path;
  742. public bool IsGridSmall => ConfigurationState.Instance.Ui.GridSize == 1;
  743. public bool IsGridMedium => ConfigurationState.Instance.Ui.GridSize == 2;
  744. public bool IsGridLarge => ConfigurationState.Instance.Ui.GridSize == 3;
  745. public bool IsGridHuge => ConfigurationState.Instance.Ui.GridSize == 4;
  746. #endregion
  747. #region PrivateMethods
  748. private IComparer<ApplicationData> GetComparer()
  749. {
  750. return SortMode switch
  751. {
  752. ApplicationSort.LastPlayed => new Models.Generic.LastPlayedSortComparer(IsAscending),
  753. ApplicationSort.FileSize => IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.FileSizeBytes)
  754. : SortExpressionComparer<ApplicationData>.Descending(app => app.FileSizeBytes),
  755. ApplicationSort.TotalTimePlayed => IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.TimePlayedNum)
  756. : SortExpressionComparer<ApplicationData>.Descending(app => app.TimePlayedNum),
  757. ApplicationSort.Title => IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.TitleName)
  758. : SortExpressionComparer<ApplicationData>.Descending(app => app.TitleName),
  759. ApplicationSort.Favorite => !IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.Favorite)
  760. : SortExpressionComparer<ApplicationData>.Descending(app => app.Favorite),
  761. ApplicationSort.Developer => IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.Developer)
  762. : SortExpressionComparer<ApplicationData>.Descending(app => app.Developer),
  763. ApplicationSort.FileType => IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.FileExtension)
  764. : SortExpressionComparer<ApplicationData>.Descending(app => app.FileExtension),
  765. ApplicationSort.Path => IsAscending ? SortExpressionComparer<ApplicationData>.Ascending(app => app.Path)
  766. : SortExpressionComparer<ApplicationData>.Descending(app => app.Path),
  767. _ => null,
  768. };
  769. }
  770. private void RefreshView()
  771. {
  772. RefreshGrid();
  773. }
  774. private void RefreshGrid()
  775. {
  776. Applications.ToObservableChangeSet()
  777. .Filter(Filter)
  778. .Sort(GetComparer())
  779. .Bind(out _appsObservableList).AsObservableList();
  780. OnPropertyChanged(nameof(AppsObservableList));
  781. }
  782. private bool Filter(object arg)
  783. {
  784. if (arg is ApplicationData app)
  785. {
  786. return string.IsNullOrWhiteSpace(_searchText) || app.TitleName.ToLower().Contains(_searchText.ToLower());
  787. }
  788. return false;
  789. }
  790. private async Task HandleFirmwareInstallation(string filename)
  791. {
  792. try
  793. {
  794. SystemVersion firmwareVersion = ContentManager.VerifyFirmwarePackage(filename);
  795. if (firmwareVersion == null)
  796. {
  797. await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareNotFoundErrorMessage], filename));
  798. return;
  799. }
  800. string dialogTitle = string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallTitle], firmwareVersion.VersionString);
  801. SystemVersion currentVersion = ContentManager.GetCurrentFirmwareVersion();
  802. string dialogMessage = string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallMessage], firmwareVersion.VersionString);
  803. if (currentVersion != null)
  804. {
  805. dialogMessage += string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallSubMessage], currentVersion.VersionString);
  806. }
  807. dialogMessage += LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallConfirmMessage];
  808. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  809. dialogTitle,
  810. dialogMessage,
  811. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  812. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  813. LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
  814. UpdateWaitWindow waitingDialog = ContentDialogHelper.CreateWaitingDialog(dialogTitle, LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallWaitMessage]);
  815. if (result == UserResult.Yes)
  816. {
  817. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  818. Thread thread = new(() =>
  819. {
  820. Dispatcher.UIThread.InvokeAsync(delegate
  821. {
  822. waitingDialog.Show();
  823. });
  824. try
  825. {
  826. ContentManager.InstallFirmware(filename);
  827. Dispatcher.UIThread.InvokeAsync(async delegate
  828. {
  829. waitingDialog.Close();
  830. string message = string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallSuccessMessage], firmwareVersion.VersionString);
  831. await ContentDialogHelper.CreateInfoDialog(dialogTitle, message, LocaleManager.Instance[LocaleKeys.InputDialogOk], "", LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  832. Logger.Info?.Print(LogClass.Application, message);
  833. // Purge Applet Cache.
  834. DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));
  835. if (miiEditorCacheFolder.Exists)
  836. {
  837. miiEditorCacheFolder.Delete(true);
  838. }
  839. });
  840. }
  841. catch (Exception ex)
  842. {
  843. Dispatcher.UIThread.InvokeAsync(async () =>
  844. {
  845. waitingDialog.Close();
  846. await ContentDialogHelper.CreateErrorDialog(ex.Message);
  847. });
  848. }
  849. finally
  850. {
  851. RefreshFirmwareStatus();
  852. }
  853. }) { Name = "GUI.FirmwareInstallerThread" };
  854. thread.Start();
  855. }
  856. }
  857. catch (LibHac.Common.Keys.MissingKeyException ex)
  858. {
  859. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  860. {
  861. Logger.Error?.Print(LogClass.Application, ex.ToString());
  862. async void Action() => await UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys, (desktop.MainWindow as MainWindow));
  863. Dispatcher.UIThread.Post(Action);
  864. }
  865. }
  866. catch (Exception ex)
  867. {
  868. await ContentDialogHelper.CreateErrorDialog(ex.Message);
  869. }
  870. }
  871. private void ProgressHandler<T>(T state, int current, int total) where T : Enum
  872. {
  873. Dispatcher.UIThread.Post((() =>
  874. {
  875. ProgressMaximum = total;
  876. ProgressValue = current;
  877. switch (state)
  878. {
  879. case LoadState ptcState:
  880. CacheLoadStatus = $"{current} / {total}";
  881. switch (ptcState)
  882. {
  883. case LoadState.Unloaded:
  884. case LoadState.Loading:
  885. LoadHeading = LocaleManager.Instance[LocaleKeys.CompilingPPTC];
  886. IsLoadingIndeterminate = false;
  887. break;
  888. case LoadState.Loaded:
  889. LoadHeading = string.Format(LocaleManager.Instance[LocaleKeys.LoadingHeading], TitleName);
  890. IsLoadingIndeterminate = true;
  891. CacheLoadStatus = "";
  892. break;
  893. }
  894. break;
  895. case ShaderCacheLoadingState shaderCacheState:
  896. CacheLoadStatus = $"{current} / {total}";
  897. switch (shaderCacheState)
  898. {
  899. case ShaderCacheLoadingState.Start:
  900. case ShaderCacheLoadingState.Loading:
  901. LoadHeading = LocaleManager.Instance[LocaleKeys.CompilingShaders];
  902. IsLoadingIndeterminate = false;
  903. break;
  904. case ShaderCacheLoadingState.Loaded:
  905. LoadHeading = string.Format(LocaleManager.Instance[LocaleKeys.LoadingHeading], TitleName);
  906. IsLoadingIndeterminate = true;
  907. CacheLoadStatus = "";
  908. break;
  909. }
  910. break;
  911. default:
  912. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  913. }
  914. }));
  915. }
  916. private void OpenSaveDirectory(in SaveDataFilter filter, ApplicationData data, ulong titleId)
  917. {
  918. ApplicationHelper.OpenSaveDir(in filter, titleId, data.ControlHolder, data.TitleName);
  919. }
  920. private async void ExtractLogo()
  921. {
  922. var selection = SelectedApplication;
  923. if (selection != null)
  924. {
  925. await ApplicationHelper.ExtractSection(NcaSectionType.Logo, selection.Path);
  926. }
  927. }
  928. private async void ExtractRomFs()
  929. {
  930. var selection = SelectedApplication;
  931. if (selection != null)
  932. {
  933. await ApplicationHelper.ExtractSection(NcaSectionType.Data, selection.Path);
  934. }
  935. }
  936. private async void ExtractExeFs()
  937. {
  938. var selection = SelectedApplication;
  939. if (selection != null)
  940. {
  941. await ApplicationHelper.ExtractSection(NcaSectionType.Code, selection.Path);
  942. }
  943. }
  944. private void PrepareLoadScreen()
  945. {
  946. using MemoryStream stream = new(SelectedIcon);
  947. using var gameIconBmp = SixLabors.ImageSharp.Image.Load<Bgra32>(stream);
  948. var dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp).ToPixel<Bgra32>();
  949. const float colorMultiple = 0.5f;
  950. Color progressFgColor = Color.FromRgb(dominantColor.R, dominantColor.G, dominantColor.B);
  951. Color progressBgColor = Color.FromRgb(
  952. (byte)(dominantColor.R * colorMultiple),
  953. (byte)(dominantColor.G * colorMultiple),
  954. (byte)(dominantColor.B * colorMultiple));
  955. ProgressBarForegroundColor = new SolidColorBrush(progressFgColor);
  956. ProgressBarBackgroundColor = new SolidColorBrush(progressBgColor);
  957. }
  958. private void InitializeGame()
  959. {
  960. RendererControl.RendererInitialized += GlRenderer_Created;
  961. AppHost.StatusUpdatedEvent += Update_StatusBar;
  962. AppHost.AppExit += AppHost_AppExit;
  963. _rendererWaitEvent.WaitOne();
  964. AppHost?.Start();
  965. AppHost?.DisposeContext();
  966. }
  967. private void HandleRelaunch()
  968. {
  969. if (UserChannelPersistence.PreviousIndex != -1 && UserChannelPersistence.ShouldRestart)
  970. {
  971. UserChannelPersistence.ShouldRestart = false;
  972. Dispatcher.UIThread.Post(() =>
  973. {
  974. LoadApplication(_currentEmulatedGamePath);
  975. });
  976. }
  977. else
  978. {
  979. // Otherwise, clear state.
  980. UserChannelPersistence = new UserChannelPersistence();
  981. _currentEmulatedGamePath = null;
  982. }
  983. }
  984. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  985. {
  986. if (ShowMenuAndStatusBar && !ShowLoadProgress)
  987. {
  988. Dispatcher.UIThread.InvokeAsync(() =>
  989. {
  990. Avalonia.Application.Current.Styles.TryGetResource(args.VSyncEnabled
  991. ? "VsyncEnabled"
  992. : "VsyncDisabled", out object color);
  993. if (color is not null)
  994. {
  995. VsyncColor = new SolidColorBrush((Color)color);
  996. }
  997. DockedStatusText = args.DockedMode;
  998. AspectRatioStatusText = args.AspectRatio;
  999. GameStatusText = args.GameStatus;
  1000. VolumeStatusText = args.VolumeStatus;
  1001. FifoStatusText = args.FifoStatus;
  1002. GpuNameText = args.GpuName;
  1003. BackendText = args.GpuBackend;
  1004. ShowStatusSeparator = true;
  1005. });
  1006. }
  1007. }
  1008. private void GlRenderer_Created(object sender, EventArgs e)
  1009. {
  1010. ShowLoading(false);
  1011. _rendererWaitEvent.Set();
  1012. }
  1013. #endregion
  1014. #region PublicMethods
  1015. public void SetUIProgressHandlers(Switch emulationContext)
  1016. {
  1017. if (emulationContext.Application.DiskCacheLoadState != null)
  1018. {
  1019. emulationContext.Application.DiskCacheLoadState.StateChanged -= ProgressHandler;
  1020. emulationContext.Application.DiskCacheLoadState.StateChanged += ProgressHandler;
  1021. }
  1022. emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  1023. emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  1024. }
  1025. public void LoadConfigurableHotKeys()
  1026. {
  1027. if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Ryujinx.Input.Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi, out var showUiKey))
  1028. {
  1029. ShowUiKey = new KeyGesture(showUiKey);
  1030. }
  1031. if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Ryujinx.Input.Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out var screenshotKey))
  1032. {
  1033. ScreenshotKey = new KeyGesture(screenshotKey);
  1034. }
  1035. if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Ryujinx.Input.Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out var pauseKey))
  1036. {
  1037. PauseKey = new KeyGesture(pauseKey);
  1038. }
  1039. }
  1040. public void TakeScreenshot()
  1041. {
  1042. AppHost.ScreenshotRequested = true;
  1043. }
  1044. public void HideUi()
  1045. {
  1046. ShowMenuAndStatusBar = false;
  1047. }
  1048. public void SetListMode()
  1049. {
  1050. Glyph = Glyph.List;
  1051. }
  1052. public void SetGridMode()
  1053. {
  1054. Glyph = Glyph.Grid;
  1055. }
  1056. public async void InstallFirmwareFromFile()
  1057. {
  1058. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  1059. {
  1060. OpenFileDialog dialog = new() { AllowMultiple = false };
  1061. dialog.Filters.Add(new FileDialogFilter { Name = LocaleManager.Instance[LocaleKeys.FileDialogAllTypes], Extensions = { "xci", "zip" } });
  1062. dialog.Filters.Add(new FileDialogFilter { Name = "XCI", Extensions = { "xci" } });
  1063. dialog.Filters.Add(new FileDialogFilter { Name = "ZIP", Extensions = { "zip" } });
  1064. string[] file = await dialog.ShowAsync(desktop.MainWindow);
  1065. if (file != null && file.Length > 0)
  1066. {
  1067. await HandleFirmwareInstallation(file[0]);
  1068. }
  1069. }
  1070. }
  1071. public async void InstallFirmwareFromFolder()
  1072. {
  1073. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  1074. {
  1075. OpenFolderDialog dialog = new();
  1076. string folder = await dialog.ShowAsync(desktop.MainWindow);
  1077. if (!string.IsNullOrEmpty(folder))
  1078. {
  1079. await HandleFirmwareInstallation(folder);
  1080. }
  1081. }
  1082. }
  1083. public static void OpenRyujinxFolder()
  1084. {
  1085. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  1086. }
  1087. public static void OpenLogsFolder()
  1088. {
  1089. string logPath = Path.Combine(ReleaseInformation.GetBaseApplicationDirectory(), "Logs");
  1090. new DirectoryInfo(logPath).Create();
  1091. OpenHelper.OpenFolder(logPath);
  1092. }
  1093. public void ToggleDockMode()
  1094. {
  1095. if (IsGameRunning)
  1096. {
  1097. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  1098. }
  1099. }
  1100. public async void ExitCurrentState()
  1101. {
  1102. if (WindowState == WindowState.FullScreen)
  1103. {
  1104. ToggleFullscreen();
  1105. }
  1106. else if (IsGameRunning)
  1107. {
  1108. await Task.Delay(100);
  1109. AppHost?.ShowExitPrompt();
  1110. }
  1111. }
  1112. public void ChangeLanguage(object obj)
  1113. {
  1114. LocaleManager.Instance.LoadDefaultLanguage();
  1115. LocaleManager.Instance.LoadLanguage((string)obj);
  1116. }
  1117. public async void ManageProfiles()
  1118. {
  1119. await NavigationDialogHost.Show(AccountManager, ContentManager, VirtualFileSystem, LibHacHorizonManager.RyujinxClient);
  1120. }
  1121. public void OpenPtcDirectory()
  1122. {
  1123. ApplicationData selection = SelectedApplication;
  1124. if (selection != null)
  1125. {
  1126. string ptcDir = Path.Combine(AppDataManager.GamesDirPath, selection.TitleId, "cache", "cpu");
  1127. string mainPath = Path.Combine(ptcDir, "0");
  1128. string backupPath = Path.Combine(ptcDir, "1");
  1129. if (!Directory.Exists(ptcDir))
  1130. {
  1131. Directory.CreateDirectory(ptcDir);
  1132. Directory.CreateDirectory(mainPath);
  1133. Directory.CreateDirectory(backupPath);
  1134. }
  1135. OpenHelper.OpenFolder(ptcDir);
  1136. }
  1137. }
  1138. public async void PurgePtcCache()
  1139. {
  1140. ApplicationData selection = SelectedApplication;
  1141. if (selection != null)
  1142. {
  1143. DirectoryInfo mainDir = new(Path.Combine(AppDataManager.GamesDirPath, selection.TitleId, "cache", "cpu", "0"));
  1144. DirectoryInfo backupDir = new(Path.Combine(AppDataManager.GamesDirPath, selection.TitleId, "cache", "cpu", "1"));
  1145. // FIXME: Found a way to reproduce the bold effect on the title name (fork?).
  1146. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(LocaleManager.Instance[LocaleKeys.DialogWarning],
  1147. string.Format(LocaleManager.Instance[LocaleKeys.DialogPPTCDeletionMessage], selection.TitleName),
  1148. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  1149. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  1150. LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
  1151. List<FileInfo> cacheFiles = new();
  1152. if (mainDir.Exists)
  1153. {
  1154. cacheFiles.AddRange(mainDir.EnumerateFiles("*.cache"));
  1155. }
  1156. if (backupDir.Exists)
  1157. {
  1158. cacheFiles.AddRange(backupDir.EnumerateFiles("*.cache"));
  1159. }
  1160. if (cacheFiles.Count > 0 && result == UserResult.Yes)
  1161. {
  1162. foreach (FileInfo file in cacheFiles)
  1163. {
  1164. try
  1165. {
  1166. file.Delete();
  1167. }
  1168. catch (Exception e)
  1169. {
  1170. await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance[LocaleKeys.DialogPPTCDeletionErrorMessage], file.Name, e));
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. public void OpenShaderCacheDirectory()
  1177. {
  1178. ApplicationData selection = SelectedApplication;
  1179. if (selection != null)
  1180. {
  1181. string shaderCacheDir = Path.Combine(AppDataManager.GamesDirPath, selection.TitleId, "cache", "shader");
  1182. if (!Directory.Exists(shaderCacheDir))
  1183. {
  1184. Directory.CreateDirectory(shaderCacheDir);
  1185. }
  1186. OpenHelper.OpenFolder(shaderCacheDir);
  1187. }
  1188. }
  1189. public void SimulateWakeUpMessage()
  1190. {
  1191. AppHost.Device.System.SimulateWakeUpMessage();
  1192. }
  1193. public async void PurgeShaderCache()
  1194. {
  1195. ApplicationData selection = SelectedApplication;
  1196. if (selection != null)
  1197. {
  1198. DirectoryInfo shaderCacheDir = new(Path.Combine(AppDataManager.GamesDirPath, selection.TitleId, "cache", "shader"));
  1199. // FIXME: Found a way to reproduce the bold effect on the title name (fork?).
  1200. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(LocaleManager.Instance[LocaleKeys.DialogWarning],
  1201. string.Format(LocaleManager.Instance[LocaleKeys.DialogShaderDeletionMessage], selection.TitleName),
  1202. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  1203. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  1204. LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
  1205. List<DirectoryInfo> oldCacheDirectories = new();
  1206. List<FileInfo> newCacheFiles = new();
  1207. if (shaderCacheDir.Exists)
  1208. {
  1209. oldCacheDirectories.AddRange(shaderCacheDir.EnumerateDirectories("*"));
  1210. newCacheFiles.AddRange(shaderCacheDir.GetFiles("*.toc"));
  1211. newCacheFiles.AddRange(shaderCacheDir.GetFiles("*.data"));
  1212. }
  1213. if ((oldCacheDirectories.Count > 0 || newCacheFiles.Count > 0) && result == UserResult.Yes)
  1214. {
  1215. foreach (DirectoryInfo directory in oldCacheDirectories)
  1216. {
  1217. try
  1218. {
  1219. directory.Delete(true);
  1220. }
  1221. catch (Exception e)
  1222. {
  1223. await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance[LocaleKeys.DialogPPTCDeletionErrorMessage], directory.Name, e));
  1224. }
  1225. }
  1226. }
  1227. foreach (FileInfo file in newCacheFiles)
  1228. {
  1229. try
  1230. {
  1231. file.Delete();
  1232. }
  1233. catch (Exception e)
  1234. {
  1235. await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance[LocaleKeys.ShaderCachePurgeError], file.Name, e));
  1236. }
  1237. }
  1238. }
  1239. }
  1240. public void OpenDeviceSaveDirectory()
  1241. {
  1242. ApplicationData selection = SelectedApplication;
  1243. if (selection != null)
  1244. {
  1245. Task.Run(() =>
  1246. {
  1247. if (!ulong.TryParse(selection.TitleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  1248. {
  1249. async void Action()
  1250. {
  1251. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogRyujinxErrorMessage], LocaleManager.Instance[LocaleKeys.DialogInvalidTitleIdErrorMessage]);
  1252. }
  1253. Dispatcher.UIThread.Post(Action);
  1254. return;
  1255. }
  1256. var saveDataFilter = SaveDataFilter.Make(titleIdNumber, SaveDataType.Device, userId: default, saveDataId: default, index: default);
  1257. OpenSaveDirectory(in saveDataFilter, selection, titleIdNumber);
  1258. });
  1259. }
  1260. }
  1261. public void OpenBcatSaveDirectory()
  1262. {
  1263. ApplicationData selection = SelectedApplication;
  1264. if (selection != null)
  1265. {
  1266. Task.Run(() =>
  1267. {
  1268. if (!ulong.TryParse(selection.TitleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  1269. {
  1270. async void Action()
  1271. {
  1272. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogRyujinxErrorMessage], LocaleManager.Instance[LocaleKeys.DialogInvalidTitleIdErrorMessage]);
  1273. }
  1274. Dispatcher.UIThread.Post(Action);
  1275. return;
  1276. }
  1277. var saveDataFilter = SaveDataFilter.Make(titleIdNumber, SaveDataType.Bcat, userId: default, saveDataId: default, index: default);
  1278. OpenSaveDirectory(in saveDataFilter, selection, titleIdNumber);
  1279. });
  1280. }
  1281. }
  1282. public void ToggleFavorite()
  1283. {
  1284. ApplicationData selection = SelectedApplication;
  1285. if (selection != null)
  1286. {
  1287. selection.Favorite = !selection.Favorite;
  1288. ApplicationLibrary.LoadAndSaveMetaData(selection.TitleId, appMetadata =>
  1289. {
  1290. appMetadata.Favorite = selection.Favorite;
  1291. });
  1292. RefreshView();
  1293. }
  1294. }
  1295. public void OpenUserSaveDirectory()
  1296. {
  1297. ApplicationData selection = SelectedApplication;
  1298. if (selection != null)
  1299. {
  1300. Task.Run(() =>
  1301. {
  1302. if (!ulong.TryParse(selection.TitleId, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ulong titleIdNumber))
  1303. {
  1304. async void Action()
  1305. {
  1306. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogRyujinxErrorMessage], LocaleManager.Instance[LocaleKeys.DialogInvalidTitleIdErrorMessage]);
  1307. }
  1308. Dispatcher.UIThread.Post(Action);
  1309. return;
  1310. }
  1311. UserId userId = new((ulong)AccountManager.LastOpenedUser.UserId.High, (ulong)AccountManager.LastOpenedUser.UserId.Low);
  1312. SaveDataFilter saveDataFilter = SaveDataFilter.Make(titleIdNumber, saveType: default, userId, saveDataId: default, index: default);
  1313. OpenSaveDirectory(in saveDataFilter, selection, titleIdNumber);
  1314. });
  1315. }
  1316. }
  1317. public void OpenModsDirectory()
  1318. {
  1319. ApplicationData selection = SelectedApplication;
  1320. if (selection != null)
  1321. {
  1322. string modsBasePath = VirtualFileSystem.ModLoader.GetModsBasePath();
  1323. string titleModsPath = VirtualFileSystem.ModLoader.GetTitleDir(modsBasePath, selection.TitleId);
  1324. OpenHelper.OpenFolder(titleModsPath);
  1325. }
  1326. }
  1327. public void OpenSdModsDirectory()
  1328. {
  1329. ApplicationData selection = SelectedApplication;
  1330. if (selection != null)
  1331. {
  1332. string sdModsBasePath = VirtualFileSystem.ModLoader.GetSdModsBasePath();
  1333. string titleModsPath = VirtualFileSystem.ModLoader.GetTitleDir(sdModsBasePath, selection.TitleId);
  1334. OpenHelper.OpenFolder(titleModsPath);
  1335. }
  1336. }
  1337. public async void OpenTitleUpdateManager()
  1338. {
  1339. if (SelectedApplication != null)
  1340. {
  1341. await TitleUpdateWindow.Show(VirtualFileSystem, ulong.Parse(SelectedApplication.TitleId, NumberStyles.HexNumber), SelectedApplication.TitleName);
  1342. }
  1343. }
  1344. public async void OpenDownloadableContentManager()
  1345. {
  1346. ApplicationData selection = SelectedApplication;
  1347. if (selection != null)
  1348. {
  1349. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  1350. {
  1351. await new DownloadableContentManagerWindow(VirtualFileSystem, ulong.Parse(selection.TitleId, NumberStyles.HexNumber), selection.TitleName).ShowDialog(desktop.MainWindow);
  1352. }
  1353. }
  1354. }
  1355. public async void OpenCheatManager()
  1356. {
  1357. ApplicationData selection = SelectedApplication;
  1358. if (selection != null)
  1359. {
  1360. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  1361. {
  1362. await new CheatWindow(VirtualFileSystem, selection.TitleId, selection.TitleName).ShowDialog(desktop.MainWindow);
  1363. }
  1364. }
  1365. }
  1366. public async void LoadApplications()
  1367. {
  1368. await Dispatcher.UIThread.InvokeAsync(() =>
  1369. {
  1370. Applications.Clear();
  1371. StatusBarVisible = true;
  1372. StatusBarProgressMaximum = 0;
  1373. StatusBarProgressValue = 0;
  1374. LocaleManager.Instance.UpdateDynamicValue(LocaleKeys.StatusBarGamesLoaded, 0, 0);
  1375. });
  1376. ReloadGameList?.Invoke();
  1377. }
  1378. public async void OpenFile()
  1379. {
  1380. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  1381. {
  1382. OpenFileDialog dialog = new()
  1383. {
  1384. Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle]
  1385. };
  1386. dialog.Filters.Add(new FileDialogFilter
  1387. {
  1388. Name = LocaleManager.Instance[LocaleKeys.AllSupportedFormats],
  1389. Extensions =
  1390. {
  1391. "nsp",
  1392. "pfs0",
  1393. "xci",
  1394. "nca",
  1395. "nro",
  1396. "nso"
  1397. }
  1398. });
  1399. dialog.Filters.Add(new FileDialogFilter { Name = "NSP", Extensions = { "nsp" } });
  1400. dialog.Filters.Add(new FileDialogFilter { Name = "PFS0", Extensions = { "pfs0" } });
  1401. dialog.Filters.Add(new FileDialogFilter { Name = "XCI", Extensions = { "xci" } });
  1402. dialog.Filters.Add(new FileDialogFilter { Name = "NCA", Extensions = { "nca" } });
  1403. dialog.Filters.Add(new FileDialogFilter { Name = "NRO", Extensions = { "nro" } });
  1404. dialog.Filters.Add(new FileDialogFilter { Name = "NSO", Extensions = { "nso" } });
  1405. string[] files = await dialog.ShowAsync(desktop.MainWindow);
  1406. if (files != null && files.Length > 0)
  1407. {
  1408. LoadApplication(files[0]);
  1409. }
  1410. }
  1411. }
  1412. public async void OpenFolder()
  1413. {
  1414. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  1415. {
  1416. OpenFolderDialog dialog = new()
  1417. {
  1418. Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle]
  1419. };
  1420. string folder = await dialog.ShowAsync(desktop.MainWindow);
  1421. if (!string.IsNullOrWhiteSpace(folder) && Directory.Exists(folder))
  1422. {
  1423. LoadApplication(folder);
  1424. }
  1425. }
  1426. }
  1427. public async void LoadApplication(string path, bool startFullscreen = false, string titleName = "")
  1428. {
  1429. if (AppHost != null)
  1430. {
  1431. await ContentDialogHelper.CreateInfoDialog(
  1432. LocaleManager.Instance[LocaleKeys.DialogLoadAppGameAlreadyLoadedMessage],
  1433. LocaleManager.Instance[LocaleKeys.DialogLoadAppGameAlreadyLoadedSubMessage],
  1434. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  1435. "",
  1436. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  1437. return;
  1438. }
  1439. #if RELEASE
  1440. await PerformanceCheck();
  1441. #endif
  1442. Logger.RestartTime();
  1443. if (SelectedIcon == null)
  1444. {
  1445. SelectedIcon = ApplicationLibrary.GetApplicationIcon(path);
  1446. }
  1447. PrepareLoadScreen();
  1448. RendererControl = new RendererHost(ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  1449. if (ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.OpenGl)
  1450. {
  1451. RendererControl.CreateOpenGL();
  1452. }
  1453. else
  1454. {
  1455. RendererControl.CreateVulkan();
  1456. }
  1457. AppHost = new AppHost(
  1458. RendererControl,
  1459. InputManager,
  1460. path,
  1461. VirtualFileSystem,
  1462. ContentManager,
  1463. AccountManager,
  1464. UserChannelPersistence,
  1465. this,
  1466. TopLevel);
  1467. async void Action()
  1468. {
  1469. if (!await AppHost.LoadGuestApplication())
  1470. {
  1471. AppHost.DisposeContext();
  1472. AppHost = null;
  1473. return;
  1474. }
  1475. CanUpdate = false;
  1476. LoadHeading = string.IsNullOrWhiteSpace(titleName) ? string.Format(LocaleManager.Instance[LocaleKeys.LoadingHeading], AppHost.Device.Application.TitleName) : titleName;
  1477. TitleName = string.IsNullOrWhiteSpace(titleName) ? AppHost.Device.Application.TitleName : titleName;
  1478. SwitchToRenderer(startFullscreen);
  1479. _currentEmulatedGamePath = path;
  1480. Thread gameThread = new(InitializeGame) { Name = "GUI.WindowThread" };
  1481. gameThread.Start();
  1482. }
  1483. Dispatcher.UIThread.Post(Action);
  1484. }
  1485. public void SwitchToRenderer(bool startFullscreen)
  1486. {
  1487. Dispatcher.UIThread.Post(() =>
  1488. {
  1489. SwitchToGameControl(startFullscreen);
  1490. SetMainContent(RendererControl);
  1491. RendererControl.Focus();
  1492. });
  1493. }
  1494. public void UpdateGameMetadata(string titleId)
  1495. {
  1496. ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  1497. {
  1498. if (DateTime.TryParse(appMetadata.LastPlayed, out DateTime lastPlayedDateTime))
  1499. {
  1500. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  1501. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  1502. }
  1503. });
  1504. }
  1505. public void RefreshFirmwareStatus()
  1506. {
  1507. SystemVersion version = null;
  1508. try
  1509. {
  1510. version = ContentManager.GetCurrentFirmwareVersion();
  1511. }
  1512. catch (Exception) { }
  1513. bool hasApplet = false;
  1514. if (version != null)
  1515. {
  1516. LocaleManager.Instance.UpdateDynamicValue(LocaleKeys.StatusBarSystemVersion,
  1517. version.VersionString);
  1518. hasApplet = version.Major > 3;
  1519. }
  1520. else
  1521. {
  1522. LocaleManager.Instance.UpdateDynamicValue(LocaleKeys.StatusBarSystemVersion, "0.0");
  1523. }
  1524. IsAppletMenuActive = hasApplet;
  1525. }
  1526. public void AppHost_AppExit(object sender, EventArgs e)
  1527. {
  1528. if (IsClosing)
  1529. {
  1530. return;
  1531. }
  1532. IsGameRunning = false;
  1533. Dispatcher.UIThread.InvokeAsync(() =>
  1534. {
  1535. ShowMenuAndStatusBar = true;
  1536. ShowContent = true;
  1537. ShowLoadProgress = false;
  1538. IsLoadingIndeterminate = false;
  1539. CanUpdate = true;
  1540. Cursor = Cursor.Default;
  1541. SetMainContent(null);
  1542. AppHost = null;
  1543. HandleRelaunch();
  1544. });
  1545. RendererControl.RendererInitialized -= GlRenderer_Created;
  1546. RendererControl = null;
  1547. SelectedIcon = null;
  1548. Dispatcher.UIThread.InvokeAsync(() =>
  1549. {
  1550. Title = $"Ryujinx {Program.Version}";
  1551. });
  1552. }
  1553. public void ToggleFullscreen()
  1554. {
  1555. if (Environment.TickCount64 - LastFullscreenToggle < HotKeyPressDelayMs)
  1556. {
  1557. return;
  1558. }
  1559. LastFullscreenToggle = Environment.TickCount64;
  1560. if (WindowState == WindowState.FullScreen)
  1561. {
  1562. WindowState = WindowState.Normal;
  1563. if (IsGameRunning)
  1564. {
  1565. ShowMenuAndStatusBar = true;
  1566. }
  1567. }
  1568. else
  1569. {
  1570. WindowState = WindowState.FullScreen;
  1571. if (IsGameRunning)
  1572. {
  1573. ShowMenuAndStatusBar = false;
  1574. }
  1575. }
  1576. IsFullScreen = WindowState == WindowState.FullScreen;
  1577. }
  1578. public static void SaveConfig()
  1579. {
  1580. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  1581. }
  1582. public static async Task PerformanceCheck()
  1583. {
  1584. if (ConfigurationState.Instance.Logger.EnableTrace.Value)
  1585. {
  1586. string mainMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckLoggingEnabledMessage];
  1587. string secondaryMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckLoggingEnabledConfirmMessage];
  1588. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  1589. mainMessage,
  1590. secondaryMessage,
  1591. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  1592. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  1593. LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
  1594. if (result == UserResult.Yes)
  1595. {
  1596. ConfigurationState.Instance.Logger.EnableTrace.Value = false;
  1597. SaveConfig();
  1598. }
  1599. }
  1600. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  1601. {
  1602. string mainMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckShaderDumpEnabledMessage];
  1603. string secondaryMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckShaderDumpEnabledConfirmMessage];
  1604. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  1605. mainMessage,
  1606. secondaryMessage,
  1607. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  1608. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  1609. LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
  1610. if (result == UserResult.Yes)
  1611. {
  1612. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  1613. SaveConfig();
  1614. }
  1615. }
  1616. }
  1617. #endregion
  1618. }
  1619. }