MainWindowViewModel.cs 64 KB

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