MainWindowViewModel.cs 65 KB

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