/// <summary> /// Called whenever the debug targets change. Note that after a save this function will be /// called. It looks for changes and applies them to the UI as needed. Switching profiles /// will also cause this to change as the active profile is stored in the profiles snapshot. /// </summary> internal virtual void InitializeDebugTargetsCore(ILaunchSettings profiles) { IWritableLaunchSettings newSettings = profiles.ToWritableLaunchSettings(); // Since this get's reentered if the user saves or the user switches active profiles. if (CurrentLaunchSettings != null && !CurrentLaunchSettings.SettingsDiffer(newSettings)) { return; } try { // This should never change the dirty state when loading the dialog PushIgnoreEvents(); // Remember the current selection string curProfileName = SelectedDebugProfile?.Name; // Update the set of settings and generate a property change so the list of profiles gets updated. Note that we always // clear the active profile on the CurrentLaunchSettings so that when we do set one and property changed event is set CurrentLaunchSettings = newSettings; CurrentLaunchSettings.ActiveProfile = null; // Reload the launch profiles collection LaunchProfiles.Clear(); foreach (IWritableLaunchProfile profile in CurrentLaunchSettings.Profiles) { LaunchProfiles.Add(profile); } // When loading new profiles we need to clear the launch type. This is so the external changes cause the current // active provider to be refreshed _selectedLaunchType = null; NotifyProfileCollectionChanged(); // If we have a selection, we want to leave it as is if (curProfileName == null || newSettings.Profiles.FirstOrDefault(p => LaunchProfile.IsSameProfileName(p.Name, curProfileName)) == null) { // Note that we have to be careful since the collection can be empty. if (profiles.ActiveProfile != null && !string.IsNullOrEmpty(profiles.ActiveProfile.Name)) { SelectedDebugProfile = LaunchProfiles.Where(p => LaunchProfile.IsSameProfileName(p.Name, profiles.ActiveProfile.Name)).Single(); } else { if (LaunchProfiles.Count > 0) { SelectedDebugProfile = LaunchProfiles[0]; } else { SetEnvironmentGrid(null); } } } else { SelectedDebugProfile = LaunchProfiles.Where(p => LaunchProfile.IsSameProfileName(p.Name, curProfileName)).Single(); } } finally { PopIgnoreEvents(); if (_firstSnapshotCompleteSource != null) { _firstSnapshotCompleteSource.TrySetResult(true); } } }
internal bool IsNewProfileNameValid(string name) { return(!LaunchProfiles.Any( profile => LaunchProfile.IsSameProfileName(profile.Name, name))); }
private ConsoleDebugTargetsProvider GetDebugTargetsProvider(string outputType = "exe", Dictionary <string, string> properties = null) { _mockFS.WriteAllText(@"c:\test\Project\someapp.exe", ""); _mockFS.CreateDirectory(@"c:\test\Project"); _mockFS.CreateDirectory(@"c:\test\Project\bin\"); _mockFS.WriteAllText(@"c:\program files\dotnet\dotnet.exe", ""); var activeProfile = new LaunchProfile() { Name = "MyApplication", CommandLineArgs = "--someArgs", ExecutablePath = @"c:\test\Project\someapp.exe" }; _mockEnvironment.Setup(s => s.GetEnvironmentVariable("Path")).Returns(() => _Path); var project = UnconfiguredProjectFactory.Create(null, null, _ProjectFile); var outputTypeEnum = new PageEnumValue(new EnumValue() { Name = outputType }); var data = new PropertyPageData() { Category = ConfigurationGeneral.SchemaName, PropertyName = ConfigurationGeneral.OutputTypeProperty, Value = outputTypeEnum }; var projectProperties = ProjectPropertiesFactory.Create(project, data); if (properties == null) { properties = new Dictionary <string, string>() { { "RunCommand", @"dotnet" }, { "RunArguments", "exec " + "\"" + @"c:\test\project\bin\project.dll" + "\"" }, { "RunWorkingDirectory", @"bin\" }, { "TargetFrameworkIdentifier", @".NetCoreApp" }, { "OutDir", @"c:\test\project\bin\" } }; } var delegatePropertiesMock = IProjectPropertiesFactory .MockWithPropertiesAndValues(properties); var delegateProvider = IProjectPropertiesProviderFactory.Create(null, delegatePropertiesMock.Object); IConfiguredProjectServices configuredProjectServices = Mock.Of <IConfiguredProjectServices>(o => o.ProjectPropertiesProvider == delegateProvider); ConfiguredProject configuredProject = Mock.Of <ConfiguredProject>(o => o.UnconfiguredProject == project && o.Services == configuredProjectServices); _mockTokenReplace.Setup(s => s.ReplaceTokensInProfileAsync(It.IsAny <ILaunchProfile>())).Returns <ILaunchProfile>(p => Task.FromResult(p)); IActiveDebugFrameworkServices activeDebugFramework = Mock.Of <IActiveDebugFrameworkServices>(o => o.GetConfiguredProjectForActiveFrameworkAsync() == Task.FromResult(configuredProject)); var debugProvider = new ConsoleDebugTargetsProvider( configuredProject, _mockTokenReplace.Object, _mockFS, _mockEnvironment.Object, activeDebugFramework, projectProperties); return(debugProvider); }
internal bool IsNewProfileNameValid(string name) { return(LaunchProfiles.Where( profile => LaunchProfile.IsSameProfileName(profile.Name, name)).Count() == 0); }
private string BuildArguments(LaunchProfile profile, Version version) { var builder = new StringBuilder(8192); // User defined JVM arguments if (!string.IsNullOrWhiteSpace(profile.JvmArgs)) { builder.Append(profile.JvmArgs).Append(' '); } else { // Configure GC builder.Append("-XX:+UnlockExperimentalVMOptions "); builder.Append("-XX:+UseG1GC "); builder.Append("-XX:G1NewSizePercent=20 "); builder.Append("-XX:G1ReservePercent=20 "); builder.Append("-XX:MaxGCPauseMillis=48 "); builder.Append("-XX:+ParallelRefProcEnabled "); builder.Append("-XX:G1HeapRegionSize=32M "); builder.Append("-XX:-UseAdaptiveSizePolicy "); builder.Append("-XX:-OmitStackTraceInFastThrow "); } // Max Memory builder.Append($"-Xmx{profile.MaxMemory}M "); // Arguments for Forge builder.Append("-Dfml.ignoreInvalidMinecraftCertificates=true "); builder.Append("-Dfml.ignorePatchDiscrepancies=true "); // WHAT THE HELL is this ??? builder.Append("-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump "); // Natives builder.Append($"-Djava.library.path=\"{_gamePathService.NativesDir}\" "); // Launcher Identifier builder.Append($"-Dminecraft.launcher.brand={AssemblyUtil.Title} "); builder.Append($"-Dminecraft.launcher.version={AssemblyUtil.Version} "); // Libraries builder.Append("-cp \""); foreach (var lib in version.Libraries) { if (lib.Type == LibraryType.Native) { continue; } builder.Append($"{_gamePathService.LibrariesDir}/{lib.Path};"); } // Main Jar builder.Append($"{_gamePathService.VersionsDir}/{version.JarID}/{version.JarID}.jar\" "); // Authlib-Injector if (profile.Account.AuthMode == AuthMode.AuthLibInjector) { builder.Append( $"-javaagent:\"{_gamePathService.RootDir}/authlib-injector.jar\"={profile.Account.AuthServerBase} "); builder.Append("-Dauthlibinjector.side=client "); builder.Append("-Dauthlibinjector.yggdrasil.prefetched="); builder.Append(profile.Account.PrefetchedAuthServerInfo); builder.Append(' '); } // Main Class builder.Append(version.MainClass).Append(' '); // Minecraft Arguments var argsDict = version.MinecraftArgsDict; argsDict["--username"] = '******' + profile.Account.Username + '\"'; argsDict["--version"] = '\"' + version.ID + '\"'; argsDict["--gameDir"] = '\"' + _gamePathService.WorkingDir + '\"'; if (version.AssetsInfo.IsLegacy) { argsDict["--assetsDir"] = _gamePathService.AssetsDir + "/virtual/legacy"; } else { argsDict["--assetsDir"] = '\"' + _gamePathService.AssetsDir + '\"'; argsDict["--assetIndex"] = version.AssetsInfo.ID; } if (argsDict.ContainsKey("--uuid")) { argsDict["--uuid"] = profile.Account.UUID; } if (argsDict.ContainsKey("--accessToken")) { argsDict["--accessToken"] = profile.Account.AccessToken; } if (argsDict.ContainsKey("--session")) { argsDict["--session"] = profile.Account.AccessToken; } if (argsDict.ContainsKey("--userType")) { argsDict["--userType"] = "mojang"; } if (argsDict.ContainsKey("--versionType")) { argsDict["--versionType"] = profile.VersionType; } if (argsDict.ContainsKey("--userProperties")) { argsDict["--userProperties"] = "{}"; } string args = string.Join(" ", argsDict.Select(pair => pair.Key + ' ' + pair.Value)); builder.Append(args).Append(' '); // Server Login if (!string.IsNullOrWhiteSpace(profile.ServerAddress)) { string[] temp = profile.ServerAddress.Split(':'); builder.Append("--server " + temp[0]).Append(' '); if (temp.Length == 2) { builder.Append("--port " + temp[1]).Append(' '); } } // Full Screen if (profile.IsFullScreen) { builder.Append("--fullscreen "); } // Window Size if (profile.WinWidth != 0 && profile.WinHeight != 0) { builder.Append($"--width {profile.WinWidth} --height {profile.WinHeight}"); } // Additional Arguments if (!string.IsNullOrWhiteSpace(profile.ExtraArgs)) { builder.Append(' ').Append(profile.ExtraArgs); } Debug.WriteLine(builder.ToString()); // Build Complete return(builder.ToString()); }
/// <summary> /// See <see cref="IDynamicEnumValuesGenerator"/> /// </summary> public async Task <IEnumValue> TryCreateEnumValueAsync(string userSuppliedValue) { return((await _listedValues.GetValueAsync().ConfigureAwait(true)) .FirstOrDefault(v => LaunchProfile.IsSameProfileName(v.Name, userSuppliedValue))); }
public async void Launch() { IsLaunching = true; GreetingVM.IsShown = false; LaunchProcessStarted?.Invoke(); // Check JRE if (_config.JreDir == null) { _windowManager.ShowMessageBox("${JreNotFound}\n${PleaseInstallJre}", "${IntegrityCheck}", MessageBoxButton.OK, MessageBoxImage.Error); _statusVM.Status = LaunchStatus.Failed; return; } _statusVM.GameOutputLog = null; this.ActivateItem(_statusVM); _statusVM.Status = LaunchStatus.LoggingIn; // No account found, the user must create one var account = _accountService.GetSelected(); if (account == null) { _accountEditVM.Setup(AccountEditType.AddAccount); if (_windowManager.ShowDialog(_accountEditVM) != true) { _statusVM.Status = LaunchStatus.Failed; return; } account = _accountService.GetSelected(); } else { // Previous login token is invalid, need re-authentication var authResult = await _authService.LoginAsync(account); if (!authResult.IsSuccessful) { _accountEditVM.Setup(AccountEditType.ReAuth, account); if (_windowManager.ShowDialog(_accountEditVM) != true) { _statusVM.Status = LaunchStatus.Failed; return; } } else if (authResult.SelectedProfile == null) { var selectedProfile = authResult.AvailableProfiles.FirstOrDefault(); _profileSelectVM.Setup(authResult.AvailableProfiles, account.ProfileServer); if (_windowManager.ShowDialog(_profileSelectVM) ?? false) { selectedProfile = _profileSelectVM.SelectedProfile; } account.Username = selectedProfile.Name; account.UUID = selectedProfile.Id; } } // Check authlib-injector if selected account is using external authentication if (account.AuthMode == AuthMode.AuthLibInjector) { if (!_authlibInjectorService.CheckIntegrity(account.AuthlibInjectorSHA256)) { // Authlib-Injector is missing or damaged var latest = await _authlibInjectorService.GetLatest(); if (latest == null) { _statusVM.Status = LaunchStatus.Failed; return; } var download = _authlibInjectorService.GetDownload(latest); if (!await StartDownloadAsync(DownloadType.AuthlibInjector, download)) { _statusVM.Status = LaunchStatus.Failed; return; } account.AuthlibInjectorSHA256 = latest.SHA256; } account.PrefetchedAuthServerInfo = await _authService.PrefetchAuthServerInfo(account.AuthServerBase); if (account.PrefetchedAuthServerInfo == null) { _statusVM.Status = LaunchStatus.Failed; return; } } _statusVM.Status = LaunchStatus.ProcessingDependencies; var launchVersion = _versionService.GetByID(_config.SelectedVersion); // Check main jar and fix possible damage if (!_versionService.CheckIntegrity(launchVersion)) { var download = _versionService.GetDownload(launchVersion); if (!await StartDownloadAsync(DownloadType.MainJar, download)) { _statusVM.Status = LaunchStatus.Failed; return; } } // Check dependent libraries and fix possible damage var damagedLibs = await _libraryService.CheckIntegrityAsync(launchVersion.Libraries); if (damagedLibs.Any()) { // For 1.13.2+ forge versions, there is no way to fix damaged forge jar unless reinstall if (launchVersion.Type == VersionType.NewForge && damagedLibs.Any( lib => lib.Type == LibraryType.ForgeMain )) { _windowManager.ShowMessageBox("${MainJarDamaged}\n${PleaseReinstallForge}", "${IntegrityCheck}", MessageBoxButton.OK, MessageBoxImage.Error); // Delete the damaged forge version (but retain the libraries) // force user to reinstall it await _versionService.DeleteFromDiskAsync(launchVersion.ID, false); _statusVM.Status = LaunchStatus.Failed; return; } var downloads = _libraryService.GetDownloads(damagedLibs); if (!await StartDownloadAsync(DownloadType.Libraries, downloads)) { _statusVM.Status = LaunchStatus.Failed; return; } } // Extract native libraries _libraryService.ExtractNatives(launchVersion.Libraries.Where(lib => lib.Type == LibraryType.Native)); // Try loading assets if (!_assetService.LoadAllObjects(launchVersion.AssetsInfo)) { if (await _assetService.DownloadIndexJsonAsync(launchVersion.AssetsInfo)) { // Successfully downloaded the missing index json, load assets _assetService.LoadAllObjects(launchVersion.AssetsInfo); } // if index json download failed (what are the odds!), not gonna retry // Prepare for enjoying a silent game XD } // Check assets and fix possible damage on user's discretion var damagedAssets = await _assetService.CheckIntegrityAsync(launchVersion.AssetsInfo); if ((damagedAssets?.Any() ?? false) && _windowManager.ShowMessageBox("${AssetsDamaged}\n${WhetherFixNow}", "${IntegrityCheck}", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { var downloads = _assetService.GetDownloads(damagedAssets); await StartDownloadAsync(DownloadType.Assets, downloads); } // For legacy versions (1.7.2 or earlier), copy hashed asset objects to virtual files if (launchVersion.AssetsInfo.IsLegacy) { await _assetService.CopyToVirtualAsync(launchVersion.AssetsInfo); } // All good to go, now build launch profile var profile = new LaunchProfile { IsDebugMode = _config.JavaDebugMode, JvmArgs = _config.JvmArgs, MaxMemory = _config.JavaMaxMem, Account = account, VersionType = AssemblyUtil.Title, WinWidth = _config.WindowWidth, WinHeight = _config.WindowHeight, IsFullScreen = _config.FullScreen, ServerAddress = _config.ServerAddress, ExtraArgs = _config.ExtraMinecraftArgs, }; _statusVM.Status = LaunchStatus.StartingProcess; void UpdateLogDisplay(string logMessage) => _statusVM.GameOutputLog = logMessage; _launchService.LogReceived += UpdateLogDisplay; if (!await _launchService.LaunchGameAsync(profile, launchVersion)) { _statusVM.Status = LaunchStatus.Failed; _launchService.LogReceived -= UpdateLogDisplay; return; } _statusVM.Status = LaunchStatus.Running; _launchService.LogReceived -= UpdateLogDisplay; _statusVM.GameOutputLog = XD; }