MainWindowViewModel.cs 64 KB

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