MainWindowViewModel.cs 63 KB

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