MainWindowViewModel.cs 62 KB

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