MainWindowViewModel.cs 63 KB

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