MainWindowViewModel.cs 64 KB

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