Exemplo n.º 1
0
        private async Task AddFactorioInstallation(FactorioFolder folder)
        {
            await PreserveContentsAsync(folder.Directory);

            var factorioDir = App.Instance.Settings.GetFactorioDirectory();

            if (!factorioDir.Exists)
            {
                factorioDir.Create();
            }

            var newFolder = await folder.CopyToAsync(factorioDir);

            newFolder.RenameToUnique();

            var factorioVersion = new FactorioVersion(newFolder);

            FactorioVersions.Add(factorioVersion);
            factorioVersion.BeginEdit();
        }
Exemplo n.º 2
0
        public void UnmaintainRelease_ShouldDeleteAndIsStored_DiscardRelease()
        {
            // Arrange
            var modName      = "TestMod";
            var version      = new FactorioVersion(1, 2, 3);
            var shouldDelete = true;
            var isStored     = true;

            var modsStorageService = new Mock <IModsStorageService>();

            modsStorageService.Setup(mss => mss.ReleaseIsStored(modName, version)).Returns(isStored);

            var mainService = new MainService(null, null, null, null, null, modsStorageService.Object);

            // Act
            mainService.UnmaintainRelease(modName, version, shouldDelete);

            // Assert
            modsStorageService.Verify(mss => mss.DiscardRelease(modName, version), Times.Once);
        }
Exemplo n.º 3
0
        private static bool TryGetFactorioVersion(string name, bool isVersion, out FactorioVersion factorioVersion)
        {
            factorioVersion = null;
            var factorioVersions = FactorioCollection.Load();

            if (isVersion)
            {
                if (!Version.TryParse(name, out var version))
                {
                    return(false);
                }
                bool exact = name.IndexOf('.') != name.LastIndexOf('.');
                factorioVersion = factorioVersions.Find(version, exact);
            }
            else
            {
                factorioVersion = factorioVersions.Find(name);
            }

            return(factorioVersion != null);
        }
Exemplo n.º 4
0
        private static async Task ApplyUpdatePackageAsync(FactorioVersion versionToUpdate, FileInfo packageFile, IProgress <double> progress)
        {
            using (var archive = ZipFile.OpenRead(packageFile.FullName))
            {
                UpdatePackageInfo packageInfo = await GetUpdatePackageInfoAsync(archive);

                if (!string.Equals(packageInfo.Type, "update", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new CriticalUpdaterException(UpdaterErrorType.PackageInvalid);
                }

                int fileCount = packageInfo.UpdatedFiles.Length;
                int counter   = 0;
                foreach (var fileUpdate in packageInfo.UpdatedFiles)
                {
                    progress.Report((double)counter / fileCount);

                    switch (fileUpdate.Action)
                    {
                    case FileUpdateAction.Added:
                        await AddFileAsync(fileUpdate, versionToUpdate, archive, packageInfo.PackageDirectory);

                        break;

                    case FileUpdateAction.Removed:
                        await DeleteFileAsync(fileUpdate, versionToUpdate);

                        break;

                    case FileUpdateAction.Differs:
                        await UpdateFileAsync(fileUpdate, versionToUpdate, archive, packageInfo.PackageDirectory);

                        break;
                    }

                    counter++;
                }
                progress.Report(1);
            }
        }
Exemplo n.º 5
0
        private static async Task AddFileAsync(FileUpdateInfo fileUpdate, FactorioVersion versionToUpdate, ZipArchive archive, string packageDirectory)
        {
            await Task.Run(() =>
            {
                var file = new FileInfo(versionToUpdate.ExpandPathVariables(fileUpdate.Path));

                string entryPath = fileUpdate.Path;
                if (!string.IsNullOrEmpty(packageDirectory))
                {
                    entryPath = string.Join("/", packageDirectory, entryPath);
                }
                entryPath = ResolveArchivePath(entryPath);
                var entry = archive.GetEntry(entryPath);

                var dir = file.Directory;
                if (!dir.Exists)
                {
                    dir.Create();
                }
                entry.ExtractToFile(file.FullName, true);
            });
        }
Exemplo n.º 6
0
        private bool ShowVersionList(CookieContainer container, out FactorioOnlineVersion selectedVersion)
        {
            selectedVersion = null;
            List <FactorioOnlineVersion> versions;

            try
            {
                if (!FactorioWebsite.GetVersions(container, out versions))
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("RetrievingVersions", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("RetrievingVersions", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }
            }
            catch (WebException)
            {
                MessageBox.Show(Window,
                                App.Instance.GetLocalizedMessage("RetrievingVersions", MessageType.Error),
                                App.Instance.GetLocalizedMessageTitle("RetrievingVersions", MessageType.Error),
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return(false);
            }
            versions.ForEach(item => item.Downloadable = GetVersionDownloadable(item));

            var versionListWindow = new VersionListWindow {
                Owner = Window
            };
            var versionListViewModel = (VersionListViewModel)versionListWindow.ViewModel;

            versions.ForEach(item => versionListViewModel.FactorioVersions.Add(item));

            bool?versionResult = versionListWindow.ShowDialog();

            selectedVersion = versionListViewModel.SelectedVersion;
            return(versionResult.HasValue && versionResult.Value);
        }
Exemplo n.º 7
0
 public bool Compatible(FactorioVersion gameVersion, CfanModule module)
 {
     return(module.IsCompatibleKSP(gameVersion));
 }
 public static FactorioVersion GenerateValidRandomizedFactorioVersion()
 {
     return(FactorioVersion.For(GenerateValidRandomizedFactorioVersionString()));
 }
Exemplo n.º 9
0
        public bool IsCompatibleKSP(FactorioVersion kspVersion)
        {
            ModDependency baseGame = BaseGameDependency;

            return(baseGame == null || baseGame.isSatisfiedBy("base", kspVersion));
        }
Exemplo n.º 10
0
 /// <summary>
 /// Creates a new resolver that will find a way to install all the modules specified.
 /// </summary>
 public RelationshipResolver(ICollection <CfanModule> modules, RelationshipResolverOptions options, IRegistryQuerier registry,
                             FactorioVersion kspversion) : this(options, registry, kspversion)
 {
     AddModulesToInstall(modules.ToArray());
 }
Exemplo n.º 11
0
 public void ToString_WhenGivenFactorioVersion_ReturnsCorrectString(FactorioVersion version, String expected)
 {
     Assert.Equal(expected, version.ToString());
 }
Exemplo n.º 12
0
        /// <summary>
        /// This function returns a changeset based on the selections of the user.
        /// Currently returns null if a conflict is detected.
        /// </summary>
        /// <param name="registry"></param>
        /// <param name="changeSet"></param>
        /// <param name="installer">A module installer for the current KSP install</param>
        /// <param name="version">The version of the current KSP install</param>
        public async Task <IEnumerable <ModChange> > ComputeChangeSetFromModList(
            IRegistryQuerier registry, HashSet <ModChange> changeSet, ModuleInstaller installer,
            FactorioVersion version)
        {
            var modules_to_install = new HashSet <CfanModule>();
            var modules_to_remove  = new HashSet <CfanModule>();
            var options            = new RelationshipResolverOptions
            {
                without_toomanyprovides_kraken = false,
                with_recommends = false
            };

            foreach (var change in changeSet)
            {
                switch (change.ChangeType)
                {
                case GUIModChangeType.None:
                    break;

                case GUIModChangeType.Update:
                case GUIModChangeType.Install:
                    //TODO: Fix
                    //This will give us a mod with a wrong version!
                    modules_to_install.Add(change.Mod.ToCkanModule());
                    break;

                case GUIModChangeType.Remove:
                    modules_to_remove.Add(change.Mod);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            var installed_modules =
                registry.InstalledModules.Select(imod => imod.Module).ToDictionary(mod => mod.identifier, mod => mod);


            bool handled_all_to_many_provides = false;

            while (!handled_all_to_many_provides)
            {
                //Can't await in catch clause - doesn't seem to work in mono. Hence this flag
                TooManyModsProvideKraken kraken;
                try
                {
                    new RelationshipResolver(modules_to_install.ToList(), options, registry, version);
                    handled_all_to_many_provides = true;
                    continue;
                }
                catch (TooManyModsProvideKraken k)
                {
                    kraken = k;
                }
                catch (ModuleNotFoundKraken k)
                {
                    //We shouldn't need this. However the relationship provider will throw TMPs with incompatible mods.
                    user.RaiseError("Module {0} has not been found. This may be because it is not compatible " +
                                    "with the currently installed version of KSP", k.module);
                    return(null);
                }
                //Shouldn't get here unless there is a kraken.
                var mod = await too_many_provides(kraken);

                if (mod != null)
                {
                    modules_to_install.Add(mod);
                }
                else
                {
                    //TODO Is could be a new type of Kraken.
                    throw kraken;
                }
            }


            foreach (var dependency in registry.FindReverseDependencies(modules_to_remove.Select(mod => mod.identifier)))
            {
                //TODO This would be a good place to have a event that alters the row's graphics to show it will be removed
                CfanModule module_by_version = registry.GetModuleByVersion(installed_modules[dependency].identifier,
                                                                           installed_modules[dependency].modVersion) ?? registry.InstalledModule(dependency).Module;
                changeSet.Add(new ModChange(new GUIMod(module_by_version, registry, version), GUIModChangeType.Remove, null));
            }
            //May throw InconsistentKraken
            var resolver = new RelationshipResolver(options, registry, version);

            resolver.RemoveModsFromInstalledList(
                changeSet.Where(change => change.ChangeType.Equals(GUIModChangeType.Remove)).Select(m => m.Mod.ToModule()));
            resolver.AddModulesToInstall(modules_to_install.ToList());
            changeSet.UnionWith(
                resolver.ModList()
                .Select(m => new ModChange(new GUIMod(m, registry, version), GUIModChangeType.Install, resolver.ReasonFor(m))));


            return(changeSet);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Return the most recent release of a module with a optional ksp version to target and a RelationshipDescriptor to satisfy.
        /// </summary>
        /// <param name="ksp_version">If not null only consider mods which match this ksp version.</param>
        /// <param name="relationship">If not null only consider mods which satisfy the RelationshipDescriptor.</param>
        /// <returns></returns>
        public CfanModule Latest(FactorioVersion ksp_version = null, ModDependency relationship = null, bool hasFactorioAuth = false)
        {
            IDictionary <ModVersion, CfanJson> module_version = this.module_version;

            if (!hasFactorioAuth)
            {
                module_version = module_version.Where(p => !CfanJson.requiresFactorioComAuthorization(p.Value)).ToDictionary(p => p.Key, p => p.Value);
            }

            var      available_versions = new List <ModVersion>(module_version.Keys);
            CfanJson module;

            log.DebugFormat("Our dictionary has {0} keys", module_version.Keys.Count);
            log.DebugFormat("Choosing between {0} available versions", available_versions.Count);

            // Uh oh, nothing available. Maybe this existed once, but not any longer.
            if (available_versions.Count == 0)
            {
                return(null);
            }

            // No restrictions? Great, we can just pick the first one!
            if (ksp_version == null && relationship == null)
            {
                module = module_version[available_versions.First()];

                log.DebugFormat("No KSP version restriction, {0} is most recent", module.modInfo.version);
                return(new CfanModule(module));
            }

            // If there's no relationship to satisfy, we can just pick the first that is
            // compatible with our version of KSP.
            if (relationship == null)
            {
                // Time to check if there's anything that we can satisfy.
                var version =
                    available_versions.FirstOrDefault(v => new CfanModule(module_version[v]).IsCompatibleKSP(ksp_version));
                if (version != null)
                {
                    return(new CfanModule(module_version[version]));
                }

                log.DebugFormat("No version of {0} is compatible with KSP {1}",
                                module_version[available_versions[0]].modInfo.name, ksp_version);

                return(null);
            }

            // If we're here, then we have a relationship to satisfy, so things get more complex.
            if (ksp_version == null)
            {
                var version = available_versions.FirstOrDefault(p => relationship.isSatisfiedBy(identifier, p));
                return(version == null ? null : new CfanModule(module_version[version]));
            }
            else
            {
                var version = available_versions.FirstOrDefault(v =>
                                                                relationship.isSatisfiedBy(identifier, v) &&
                                                                new CfanModule(module_version[v]).IsCompatibleKSP(ksp_version));
                return(version == null ? null : new CfanModule(module_version[version]));
            }
        }
Exemplo n.º 14
0
        private async Task AddLocalVersion()
        {
            var  dialog = new VistaFolderBrowserDialog();
            bool?result = dialog.ShowDialog(Window);

            if (result.HasValue && result.Value)
            {
                var     installationDirectory = new DirectoryInfo(dialog.SelectedPath);
                Version version;

                bool is64Bit;
                if (!FactorioVersion.LocalInstallationValid(installationDirectory, out version, out is64Bit))
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("InvalidFactorioFolder", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("InvalidFactorioFolder", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (is64Bit != Environment.Is64BitOperatingSystem)
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("IncompatiblePlatform", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("IncompatiblePlatform", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (FactorioVersions.Any(factorioVersion => factorioVersion.Version == version))
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("FactorioVersionInstalled", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("FactorioVersionInstalled", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }


                var copyOrMoveWindow = new CopyOrMoveMessageWindow()
                {
                    Owner = Window
                };
                ((CopyOrMoveViewModel)copyOrMoveWindow.ViewModel).CopyOrMoveType = CopyOrMoveType.Factorio;
                result = copyOrMoveWindow.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    bool move = copyOrMoveWindow.Move;

                    DirectoryInfo factorioDirectory = App.Instance.Settings.GetFactorioDirectory();
                    if (!factorioDirectory.Exists)
                    {
                        factorioDirectory.Create();
                    }
                    DirectoryInfo destinationDirectory = new DirectoryInfo(Path.Combine(factorioDirectory.FullName, version.ToString(3)));

                    var progressWindow = new ProgressWindow()
                    {
                        Owner = Window
                    };
                    var progressViewModel = (ProgressViewModel)progressWindow.ViewModel;
                    progressViewModel.ActionName          = App.Instance.GetLocalizedResourceString("AddingLocalInstallationAction");
                    progressViewModel.ProgressDescription = move ? App.Instance.GetLocalizedResourceString("MovingFilesDescription") : App.Instance.GetLocalizedResourceString("CopyingFilesDescription");
                    progressViewModel.IsIndeterminate     = true;

                    Task addTask = move
                        ? MoveFactorioInstallationAsync(installationDirectory, destinationDirectory)
                        : CopyFactorioInstallationAsync(installationDirectory, destinationDirectory);

                    Task closeWindowTask = addTask.ContinueWith(t => progressWindow.Dispatcher.Invoke(progressWindow.Close));
                    progressWindow.ShowDialog();

                    await addTask;
                    await closeWindowTask;

                    FactorioVersions.Add(new FactorioVersion(destinationDirectory, version));
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Is the mod installed and does it have a newer version compatible with version
        /// We can't update AD mods
        /// </summary>
        public static bool HasUpdate(this IRegistryQuerier querier, string identifier, FactorioVersion version)
        {
            CfanModule newest_version;

            try
            {
                newest_version = querier.LatestAvailable(identifier, version);
            }
            catch (ModuleNotFoundKraken)
            {
                return(false);
            }
            if (newest_version == null)
            {
                return(false);
            }
            return(!new List <string>(querier.InstalledPreexistingModules).Contains(identifier) && querier.IsInstalled(identifier, false) &&
                   newest_version.modVersion.IsGreaterThan(querier.InstalledVersion(identifier)));
        }
Exemplo n.º 16
0
 public static CfanModule GetModuleByIdentifierAndOptionalVersion(this IRegistryQuerier querier, CfanModuleIdAndVersion moduleIdAndVersion, FactorioVersion factorioVersion)
 {
     if (moduleIdAndVersion.version != null)
     {
         return(GetModuleByVersion(querier, moduleIdAndVersion.identifier, moduleIdAndVersion.version.ToString()));
     }
     else
     {
         return(querier.LatestAvailable(moduleIdAndVersion.identifier, factorioVersion));
     }
 }
Exemplo n.º 17
0
        public void For_WhenGivenStringWithValidMinorVersion_ReturnsCorrectMinorVersion(String factorioVersionString, Int32 minor)
        {
            var factorioVersion = FactorioVersion.For(factorioVersionString);

            Assert.Equal(minor, factorioVersion.Minor);
        }
Exemplo n.º 18
0
        public void For_WhenGivenStringWithNegativeMinorVersion_ThrowsArgumentOutOfRangeException(String factorioVersionString)
        {
            var exception = Assert.Throws <ArgumentOutOfRangeException>(() => FactorioVersion.For(factorioVersionString));

            Assert.Equal($"Unable to parse \"{factorioVersionString}\" into a FactorioVersion - version parts must be positive. (Parameter 'factorioVersionString')", exception.Message);
        }
Exemplo n.º 19
0
        public void For_WhenGivenEmptyStringOrWhitespace_ThrowsArgumentException(String factorioVersionString)
        {
            var exception = Assert.Throws <ArgumentException>(() => FactorioVersion.For(factorioVersionString));

            Assert.Equal($"factorioVersionString may not be empty. (Parameter 'factorioVersionString')", exception.Message);
        }
Exemplo n.º 20
0
        public void For_WhenGivenNull_ThrowsArgumentNullException()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => FactorioVersion.For(null));

            Assert.Equal("factorioVersionString is required. (Parameter 'factorioVersionString')", exception.Message);
        }
Exemplo n.º 21
0
        private async Task AddZippedVersion()
        {
            var dialog = new VistaOpenFileDialog();

            dialog.Filter = App.Instance.GetLocalizedResourceString("ZipDescription") + @" (*.zip)|*.zip";
            bool?result = dialog.ShowDialog(Window);

            if (result.HasValue && result.Value)
            {
                var           archiveFile      = new FileInfo(dialog.FileName);
                Version       version          = null;
                DirectoryInfo versionDirectory = null;

                var progressWindow = new ProgressWindow()
                {
                    Owner = Window
                };
                var progressViewModel = (ProgressViewModel)progressWindow.ViewModel;
                progressViewModel.ActionName          = App.Instance.GetLocalizedResourceString("AddingFromZipAction");
                progressViewModel.ProgressDescription = App.Instance.GetLocalizedResourceString("CheckingValidityDescription");
                progressViewModel.IsIndeterminate     = true;

                bool            invalidArchiveFile = false;
                bool            invalidPlatform    = false;
                bool            versionInstalled   = false;
                IProgress <int> progress           = new Progress <int>(stage =>
                {
                    switch (stage)
                    {
                    case 1:
                        progressViewModel.ProgressDescription = App.Instance.GetLocalizedResourceString("ExtractingDescription");
                        break;

                    case -1:
                        invalidArchiveFile = true;
                        break;

                    case -2:
                        invalidPlatform = true;
                        break;

                    case -3:
                        versionInstalled = true;
                        break;
                    }
                });

                Task extractTask = Task.Run(() =>
                {
                    bool is64Bit;
                    if (FactorioVersion.ArchiveFileValid(archiveFile, out version, out is64Bit))
                    {
                        if (is64Bit == Environment.Is64BitOperatingSystem)
                        {
                            if (FactorioVersions.All(factorioVersion => factorioVersion.Version != version))
                            {
                                progress.Report(1);

                                DirectoryInfo factorioDirectory = App.Instance.Settings.GetFactorioDirectory();
                                ZipFile.ExtractToDirectory(archiveFile.FullName, factorioDirectory.FullName);

                                string versionString = version.ToString(3);
                                versionDirectory     = factorioDirectory.EnumerateDirectories($"Factorio_{versionString}*").First();
                                versionDirectory.MoveTo(Path.Combine(factorioDirectory.FullName, versionString));
                            }
                            else
                            {
                                progress.Report(-3);
                            }
                        }
                        else
                        {
                            progress.Report(-2);
                        }
                    }
                    else
                    {
                        progress.Report(-1);
                    }
                });

                Task closeWindowTask =
                    extractTask.ContinueWith(t => progressWindow.Dispatcher.Invoke(progressWindow.Close));
                progressWindow.ShowDialog();

                await extractTask;
                await closeWindowTask;

                if (invalidArchiveFile)
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("InvalidFactorioArchive", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("InvalidFactorioArchive", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (invalidPlatform)
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("IncompatiblePlatform", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("IncompatiblePlatform", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (versionInstalled)
                {
                    MessageBox.Show(Window,
                                    App.Instance.GetLocalizedMessage("FactorioVersionInstalled", MessageType.Error),
                                    App.Instance.GetLocalizedMessageTitle("FactorioVersionInstalled", MessageType.Error),
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    FactorioVersions.Add(new FactorioVersion(versionDirectory, version));

                    if (MessageBox.Show(Window,
                                        App.Instance.GetLocalizedMessage("DeleteFactorioArchive", MessageType.Question),
                                        App.Instance.GetLocalizedMessageTitle("DeleteFactorioArchive", MessageType.Question),
                                        MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        archiveFile.Delete();
                    }
                }
            }
        }
 public bool ReleaseIsStored(string modName, FactorioVersion version)
 {
     return(File.Exists(Path.Combine(modsPath, ReleaseData.GetFileName(modName, version))));
 }
Exemplo n.º 23
0
        /// <summary>
        /// Starts Factorio if the command line specifies to do so.
        /// </summary>
        /// <param name="commandLine">The programs command line.</param>
        /// <param name="createApp">Specifies whether an app should be created.</param>
        /// <returns>Returns true if the game was started, otherwise false.</returns>
        private static bool StartGameIfSpecified(CommandLine commandLine, bool createApp)
        {
            string versionString;

            if (commandLine.TryGetArgument('f', "factorio-version", out versionString))
            {
                // Variable not used but sets 'Application.Current'.
                App app = null;
                if (createApp)
                {
                    app = CreateApp(commandLine);
                }

                var             versions = FactorioVersion.GetInstalledVersions();
                FactorioVersion steamVersion;
                if (FactorioSteamVersion.TryLoad(out steamVersion))
                {
                    versions.Add(steamVersion);
                }

                FactorioVersion factorioVersion = null;
                if (string.Equals(versionString, FactorioVersion.LatestKey, StringComparison.InvariantCultureIgnoreCase))
                {
                    factorioVersion = versions.MaxBy(item => item.Version, new VersionComparer());
                }
                else
                {
                    factorioVersion = versions.Find(item => string.Equals(item.VersionString, versionString, StringComparison.InvariantCultureIgnoreCase));
                }

                if (factorioVersion != null)
                {
                    var mods     = new List <Mod>();
                    var modpacks = new List <Modpack>();

                    ModManager.BeginUpdateTemplates();
                    Mod.LoadMods(mods, modpacks);
                    ModpackTemplateList.Instance.PopulateModpackList(mods, modpacks, null);

                    mods.ForEach(mod => mod.Active = false);

                    string modpackName;
                    if (commandLine.TryGetArgument('p', "modpack", out modpackName))
                    {
                        Modpack modpack = modpacks.FirstOrDefault(item => item.Name == modpackName);
                        if (modpack != null)
                        {
                            modpack.Active = true;
                        }
                        else
                        {
                            MessageBox.Show(
                                $"No modpack named '{modpackName}' found.\nThe game will be launched without any mods enabled.",
                                "Error loading modpack!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }

                    ModManager.EndUpdateTemplates(true);
                    ModManager.SaveTemplates();

                    Process.Start(factorioVersion.ExecutablePath);
                }
                else
                {
                    MessageBox.Show(
                        $"Factorio version {versionString} is not available.\nCheck your installed Factorio versions.",
                        "Error starting game!", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                return(true);
            }

            return(false);
        }
 public void DiscardRelease(string modName, FactorioVersion version)
 {
     File.Delete(Path.Combine(modsPath, ReleaseData.GetFileName(modName, version)));
     RemoveFromAllStoredReleases(modName, version);
 }
Exemplo n.º 25
0
        private void _UpdateModsList(bool repo_updated)
        {
            log.Debug("Updating the mod list");

            FactorioVersion  version  = CurrentInstance.Version();
            IRegistryQuerier registry = RegistryManager.Instance(CurrentInstance).registry;
            var gui_mods = new HashSet <GUIMod>(registry.Available(version)
                                                .Select(m => new GUIMod(m, registry, version)));

            gui_mods.UnionWith(registry.Incompatible(version)
                               .Select(m => new GUIMod(m, registry, version)));
            var installed = registry.InstalledModules
                            .Select(m => new GUIMod(m.Module, registry, version));

            //Hashset does not define if add/unionwith replaces existing elements.
            //In this case that could cause a CkanModule to be replaced by a Module.
            //Hence the explicit checking
            foreach (var mod in installed.Where(mod => !gui_mods.Contains(mod)))
            {
                gui_mods.Add(mod);
            }
            var old_modules = new HashSet <GUIMod>(mainModList.Modules);

            if (repo_updated)
            {
                foreach (var gui_mod in gui_mods.Where(m => !old_modules.Contains(m)))
                {
                    gui_mod.IsNew = true;
                }
            }
            else
            {
                //Copy the new mod flag from the old list.
                var old_new_mods = new HashSet <GUIMod>(old_modules.Where(m => m.IsNew));
                foreach (var gui_mod in gui_mods.Where(m => old_new_mods.Contains(m)))
                {
                    gui_mod.IsNew = true;
                }
            }

            // Update our mod listing. If we're doing a repo update, then we don't refresh
            // all (in case the user has selected changes they wish to apply).
            mainModList.ConstructModList(gui_mods.ToList(), refreshAll: !repo_updated);
            mainModList.Modules = new ReadOnlyCollection <GUIMod>(
                mainModList.full_list_of_mod_rows.Values.Select(row => row.Tag as GUIMod).ToList());

            //TODO Consider using smart enum patten so stuff like this is easier
            FilterToolButton.DropDownItems[0].Text = String.Format("Compatible ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.Compatible));
            FilterToolButton.DropDownItems[1].Text = String.Format("Installed ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.Installed));
            FilterToolButton.DropDownItems[2].Text = String.Format("Upgradeable ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.InstalledUpdateAvailable));
            FilterToolButton.DropDownItems[3].Text = String.Format("Cached ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.Cached));
            FilterToolButton.DropDownItems[4].Text = String.Format("New in repository ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.NewInRepository));
            FilterToolButton.DropDownItems[5].Text = String.Format("Not installed ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.NotInstalled));
            FilterToolButton.DropDownItems[6].Text = String.Format("Incompatible ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.Incompatible));
            FilterToolButton.DropDownItems[7].Text = String.Format("All ({0})",
                                                                   mainModList.CountModsByFilter(GUIModFilter.All));
            var has_any_updates = gui_mods.Any(mod => mod.HasUpdate);

            UpdateAllToolButton.Enabled = has_any_updates;
            UpdateFilters(this);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Creates a new Relationship resolver.
        /// </summary>
        /// <param name="options"><see cref="RelationshipResolverOptions"/></param>
        /// <param name="registry">The registry to use</param>
        /// <param name="kspversion">The version of the install that the registry corresponds to</param>
        public RelationshipResolver(RelationshipResolverOptions options, IRegistryQuerier registry, FactorioVersion kspversion)
        {
            this.registry   = registry;
            this.kspversion = kspversion;
            this.options    = options;

            installed_modules = new HashSet <CfanModule>(registry.InstalledModules.Select(i_module => i_module.Module));
            var installed_relationship = new SelectionReason.Installed();

            foreach (var module in installed_modules)
            {
                reasons.Add(module, installed_relationship);
            }
        }
Exemplo n.º 27
0
        public static Dictionary <GUIMod, string> ComputeConflictsFromModList(IRegistryQuerier registry,
                                                                              IEnumerable <ModChange> change_set, FactorioVersion ksp_version)
        {
            var modules_to_install = new HashSet <string>();
            var modules_to_remove  = new HashSet <string>();
            var options            = new RelationshipResolverOptions
            {
                without_toomanyprovides_kraken = true,
                procede_with_inconsistencies   = true,
                without_enforce_consistency    = true,
                with_recommends = false
            };

            foreach (var change in change_set)
            {
                switch (change.ChangeType)
                {
                case GUIModChangeType.None:
                    break;

                case GUIModChangeType.Install:
                    modules_to_install.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Remove:
                    modules_to_remove.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Update:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            var installed =
                registry.Installed()
                .Where(pair => pair.Value.CompareTo(new ProvidedVersion("", "0.0.0")) != 0)
                .Select(pair => pair.Key);

            //We wish to only check mods that would exist after the changes are made.
            var mods_to_check =
                installed.Union(modules_to_install).Except(modules_to_remove).Select(p => new CfanModuleIdAndVersion(p));
            var resolver = new RelationshipResolver(mods_to_check.ToList(), options, registry, ksp_version);

            return(resolver.ConflictList.ToDictionary(item => new GUIMod(item.Key, registry, ksp_version),
                                                      item => item.Value));
        }
Exemplo n.º 28
0
 private static List <CfanModule> getModulesFromRegistry(
     IEnumerable <CfanModuleIdAndVersion> module_names, IRegistryQuerier registry, FactorioVersion kspversion)
 {
     return(module_names.Select(
                p =>
     {
         var mod = p.version != null
                     ? registry.GetModuleByVersion(p.identifier, p.version)
                     : registry.LatestAvailable(p.identifier, kspversion);
         if (mod == null)
         {
             throw new ModuleNotFoundKraken(p.identifier, p.version?.ToString(), "Module not found.");
         }
         return mod;
     }).ToList());
 }
Exemplo n.º 29
0
 /// <summary>
 /// Attempts to convert the module_names to ckan modules via  CkanModule.FromIDandVersion and then calls RelationshipResolver.ctor(IEnumerable{CkanModule}, Registry, KSPVersion)"/>
 /// </summary>
 /// <param name="module_names"></param>
 /// <param name="options"></param>
 /// <param name="registry"></param>
 /// <param name="kspversion"></param>
 public RelationshipResolver(IEnumerable <CfanModuleIdAndVersion> module_names, RelationshipResolverOptions options, IRegistryQuerier registry, FactorioVersion kspversion) :
     this(getModulesFromRegistry(module_names, registry, kspversion),
          options,
          registry,
          kspversion)
 {
     // Does nothing, just calls the other overloaded constructor
 }
Exemplo n.º 30
0
 public void CompareTo_WhenProvidedSmallerVersion_ReturnsOne(String left, String right)
 {
     Assert.Equal(1, FactorioVersion.For(left).CompareTo(FactorioVersion.For(right)));
 }