MainWindowViewModel.cs 65 KB

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