| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273 |
- using Avalonia;
- using Avalonia.Controls;
- using Avalonia.Controls.ApplicationLifetimes;
- using Avalonia.Input;
- using Avalonia.Media;
- using Avalonia.Media.Imaging;
- using Avalonia.Platform.Storage;
- using Avalonia.Threading;
- using DynamicData;
- using DynamicData.Binding;
- using FluentAvalonia.UI.Controls;
- using Gommon;
- using LibHac.Common;
- using LibHac.Ns;
- using Ryujinx.Ava.Common;
- using Ryujinx.Ava.Common.Locale;
- using Ryujinx.Ava.Input;
- using Ryujinx.Ava.UI.Controls;
- using Ryujinx.Ava.UI.Helpers;
- using Ryujinx.Ava.UI.Models;
- using Ryujinx.Ava.UI.Models.Generic;
- using Ryujinx.Ava.UI.Renderer;
- using Ryujinx.Ava.UI.Windows;
- using Ryujinx.Ava.Utilities.AppLibrary;
- using Ryujinx.Common;
- using Ryujinx.Common.Configuration;
- using Ryujinx.Common.Logging;
- using Ryujinx.Common.UI;
- using Ryujinx.Common.Utilities;
- using Ryujinx.Cpu;
- using Ryujinx.HLE;
- using Ryujinx.HLE.FileSystem;
- using Ryujinx.HLE.HOS;
- using Ryujinx.HLE.HOS.Services.Account.Acc;
- using Ryujinx.HLE.HOS.Services.Nfc.AmiiboDecryption;
- using Ryujinx.HLE.UI;
- using Ryujinx.Input.HLE;
- using Ryujinx.UI.Common;
- using Ryujinx.UI.Common.Configuration;
- using Ryujinx.UI.Common.Helper;
- using Silk.NET.Vulkan;
- using SkiaSharp;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Threading;
- using System.Threading.Tasks;
- using Key = Ryujinx.Input.Key;
- using MissingKeyException = LibHac.Common.Keys.MissingKeyException;
- using ShaderCacheLoadingState = Ryujinx.Graphics.Gpu.Shader.ShaderCacheState;
- namespace Ryujinx.Ava.UI.ViewModels
- {
- public class MainWindowViewModel : BaseModel
- {
- private const int HotKeyPressDelayMs = 500;
- private delegate int LoadContentFromFolderDelegate(List<string> dirs, out int numRemoved);
- private ObservableCollectionExtended<ApplicationData> _applications;
- private string _aspectStatusText;
- private string _loadHeading;
- private string _cacheLoadStatus;
- private string _searchText;
- private Timer _searchTimer;
- private string _dockedStatusText;
- private string _vSyncModeText;
- private string _fifoStatusText;
- private string _gameStatusText;
- private string _volumeStatusText;
- private string _gpuStatusText;
- private string _shaderCountText;
- private bool _isAmiiboRequested;
- private bool _isAmiiboBinRequested;
- private bool _showShaderCompilationHint;
- private bool _isGameRunning;
- private bool _isFullScreen;
- private int _progressMaximum;
- private int _progressValue;
- private long _lastFullscreenToggle = Environment.TickCount64;
- private bool _showLoadProgress;
- private bool _showMenuAndStatusBar = true;
- private bool _showStatusSeparator;
- private Brush _progressBarForegroundColor;
- private Brush _progressBarBackgroundColor;
- private Brush _vSyncModeColor;
- private byte[] _selectedIcon;
- private bool _isAppletMenuActive;
- private int _statusBarProgressMaximum;
- private int _statusBarProgressValue;
- private string _statusBarProgressStatusText;
- private bool _statusBarProgressStatusVisible;
- private bool _isPaused;
- private bool _showContent = true;
- private bool _isLoadingIndeterminate = true;
- private bool _showAll;
- private string _lastScannedAmiiboId;
- private bool _statusBarVisible;
- private ReadOnlyObservableCollection<ApplicationData> _appsObservableList;
- private string _showUiKey = "F4";
- private string _pauseKey = "F5";
- private string _screenshotKey = "F8";
- private float _volume;
- private float _volumeBeforeMute;
- private string _backendText;
- private bool _areMimeTypesRegistered = FileAssociationHelper.AreMimeTypesRegistered;
- private bool _canUpdate = true;
- private Cursor _cursor;
- private string _title;
- private ApplicationData _currentApplicationData;
- private readonly AutoResetEvent _rendererWaitEvent;
- private WindowState _windowState;
- private double _windowWidth;
- private double _windowHeight;
- private int _customVSyncInterval;
- private int _customVSyncIntervalPercentageProxy;
- private bool _isActive;
- private bool _isSubMenuOpen;
- public ApplicationData ListSelectedApplication;
- public ApplicationData GridSelectedApplication;
-
- // Key is Title ID
- public SafeDictionary<string, LdnGameData.Array> LdnData = [];
- // The UI specifically uses a thicker bordered variant of the icon to avoid crunching out the border at lower resolutions.
- // For an example of this, download canary 1.2.95, then open the settings menu, and look at the icon in the top-left.
- // The border gets reduced to colored pixels in the 4 corners.
- public static readonly Bitmap IconBitmap =
- new(Assembly.GetAssembly(typeof(MainWindowViewModel))!.GetManifestResourceStream("Ryujinx.Assets.UIImages.Logo_Ryujinx_AntiAlias.png")!);
- public MainWindow Window { get; init; }
- internal AppHost AppHost { get; set; }
- public MainWindowViewModel()
- {
- Applications = [];
- Applications.ToObservableChangeSet()
- .Filter(Filter)
- .Sort(GetComparer())
- .Bind(out _appsObservableList)
- .AsObservableList();
- _rendererWaitEvent = new AutoResetEvent(false);
- if (Program.PreviewerDetached)
- {
- LoadConfigurableHotKeys();
- Volume = ConfigurationState.Instance.System.AudioVolume;
- }
- CustomVSyncInterval = ConfigurationState.Instance.Graphics.CustomVSyncInterval.Value;
- }
- public void Initialize(
- ContentManager contentManager,
- IStorageProvider storageProvider,
- ApplicationLibrary applicationLibrary,
- VirtualFileSystem virtualFileSystem,
- AccountManager accountManager,
- InputManager inputManager,
- UserChannelPersistence userChannelPersistence,
- LibHacHorizonManager libHacHorizonManager,
- IHostUIHandler uiHandler,
- Action<bool> showLoading,
- Action<bool> switchToGameControl,
- Action<Control> setMainContent,
- TopLevel topLevel)
- {
- ContentManager = contentManager;
- StorageProvider = storageProvider;
- ApplicationLibrary = applicationLibrary;
- VirtualFileSystem = virtualFileSystem;
- AccountManager = accountManager;
- InputManager = inputManager;
- UserChannelPersistence = userChannelPersistence;
- LibHacHorizonManager = libHacHorizonManager;
- UiHandler = uiHandler;
- ShowLoading = showLoading;
- SwitchToGameControl = switchToGameControl;
- SetMainContent = setMainContent;
- TopLevel = topLevel;
- #if DEBUG
- topLevel.AttachDevTools(new KeyGesture(Avalonia.Input.Key.F12, KeyModifiers.Control));
- #endif
- }
- #region Properties
- public string SearchText
- {
- get => _searchText;
- set
- {
- _searchText = value;
- _searchTimer?.Dispose();
- _searchTimer = new Timer(_ =>
- {
- RefreshView();
- _searchTimer.Dispose();
- _searchTimer = null;
- }, null, 1000, 0);
- }
- }
- public bool CanUpdate
- {
- get => _canUpdate && EnableNonGameRunningControls && Updater.CanUpdate(false);
- set
- {
- _canUpdate = value;
- OnPropertyChanged();
- }
- }
- public Cursor Cursor
- {
- get => _cursor;
- set
- {
- _cursor = value;
- OnPropertyChanged();
- }
- }
- public ReadOnlyObservableCollection<ApplicationData> AppsObservableList
- {
- get => _appsObservableList;
- set
- {
- _appsObservableList = value;
- OnPropertyChanged();
- }
- }
- public bool IsPaused
- {
- get => _isPaused;
- set
- {
- _isPaused = value;
- OnPropertyChanged();
- }
- }
- public long LastFullscreenToggle
- {
- get => _lastFullscreenToggle;
- set
- {
- _lastFullscreenToggle = value;
- OnPropertyChanged();
- }
- }
- public bool StatusBarVisible
- {
- get => _statusBarVisible && EnableNonGameRunningControls;
- set
- {
- _statusBarVisible = value;
- OnPropertyChanged();
- }
- }
- public bool EnableNonGameRunningControls => !IsGameRunning;
- public bool ShowFirmwareStatus => !ShowLoadProgress;
- public bool ShowShaderCompilationHint
- {
- get => _showShaderCompilationHint;
- set
- {
- _showShaderCompilationHint = value;
- OnPropertyChanged();
- }
- }
- public bool IsGameRunning
- {
- get => _isGameRunning;
- set
- {
- _isGameRunning = value;
- if (!value)
- {
- ShowMenuAndStatusBar = false;
- }
- OnPropertyChanged();
- OnPropertyChanged(nameof(EnableNonGameRunningControls));
- OnPropertyChanged(nameof(IsAppletMenuActive));
- OnPropertyChanged(nameof(StatusBarVisible));
- OnPropertyChanged(nameof(ShowFirmwareStatus));
- }
- }
- public bool IsAmiiboRequested
- {
- get => _isAmiiboRequested && _isGameRunning;
- set
- {
- _isAmiiboRequested = value;
- OnPropertyChanged();
- }
- }
- public bool IsAmiiboBinRequested
- {
- get => _isAmiiboBinRequested && _isGameRunning;
- set
- {
- _isAmiiboBinRequested = value;
- OnPropertyChanged();
- }
- }
- public bool CanScanAmiiboBinaries => AmiiboBinReader.HasAmiiboKeyFile;
-
- public bool ShowLoadProgress
- {
- get => _showLoadProgress;
- set
- {
- _showLoadProgress = value;
- OnPropertyChanged();
- OnPropertyChanged(nameof(ShowFirmwareStatus));
- }
- }
- public string GameStatusText
- {
- get => _gameStatusText;
- set
- {
- _gameStatusText = value;
- OnPropertyChanged();
- }
- }
- public bool IsFullScreen
- {
- get => _isFullScreen;
- set
- {
- _isFullScreen = value;
- OnPropertyChanged();
- }
- }
- public bool IsSubMenuOpen
- {
- get => _isSubMenuOpen;
- set
- {
- _isSubMenuOpen = value;
- OnPropertyChanged();
- }
- }
- public bool ShowAll
- {
- get => _showAll;
- set
- {
- _showAll = value;
- OnPropertyChanged();
- }
- }
- public string LastScannedAmiiboId
- {
- get => _lastScannedAmiiboId;
- set
- {
- _lastScannedAmiiboId = value;
- OnPropertyChanged();
- }
- }
- public ApplicationData SelectedApplication
- {
- get
- {
- return Glyph switch
- {
- Glyph.List => ListSelectedApplication,
- Glyph.Grid => GridSelectedApplication,
- _ => null,
- };
- }
- }
- public bool OpenUserSaveDirectoryEnabled => !SelectedApplication.ControlHolder.ByteSpan.IsZeros() && SelectedApplication.ControlHolder.Value.UserAccountSaveDataSize > 0;
- public bool OpenDeviceSaveDirectoryEnabled => !SelectedApplication.ControlHolder.ByteSpan.IsZeros() && SelectedApplication.ControlHolder.Value.DeviceSaveDataSize > 0;
- public bool TrimXCIEnabled => XCIFileTrimmer.CanTrim(SelectedApplication.Path, new XCITrimmerLog.MainWindow(this));
- public bool OpenBcatSaveDirectoryEnabled => !SelectedApplication.ControlHolder.ByteSpan.IsZeros() && SelectedApplication.ControlHolder.Value.BcatDeliveryCacheStorageSize > 0;
- public string LoadHeading
- {
- get => _loadHeading;
- set
- {
- _loadHeading = value;
- OnPropertyChanged();
- }
- }
- public string CacheLoadStatus
- {
- get => _cacheLoadStatus;
- set
- {
- _cacheLoadStatus = value;
- OnPropertyChanged();
- }
- }
- public Brush ProgressBarBackgroundColor
- {
- get => _progressBarBackgroundColor;
- set
- {
- _progressBarBackgroundColor = value;
- OnPropertyChanged();
- }
- }
- public Brush ProgressBarForegroundColor
- {
- get => _progressBarForegroundColor;
- set
- {
- _progressBarForegroundColor = value;
- OnPropertyChanged();
- }
- }
- public Brush VSyncModeColor
- {
- get => _vSyncModeColor;
- set
- {
- _vSyncModeColor = value;
- OnPropertyChanged();
- }
- }
- public bool ShowCustomVSyncIntervalPicker
- {
- get
- {
- if (_isGameRunning)
- {
- return AppHost.Device.VSyncMode ==
- VSyncMode.Custom;
- }
- else
- {
- return false;
- }
- }
- set
- {
- OnPropertyChanged();
- }
- }
- public int CustomVSyncIntervalPercentageProxy
- {
- get => _customVSyncIntervalPercentageProxy;
- set
- {
- int newInterval = (int)((value / 100f) * 60);
- _customVSyncInterval = newInterval;
- _customVSyncIntervalPercentageProxy = value;
- if (_isGameRunning)
- {
- AppHost.Device.CustomVSyncInterval = newInterval;
- AppHost.Device.UpdateVSyncInterval();
- }
- OnPropertyChanged((nameof(CustomVSyncInterval)));
- OnPropertyChanged((nameof(CustomVSyncIntervalPercentageText)));
- }
- }
- public string CustomVSyncIntervalPercentageText
- {
- get
- {
- string text = CustomVSyncIntervalPercentageProxy.ToString() + "%";
- return text;
- }
- set
- {
- }
- }
- public int CustomVSyncInterval
- {
- get => _customVSyncInterval;
- set
- {
- _customVSyncInterval = value;
- int newPercent = (int)((value / 60f) * 100);
- _customVSyncIntervalPercentageProxy = newPercent;
- if (_isGameRunning)
- {
- AppHost.Device.CustomVSyncInterval = value;
- AppHost.Device.UpdateVSyncInterval();
- }
- OnPropertyChanged(nameof(CustomVSyncIntervalPercentageProxy));
- OnPropertyChanged(nameof(CustomVSyncIntervalPercentageText));
- OnPropertyChanged();
- }
- }
- public byte[] SelectedIcon
- {
- get => _selectedIcon;
- set
- {
- _selectedIcon = value;
- OnPropertyChanged();
- }
- }
- public int ProgressMaximum
- {
- get => _progressMaximum;
- set
- {
- _progressMaximum = value;
- OnPropertyChanged();
- }
- }
- public int ProgressValue
- {
- get => _progressValue;
- set
- {
- _progressValue = value;
- OnPropertyChanged();
- }
- }
- public int StatusBarProgressMaximum
- {
- get => _statusBarProgressMaximum;
- set
- {
- _statusBarProgressMaximum = value;
- OnPropertyChanged();
- }
- }
- public int StatusBarProgressValue
- {
- get => _statusBarProgressValue;
- set
- {
- _statusBarProgressValue = value;
- OnPropertyChanged();
- }
- }
- public bool StatusBarProgressStatusVisible
- {
- get => _statusBarProgressStatusVisible;
- set
- {
- _statusBarProgressStatusVisible = value;
- OnPropertyChanged();
- }
- }
- public string StatusBarProgressStatusText
- {
- get => _statusBarProgressStatusText;
- set
- {
- _statusBarProgressStatusText = value;
- OnPropertyChanged();
- }
- }
- public string FifoStatusText
- {
- get => _fifoStatusText;
- set
- {
- _fifoStatusText = value;
- OnPropertyChanged();
- }
- }
- public string GpuNameText
- {
- get => _gpuStatusText;
- set
- {
- _gpuStatusText = value;
- OnPropertyChanged();
- }
- }
- public string ShaderCountText
- {
- get => _shaderCountText;
- set
- {
- _shaderCountText = value;
- OnPropertyChanged();
- }
- }
- public string BackendText
- {
- get => _backendText;
- set
- {
- _backendText = value;
- OnPropertyChanged();
- }
- }
- public string VSyncModeText
- {
- get => _vSyncModeText;
- set
- {
- _vSyncModeText = value;
- OnPropertyChanged();
- }
- }
- public string DockedStatusText
- {
- get => _dockedStatusText;
- set
- {
- _dockedStatusText = value;
- OnPropertyChanged();
- }
- }
- public string AspectRatioStatusText
- {
- get => _aspectStatusText;
- set
- {
- _aspectStatusText = value;
- OnPropertyChanged();
- }
- }
- public string VolumeStatusText
- {
- get => _volumeStatusText;
- set
- {
- _volumeStatusText = value;
- OnPropertyChanged();
- }
- }
- public bool VolumeMuted => _volume == 0;
- public float Volume
- {
- get => _volume;
- set
- {
- _volume = value;
- if (_isGameRunning)
- {
- AppHost.Device.SetVolume(_volume);
- }
- OnPropertyChanged(nameof(VolumeStatusText));
- OnPropertyChanged(nameof(VolumeMuted));
- OnPropertyChanged();
- }
- }
- public float VolumeBeforeMute
- {
- get => _volumeBeforeMute;
- set
- {
- _volumeBeforeMute = value;
- OnPropertyChanged();
- }
- }
- public bool ShowStatusSeparator
- {
- get => _showStatusSeparator;
- set
- {
- _showStatusSeparator = value;
- OnPropertyChanged();
- }
- }
- public bool ShowMenuAndStatusBar
- {
- get => _showMenuAndStatusBar;
- set
- {
- _showMenuAndStatusBar = value;
- OnPropertyChanged();
- }
- }
- public bool IsLoadingIndeterminate
- {
- get => _isLoadingIndeterminate;
- set
- {
- _isLoadingIndeterminate = value;
- OnPropertyChanged();
- }
- }
- public bool IsActive
- {
- get => _isActive;
- set
- {
- _isActive = value;
- OnPropertyChanged();
- }
- }
- public bool ShowContent
- {
- get => _showContent;
- set
- {
- _showContent = value;
- OnPropertyChanged();
- }
- }
- public bool IsAppletMenuActive
- {
- get => _isAppletMenuActive && EnableNonGameRunningControls;
- set
- {
- _isAppletMenuActive = value;
- OnPropertyChanged();
- }
- }
- public WindowState WindowState
- {
- get => _windowState;
- internal set
- {
- _windowState = value;
- OnPropertyChanged();
- }
- }
- public double WindowWidth
- {
- get => _windowWidth;
- set
- {
- _windowWidth = value;
- OnPropertyChanged();
- }
- }
- public double WindowHeight
- {
- get => _windowHeight;
- set
- {
- _windowHeight = value;
- OnPropertyChanged();
- }
- }
- public bool IsGrid => Glyph == Glyph.Grid;
- public bool IsList => Glyph == Glyph.List;
- internal void Sort(bool isAscending)
- {
- IsAscending = isAscending;
- RefreshView();
- }
- internal void Sort(ApplicationSort sort)
- {
- SortMode = sort;
- RefreshView();
- }
- public bool StartGamesInFullscreen
- {
- get => ConfigurationState.Instance.UI.StartFullscreen;
- set
- {
- ConfigurationState.Instance.UI.StartFullscreen.Value = value;
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- OnPropertyChanged();
- }
- }
- public bool ShowConsole
- {
- get => ConfigurationState.Instance.UI.ShowConsole;
- set
- {
- ConfigurationState.Instance.UI.ShowConsole.Value = value;
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- OnPropertyChanged();
- }
- }
- public string Title
- {
- get => _title;
- set
- {
- _title = value;
- OnPropertyChanged();
- }
- }
- public bool ShowConsoleVisible
- {
- get => ConsoleHelper.SetConsoleWindowStateSupported;
- }
- public bool ManageFileTypesVisible
- {
- get => FileAssociationHelper.IsTypeAssociationSupported;
- }
- public bool AreMimeTypesRegistered
- {
- get => _areMimeTypesRegistered;
- set {
- _areMimeTypesRegistered = value;
- OnPropertyChanged();
- }
- }
- public ObservableCollectionExtended<ApplicationData> Applications
- {
- get => _applications;
- set
- {
- _applications = value;
- OnPropertyChanged();
- }
- }
- public Glyph Glyph
- {
- get => (Glyph)ConfigurationState.Instance.UI.GameListViewMode.Value;
- set
- {
- ConfigurationState.Instance.UI.GameListViewMode.Value = (int)value;
- OnPropertyChanged();
- OnPropertyChanged(nameof(IsGrid));
- OnPropertyChanged(nameof(IsList));
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- }
- public bool ShowNames
- {
- get => ConfigurationState.Instance.UI.ShowNames && ConfigurationState.Instance.UI.GridSize > 1; set
- {
- ConfigurationState.Instance.UI.ShowNames.Value = value;
- OnPropertyChanged();
- OnPropertyChanged(nameof(GridSizeScale));
- OnPropertyChanged(nameof(GridItemSelectorSize));
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- }
- internal ApplicationSort SortMode
- {
- get => (ApplicationSort)ConfigurationState.Instance.UI.ApplicationSort.Value;
- private set
- {
- ConfigurationState.Instance.UI.ApplicationSort.Value = (int)value;
- OnPropertyChanged();
- OnPropertyChanged(nameof(SortName));
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- }
- public int ListItemSelectorSize
- {
- get
- {
- return ConfigurationState.Instance.UI.GridSize.Value switch
- {
- 1 => 78,
- 2 => 100,
- 3 => 120,
- 4 => 140,
- _ => 16,
- };
- }
- }
- public int GridItemSelectorSize
- {
- get
- {
- return ConfigurationState.Instance.UI.GridSize.Value switch
- {
- 1 => 120,
- 2 => ShowNames ? 210 : 150,
- 3 => ShowNames ? 240 : 180,
- 4 => ShowNames ? 280 : 220,
- _ => 16,
- };
- }
- }
- public int GridSizeScale
- {
- get => ConfigurationState.Instance.UI.GridSize;
- set
- {
- ConfigurationState.Instance.UI.GridSize.Value = value;
- if (value < 2)
- {
- ShowNames = false;
- }
- OnPropertyChanged();
- OnPropertyChanged(nameof(IsGridSmall));
- OnPropertyChanged(nameof(IsGridMedium));
- OnPropertyChanged(nameof(IsGridLarge));
- OnPropertyChanged(nameof(IsGridHuge));
- OnPropertyChanged(nameof(ListItemSelectorSize));
- OnPropertyChanged(nameof(GridItemSelectorSize));
- OnPropertyChanged(nameof(ShowNames));
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- }
- public string SortName
- {
- get
- {
- return SortMode switch
- {
- ApplicationSort.Title => LocaleManager.Instance[LocaleKeys.GameListHeaderApplication],
- ApplicationSort.Developer => LocaleManager.Instance[LocaleKeys.GameListHeaderDeveloper],
- ApplicationSort.LastPlayed => LocaleManager.Instance[LocaleKeys.GameListHeaderLastPlayed],
- ApplicationSort.TotalTimePlayed => LocaleManager.Instance[LocaleKeys.GameListHeaderTimePlayed],
- ApplicationSort.FileType => LocaleManager.Instance[LocaleKeys.GameListHeaderFileExtension],
- ApplicationSort.FileSize => LocaleManager.Instance[LocaleKeys.GameListHeaderFileSize],
- ApplicationSort.Path => LocaleManager.Instance[LocaleKeys.GameListHeaderPath],
- ApplicationSort.Favorite => LocaleManager.Instance[LocaleKeys.CommonFavorite],
- _ => string.Empty,
- };
- }
- }
- public bool IsAscending
- {
- get => ConfigurationState.Instance.UI.IsAscendingOrder;
- private set
- {
- ConfigurationState.Instance.UI.IsAscendingOrder.Value = value;
- OnPropertyChanged();
- OnPropertyChanged(nameof(SortMode));
- OnPropertyChanged(nameof(SortName));
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- }
- public KeyGesture ShowUiKey
- {
- get => KeyGesture.Parse(_showUiKey);
- set
- {
- _showUiKey = value.ToString();
- OnPropertyChanged();
- }
- }
- public KeyGesture ScreenshotKey
- {
- get => KeyGesture.Parse(_screenshotKey);
- set
- {
- _screenshotKey = value.ToString();
- OnPropertyChanged();
- }
- }
- public KeyGesture PauseKey
- {
- get => KeyGesture.Parse(_pauseKey);
- set
- {
- _pauseKey = value.ToString();
- OnPropertyChanged();
- }
- }
- public ContentManager ContentManager { get; private set; }
- public IStorageProvider StorageProvider { get; private set; }
- public ApplicationLibrary ApplicationLibrary { get; private set; }
- public VirtualFileSystem VirtualFileSystem { get; private set; }
- public AccountManager AccountManager { get; private set; }
- public InputManager InputManager { get; private set; }
- public UserChannelPersistence UserChannelPersistence { get; private set; }
- public Action<bool> ShowLoading { get; private set; }
- public Action<bool> SwitchToGameControl { get; private set; }
- public Action<Control> SetMainContent { get; private set; }
- public TopLevel TopLevel { get; private set; }
- public RendererHost RendererHostControl { get; private set; }
- public bool IsClosing { get; set; }
- public LibHacHorizonManager LibHacHorizonManager { get; internal set; }
- public IHostUIHandler UiHandler { get; internal set; }
- public bool IsSortedByFavorite => SortMode == ApplicationSort.Favorite;
- public bool IsSortedByTitle => SortMode == ApplicationSort.Title;
- public bool IsSortedByDeveloper => SortMode == ApplicationSort.Developer;
- public bool IsSortedByLastPlayed => SortMode == ApplicationSort.LastPlayed;
- public bool IsSortedByTimePlayed => SortMode == ApplicationSort.TotalTimePlayed;
- public bool IsSortedByType => SortMode == ApplicationSort.FileType;
- public bool IsSortedBySize => SortMode == ApplicationSort.FileSize;
- public bool IsSortedByPath => SortMode == ApplicationSort.Path;
- public bool IsGridSmall => ConfigurationState.Instance.UI.GridSize == 1;
- public bool IsGridMedium => ConfigurationState.Instance.UI.GridSize == 2;
- public bool IsGridLarge => ConfigurationState.Instance.UI.GridSize == 3;
- public bool IsGridHuge => ConfigurationState.Instance.UI.GridSize == 4;
- #endregion
- #region PrivateMethods
- private static IComparer<ApplicationData> CreateComparer(bool ascending, Func<ApplicationData, IComparable> selector) =>
- ascending
- ? SortExpressionComparer<ApplicationData>.Ascending(selector)
- : SortExpressionComparer<ApplicationData>.Descending(selector);
- private IComparer<ApplicationData> GetComparer()
- => SortMode switch
- {
- #pragma warning disable IDE0055 // Disable formatting
- ApplicationSort.Title => CreateComparer(IsAscending, app => app.Name),
- ApplicationSort.Developer => CreateComparer(IsAscending, app => app.Developer),
- ApplicationSort.LastPlayed => new LastPlayedSortComparer(IsAscending),
- ApplicationSort.TotalTimePlayed => new TimePlayedSortComparer(IsAscending),
- ApplicationSort.FileType => CreateComparer(IsAscending, app => app.FileExtension),
- ApplicationSort.FileSize => CreateComparer(IsAscending, app => app.FileSize),
- ApplicationSort.Path => CreateComparer(IsAscending, app => app.Path),
- ApplicationSort.Favorite => CreateComparer(IsAscending, app => new AppListFavoriteComparable(app)),
- _ => null,
- #pragma warning restore IDE0055
- };
- public void RefreshView()
- {
- RefreshGrid();
- }
- private void RefreshGrid()
- {
- Applications.ToObservableChangeSet()
- .Filter(Filter)
- .Sort(GetComparer())
- .Bind(out _appsObservableList).AsObservableList();
- OnPropertyChanged(nameof(AppsObservableList));
- }
- private bool Filter(object arg)
- {
- if (arg is ApplicationData app)
- {
- if (string.IsNullOrWhiteSpace(_searchText))
- {
- return true;
- }
- CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo;
- return compareInfo.IndexOf(app.Name, _searchText, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace) >= 0;
- }
- return false;
- }
- private async Task HandleFirmwareInstallation(string filename)
- {
- try
- {
- SystemVersion firmwareVersion = ContentManager.VerifyFirmwarePackage(filename);
- if (firmwareVersion == null)
- {
- await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallerFirmwareNotFoundErrorMessage, filename));
- return;
- }
- string dialogTitle = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallerFirmwareInstallTitle, firmwareVersion.VersionString);
- string dialogMessage = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallerFirmwareInstallMessage, firmwareVersion.VersionString);
- SystemVersion currentVersion = ContentManager.GetCurrentFirmwareVersion();
- if (currentVersion != null)
- {
- dialogMessage += LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallerFirmwareInstallSubMessage, currentVersion.VersionString);
- }
- dialogMessage += LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallConfirmMessage];
- UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
- dialogTitle,
- dialogMessage,
- LocaleManager.Instance[LocaleKeys.InputDialogYes],
- LocaleManager.Instance[LocaleKeys.InputDialogNo],
- LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
- UpdateWaitWindow waitingDialog = new(dialogTitle, LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallerFirmwareInstallWaitMessage]);
- if (result == UserResult.Yes)
- {
- Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
- Thread thread = new(() =>
- {
- Dispatcher.UIThread.InvokeAsync(delegate
- {
- waitingDialog.Show();
- });
- try
- {
- ContentManager.InstallFirmware(filename);
- Dispatcher.UIThread.InvokeAsync(async delegate
- {
- waitingDialog.Close();
- string message = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogFirmwareInstallerFirmwareInstallSuccessMessage, firmwareVersion.VersionString);
- await ContentDialogHelper.CreateInfoDialog(
- dialogTitle,
- message,
- LocaleManager.Instance[LocaleKeys.InputDialogOk],
- string.Empty,
- LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
- Logger.Info?.Print(LogClass.Application, message);
- // Purge Applet Cache.
- DirectoryInfo miiEditorCacheFolder = new(Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));
- if (miiEditorCacheFolder.Exists)
- {
- miiEditorCacheFolder.Delete(true);
- }
- });
- }
- catch (Exception ex)
- {
- Dispatcher.UIThread.InvokeAsync(async () =>
- {
- waitingDialog.Close();
- await ContentDialogHelper.CreateErrorDialog(ex.Message);
- });
- }
- finally
- {
- RefreshFirmwareStatus();
- }
- })
- {
- Name = "GUI.FirmwareInstallerThread",
- };
- thread.Start();
- }
- }
- catch (MissingKeyException ex)
- {
- if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime)
- {
- Logger.Error?.Print(LogClass.Application, ex.ToString());
- await UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys);
- }
- }
- catch (Exception ex)
- {
- await ContentDialogHelper.CreateErrorDialog(ex.Message);
- }
- }
- private async Task HandleKeysInstallation(string filename)
- {
- try
- {
- string systemDirectory = AppDataManager.KeysDirPath;
- if (AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && Directory.Exists(AppDataManager.KeysDirPathUser))
- {
- systemDirectory = AppDataManager.KeysDirPathUser;
- }
- string dialogTitle = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogKeysInstallerKeysInstallTitle);
- string dialogMessage = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogKeysInstallerKeysInstallMessage);
- bool alreadyKesyInstalled = ContentManager.AreKeysAlredyPresent(systemDirectory);
- if (alreadyKesyInstalled)
- {
- dialogMessage += LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogKeysInstallerKeysInstallSubMessage);
- }
- dialogMessage += LocaleManager.Instance[LocaleKeys.DialogKeysInstallerKeysInstallConfirmMessage];
- UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
- dialogTitle,
- dialogMessage,
- LocaleManager.Instance[LocaleKeys.InputDialogYes],
- LocaleManager.Instance[LocaleKeys.InputDialogNo],
- LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
- UpdateWaitWindow waitingDialog = new(dialogTitle, LocaleManager.Instance[LocaleKeys.DialogKeysInstallerKeysInstallWaitMessage]);
- if (result == UserResult.Yes)
- {
- Logger.Info?.Print(LogClass.Application, $"Installing Keys");
- Thread thread = new(() =>
- {
- Dispatcher.UIThread.InvokeAsync(delegate
- {
- waitingDialog.Show();
- });
- try
- {
- ContentManager.InstallKeys(filename, systemDirectory);
- Dispatcher.UIThread.InvokeAsync(async delegate
- {
- waitingDialog.Close();
- string message = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogKeysInstallerKeysInstallSuccessMessage);
- await ContentDialogHelper.CreateInfoDialog(
- dialogTitle,
- message,
- LocaleManager.Instance[LocaleKeys.InputDialogOk],
- string.Empty,
- LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
- Logger.Info?.Print(LogClass.Application, message);
- });
- }
- catch (Exception ex)
- {
- Dispatcher.UIThread.InvokeAsync(async () =>
- {
- waitingDialog.Close();
- string message = ex.Message;
- if(ex is FormatException)
- {
- message = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogKeysInstallerKeysNotFoundErrorMessage, filename);
- }
- await ContentDialogHelper.CreateErrorDialog(message);
- });
- }
- finally
- {
- VirtualFileSystem.ReloadKeySet();
- }
- })
- {
- Name = "GUI.KeysInstallerThread",
- };
- thread.Start();
- }
- }
- catch (MissingKeyException ex)
- {
- if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime)
- {
- Logger.Error?.Print(LogClass.Application, ex.ToString());
- await UserErrorDialog.ShowUserErrorDialog(UserError.NoKeys);
- }
- }
- catch (Exception ex)
- {
- await ContentDialogHelper.CreateErrorDialog(ex.Message);
- }
- }
- private void ProgressHandler<T>(T state, int current, int total) where T : Enum
- {
- Dispatcher.UIThread.Post(() =>
- {
- ProgressMaximum = total;
- ProgressValue = current;
- switch (state)
- {
- case LoadState ptcState:
- CacheLoadStatus = $"{current} / {total}";
- switch (ptcState)
- {
- case LoadState.Unloaded:
- case LoadState.Loading:
- LoadHeading = LocaleManager.Instance[LocaleKeys.CompilingPPTC];
- IsLoadingIndeterminate = false;
- break;
- case LoadState.Loaded:
- LoadHeading = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.LoadingHeading, _currentApplicationData.Name);
- IsLoadingIndeterminate = true;
- CacheLoadStatus = string.Empty;
- break;
- }
- break;
- case ShaderCacheLoadingState shaderCacheState:
- CacheLoadStatus = $"{current} / {total}";
- switch (shaderCacheState)
- {
- case ShaderCacheLoadingState.Start:
- case ShaderCacheLoadingState.Loading:
- LoadHeading = LocaleManager.Instance[LocaleKeys.CompilingShaders];
- IsLoadingIndeterminate = false;
- break;
- case ShaderCacheLoadingState.Packaging:
- LoadHeading = LocaleManager.Instance[LocaleKeys.PackagingShaders];
- IsLoadingIndeterminate = false;
- break;
- case ShaderCacheLoadingState.Loaded:
- LoadHeading = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.LoadingHeading, _currentApplicationData.Name);
- IsLoadingIndeterminate = true;
- CacheLoadStatus = string.Empty;
- break;
- }
- break;
- default:
- throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
- }
- });
- }
- private void PrepareLoadScreen()
- {
- using MemoryStream stream = new(SelectedIcon);
- using var gameIconBmp = SKBitmap.Decode(stream);
- var dominantColor = IconColorPicker.GetFilteredColor(gameIconBmp);
- const float ColorMultiple = 0.5f;
- Color progressFgColor = Color.FromRgb(dominantColor.Red, dominantColor.Green, dominantColor.Blue);
- Color progressBgColor = Color.FromRgb(
- (byte)(dominantColor.Red * ColorMultiple),
- (byte)(dominantColor.Green * ColorMultiple),
- (byte)(dominantColor.Blue * ColorMultiple));
- ProgressBarForegroundColor = new SolidColorBrush(progressFgColor);
- ProgressBarBackgroundColor = new SolidColorBrush(progressBgColor);
- }
- private void InitializeGame()
- {
- RendererHostControl.WindowCreated += RendererHost_Created;
- AppHost.StatusUpdatedEvent += Update_StatusBar;
- AppHost.AppExit += AppHost_AppExit;
- _rendererWaitEvent.WaitOne();
- AppHost?.Start();
- AppHost?.DisposeContext();
- }
- private async Task HandleRelaunch()
- {
- if (UserChannelPersistence.PreviousIndex != -1 && UserChannelPersistence.ShouldRestart)
- {
- UserChannelPersistence.ShouldRestart = false;
- await LoadApplication(_currentApplicationData);
- }
- else
- {
- // Otherwise, clear state.
- UserChannelPersistence = new UserChannelPersistence();
- _currentApplicationData = null;
- }
- }
- private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
- {
- if (ShowMenuAndStatusBar && !ShowLoadProgress)
- {
- Dispatcher.UIThread.InvokeAsync(() =>
- {
- Application.Current!.Styles.TryGetResource(args.VSyncMode,
- Application.Current.ActualThemeVariant,
- out object color);
- if (color is Color clr)
- {
- VSyncModeColor = new SolidColorBrush(clr);
- }
- VSyncModeText = args.VSyncMode == "Custom" ? "Custom" : "VSync";
- ShowCustomVSyncIntervalPicker =
- args.VSyncMode == VSyncMode.Custom.ToString();
- DockedStatusText = args.DockedMode;
- AspectRatioStatusText = args.AspectRatio;
- GameStatusText = args.GameStatus;
- VolumeStatusText = args.VolumeStatus;
- FifoStatusText = args.FifoStatus;
- ShaderCountText = (ShowShaderCompilationHint = args.ShaderCount > 0)
- ? $"{LocaleManager.Instance[LocaleKeys.CompilingShaders]}: {args.ShaderCount}"
- : string.Empty;
- ShowStatusSeparator = true;
- });
- }
- }
- private void RendererHost_Created(object sender, EventArgs e)
- {
- ShowLoading(false);
- _rendererWaitEvent.Set();
- }
- private async Task LoadContentFromFolder(LocaleKeys localeMessageAddedKey, LocaleKeys localeMessageRemovedKey, LoadContentFromFolderDelegate onDirsSelected)
- {
- var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
- {
- Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle],
- AllowMultiple = true,
- });
- if (result.Count > 0)
- {
- var dirs = result.Select(it => it.Path.LocalPath).ToList();
- var numAdded = onDirsSelected(dirs, out int numRemoved);
- var msg = String.Join("\r\n", new string[] {
- string.Format(LocaleManager.Instance[localeMessageRemovedKey], numRemoved),
- string.Format(LocaleManager.Instance[localeMessageAddedKey], numAdded)
- });
- await Dispatcher.UIThread.InvokeAsync(async () =>
- {
- await ContentDialogHelper.ShowTextDialog(
- LocaleManager.Instance[numAdded > 0 || numRemoved > 0 ? LocaleKeys.RyujinxConfirm : LocaleKeys.RyujinxInfo],
- msg,
- string.Empty,
- string.Empty,
- string.Empty,
- LocaleManager.Instance[LocaleKeys.InputDialogOk],
- (int)Symbol.Checkmark);
- });
- }
- }
- #endregion
- #region PublicMethods
- public void SetUiProgressHandlers(Switch emulationContext)
- {
- if (emulationContext.Processes.ActiveApplication.DiskCacheLoadState != null)
- {
- emulationContext.Processes.ActiveApplication.DiskCacheLoadState.StateChanged -= ProgressHandler;
- emulationContext.Processes.ActiveApplication.DiskCacheLoadState.StateChanged += ProgressHandler;
- }
- emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
- emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
- }
- public void LoadConfigurableHotKeys()
- {
- if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUI, out var showUiKey))
- {
- ShowUiKey = new KeyGesture(showUiKey);
- }
- if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot, out var screenshotKey))
- {
- ScreenshotKey = new KeyGesture(screenshotKey);
- }
- if (AvaloniaKeyboardMappingHelper.TryGetAvaKey((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause, out var pauseKey))
- {
- PauseKey = new KeyGesture(pauseKey);
- }
- }
- public void TakeScreenshot()
- {
- AppHost.ScreenshotRequested = true;
- }
- public void HideUi()
- {
- ShowMenuAndStatusBar = false;
- }
- public void ToggleStartGamesInFullscreen()
- {
- StartGamesInFullscreen = !StartGamesInFullscreen;
- }
- public void ToggleShowConsole()
- {
- ShowConsole = !ShowConsole;
- }
- public void SetListMode()
- {
- Glyph = Glyph.List;
- }
- public void SetGridMode()
- {
- Glyph = Glyph.Grid;
- }
- public void SetAspectRatio(AspectRatio aspectRatio)
- {
- ConfigurationState.Instance.Graphics.AspectRatio.Value = aspectRatio;
- }
- public async Task InstallFirmwareFromFile()
- {
- var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
- {
- AllowMultiple = false,
- FileTypeFilter = new List<FilePickerFileType>
- {
- new(LocaleManager.Instance[LocaleKeys.FileDialogAllTypes])
- {
- Patterns = new[] { "*.xci", "*.zip" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.xci", "public.zip-archive" },
- MimeTypes = new[] { "application/x-nx-xci", "application/zip" },
- },
- new("XCI")
- {
- Patterns = new[] { "*.xci" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.xci" },
- MimeTypes = new[] { "application/x-nx-xci" },
- },
- new("ZIP")
- {
- Patterns = new[] { "*.zip" },
- AppleUniformTypeIdentifiers = new[] { "public.zip-archive" },
- MimeTypes = new[] { "application/zip" },
- },
- },
- });
- if (result.Count > 0)
- {
- await HandleFirmwareInstallation(result[0].Path.LocalPath);
- }
- }
- public async Task InstallFirmwareFromFolder()
- {
- var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
- {
- AllowMultiple = false,
- });
- if (result.Count > 0)
- {
- await HandleFirmwareInstallation(result[0].Path.LocalPath);
- }
- }
- public async Task InstallKeysFromFile()
- {
- var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
- {
- AllowMultiple = false,
- FileTypeFilter = new List<FilePickerFileType>
- {
- new(LocaleManager.Instance[LocaleKeys.FileDialogAllTypes])
- {
- Patterns = new[] { "*.keys", "*.zip" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.xci", "public.zip-archive" },
- MimeTypes = new[] { "application/keys", "application/zip" },
- },
- new("KEYS")
- {
- Patterns = new[] { "*.keys" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.xci" },
- MimeTypes = new[] { "application/keys" },
- },
- new("ZIP")
- {
- Patterns = new[] { "*.zip" },
- AppleUniformTypeIdentifiers = new[] { "public.zip-archive" },
- MimeTypes = new[] { "application/zip" },
- },
- },
- });
- if (result.Count > 0)
- {
- await HandleKeysInstallation(result[0].Path.LocalPath);
- }
- }
- public async Task InstallKeysFromFolder()
- {
- var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
- {
- AllowMultiple = false,
- });
- if (result.Count > 0)
- {
- await HandleKeysInstallation(result[0].Path.LocalPath);
- }
- }
- public void OpenRyujinxFolder()
- {
- OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
- }
- public void OpenLogsFolder()
- {
- string logPath = AppDataManager.GetOrCreateLogsDir();
- if (!string.IsNullOrEmpty(logPath))
- {
- OpenHelper.OpenFolder(logPath);
- }
- }
- public void ToggleDockMode()
- {
- if (IsGameRunning)
- {
- ConfigurationState.Instance.System.EnableDockedMode.Toggle();
- }
- }
- public void ToggleVSyncMode()
- {
- AppHost.VSyncModeToggle();
- OnPropertyChanged(nameof(ShowCustomVSyncIntervalPicker));
- }
- public void VSyncModeSettingChanged()
- {
- if (_isGameRunning)
- {
- AppHost.Device.CustomVSyncInterval = ConfigurationState.Instance.Graphics.CustomVSyncInterval.Value;
- AppHost.Device.UpdateVSyncInterval();
- }
- CustomVSyncInterval = ConfigurationState.Instance.Graphics.CustomVSyncInterval.Value;
- OnPropertyChanged(nameof(ShowCustomVSyncIntervalPicker));
- OnPropertyChanged(nameof(CustomVSyncIntervalPercentageProxy));
- OnPropertyChanged(nameof(CustomVSyncIntervalPercentageText));
- OnPropertyChanged(nameof(CustomVSyncInterval));
- }
- public async Task ExitCurrentState()
- {
- if (WindowState is WindowState.FullScreen)
- {
- ToggleFullscreen();
- }
- else if (IsGameRunning)
- {
- await Task.Delay(100);
- AppHost?.ShowExitPrompt();
- }
- }
- public static void ChangeLanguage(object languageCode)
- {
- LocaleManager.Instance.LoadLanguage((string)languageCode);
- if (Program.PreviewerDetached)
- {
- ConfigurationState.Instance.UI.LanguageCode.Value = (string)languageCode;
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- }
- public async Task ManageProfiles()
- {
- await NavigationDialogHost.Show(AccountManager, ContentManager, VirtualFileSystem, LibHacHorizonManager.RyujinxClient);
- }
- public void SimulateWakeUpMessage()
- {
- AppHost.Device.System.SimulateWakeUpMessage();
- }
- public async Task OpenFile()
- {
- var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
- {
- Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle],
- AllowMultiple = false,
- FileTypeFilter = new List<FilePickerFileType>
- {
- new(LocaleManager.Instance[LocaleKeys.AllSupportedFormats])
- {
- Patterns = new[] { "*.nsp", "*.xci", "*.nca", "*.nro", "*.nso" },
- AppleUniformTypeIdentifiers = new[]
- {
- "com.ryujinx.nsp",
- "com.ryujinx.xci",
- "com.ryujinx.nca",
- "com.ryujinx.nro",
- "com.ryujinx.nso",
- },
- MimeTypes = new[]
- {
- "application/x-nx-nsp",
- "application/x-nx-xci",
- "application/x-nx-nca",
- "application/x-nx-nro",
- "application/x-nx-nso",
- },
- },
- new("NSP")
- {
- Patterns = new[] { "*.nsp" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.nsp" },
- MimeTypes = new[] { "application/x-nx-nsp" },
- },
- new("XCI")
- {
- Patterns = new[] { "*.xci" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.xci" },
- MimeTypes = new[] { "application/x-nx-xci" },
- },
- new("NCA")
- {
- Patterns = new[] { "*.nca" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.nca" },
- MimeTypes = new[] { "application/x-nx-nca" },
- },
- new("NRO")
- {
- Patterns = new[] { "*.nro" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.nro" },
- MimeTypes = new[] { "application/x-nx-nro" },
- },
- new("NSO")
- {
- Patterns = new[] { "*.nso" },
- AppleUniformTypeIdentifiers = new[] { "com.ryujinx.nso" },
- MimeTypes = new[] { "application/x-nx-nso" },
- },
- },
- });
- if (result.Count > 0)
- {
- if (ApplicationLibrary.TryGetApplicationsFromFile(result[0].Path.LocalPath,
- out List<ApplicationData> applications))
- {
- await LoadApplication(applications[0]);
- }
- else
- {
- await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.MenuBarFileOpenFromFileError]);
- }
- }
- }
- public async Task LoadDlcFromFolder()
- {
- await LoadContentFromFolder(
- LocaleKeys.AutoloadDlcAddedMessage,
- LocaleKeys.AutoloadDlcRemovedMessage,
- ApplicationLibrary.AutoLoadDownloadableContents);
- }
- public async Task LoadTitleUpdatesFromFolder()
- {
- await LoadContentFromFolder(
- LocaleKeys.AutoloadUpdateAddedMessage,
- LocaleKeys.AutoloadUpdateRemovedMessage,
- ApplicationLibrary.AutoLoadTitleUpdates);
- }
- public async Task OpenFolder()
- {
- var result = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
- {
- Title = LocaleManager.Instance[LocaleKeys.OpenFolderDialogTitle],
- AllowMultiple = false,
- });
- if (result.Count > 0)
- {
- ApplicationData applicationData = new()
- {
- Name = Path.GetFileNameWithoutExtension(result[0].Path.LocalPath),
- Path = result[0].Path.LocalPath,
- };
- await LoadApplication(applicationData);
- }
- }
- public async Task LoadApplication(ApplicationData application, bool startFullscreen = false, BlitStruct<ApplicationControlProperty>? customNacpData = null)
- {
- if (AppHost != null)
- {
- await ContentDialogHelper.CreateInfoDialog(
- LocaleManager.Instance[LocaleKeys.DialogLoadAppGameAlreadyLoadedMessage],
- LocaleManager.Instance[LocaleKeys.DialogLoadAppGameAlreadyLoadedSubMessage],
- LocaleManager.Instance[LocaleKeys.InputDialogOk],
- string.Empty,
- LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
- return;
- }
- #if RELEASE
- await PerformanceCheck();
- #endif
- Logger.RestartTime();
- SelectedIcon ??= ApplicationLibrary.GetApplicationIcon(application.Path, ConfigurationState.Instance.System.Language, application.Id);
- PrepareLoadScreen();
- RendererHostControl = new RendererHost(application.Id.ToString("X16"));
- AppHost = new AppHost(
- RendererHostControl,
- InputManager,
- application.Path,
- application.Id,
- VirtualFileSystem,
- ContentManager,
- AccountManager,
- UserChannelPersistence,
- this,
- TopLevel);
- if (!await AppHost.LoadGuestApplication(customNacpData))
- {
- AppHost.DisposeContext();
- AppHost = null;
- return;
- }
- CanUpdate = false;
- LoadHeading = application.Name;
- if (string.IsNullOrWhiteSpace(application.Name))
- {
- LoadHeading = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.LoadingHeading, AppHost.Device.Processes.ActiveApplication.Name);
- application.Name = AppHost.Device.Processes.ActiveApplication.Name;
- }
- SwitchToRenderer(startFullscreen);
- _currentApplicationData = application;
- Thread gameThread = new(InitializeGame) { Name = "GUI.WindowThread" };
- gameThread.Start();
- }
- public void SwitchToRenderer(bool startFullscreen) =>
- Dispatcher.UIThread.Post(() =>
- {
- SwitchToGameControl(startFullscreen);
- SetMainContent(RendererHostControl);
- RendererHostControl.Focus();
- });
- public static void UpdateGameMetadata(string titleId)
- => ApplicationLibrary.LoadAndSaveMetaData(titleId, appMetadata => appMetadata.UpdatePostGame());
- public void RefreshFirmwareStatus()
- {
- SystemVersion version = null;
- try
- {
- version = ContentManager.GetCurrentFirmwareVersion();
- }
- catch (Exception)
- {
- // ignored
- }
- bool hasApplet = false;
- if (version != null)
- {
- LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarSystemVersion, version.VersionString);
- hasApplet = version.Major > 3;
- }
- else
- {
- LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarSystemVersion, "NaN");
- }
- IsAppletMenuActive = hasApplet;
- }
- public void AppHost_AppExit(object sender, EventArgs e)
- {
- if (IsClosing)
- {
- return;
- }
- IsGameRunning = false;
- Dispatcher.UIThread.InvokeAsync(async () =>
- {
- ShowMenuAndStatusBar = true;
- ShowContent = true;
- ShowLoadProgress = false;
- IsLoadingIndeterminate = false;
- CanUpdate = true;
- Cursor = Cursor.Default;
- SetMainContent(null);
- AppHost = null;
- await HandleRelaunch();
- });
- RendererHostControl.WindowCreated -= RendererHost_Created;
- RendererHostControl = null;
- SelectedIcon = null;
- Dispatcher.UIThread.InvokeAsync(() =>
- {
- Title = RyujinxApp.FormatTitle();
- });
- }
- public async Task OpenAmiiboWindow()
- {
- if (!IsAmiiboRequested)
- return;
- if (AppHost.Device.System.SearchingForAmiibo(out int deviceId))
- {
- string titleId = AppHost.Device.Processes.ActiveApplication.ProgramIdText.ToUpper();
- AmiiboWindow window = new(ShowAll, LastScannedAmiiboId, titleId);
- await window.ShowDialog(Window);
- if (window.IsScanned)
- {
- ShowAll = window.ViewModel.ShowAllAmiibo;
- LastScannedAmiiboId = window.ScannedAmiibo.GetId();
- AppHost.Device.System.ScanAmiibo(deviceId, LastScannedAmiiboId, window.ViewModel.UseRandomUuid);
- }
- }
- }
- public async Task OpenBinFile()
- {
- if (!IsAmiiboRequested)
- return;
- if (AppHost.Device.System.SearchingForAmiibo(out int deviceId))
- {
- var result = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
- {
- Title = LocaleManager.Instance[LocaleKeys.OpenFileDialogTitle],
- AllowMultiple = false,
- FileTypeFilter = new List<FilePickerFileType>
- {
- new(LocaleManager.Instance[LocaleKeys.AllSupportedFormats])
- {
- Patterns = new[] { "*.bin" },
- }
- }
- });
- if (result.Count > 0)
- {
- AppHost.Device.System.ScanAmiiboFromBin(result[0].Path.LocalPath);
- }
- }
- }
- public void ToggleFullscreen()
- {
- if (Environment.TickCount64 - LastFullscreenToggle < HotKeyPressDelayMs)
- {
- return;
- }
- LastFullscreenToggle = Environment.TickCount64;
- if (WindowState is not WindowState.Normal)
- {
- WindowState = WindowState.Normal;
- Window.TitleBar.ExtendsContentIntoTitleBar = !ConfigurationState.Instance.ShowTitleBar;
- if (IsGameRunning)
- {
- ShowMenuAndStatusBar = true;
- }
- }
- else
- {
- WindowState = WindowState.FullScreen;
- Window.TitleBar.ExtendsContentIntoTitleBar = true;
- if (IsGameRunning)
- {
- ShowMenuAndStatusBar = false;
- }
- }
- IsFullScreen = WindowState is WindowState.FullScreen;
- }
- public static void SaveConfig()
- {
- ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
- }
- public static async Task PerformanceCheck()
- {
- if (ConfigurationState.Instance.Logger.EnableTrace.Value)
- {
- string mainMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckLoggingEnabledMessage];
- string secondaryMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckLoggingEnabledConfirmMessage];
- UserResult result = await ContentDialogHelper.CreateLocalizedConfirmationDialog(mainMessage, secondaryMessage);
- if (result == UserResult.Yes)
- {
- ConfigurationState.Instance.Logger.EnableTrace.Value = false;
- SaveConfig();
- }
- }
- if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
- {
- string mainMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckShaderDumpEnabledMessage];
- string secondaryMessage = LocaleManager.Instance[LocaleKeys.DialogPerformanceCheckShaderDumpEnabledConfirmMessage];
- UserResult result = await ContentDialogHelper.CreateLocalizedConfirmationDialog(mainMessage, secondaryMessage);
- if (result == UserResult.Yes)
- {
- ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = string.Empty;
- SaveConfig();
- }
- }
- }
- public async void ProcessTrimResult(String filename, Ryujinx.Common.Utilities.XCIFileTrimmer.OperationOutcome operationOutcome)
- {
- string notifyUser = operationOutcome.ToLocalisedText();
- if (notifyUser != null)
- {
- await ContentDialogHelper.CreateWarningDialog(
- LocaleManager.Instance[LocaleKeys.TrimXCIFileFailedPrimaryText],
- notifyUser
- );
- }
- else
- {
- switch (operationOutcome)
- {
- case Ryujinx.Common.Utilities.XCIFileTrimmer.OperationOutcome.Successful:
- if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
- if (desktop.MainWindow is MainWindow mainWindow)
- mainWindow.LoadApplications();
- }
- break;
- }
- }
- }
- public async Task TrimXCIFile(string filename)
- {
- if (filename == null)
- {
- return;
- }
- var trimmer = new XCIFileTrimmer(filename, new XCITrimmerLog.MainWindow(this));
- if (trimmer.CanBeTrimmed)
- {
- var savings = (double)trimmer.DiskSpaceSavingsB / 1024.0 / 1024.0;
- var currentFileSize = (double)trimmer.FileSizeB / 1024.0 / 1024.0;
- var cartDataSize = (double)trimmer.DataSizeB / 1024.0 / 1024.0;
- string secondaryText = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.TrimXCIFileDialogSecondaryText, currentFileSize, cartDataSize, savings);
- var result = await ContentDialogHelper.CreateConfirmationDialog(
- LocaleManager.Instance[LocaleKeys.TrimXCIFileDialogPrimaryText],
- secondaryText,
- LocaleManager.Instance[LocaleKeys.Continue],
- LocaleManager.Instance[LocaleKeys.Cancel],
- LocaleManager.Instance[LocaleKeys.TrimXCIFileDialogTitle]
- );
- if (result == UserResult.Yes)
- {
- Thread XCIFileTrimThread = new(() =>
- {
- Dispatcher.UIThread.Post(() =>
- {
- StatusBarProgressStatusText = LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.StatusBarXCIFileTrimming, Path.GetFileName(filename));
- StatusBarProgressStatusVisible = true;
- StatusBarProgressMaximum = 1;
- StatusBarProgressValue = 0;
- StatusBarVisible = true;
- });
- try
- {
- XCIFileTrimmer.OperationOutcome operationOutcome = trimmer.Trim();
- Dispatcher.UIThread.Post(() =>
- {
- ProcessTrimResult(filename, operationOutcome);
- });
- }
- finally
- {
- Dispatcher.UIThread.Post(() =>
- {
- StatusBarProgressStatusVisible = false;
- StatusBarProgressStatusText = string.Empty;
- StatusBarVisible = false;
- });
- }
- })
- {
- Name = "GUI.XCIFileTrimmerThread",
- IsBackground = true,
- };
- XCIFileTrimThread.Start();
- }
- }
- }
- #endregion
- }
- }
|