diff --git a/Cmdline/Action/AuthToken.cs b/Cmdline/Action/AuthToken.cs index 4db31ece21..d5bd9ff60c 100644 --- a/Cmdline/Action/AuthToken.cs +++ b/Cmdline/Action/AuthToken.cs @@ -27,7 +27,7 @@ public AuthToken() { } /// /// Exit code /// - public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptions unparsed) + public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions unparsed) { string[] args = unparsed.options.ToArray(); int exitCode = Exit.OK; @@ -41,7 +41,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio user = new ConsoleUser(options.Headless); if (manager == null) { - manager = new KSPManager(user); + manager = new GameInstanceManager(user); } exitCode = options.Handle(manager, user); if (exitCode == Exit.OK) diff --git a/Cmdline/Action/Available.cs b/Cmdline/Action/Available.cs index 2bd76b275f..ae445fe6d9 100644 --- a/Cmdline/Action/Available.cs +++ b/Cmdline/Action/Available.cs @@ -12,7 +12,7 @@ public Available(IUser user) this.user = user; } - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { AvailableOptions opts = (AvailableOptions)raw_options; IRegistryQuerier registry = RegistryManager.Instance(ksp).registry; diff --git a/Cmdline/Action/Cache.cs b/Cmdline/Action/Cache.cs index 77017e6949..5463709664 100644 --- a/Cmdline/Action/Cache.cs +++ b/Cmdline/Action/Cache.cs @@ -83,13 +83,13 @@ private class SetLimitOptions : CommonOptions /// /// Execute a cache subcommand /// - /// KSPManager object containing our instances and cache + /// GameInstanceManager object containing our instances and cache /// Command line options object /// Raw command line options /// /// Exit code for shell environment /// - public int RunSubCommand(KSPManager mgr, CommonOptions opts, SubCommandOptions unparsed) + public int RunSubCommand(GameInstanceManager mgr, CommonOptions opts, SubCommandOptions unparsed) { string[] args = unparsed.options.ToArray(); @@ -103,7 +103,7 @@ public int RunSubCommand(KSPManager mgr, CommonOptions opts, SubCommandOptions u CommonOptions options = (CommonOptions)suboptions; options.Merge(opts); user = new ConsoleUser(options.Headless); - manager = mgr ?? new KSPManager(user); + manager = mgr ?? new GameInstanceManager(user); exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) return; @@ -235,7 +235,7 @@ private void printCacheInfo() user.RaiseMessage($"{fileCount} files, {CkanModule.FmtSize(bytes)}"); } - private KSPManager manager; + private GameInstanceManager manager; private IUser user; private static readonly ILog log = LogManager.GetLogger(typeof(Cache)); diff --git a/Cmdline/Action/Compat.cs b/Cmdline/Action/Compat.cs index 86d54a545c..785b82fe6c 100644 --- a/Cmdline/Action/Compat.cs +++ b/Cmdline/Action/Compat.cs @@ -65,7 +65,7 @@ public class CompatForgetOptions : InstanceSpecificOptions [ValueOption(0)] public string Version { get; set; } } - public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptions options) + public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions options) { var exitCode = Exit.OK; @@ -77,7 +77,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio CommonOptions comOpts = (CommonOptions)suboptions; comOpts.Merge(opts); _user = new ConsoleUser(comOpts.Headless); - _kspManager = manager ?? new KSPManager(_user); + _kspManager = manager ?? new GameInstanceManager(_user); exitCode = comOpts.Handle(_kspManager, _user); if (exitCode != Exit.OK) return; @@ -148,11 +148,11 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio var ksp = MainClass.GetGameInstance(_kspManager); var addOptions = (CompatAddOptions)suboptions; - KspVersion kspVersion; - if (KspVersion.TryParse(addOptions.Version, out kspVersion)) + GameVersion GameVersion; + if (GameVersion.TryParse(addOptions.Version, out GameVersion)) { var newCompatibleVersion = ksp.GetCompatibleVersions(); - newCompatibleVersion.Add(kspVersion); + newCompatibleVersion.Add(GameVersion); ksp.SetCompatibleVersions(newCompatibleVersion); } else @@ -168,13 +168,13 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio var ksp = MainClass.GetGameInstance(_kspManager); var addOptions = (CompatForgetOptions)suboptions; - KspVersion kspVersion; - if (KspVersion.TryParse(addOptions.Version, out kspVersion)) + GameVersion GameVersion; + if (GameVersion.TryParse(addOptions.Version, out GameVersion)) { - if (kspVersion != ksp.Version()) + if (GameVersion != ksp.Version()) { var newCompatibleVersion = ksp.GetCompatibleVersions(); - newCompatibleVersion.RemoveAll(i => i == kspVersion); + newCompatibleVersion.RemoveAll(i => i == GameVersion); ksp.SetCompatibleVersions(newCompatibleVersion); } else @@ -200,7 +200,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio return exitCode; } - private KSPManager _kspManager; + private GameInstanceManager _kspManager; private IUser _user; } } diff --git a/Cmdline/Action/KSP.cs b/Cmdline/Action/GameInstance.cs similarity index 83% rename from Cmdline/Action/KSP.cs rename to Cmdline/Action/GameInstance.cs index 6ccb23bfa3..5112d76a50 100644 --- a/Cmdline/Action/KSP.cs +++ b/Cmdline/Action/GameInstance.cs @@ -2,39 +2,40 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using CKAN.Versioning; using CommandLine; using CommandLine.Text; using log4net; +using CKAN.Versioning; +using CKAN.Games; namespace CKAN.CmdLine { - public class KSP : ISubCommand + public class GameInstance : ISubCommand { - public KSP() { } - protected static readonly ILog log = LogManager.GetLogger(typeof(KSP)); + public GameInstance() { } + protected static readonly ILog log = LogManager.GetLogger(typeof(GameInstance)); - internal class KSPSubOptions : VerbCommandOptions + internal class InstanceSubOptions : VerbCommandOptions { - [VerbOption("list", HelpText = "List KSP installs")] + [VerbOption("list", HelpText = "List game instances")] public CommonOptions ListOptions { get; set; } - [VerbOption("add", HelpText = "Add a KSP install")] + [VerbOption("add", HelpText = "Add a game instance")] public AddOptions AddOptions { get; set; } - [VerbOption("clone", HelpText = "Clone an existing KSP install")] + [VerbOption("clone", HelpText = "Clone an existing game instance")] public CloneOptions CloneOptions { get; set; } - [VerbOption("rename", HelpText = "Rename a KSP install")] + [VerbOption("rename", HelpText = "Rename a game instance")] public RenameOptions RenameOptions { get; set; } - [VerbOption("forget", HelpText = "Forget a KSP install")] + [VerbOption("forget", HelpText = "Forget a game instance")] public ForgetOptions ForgetOptions { get; set; } - [VerbOption("default", HelpText = "Set the default KSP install")] + [VerbOption("default", HelpText = "Set the default game instance")] public DefaultOptions DefaultOptions { get; set; } - [VerbOption("fake", HelpText = "Fake a KSP install")] + [VerbOption("fake", HelpText = "Fake a game instance")] public FakeOptions FakeOptions { get; set; } [HelpVerbOption] @@ -45,29 +46,29 @@ public string GetUsage(string verb) ht.AddPreOptionsLine(" "); if (string.IsNullOrEmpty(verb)) { - ht.AddPreOptionsLine("ckan ksp - Manage KSP installs"); - ht.AddPreOptionsLine($"Usage: ckan ksp [options]"); + ht.AddPreOptionsLine("ckan instance - Manage game instances"); + ht.AddPreOptionsLine($"Usage: ckan instance [options]"); } else { - ht.AddPreOptionsLine("ksp " + verb + " - " + GetDescription(verb)); + ht.AddPreOptionsLine("instance " + verb + " - " + GetDescription(verb)); switch (verb) { // First the commands with three string arguments case "fake": - ht.AddPreOptionsLine($"Usage: ckan ksp {verb} [options] name path version [--MakingHistory ] [--BreakingGround ]"); + ht.AddPreOptionsLine($"Usage: ckan instance {verb} [options] name path version [--MakingHistory ] [--BreakingGround ]"); break; case "clone": - ht.AddPreOptionsLine($"Usage: ckan ksp {verb} [options] instanceNameOrPath newname newpath"); + ht.AddPreOptionsLine($"Usage: ckan instance {verb} [options] instanceNameOrPath newname newpath"); break; // Second the commands with two string arguments case "add": - ht.AddPreOptionsLine($"Usage: ckan ksp {verb} [options] name url"); + ht.AddPreOptionsLine($"Usage: ckan instance {verb} [options] name url"); break; case "rename": - ht.AddPreOptionsLine($"Usage: ckan ksp {verb} [options] oldname newname"); + ht.AddPreOptionsLine($"Usage: ckan instance {verb} [options] oldname newname"); break; // Now the commands with one string argument @@ -75,13 +76,13 @@ public string GetUsage(string verb) case "forget": case "use": case "default": - ht.AddPreOptionsLine($"Usage: ckan ksp {verb} [options] name"); + ht.AddPreOptionsLine($"Usage: ckan instance {verb} [options] name"); break; // Now the commands with only --flag type options case "list": default: - ht.AddPreOptionsLine($"Usage: ckan ksp {verb} [options]"); + ht.AddPreOptionsLine($"Usage: ckan instance {verb} [options]"); break; } @@ -135,7 +136,7 @@ internal class FakeOptions : CommonOptions } // This is required by ISubCommand - public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptions unparsed) + public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions unparsed) { string[] args = unparsed.options.ToArray(); @@ -158,7 +159,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio int exitCode = Exit.OK; // Parse and process our sub-verbs - Parser.Default.ParseArgumentsStrict(args, new KSPSubOptions(), (string option, object suboptions) => + Parser.Default.ParseArgumentsStrict(args, new InstanceSubOptions(), (string option, object suboptions) => { // ParseArgumentsStrict calls us unconditionally, even with bad arguments if (!string.IsNullOrEmpty(option) && suboptions != null) @@ -166,7 +167,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio CommonOptions options = (CommonOptions)suboptions; options.Merge(opts); User = new ConsoleUser(options.Headless); - Manager = manager ?? new KSPManager(User); + Manager = manager ?? new GameInstanceManager(User); exitCode = options.Handle(Manager, User); if (exitCode != Exit.OK) return; @@ -199,11 +200,11 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio break; case "fake": - exitCode = FakeNewKSPInstall((FakeOptions)suboptions); + exitCode = FakeNewGameInstance((FakeOptions)suboptions); break; default: - User.RaiseMessage("Unknown command: ksp {0}", option); + User.RaiseMessage("Unknown command: instance {0}", option); exitCode = Exit.BADOPT; break; } @@ -212,7 +213,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio return exitCode; } - private KSPManager Manager { get; set; } + private GameInstanceManager Manager { get; set; } private IUser User { get; set; } #region option functions @@ -221,7 +222,7 @@ private int ListInstalls() { var output = Manager.Instances .OrderByDescending(i => i.Value.Name == Manager.AutoStartInstance) - .ThenByDescending(i => i.Value.Version() ?? KspVersion.Any) + .ThenByDescending(i => i.Value.Version() ?? GameVersion.Any) .ThenBy(i => i.Key) .Select(i => new { @@ -288,13 +289,13 @@ private int AddInstall(AddOptions options) try { string path = options.path; - Manager.AddInstance(new CKAN.KSP(path, options.name, User)); + Manager.AddInstance(path, options.name, User); User.RaiseMessage("Added \"{0}\" with root \"{1}\" to known installs", options.name, options.path); return Exit.OK; } catch (NotKSPDirKraken ex) { - User.RaiseMessage("Sorry, {0} does not appear to be a KSP directory", ex.path); + User.RaiseMessage("Sorry, {0} does not appear to be a game instance", ex.path); return Exit.BADOPT; } } @@ -303,7 +304,7 @@ private int CloneInstall(CloneOptions options) { if (options.nameOrPath == null || options.new_name == null || options.new_path == null) { - User.RaiseMessage("ksp clone - argument(s) missing"); + User.RaiseMessage("instance clone - argument(s) missing"); return Exit.BADOPT; } @@ -313,15 +314,15 @@ private int CloneInstall(CloneOptions options) string newPath = options.new_path; - log.Info("Cloning the KSP instance: " + options.nameOrPath); + log.Info("Cloning the game instance: " + options.nameOrPath); try { // Try instanceNameOrPath as name and search the registry for it. if (Manager.HasInstance(instanceNameOrPath)) { - CKAN.KSP[] listOfInstances = Manager.Instances.Values.ToArray(); - foreach (CKAN.KSP instance in listOfInstances) + CKAN.GameInstance[] listOfInstances = Manager.Instances.Values.ToArray(); + foreach (CKAN.GameInstance instance in listOfInstances) { if (instance.Name == instanceNameOrPath) { @@ -331,12 +332,11 @@ private int CloneInstall(CloneOptions options) } } } - // Try to use instanceNameOrPath as a path and create a new KSP object. + // Try to use instanceNameOrPath as a path and create a new game instance. // If it's valid, go on. - else if (new CKAN.KSP(instanceNameOrPath, newName, User) is CKAN.KSP instance && instance.Valid) + else if (Manager.InstanceAt(instanceNameOrPath, newName) is CKAN.GameInstance instance && instance.Valid) { Manager.CloneInstance(instance, newName, newPath); - } // There is no instance with this name or at this path. else @@ -347,7 +347,7 @@ private int CloneInstall(CloneOptions options) catch (NotKSPDirKraken kraken) { // Two possible reasons: - // First: The instance to clone is not a valid KSP instance. + // First: The instance to clone is not a valid game instance. // Only occurs if user manipulated directory and deleted files/folders // which CKAN searches for in validity test. @@ -392,7 +392,7 @@ private int CloneInstall(CloneOptions options) else { User.RaiseMessage("Something went wrong. Please look if the new directory has been created.\n", - "Try to add the new instance manually with \"ckan ksp add\".\n"); + "Try to add the new instance manually with \"ckan instance add\".\n"); return Exit.ERROR; } } @@ -502,19 +502,19 @@ private int SetDefaultInstall(DefaultOptions options) } catch (NotKSPDirKraken k) { - User.RaiseMessage("Sorry, {0} does not appear to be a KSP directory", k.path); + User.RaiseMessage("Sorry, {0} does not appear to be a game instance", k.path); return Exit.BADOPT; } - User.RaiseMessage("Successfully set \"{0}\" as the default KSP installation", name); + User.RaiseMessage("Successfully set \"{0}\" as the default game instance", name); return Exit.OK; } /// - /// Creates a new fake KSP install after the conditions CKAN tests for valid install directories. + /// Creates a new fake game instance after the conditions CKAN tests for valid install directories. /// Used for developing and testing purposes. /// - private int FakeNewKSPInstall (FakeOptions options) + private int FakeNewGameInstance(FakeOptions options) { int error() { @@ -533,7 +533,7 @@ int badArgument() if (options.name == null || options.path == null || options.version == null) { - User.RaiseMessage("ksp fake " + + User.RaiseMessage("instance fake " + "[--MakingHistory ] [--BreakingGround ] - argument(s) missing"); return badArgument(); } @@ -542,14 +542,14 @@ int badArgument() // Parse all options string installName = options.name; string path = options.path; - KspVersion version; + GameVersion version; bool setDefault = options.setDefault; // options.Version is "none" if the DLC should not be simulated. - Dictionary dlcs = new Dictionary(); + Dictionary dlcs = new Dictionary(); if (options.makingHistoryVersion != null && options.makingHistoryVersion.ToLower() != "none") { - if (KspVersion.TryParse(options.makingHistoryVersion, out KspVersion ver)) + if (GameVersion.TryParse(options.makingHistoryVersion, out GameVersion ver)) { dlcs.Add(new DLC.MakingHistoryDlcDetector(), ver); } @@ -561,7 +561,7 @@ int badArgument() } if (options.breakingGroundVersion != null && options.breakingGroundVersion.ToLower() != "none") { - if (KspVersion.TryParse(options.breakingGroundVersion, out KspVersion ver)) + if (GameVersion.TryParse(options.breakingGroundVersion, out GameVersion ver)) { dlcs.Add(new DLC.BreakingGroundDlcDetector(), ver); } @@ -572,10 +572,10 @@ int badArgument() } } - // Parse the choosen KSP version + // Parse the choosen game version try { - version = KspVersion.Parse(options.version); + version = GameVersion.Parse(options.version); } catch (FormatException) { @@ -587,27 +587,27 @@ int badArgument() // Get the full version including build number. try { - version = version.RaiseVersionSelectionDialog(User); + version = version.RaiseVersionSelectionDialog(new KerbalSpaceProgram(), User); } - catch (BadKSPVersionKraken) + catch (BadGameVersionKraken) { - User.RaiseError("Couldn't find a valid KSP version for your input.\n" + + User.RaiseError("Couldn't find a valid game version for your input.\n" + "Make sure to enter the at least the version major and minor values in the form Maj.Min - e.g. 1.5"); return badArgument(); } catch (CancelledActionKraken) { - User.RaiseError("Selection cancelled! Please call 'ckan ksp fake' again."); + User.RaiseError("Selection cancelled! Please call 'ckan instance fake' again."); return error(); } - User.RaiseMessage(String.Format("Creating new fake KSP install {0} at {1} with version {2}", installName, path, version.ToString())); + User.RaiseMessage(String.Format("Creating new fake game instance {0} at {1} with version {2}", installName, path, version.ToString())); log.Debug("Faking instance..."); try { - // Pass all arguments to CKAN.KSPManager.FakeInstance() and create a new one. - Manager.FakeInstance(installName, path, version, dlcs); + // Pass all arguments to CKAN.GameInstanceManager.FakeInstance() and create a new one. + Manager.FakeInstance(new KerbalSpaceProgram(), installName, path, version, dlcs); if (setDefault) { User.RaiseMessage("Setting new instance to default..."); @@ -625,9 +625,9 @@ int badArgument() User.RaiseError(kraken.Message); return badArgument(); } - catch (WrongKSPVersionKraken kraken) + catch (WrongGameVersionKraken kraken) { - // Thrown because the specified KSP version is too old for one of the selected DLCs. + // Thrown because the specified game instance is too old for one of the selected DLCs. User.RaiseError(kraken.Message); return badArgument(); } @@ -654,7 +654,7 @@ int badArgument() } else { - User.RaiseError("Something went wrong. Try to add the instance yourself with \"ckan ksp add\".", + User.RaiseError("Something went wrong. Try to add the instance yourself with \"ckan instance add\".", "Also look if the new directory has been created."); return error(); } diff --git a/Cmdline/Action/ICommand.cs b/Cmdline/Action/ICommand.cs index 207617ab64..85ba382baa 100644 --- a/Cmdline/Action/ICommand.cs +++ b/Cmdline/Action/ICommand.cs @@ -2,6 +2,6 @@ { public interface ICommand { - int RunCommand(CKAN.KSP ksp, object options); + int RunCommand(CKAN.GameInstance ksp, object options); } } diff --git a/Cmdline/Action/ISubCommand.cs b/Cmdline/Action/ISubCommand.cs index 27db3e41bc..409f49dbee 100644 --- a/Cmdline/Action/ISubCommand.cs +++ b/Cmdline/Action/ISubCommand.cs @@ -2,6 +2,6 @@ { internal interface ISubCommand { - int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptions options); + int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions options); } } diff --git a/Cmdline/Action/Import.cs b/Cmdline/Action/Import.cs index a6fe28eec7..fe09292c77 100644 --- a/Cmdline/Action/Import.cs +++ b/Cmdline/Action/Import.cs @@ -17,7 +17,7 @@ public class Import : ICommand /// Initialize the command /// /// IUser object for user interaction - public Import(KSPManager mgr, IUser user) + public Import(GameInstanceManager mgr, IUser user) { manager = mgr; this.user = user; @@ -31,7 +31,7 @@ public Import(KSPManager mgr, IUser user) /// /// Process exit code /// - public int RunCommand(CKAN.KSP ksp, object options) + public int RunCommand(CKAN.GameInstance ksp, object options) { try { @@ -104,7 +104,7 @@ private void AddFile(HashSet files, string filename) } } - private readonly KSPManager manager; + private readonly GameInstanceManager manager; private readonly IUser user; private static readonly ILog log = LogManager.GetLogger(typeof(Import)); } diff --git a/Cmdline/Action/Install.cs b/Cmdline/Action/Install.cs index ef89882743..7c4eaaf93c 100644 --- a/Cmdline/Action/Install.cs +++ b/Cmdline/Action/Install.cs @@ -11,14 +11,14 @@ public class Install : ICommand private static readonly ILog log = LogManager.GetLogger(typeof(Install)); public IUser user { get; set; } - private KSPManager manager; + private GameInstanceManager manager; /// /// Initialize the install command object /// - /// KSPManager containing our instances + /// GameInstanceManager containing our instances /// IUser object for interaction - public Install(KSPManager mgr, IUser user) + public Install(GameInstanceManager mgr, IUser user) { manager = mgr; this.user = user; @@ -32,7 +32,7 @@ public Install(KSPManager mgr, IUser user) /// /// Exit code for shell environment /// - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { InstallOptions options = (InstallOptions) raw_options; diff --git a/Cmdline/Action/List.cs b/Cmdline/Action/List.cs index 871f71cab9..04b0220202 100644 --- a/Cmdline/Action/List.cs +++ b/Cmdline/Action/List.cs @@ -18,7 +18,7 @@ public List(IUser user) this.user = user; } - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { ListOptions options = (ListOptions) raw_options; diff --git a/Cmdline/Action/Mark.cs b/Cmdline/Action/Mark.cs index fb52af08bf..777f73aeb5 100644 --- a/Cmdline/Action/Mark.cs +++ b/Cmdline/Action/Mark.cs @@ -25,7 +25,7 @@ public Mark() { } /// /// Exit code /// - public int RunSubCommand(KSPManager mgr, CommonOptions opts, SubCommandOptions unparsed) + public int RunSubCommand(GameInstanceManager mgr, CommonOptions opts, SubCommandOptions unparsed) { string[] args = unparsed.options.ToArray(); int exitCode = Exit.OK; @@ -38,7 +38,7 @@ public int RunSubCommand(KSPManager mgr, CommonOptions opts, SubCommandOptions u CommonOptions options = (CommonOptions)suboptions; options.Merge(opts); user = new ConsoleUser(options.Headless); - manager = mgr ?? new KSPManager(user); + manager = mgr ?? new GameInstanceManager(user); exitCode = options.Handle(manager, user); if (exitCode != Exit.OK) return; @@ -115,7 +115,7 @@ private int MarkAuto(MarkAutoOptions opts, bool value, string verb, string descr return Exit.OK; } - private KSPManager manager { get; set; } + private GameInstanceManager manager { get; set; } private IUser user { get; set; } private static readonly ILog log = LogManager.GetLogger(typeof(Mark)); diff --git a/Cmdline/Action/Prompt.cs b/Cmdline/Action/Prompt.cs index 336fcc7f12..c8d756b7bf 100644 --- a/Cmdline/Action/Prompt.cs +++ b/Cmdline/Action/Prompt.cs @@ -10,7 +10,7 @@ public class Prompt { public Prompt() { } - public int RunCommand(KSPManager manager, object raw_options) + public int RunCommand(GameInstanceManager manager, object raw_options) { CommonOptions opts = raw_options as CommonOptions; bool done = false; @@ -21,7 +21,7 @@ public int RunCommand(KSPManager manager, object raw_options) { Console.Write( manager.CurrentInstance != null - ? $"CKAN {Meta.GetVersion()}: KSP {manager.CurrentInstance.Version()} ({manager.CurrentInstance.Name})> " + ? $"CKAN {Meta.GetVersion()}: {manager.CurrentInstance.game.ShortName} {manager.CurrentInstance.Version()} ({manager.CurrentInstance.Name})> " : $"CKAN {Meta.GetVersion()}> " ); } @@ -34,7 +34,7 @@ public int RunCommand(KSPManager manager, object raw_options) else if (command != "") { // Parse input as if it was a normal command line, - // but with a persistent KSPManager object. + // but with a persistent GameInstanceManager object. int cmdExitCode = MainClass.Execute(manager, opts, command.Split(' ')); if ((opts?.Headless ?? false) && cmdExitCode != Exit.OK) { diff --git a/Cmdline/Action/Remove.cs b/Cmdline/Action/Remove.cs index 538de1484f..687f5c8b67 100644 --- a/Cmdline/Action/Remove.cs +++ b/Cmdline/Action/Remove.cs @@ -11,14 +11,14 @@ public class Remove : ICommand private static readonly ILog log = LogManager.GetLogger(typeof(Remove)); public IUser user { get; set; } - private KSPManager manager; + private GameInstanceManager manager; /// /// Initialize the remove command object /// - /// KSPManager containing our instances + /// GameInstanceManager containing our instances /// IUser object for interaction - public Remove(KSPManager mgr, IUser user) + public Remove(GameInstanceManager mgr, IUser user) { manager = mgr; this.user = user; @@ -32,7 +32,7 @@ public Remove(KSPManager mgr, IUser user) /// /// Exit code for shell environment /// - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { RemoveOptions options = (RemoveOptions) raw_options; RegistryManager regMgr = RegistryManager.Instance(ksp); diff --git a/Cmdline/Action/Repair.cs b/Cmdline/Action/Repair.cs index 131cd7ccd1..fa8eeeb4c7 100644 --- a/Cmdline/Action/Repair.cs +++ b/Cmdline/Action/Repair.cs @@ -39,7 +39,7 @@ public string GetUsage(string verb) } } - public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptions unparsed) + public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions unparsed) { int exitCode = Exit.OK; // Parse and process our sub-verbs @@ -53,7 +53,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio User = new ConsoleUser(options.Headless); if (manager == null) { - manager = new KSPManager(User); + manager = new GameInstanceManager(User); } exitCode = options.Handle(manager, User); if (exitCode != Exit.OK) @@ -80,7 +80,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio /// /// Try to repair our registry. /// - private int Registry(CKAN.KSP ksp) + private int Registry(CKAN.GameInstance ksp) { RegistryManager manager = RegistryManager.Instance(ksp); manager.registry.Repair(); diff --git a/Cmdline/Action/Replace.cs b/Cmdline/Action/Replace.cs index 2ba02314a5..1c4fe6af23 100644 --- a/Cmdline/Action/Replace.cs +++ b/Cmdline/Action/Replace.cs @@ -12,15 +12,15 @@ public class Replace : ICommand public IUser User { get; set; } - public Replace(CKAN.KSPManager mgr, IUser user) + public Replace(CKAN.GameInstanceManager mgr, IUser user) { manager = mgr; User = user; } - private KSPManager manager; + private GameInstanceManager manager; - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { ReplaceOptions options = (ReplaceOptions) raw_options; diff --git a/Cmdline/Action/Repo.cs b/Cmdline/Action/Repo.cs index 3e510e01d6..a3b4b2b545 100644 --- a/Cmdline/Action/Repo.cs +++ b/Cmdline/Action/Repo.cs @@ -91,7 +91,7 @@ internal class ForgetOptions : InstanceSpecificOptions } // This is required by ISubCommand - public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptions unparsed) + public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions unparsed) { string[] args = unparsed.options.ToArray(); @@ -120,7 +120,7 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio CommonOptions options = (CommonOptions)suboptions; options.Merge(opts); User = new ConsoleUser(options.Headless); - Manager = manager ?? new KSPManager(User); + Manager = manager ?? new GameInstanceManager(User); exitCode = options.Handle(Manager, User); if (exitCode != Exit.OK) return; @@ -158,11 +158,11 @@ public int RunSubCommand(KSPManager manager, CommonOptions opts, SubCommandOptio return exitCode; } - private static RepositoryList FetchMasterRepositoryList(Uri master_uri = null) + private RepositoryList FetchMasterRepositoryList(Uri master_uri = null) { if (master_uri == null) { - master_uri = Repository.default_repo_master_list; + master_uri = MainClass.GetGameInstance(Manager).game.RepositoryListURL; } string json = Net.DownloadText(master_uri); @@ -180,7 +180,7 @@ private int AvailableRepositories() } catch { - User.RaiseError("Couldn't fetch CKAN repositories master list from {0}", Repository.default_repo_master_list.ToString()); + User.RaiseError("Couldn't fetch CKAN repositories master list from {0}", MainClass.GetGameInstance(Manager).game.RepositoryListURL.ToString()); return Exit.ERROR; } @@ -238,7 +238,7 @@ private int AddRepository(AddOptions options) } catch { - User.RaiseError("Couldn't fetch CKAN repositories master list from {0}", Repository.default_repo_master_list.ToString()); + User.RaiseError("Couldn't fetch CKAN repositories master list from {0}", Manager.CurrentInstance.game.RepositoryListURL.ToString()); return Exit.ERROR; } @@ -322,12 +322,13 @@ private int DefaultRepository(DefaultOptions options) log.DebugFormat("About to add repository '{0}' - '{1}'", Repository.default_ckan_repo_name, options.uri); SortedDictionary repositories = manager.registry.Repositories; - if (repositories.ContainsKey (Repository.default_ckan_repo_name)) + if (repositories.ContainsKey(Repository.default_ckan_repo_name)) { - repositories.Remove (Repository.default_ckan_repo_name); + repositories.Remove(Repository.default_ckan_repo_name); } - repositories.Add(Repository.default_ckan_repo_name, new Repository(Repository.default_ckan_repo_name, Repository.default_ckan_repo_uri)); + repositories.Add(Repository.default_ckan_repo_name, new Repository( + Repository.default_ckan_repo_name, options.uri)); User.RaiseMessage("Set {0} repository to '{1}'", Repository.default_ckan_repo_name, options.uri); manager.Save(); @@ -335,8 +336,8 @@ private int DefaultRepository(DefaultOptions options) return Exit.OK; } - private KSPManager Manager { get; set; } - private IUser User { get; set; } + private GameInstanceManager Manager { get; set; } + private IUser User { get; set; } private static readonly ILog log = LogManager.GetLogger(typeof (Repo)); } diff --git a/Cmdline/Action/Search.cs b/Cmdline/Action/Search.cs index 0ee8791f73..4064480f01 100644 --- a/Cmdline/Action/Search.cs +++ b/Cmdline/Action/Search.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; +using CKAN.Games; namespace CKAN.CmdLine { @@ -14,7 +15,7 @@ public Search(IUser user) this.user = user; } - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { SearchOptions options = (SearchOptions)raw_options; @@ -88,12 +89,12 @@ public int RunCommand(CKAN.KSP ksp, object raw_options) foreach (CkanModule mod in matching_incompatible) { Registry.GetMinMaxVersions(new List { mod } , out _, out _, out var minKsp, out var maxKsp); - string kspVersion = Versioning.KspVersionRange.VersionSpan(minKsp, maxKsp).ToString(); + string GameVersion = Versioning.GameVersionRange.VersionSpan(ksp.game, minKsp, maxKsp).ToString(); user.RaiseMessage("* {0} ({1} - {2}) - {3} by {4} - {5}", mod.identifier, mod.version, - kspVersion, + GameVersion, mod.name, mod.author == null ? "N/A" : String.Join(", ", mod.author), mod.@abstract); @@ -121,7 +122,7 @@ public int RunCommand(CKAN.KSP ksp, object raw_options) /// List of matching modules. /// The KSP instance to perform the search for. /// The search term. Case insensitive. - public List PerformSearch(CKAN.KSP ksp, string term, string author = null, bool searchIncompatible = false) + public List PerformSearch(CKAN.GameInstance ksp, string term, string author = null, bool searchIncompatible = false) { // Remove spaces and special characters from the search term. term = String.IsNullOrWhiteSpace(term) ? string.Empty : CkanModule.nonAlphaNums.Replace(term, ""); @@ -182,7 +183,7 @@ private static string CaseInsensitiveExactMatch(List mods, string mo /// /// Game instance forgetting the mods /// List of strings to convert, format 'identifier' or 'identifier=version' - public static void AdjustModulesCase(CKAN.KSP ksp, List modules) + public static void AdjustModulesCase(CKAN.GameInstance ksp, List modules) { IRegistryQuerier registry = RegistryManager.Instance(ksp).registry; // Get the list of all compatible and incompatible mods diff --git a/Cmdline/Action/Show.cs b/Cmdline/Action/Show.cs index fda6dd4c66..e7c55d6ec9 100644 --- a/Cmdline/Action/Show.cs +++ b/Cmdline/Action/Show.cs @@ -14,7 +14,7 @@ public Show(IUser user) this.user = user; } - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { ShowOptions options = (ShowOptions) raw_options; diff --git a/Cmdline/Action/Update.cs b/Cmdline/Action/Update.cs index e4f7d66f71..42fdaf51bd 100644 --- a/Cmdline/Action/Update.cs +++ b/Cmdline/Action/Update.cs @@ -6,14 +6,14 @@ namespace CKAN.CmdLine public class Update : ICommand { public IUser user { get; set; } - private KSPManager manager; + private GameInstanceManager manager; /// /// Initialize the update command object /// - /// KSPManager containing our instances + /// GameInstanceManager containing our instances /// IUser object for interaction - public Update(KSPManager mgr, IUser user) + public Update(GameInstanceManager mgr, IUser user) { manager = mgr; this.user = user; @@ -27,7 +27,7 @@ public Update(KSPManager mgr, IUser user) /// /// Exit code for shell environment /// - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { UpdateOptions options = (UpdateOptions) raw_options; @@ -143,7 +143,7 @@ private void PrintModules(string message, IEnumerable modules) /// /// The KSP instance to work on. /// Repository to update. If null all repositories are used. - private void UpdateRepository(CKAN.KSP ksp, string repository = null) + private void UpdateRepository(CKAN.GameInstance ksp, string repository = null) { RegistryManager registry_manager = RegistryManager.Instance(ksp); diff --git a/Cmdline/Action/Upgrade.cs b/Cmdline/Action/Upgrade.cs index 8e1d329b11..f502afbb0a 100644 --- a/Cmdline/Action/Upgrade.cs +++ b/Cmdline/Action/Upgrade.cs @@ -11,14 +11,14 @@ public class Upgrade : ICommand private static readonly ILog log = LogManager.GetLogger(typeof(Upgrade)); public IUser User { get; set; } - private KSPManager manager; + private GameInstanceManager manager; /// /// Initialize the upgrade command object /// - /// KSPManager containing our instances + /// GameInstanceManager containing our instances /// IUser object for interaction - public Upgrade(KSPManager mgr, IUser user) + public Upgrade(GameInstanceManager mgr, IUser user) { manager = mgr; User = user; @@ -32,7 +32,7 @@ public Upgrade(KSPManager mgr, IUser user) /// /// Exit code for shell environment /// - public int RunCommand(CKAN.KSP ksp, object raw_options) + public int RunCommand(CKAN.GameInstance ksp, object raw_options) { UpgradeOptions options = (UpgradeOptions) raw_options; diff --git a/Cmdline/CKAN-cmdline.csproj b/Cmdline/CKAN-cmdline.csproj index b5bd86ceea..d12b9d0851 100644 --- a/Cmdline/CKAN-cmdline.csproj +++ b/Cmdline/CKAN-cmdline.csproj @@ -62,7 +62,7 @@ - + diff --git a/Cmdline/Main.cs b/Cmdline/Main.cs index 31c3e065c7..3b54d1feea 100644 --- a/Cmdline/Main.cs +++ b/Cmdline/Main.cs @@ -65,7 +65,7 @@ public static int Main(string[] args) } } - public static int Execute(KSPManager manager, CommonOptions opts, string[] args) + public static int Execute(GameInstanceManager manager, CommonOptions opts, string[] args) { // We shouldn't instantiate Options if it's a subcommand. // It breaks command-specific help, for starters. @@ -76,8 +76,8 @@ public static int Execute(KSPManager manager, CommonOptions opts, string[] args) case "repair": return (new Repair()).RunSubCommand(manager, opts, new SubCommandOptions(args)); - case "ksp": - return (new KSP()).RunSubCommand(manager, opts, new SubCommandOptions(args)); + case "instance": + return (new GameInstance()).RunSubCommand(manager, opts, new SubCommandOptions(args)); case "compat": return (new Compat()).RunSubCommand(manager, opts, new SubCommandOptions(args)); @@ -124,7 +124,7 @@ public static int Execute(KSPManager manager, CommonOptions opts, string[] args) IUser user = new ConsoleUser(options.Headless); if (manager == null) { - manager = new KSPManager(user); + manager = new GameInstanceManager(user); } else { @@ -152,22 +152,22 @@ public static int AfterHelp() return Exit.BADOPT; } - public static CKAN.KSP GetGameInstance(KSPManager manager) + public static CKAN.GameInstance GetGameInstance(GameInstanceManager manager) { - CKAN.KSP ksp = manager.CurrentInstance + CKAN.GameInstance inst = manager.CurrentInstance ?? manager.GetPreferredInstance(); - if (ksp == null) + if (inst == null) { throw new NoGameInstanceKraken(); } - return ksp; + return inst; } /// /// Run whatever action the user has provided /// /// The exit status that should be returned to the system. - private static int RunSimpleAction(Options cmdline, CommonOptions options, string[] args, IUser user, KSPManager manager) + private static int RunSimpleAction(Options cmdline, CommonOptions options, string[] args, IUser user, GameInstanceManager manager) { try { @@ -244,7 +244,7 @@ private static int RunSimpleAction(Options cmdline, CommonOptions options, strin } } - internal static CkanModule LoadCkanFromFile(CKAN.KSP current_instance, string ckan_file) + internal static CkanModule LoadCkanFromFile(CKAN.GameInstance current_instance, string ckan_file) { CkanModule module = CkanModule.FromFile(ckan_file); @@ -262,12 +262,12 @@ internal static CkanModule LoadCkanFromFile(CKAN.KSP current_instance, string ck private static int printMissingInstanceError(IUser user) { - user.RaiseMessage("I don't know where KSP is installed."); - user.RaiseMessage("Use 'ckan ksp help' for assistance in setting this."); + user.RaiseMessage("I don't know where a game instance is installed."); + user.RaiseMessage("Use 'ckan instance help' for assistance in setting this."); return Exit.ERROR; } - private static int Gui(KSPManager manager, GuiOptions options, string[] args) + private static int Gui(GameInstanceManager manager, GuiOptions options, string[] args) { // TODO: Sometimes when the GUI exits, we get a System.ArgumentException, // but trying to catch it here doesn't seem to help. Dunno why. @@ -277,7 +277,7 @@ private static int Gui(KSPManager manager, GuiOptions options, string[] args) return Exit.OK; } - private static int ConsoleUi(KSPManager manager, CommonOptions opts, string[] args) + private static int ConsoleUi(GameInstanceManager manager, CommonOptions opts, string[] args) { // Debug/verbose output just messes up the screen LogManager.GetRepository().Threshold = Level.Warn; @@ -292,17 +292,17 @@ private static int Version(IUser user) } /// - /// Scans the ksp instance. Detects installed mods to mark as auto-detected and checks the consistency + /// Scans the game instance. Detects installed mods to mark as auto-detected and checks the consistency /// - /// The instance to scan + /// The instance to scan /// /// Changes the output message if set. /// Exit.OK if instance is consistent, Exit.ERROR otherwise - private static int Scan(CKAN.KSP ksp_instance, IUser user, string next_command = null) + private static int Scan(CKAN.GameInstance inst, IUser user, string next_command = null) { try { - ksp_instance.ScanGameData(); + inst.Scan(); return Exit.OK; } catch (InconsistentKraken kraken) diff --git a/Cmdline/Options.cs b/Cmdline/Options.cs index a7f0fd336a..821d018c71 100644 --- a/Cmdline/Options.cs +++ b/Cmdline/Options.cs @@ -64,7 +64,7 @@ internal class Actions : VerbCommandOptions [VerbOption("available", HelpText = "List available mods")] public AvailableOptions Available { get; set; } - [VerbOption("install", HelpText = "Install a KSP mod")] + [VerbOption("install", HelpText = "Install a mod")] public InstallOptions Install { get; set; } [VerbOption("remove", HelpText = "Remove an installed mod")] @@ -73,7 +73,7 @@ internal class Actions : VerbCommandOptions [VerbOption("import", HelpText = "Import manually downloaded mods")] public ImportOptions Import { get; set; } - [VerbOption("scan", HelpText = "Scan for manually installed KSP mods")] + [VerbOption("scan", HelpText = "Scan for manually installed mods")] public ScanOptions Scan { get; set; } [VerbOption("list", HelpText = "List installed modules")] @@ -97,8 +97,8 @@ internal class Actions : VerbCommandOptions [VerbOption("mark", HelpText = "Edit flags on modules")] public SubCommandOptions Mark { get; set; } - [VerbOption("ksp", HelpText = "Manage KSP installs")] - public SubCommandOptions KSP { get; set; } + [VerbOption("instance", HelpText = "Manage game instances")] + public SubCommandOptions Instance { get; set; } [VerbOption("authtoken", HelpText = "Manage authentication tokens")] public AuthTokenSubOptions AuthToken { get; set; } @@ -106,7 +106,7 @@ internal class Actions : VerbCommandOptions [VerbOption("cache", HelpText = "Manage download cache path")] public SubCommandOptions Cache { get; set; } - [VerbOption("compat", HelpText = "Manage KSP version compatibility")] + [VerbOption("compat", HelpText = "Manage game version compatibility")] public SubCommandOptions Compat { get; set; } [VerbOption("compare", HelpText = "Compare version strings")] @@ -216,7 +216,7 @@ public string GetUsage(string verb) return HelpText.AutoBuild(this, verb); } - public virtual int Handle(KSPManager manager, IUser user) + public virtual int Handle(GameInstanceManager manager, IUser user) { CheckMonoVersion(user, 3, 1, 0); @@ -316,45 +316,45 @@ private static void CheckMonoVersion(IUser user, int rec_major, int rec_minor, i public class InstanceSpecificOptions : CommonOptions { - [Option("ksp", HelpText = "KSP install to use")] - public string KSP { get; set; } + [Option("instance", HelpText = "Game instance to use")] + public string Instance { get; set; } - [Option("kspdir", HelpText = "KSP dir to use")] - public string KSPdir { get; set; } + [Option("gamedir", HelpText = "Game dir to use")] + public string Gamedir { get; set; } - public override int Handle(KSPManager manager, IUser user) + public override int Handle(GameInstanceManager manager, IUser user) { int exitCode = base.Handle(manager, user); if (exitCode == Exit.OK) { - // User provided KSP instance - if (KSPdir != null && KSP != null) + // User provided game instance + if (Gamedir != null && Instance != null) { - user.RaiseMessage("--ksp and --kspdir can't be specified at the same time"); + user.RaiseMessage("--instance and --gamedir can't be specified at the same time"); return Exit.BADOPT; } try { - if (!string.IsNullOrEmpty(KSP)) + if (!string.IsNullOrEmpty(Instance)) { - // Set a KSP directory by its alias. - manager.SetCurrentInstance(KSP); + // Set a game directory by its alias. + manager.SetCurrentInstance(Instance); } - else if (!string.IsNullOrEmpty(KSPdir)) + else if (!string.IsNullOrEmpty(Gamedir)) { - // Set a KSP directory by its path - manager.SetCurrentInstanceByPath(KSPdir); + // Set a game directory by its path + manager.SetCurrentInstanceByPath(Gamedir); } } catch (NotKSPDirKraken k) { - user.RaiseMessage("Sorry, {0} does not appear to be a KSP directory", k.path); + user.RaiseMessage("Sorry, {0} does not appear to be a game instance", k.path); return Exit.BADOPT; } catch (InvalidKSPInstanceKraken k) { - user.RaiseMessage("Invalid KSP installation specified \"{0}\", use '--kspdir' to specify by path, or 'ksp list' to see known KSP installations", k.instance); + user.RaiseMessage("Invalid game instance specified \"{0}\", use '--gamedir' to specify by path, or 'instance list' to see known game instances", k.instance); return Exit.BADOPT; } } @@ -363,7 +363,7 @@ public override int Handle(KSPManager manager, IUser user) } /// - /// For things which are subcommands ('ksp', 'repair' etc), we just grab a list + /// For things which are subcommands ('instance', 'repair' etc), we just grab a list /// we can pass on. /// public class SubCommandOptions : CommonOptions @@ -375,7 +375,7 @@ public SubCommandOptions() { } public SubCommandOptions(string[] args) { - options = new System.Collections.Generic.List(args).GetRange(1, args.Length - 1); + options = new List(args).GetRange(1, args.Length - 1); } } diff --git a/ConsoleUI/CKAN-ConsoleUI.csproj b/ConsoleUI/CKAN-ConsoleUI.csproj index c7169faf06..c2a5c77be6 100644 --- a/ConsoleUI/CKAN-ConsoleUI.csproj +++ b/ConsoleUI/CKAN-ConsoleUI.csproj @@ -60,10 +60,10 @@ - - - - + + + + diff --git a/ConsoleUI/CompatibleVersionDialog.cs b/ConsoleUI/CompatibleVersionDialog.cs index 01142e466e..80fd96355a 100644 --- a/ConsoleUI/CompatibleVersionDialog.cs +++ b/ConsoleUI/CompatibleVersionDialog.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using CKAN.Versioning; +using CKAN.Games; using CKAN.GameVersionProviders; using CKAN.ConsoleUI.Toolkit; using Autofac; @@ -16,18 +17,19 @@ public class CompatibleVersionDialog : ConsoleDialog { /// /// Initialize the popup /// - public CompatibleVersionDialog() : base() + public CompatibleVersionDialog(IGame game) : base() { int l = GetLeft(), r = GetRight(); int t = GetTop(), b = GetBottom(); - choices = new ConsoleListBox( + loadOptions(game); + choices = new ConsoleListBox( l + 2, t + 2, r - 2, b - 4, options, - new List>() { - new ConsoleListBoxColumn() { + new List>() { + new ConsoleListBoxColumn() { Header = "Predefined Version", Width = r - l - 5, Renderer = v => v.ToString(), @@ -49,9 +51,9 @@ public CompatibleVersionDialog() : base() GhostText = () => "" }; AddObject(manualEntry); - manualEntry.AddTip("Enter", "Accept value", () => KspVersion.TryParse(manualEntry.Value, out choice)); + manualEntry.AddTip("Enter", "Accept value", () => GameVersion.TryParse(manualEntry.Value, out choice)); manualEntry.AddBinding(Keys.Enter, (object sender) => { - if (KspVersion.TryParse(manualEntry.Value, out choice)) { + if (GameVersion.TryParse(manualEntry.Value, out choice)) { // Good value, done running return false; } else { @@ -76,31 +78,31 @@ public CompatibleVersionDialog() : base() /// /// Row user selected /// - public new KspVersion Run(Action process = null) + public new GameVersion Run(Action process = null) { base.Run(process); return choice; } - static CompatibleVersionDialog() + private void loadOptions(IGame game) { - options = ServiceLocator.Container.Resolve().KnownVersions; + options = game.KnownVersions; // C# won't let us foreach over an array while modifying it for (int i = options.Count - 1; i >= 0; --i) { - KspVersion v = options[i]; - // From GUI/CompatibleKspVersionsDialog.cs - KspVersion fullKnownVersion = v.ToVersionRange().Lower.Value; - KspVersion toAdd = new KspVersion(fullKnownVersion.Major, fullKnownVersion.Minor); + GameVersion v = options[i]; + // From GUI/CompatibleGameVersionsDialog.cs + GameVersion fullKnownVersion = v.ToVersionRange().Lower.Value; + GameVersion toAdd = new GameVersion(fullKnownVersion.Major, fullKnownVersion.Minor); if (!options.Contains(toAdd)) { options.Add(toAdd); } } } - private static List options; + private List options; - private ConsoleListBox choices; - private ConsoleField manualEntry; - private KspVersion choice; + private ConsoleListBox choices; + private ConsoleField manualEntry; + private GameVersion choice; } } diff --git a/ConsoleUI/ConsoleCKAN.cs b/ConsoleUI/ConsoleCKAN.cs index 566887670c..5422ef6395 100644 --- a/ConsoleUI/ConsoleCKAN.cs +++ b/ConsoleUI/ConsoleCKAN.cs @@ -13,13 +13,13 @@ public class ConsoleCKAN { /// Starts with a splash screen, then instance selection if no default, /// then list of mods. /// - public ConsoleCKAN(KSPManager mgr, bool debug) + public ConsoleCKAN(GameInstanceManager mgr, bool debug) { - // KSPManager only uses its IUser object to construct KSP objects, + // GameInstanceManager only uses its IUser object to construct game instance objects, // which only use it to inform the user about the creation of the CKAN/ folder. // These aren't really intended to be displayed, so the manager // can keep a NullUser reference forever. - KSPManager manager = mgr ?? new KSPManager(new NullUser()); + GameInstanceManager manager = mgr ?? new GameInstanceManager(new NullUser()); // The splash screen returns true when it's safe to run the rest of the app. // This can be blocked by a lock file, for example. @@ -28,12 +28,12 @@ public ConsoleCKAN(KSPManager mgr, bool debug) if (manager.CurrentInstance == null) { if (manager.Instances.Count == 0) { // No instances, add one - new KSPAddScreen(manager).Run(); + new GameInstanceAddScreen(manager).Run(); // Set instance to current if they added one manager.GetPreferredInstance(); } else { // Multiple instances, no default, pick one - new KSPListScreen(manager).Run(); + new GameInstanceListScreen(manager).Run(); } } if (manager.CurrentInstance != null) { diff --git a/ConsoleUI/DependencyScreen.cs b/ConsoleUI/DependencyScreen.cs index ae67c2139b..be89dec54b 100644 --- a/ConsoleUI/DependencyScreen.cs +++ b/ConsoleUI/DependencyScreen.cs @@ -15,11 +15,11 @@ public class DependencyScreen : ConsoleScreen { /// /// Initialize the screen /// - /// KSP manager containing instances + /// Game instance manager containing instances /// Plan of mods to add and remove /// Mods that the user saw and did not select, in this pass or a previous pass /// True if debug options should be available, false otherwise - public DependencyScreen(KSPManager mgr, ChangePlan cp, HashSet rej, bool dbg) : base() + public DependencyScreen(GameInstanceManager mgr, ChangePlan cp, HashSet rej, bool dbg) : base() { debug = dbg; manager = mgr; @@ -208,7 +208,7 @@ private string StatusSymbol(CkanModule mod) private HashSet rejected; private IRegistryQuerier registry; - private KSPManager manager; + private GameInstanceManager manager; private ModuleInstaller installer; private ChangePlan plan; private bool debug; diff --git a/ConsoleUI/DownloadImportDialog.cs b/ConsoleUI/DownloadImportDialog.cs index 0fc698ed20..e05ea3c6b7 100644 --- a/ConsoleUI/DownloadImportDialog.cs +++ b/ConsoleUI/DownloadImportDialog.cs @@ -17,7 +17,7 @@ public static class DownloadImportDialog { /// Game instance to import into /// Cache object to import into /// Change plan object for marking things to be installed - public static void ImportDownloads(KSP gameInst, NetModuleCache cache, ChangePlan cp) + public static void ImportDownloads(GameInstance gameInst, NetModuleCache cache, ChangePlan cp) { ConsoleFileMultiSelectDialog cfmsd = new ConsoleFileMultiSelectDialog( "Import Downloads", @@ -42,7 +42,7 @@ public static void ImportDownloads(KSP gameInst, NetModuleCache cache, ChangePla Environment.GetFolderPath(Environment.SpecialFolder.Desktop) }; - private static string FindDownloadsPath(KSP gameInst) + private static string FindDownloadsPath(GameInstance gameInst) { foreach (string p in downloadPaths) { if (!string.IsNullOrEmpty(p) && Directory.Exists(p)) { diff --git a/ConsoleUI/KSPAddScreen.cs b/ConsoleUI/GameInstanceAddScreen.cs similarity index 79% rename from ConsoleUI/KSPAddScreen.cs rename to ConsoleUI/GameInstanceAddScreen.cs index 1970e1d753..a43048f768 100644 --- a/ConsoleUI/KSPAddScreen.cs +++ b/ConsoleUI/GameInstanceAddScreen.cs @@ -5,15 +5,15 @@ namespace CKAN.ConsoleUI { /// - /// Screen for adding a new KSP instance + /// Screen for adding a new game instance /// - public class KSPAddScreen : KSPScreen { + public class GameInstanceAddScreen : GameInstanceScreen { /// /// Initialize the Screen /// - /// KSP manager containing the instances - public KSPAddScreen(KSPManager mgr) : base(mgr) + /// Game instance manager containing the instances + public GameInstanceAddScreen(GameInstanceManager mgr) : base(mgr) { AddObject(new ConsoleLabel( labelWidth, pathRow + 1, -1, @@ -39,7 +39,7 @@ protected override bool Valid() /// protected override string CenterHeader() { - return "Add KSP Instance"; + return "Add Game Instance"; } /// @@ -47,7 +47,7 @@ protected override string CenterHeader() /// protected override void Save() { - manager.AddInstance(new KSP(path.Value, name.Value, new NullUser())); + manager.AddInstance(path.Value, name.Value, new NullUser()); } private static readonly string examplePath = Path.Combine( diff --git a/ConsoleUI/KSPEditScreen.cs b/ConsoleUI/GameInstanceEditScreen.cs similarity index 89% rename from ConsoleUI/KSPEditScreen.cs rename to ConsoleUI/GameInstanceEditScreen.cs index 0727bf2cbf..fdeb00cd88 100644 --- a/ConsoleUI/KSPEditScreen.cs +++ b/ConsoleUI/GameInstanceEditScreen.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using CKAN.Versioning; +using CKAN.Games; using CKAN.ConsoleUI.Toolkit; namespace CKAN.ConsoleUI { @@ -9,14 +10,14 @@ namespace CKAN.ConsoleUI { /// /// Screen for editing an existing game instance /// - public class KSPEditScreen : KSPScreen { + public class GameInstanceEditScreen : GameInstanceScreen { /// /// Initialize the Screen /// - /// KSP manager containing the instances + /// Game instance manager containing the instances /// Instance to edit - public KSPEditScreen(KSPManager mgr, KSP k) + public GameInstanceEditScreen(GameInstanceManager mgr, GameInstance k) : base(mgr, k.Name, k.GameDir()) { ksp = k; @@ -39,7 +40,7 @@ public KSPEditScreen(KSPManager mgr, KSP k) } // Also edit copy of the compatible versions - compatEditList = new List(ksp.GetCompatibleVersions()); + compatEditList = new List(ksp.GetCompatibleVersions()); // I'm not a huge fan of this layout, but I think it's better than just a label AddObject(new ConsoleDoubleFrame( @@ -72,7 +73,7 @@ public KSPEditScreen(KSPManager mgr, KSP k) AddObject(repoList); repoList.AddTip("A", "Add"); repoList.AddBinding(Keys.A, (object sender) => { - LaunchSubScreen(new RepoAddScreen(repoEditList)); + LaunchSubScreen(new RepoAddScreen(ksp.game, repoEditList)); repoList.SetData(new List(repoEditList.Values)); return true; }); @@ -91,7 +92,7 @@ public KSPEditScreen(KSPManager mgr, KSP k) }); repoList.AddTip("E", "Edit"); repoList.AddBinding(Keys.E, (object sender) => { - LaunchSubScreen(new RepoEditScreen(repoEditList, repoList.Selection)); + LaunchSubScreen(new RepoEditScreen(ksp.game, repoEditList, repoList.Selection)); repoList.SetData(new List(repoEditList.Values)); return true; }); @@ -120,11 +121,11 @@ public KSPEditScreen(KSPManager mgr, KSP k) return true; }); - compatList = new ConsoleListBox( + compatList = new ConsoleListBox( 3, compatListTop, -3, compatListBottom, compatEditList, - new List>() { - new ConsoleListBoxColumn() { + new List>() { + new ConsoleListBoxColumn() { Header = "Version", Width = 10, Renderer = v => v.ToString(), @@ -137,8 +138,8 @@ public KSPEditScreen(KSPManager mgr, KSP k) compatList.AddTip("A", "Add"); compatList.AddBinding(Keys.A, (object sender) => { - CompatibleVersionDialog vd = new CompatibleVersionDialog(); - KspVersion newVersion = vd.Run(); + CompatibleVersionDialog vd = new CompatibleVersionDialog(ksp.game); + GameVersion newVersion = vd.Run(); DrawBackground(); if (newVersion != null && !compatEditList.Contains(newVersion)) { compatEditList.Add(newVersion); @@ -179,7 +180,7 @@ private static V SortedDictFind(SortedDictionary dict, Func /// protected override string CenterHeader() { - return "Edit KSP Instance"; + return "Edit Game Instance"; } /// @@ -220,20 +221,20 @@ protected override void Save() // If the path is changed, then we have to remove the old instance // and replace it with a new one, whether or not the name is changed. manager.RemoveInstance(oldName); - manager.AddInstance(new KSP(path.Value, name.Value, new NullUser())); + manager.AddInstance(path.Value, name.Value, new NullUser()); } else if (name.Value != oldName) { // If only the name changed, there's an API for that. manager.RenameInstance(ksp.Name, name.Value); } } - private KSP ksp; - private Registry registry; + private GameInstance ksp; + private Registry registry; private SortedDictionary repoEditList; private ConsoleListBox repoList; - private List compatEditList; - private ConsoleListBox compatList; + private List compatEditList; + private ConsoleListBox compatList; private const int repoFrameTop = pathRow + 2; private const int repoListTop = repoFrameTop + 2; diff --git a/ConsoleUI/KSPListScreen.cs b/ConsoleUI/GameInstanceListScreen.cs similarity index 72% rename from ConsoleUI/KSPListScreen.cs rename to ConsoleUI/GameInstanceListScreen.cs index 43b3b70534..3a4c27e254 100644 --- a/ConsoleUI/KSPListScreen.cs +++ b/ConsoleUI/GameInstanceListScreen.cs @@ -8,16 +8,16 @@ namespace CKAN.ConsoleUI { /// - /// Object representing list of available instances of KSP. + /// Object representing list of available game instances. /// - public class KSPListScreen : ConsoleScreen { + public class GameInstanceListScreen : ConsoleScreen { /// /// Initialize the screen. /// - /// KSP manager object for getting hte Instances + /// Game instance manager object for getting hte Instances /// If true, this is the first screen after the splash, so Ctrl+Q exits, else Esc exits - public KSPListScreen(KSPManager mgr, bool first = false) + public GameInstanceListScreen(GameInstanceManager mgr, bool first = false) { manager = mgr; @@ -26,24 +26,28 @@ public KSPListScreen(KSPManager mgr, bool first = false) () => "Select or add a game instance:" )); - kspList = new ConsoleListBox( + instanceList = new ConsoleListBox( 1, 4, -1, -2, manager.Instances.Values, - new List>() { - new ConsoleListBoxColumn() { + new List>() { + new ConsoleListBoxColumn() { Header = "Default", Width = 7, Renderer = StatusSymbol - }, new ConsoleListBoxColumn() { + }, new ConsoleListBoxColumn() { Header = "Name", Width = 20, Renderer = k => k.Name - }, new ConsoleListBoxColumn() { + }, new ConsoleListBoxColumn() { + Header = "Game", + Width = 5, + Renderer = k => k.game.ShortName + }, new ConsoleListBoxColumn() { Header = "Version", Width = 12, Renderer = k => k.Version()?.ToString() ?? noVersion, - Comparer = (a, b) => a.Version()?.CompareTo(b.Version() ?? KspVersion.Any) ?? 1 - }, new ConsoleListBoxColumn() { + Comparer = (a, b) => a.Version()?.CompareTo(b.Version() ?? GameVersion.Any) ?? 1 + }, new ConsoleListBoxColumn() { Header = "Path", Width = 70, Renderer = k => k.GameDir() @@ -65,13 +69,13 @@ public KSPListScreen(KSPManager mgr, bool first = false) AddBinding(Keys.Enter, (object sender) => { ConsoleMessageDialog d = new ConsoleMessageDialog( - $"Loading instance {kspList.Selection.Name}...", + $"Loading instance {instanceList.Selection.Name}...", new List() ); - if (TryGetInstance(kspList.Selection, () => { d.Run(() => {}); })) { + if (TryGetInstance(instanceList.Selection, () => { d.Run(() => {}); })) { try { - manager.SetCurrentInstance(kspList.Selection.Name); + manager.SetCurrentInstance(instanceList.Selection.Name); } catch (Exception ex) { // This can throw if the previous current instance had an error, // since it gets destructed when it's replaced. @@ -83,36 +87,36 @@ public KSPListScreen(KSPManager mgr, bool first = false) } }); - kspList.AddTip("A", "Add"); - kspList.AddBinding(Keys.A, (object sender) => { - LaunchSubScreen(new KSPAddScreen(manager)); - kspList.SetData(manager.Instances.Values); + instanceList.AddTip("A", "Add"); + instanceList.AddBinding(Keys.A, (object sender) => { + LaunchSubScreen(new GameInstanceAddScreen(manager)); + instanceList.SetData(manager.Instances.Values); return true; }); - kspList.AddTip("R", "Remove"); - kspList.AddBinding(Keys.R, (object sender) => { - manager.RemoveInstance(kspList.Selection.Name); - kspList.SetData(manager.Instances.Values); + instanceList.AddTip("R", "Remove"); + instanceList.AddBinding(Keys.R, (object sender) => { + manager.RemoveInstance(instanceList.Selection.Name); + instanceList.SetData(manager.Instances.Values); return true; }); - kspList.AddTip("E", "Edit"); - kspList.AddBinding(Keys.E, (object sender) => { + instanceList.AddTip("E", "Edit"); + instanceList.AddBinding(Keys.E, (object sender) => { ConsoleMessageDialog d = new ConsoleMessageDialog( - $"Loading instance {kspList.Selection.Name}...", + $"Loading instance {instanceList.Selection.Name}...", new List() ); - TryGetInstance(kspList.Selection, () => { d.Run(() => {}); }); + TryGetInstance(instanceList.Selection, () => { d.Run(() => {}); }); // Still launch the screen even if the load fails, // because you need to be able to fix the name/path. - LaunchSubScreen(new KSPEditScreen(manager, kspList.Selection)); + LaunchSubScreen(new GameInstanceEditScreen(manager, instanceList.Selection)); return true; }); - kspList.AddTip("D", "Default"); - kspList.AddBinding(Keys.D, (object sender) => { - string name = kspList.Selection.Name; + instanceList.AddTip("D", "Default"); + instanceList.AddBinding(Keys.D, (object sender) => { + string name = instanceList.Selection.Name; if (name == manager.AutoStartInstance) { manager.ClearAutoStart(); } else { @@ -129,8 +133,8 @@ public KSPListScreen(KSPManager mgr, bool first = false) return true; }); - AddObject(kspList); - mainMenu = kspList.SortMenu(); + AddObject(instanceList); + mainMenu = instanceList.SortMenu(); } /// @@ -146,7 +150,7 @@ protected override string LeftHeader() /// protected override string CenterHeader() { - return "KSP Instances"; + return "Game Instances"; } /// @@ -165,7 +169,7 @@ protected override string MenuTip() /// /// True if successfully loaded, false if it's locked or the registry was corrupted, etc. /// - public static bool TryGetInstance(KSP ksp, Action render) + public static bool TryGetInstance(GameInstance ksp, Action render) { bool retry; do { @@ -221,15 +225,15 @@ public static bool TryGetInstance(KSP ksp, Action render) return true; } - private string StatusSymbol(KSP k) + private string StatusSymbol(GameInstance k) { return k.Name == manager.AutoStartInstance ? defaultMark : " "; } - private KSPManager manager; - private ConsoleListBox kspList; + private GameInstanceManager manager; + private ConsoleListBox instanceList; private const string noVersion = ""; private static readonly string defaultMark = Symbols.checkmark; diff --git a/ConsoleUI/KSPScreen.cs b/ConsoleUI/GameInstanceScreen.cs similarity index 79% rename from ConsoleUI/KSPScreen.cs rename to ConsoleUI/GameInstanceScreen.cs index 37dd9fa4f7..5a7d857a84 100644 --- a/ConsoleUI/KSPScreen.cs +++ b/ConsoleUI/GameInstanceScreen.cs @@ -4,17 +4,17 @@ namespace CKAN.ConsoleUI { /// - /// Base class for screens adding/editing KSP instances + /// Base class for screens adding/editing game instances /// - public abstract class KSPScreen : ConsoleScreen { + public abstract class GameInstanceScreen : ConsoleScreen { /// /// Initialize the screen /// - /// KSP manager containing the instances, needed for saving changes + /// Game instance manager containing the instances, needed for saving changes /// Initial value of name field /// Initial value of path field - protected KSPScreen(KSPManager mgr, string initName = "", string initPath = "") : base() + protected GameInstanceScreen(GameInstanceManager mgr, string initName = "", string initPath = "") : base() { manager = mgr; @@ -37,15 +37,15 @@ protected KSPScreen(KSPManager mgr, string initName = "", string initPath = "") }); name = new ConsoleField(labelWidth, nameRow, -1, initName) { - GhostText = () => "" + GhostText = () => "" }; path = new ConsoleField(labelWidth, pathRow, -1, initPath) { - GhostText = () => "" + GhostText = () => "" }; AddObject(new ConsoleLabel(1, nameRow, labelWidth, () => "Name:")); AddObject(name); - AddObject(new ConsoleLabel(1, pathRow, labelWidth, () => "Path to KSP:")); + AddObject(new ConsoleLabel(1, pathRow, labelWidth, () => "Path to game instance:")); AddObject(path); } @@ -98,9 +98,9 @@ protected bool pathValid() // Handle default path dragged-and-dropped onto Mac's Terminal path.Value = path.Value.Replace("Kerbal\\ Space\\ Program", "Kerbal Space Program"); } - if (!KSP.IsKspDir(path.Value)) { + if (!GameInstanceManager.IsGameInstanceDir(new DirectoryInfo(path.Value))) { // Complain about non-KSP path - RaiseError("Path does not correspond to a KSP folder!"); + RaiseError("Path does not correspond to a game folder!"); SetFocus(path); return false; } else { @@ -118,11 +118,14 @@ protected bool pathValid() protected ConsoleField path; /// - /// KSP manager object that contains the instances + /// Game instance manager object that contains the instances /// - protected KSPManager manager; + protected GameInstanceManager manager; - protected const int labelWidth = 16; + /// + /// Number of columns reserved at left of screen for labels + /// + protected const int labelWidth = 24; private const int nameRow = 2; /// /// Y coordinate of path field diff --git a/ConsoleUI/InstallScreen.cs b/ConsoleUI/InstallScreen.cs index b48667c56d..e56bee2584 100644 --- a/ConsoleUI/InstallScreen.cs +++ b/ConsoleUI/InstallScreen.cs @@ -13,10 +13,10 @@ public class InstallScreen : ProgressScreen { /// /// Initialize the Screen /// - /// KSP manager containing instances + /// Game instance manager containing instances /// Plan of mods to install or remove /// True if debug options should be available, false otherwise - public InstallScreen(KSPManager mgr, ChangePlan cp, bool dbg) + public InstallScreen(GameInstanceManager mgr, ChangePlan cp, bool dbg) : base( "Installing, Updating, and Removing Mods", "Calculating..." @@ -133,9 +133,9 @@ public override void Run(Action process = null) } catch (BadMetadataKraken ex) { RaiseError($"Bad metadata detected for {ex.module}: {ex.Message}"); } catch (DependencyNotSatisfiedKraken ex) { - RaiseError($"{ex.parent} requires {ex.module}, but it is not listed in the index, or not available for your version of KSP.\r\n{ex.Message}"); + RaiseError($"{ex.parent} requires {ex.module}, but it is not listed in the index, or not available for your version of the game.\r\n{ex.Message}"); } catch (ModuleNotFoundKraken ex) { - RaiseError($"Module {ex.module} required but it is not listed in the index, or not available for your version of KSP.\r\n{ex.Message}"); + RaiseError($"Module {ex.module} required but it is not listed in the index, or not available for your version of the game.\r\n{ex.Message}"); } catch (ModNotInstalledKraken ex) { RaiseError($"{ex.mod} is not installed, can't remove"); } @@ -170,7 +170,7 @@ private IEnumerable AllReplacements(IEnumerable ident without_enforce_consistency = false }; - private KSPManager manager; + private GameInstanceManager manager; private ChangePlan plan; private bool debug; } diff --git a/ConsoleUI/ModInfoScreen.cs b/ConsoleUI/ModInfoScreen.cs index 77adc823f5..27be0e4050 100644 --- a/ConsoleUI/ModInfoScreen.cs +++ b/ConsoleUI/ModInfoScreen.cs @@ -16,11 +16,11 @@ public class ModInfoScreen : ConsoleScreen { /// /// Initialize the Screen /// - /// KSP manager containing game instances + /// Game instance manager containing game instances /// Plan of other mods to be added or removed /// The module to display /// True if debug options should be available, false otherwise - public ModInfoScreen(KSPManager mgr, ChangePlan cp, CkanModule m, bool dbg) + public ModInfoScreen(GameInstanceManager mgr, ChangePlan cp, CkanModule m, bool dbg) { debug = dbg; mod = m; @@ -461,7 +461,7 @@ private void addVersionBox(int l, int t, int r, int b, Func title, Func< if (releases != null && releases.Count > 0) { ModuleVersion minMod = null, maxMod = null; - KspVersion minKsp = null, maxKsp = null; + GameVersion minKsp = null, maxKsp = null; Registry.GetMinMaxVersions(releases, out minMod, out maxMod, out minKsp, out maxKsp); AddObject(new ConsoleLabel( l + 2, t + 1, r - 2, @@ -479,7 +479,7 @@ private void addVersionBox(int l, int t, int r, int b, Func title, Func< )); AddObject(new ConsoleLabel( l + 4, t + 3, r - 2, - () => KspVersionRange.VersionSpan(minKsp, maxKsp), + () => GameVersionRange.VersionSpan(manager.CurrentInstance.game, minKsp, maxKsp), null, color )); @@ -567,11 +567,11 @@ private void Download() { "forum.kerbalspaceprogram.com", "KSP Forums" } }; - private KSPManager manager; - private IRegistryQuerier registry; - private ChangePlan plan; - private CkanModule mod; - private bool debug; + private GameInstanceManager manager; + private IRegistryQuerier registry; + private ChangePlan plan; + private CkanModule mod; + private bool debug; } } diff --git a/ConsoleUI/ModListScreen.cs b/ConsoleUI/ModListScreen.cs index a4b8c4f702..0ecf732292 100644 --- a/ConsoleUI/ModListScreen.cs +++ b/ConsoleUI/ModListScreen.cs @@ -15,9 +15,9 @@ public class ModListScreen : ConsoleScreen { /// /// Initialize the screen /// - /// KSP manager object containing the current instance + /// Game instance manager object containing the current instance /// True if debug options should be available, false otherwise - public ModListScreen(KSPManager mgr, bool dbg) + public ModListScreen(GameInstanceManager mgr, bool dbg) { debug = dbg; manager = mgr; @@ -41,7 +41,7 @@ public ModListScreen(KSPManager mgr, bool dbg) Renderer = m => ModuleInstaller.StripEpoch(m.version?.ToString() ?? ""), Comparer = (a, b) => a.version.CompareTo(b.version) }, new ConsoleListBoxColumn() { - Header = "Max KSP version", + Header = "Max game version", Width = 17, Renderer = m => registry.LatestCompatibleKSP(m.identifier)?.ToString() ?? "", Comparer = (a, b) => registry.LatestCompatibleKSP(a.identifier).CompareTo(registry.LatestCompatibleKSP(b.identifier)) @@ -279,7 +279,7 @@ public ModListScreen(KSPManager mgr, bool dbg) "Save your mod list", true, ExportInstalled), null, - new ConsoleMenuOption("Select KSP install...", "", + new ConsoleMenuOption("Select game instance...", "", "Switch to a different game instance", true, SelectInstall), new ConsoleMenuOption("Authentication tokens...", "", @@ -316,7 +316,7 @@ protected override string LeftHeader() /// protected override string CenterHeader() { - return $"KSP {manager.CurrentInstance.Version()} ({manager.CurrentInstance.Name})"; + return $"{manager.CurrentInstance.game.ShortName} {manager.CurrentInstance.Version()} ({manager.CurrentInstance.Name})"; } // Alt+H doesn't work on Mac, but F1 does, and we need @@ -465,7 +465,7 @@ private string newModPrompt(int howMany) private bool ScanForMods() { try { - manager.CurrentInstance.ScanGameData(); + manager.CurrentInstance.Scan(); } catch (InconsistentKraken ex) { // Warn about inconsistent state RaiseError(ex.InconsistenciesPretty + " The repo has not been saved."); @@ -475,8 +475,8 @@ private bool ScanForMods() private bool SelectInstall() { - KSP prevInst = manager.CurrentInstance; - LaunchSubScreen(new KSPListScreen(manager)); + GameInstance prevInst = manager.CurrentInstance; + LaunchSubScreen(new GameInstanceListScreen(manager)); // Abort if same instance as before if (!prevInst.Equals(manager.CurrentInstance)) { plan.Reset(); @@ -598,7 +598,7 @@ private long totalInstalledDownloadSize() return total; } - private KSPManager manager; + private GameInstanceManager manager; private IRegistryQuerier registry; private bool debug; @@ -702,13 +702,13 @@ public void Reset() /// This function is extremely performance-sensitive because it's the default sort for /// the main mod list, so anything in here should be O(1) and fast. /// - /// KSP manager containing the instances + /// Game instance manager containing the instances /// Registry of instance being displayed /// The mod /// /// Status of mod /// - public InstallStatus GetModStatus(KSPManager manager, IRegistryQuerier registry, string identifier) + public InstallStatus GetModStatus(GameInstanceManager manager, IRegistryQuerier registry, string identifier) { if (registry.IsInstalled(identifier, false)) { if (Remove.Contains(identifier)) { diff --git a/ConsoleUI/Program.cs b/ConsoleUI/Program.cs index 02ac2a8209..b602a10de4 100644 --- a/ConsoleUI/Program.cs +++ b/ConsoleUI/Program.cs @@ -29,7 +29,7 @@ public static void Main(string[] args) /// /// Process exit status /// - public static int Main_(string[] args, KSPManager manager, bool debug = false) + public static int Main_(string[] args, GameInstanceManager manager, bool debug = false) { Logging.Initialize(); diff --git a/ConsoleUI/RepoAddScreen.cs b/ConsoleUI/RepoAddScreen.cs index 60882eafc5..0e3629f406 100644 --- a/ConsoleUI/RepoAddScreen.cs +++ b/ConsoleUI/RepoAddScreen.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using CKAN.Games; namespace CKAN.ConsoleUI { @@ -10,9 +11,10 @@ public class RepoAddScreen : RepoScreen { /// /// Construct the screen /// + /// Game from which to get repos /// Collection of Repository objects - public RepoAddScreen(SortedDictionary reps) - : base(reps, "", "") { } + public RepoAddScreen(IGame game, SortedDictionary reps) + : base(game, reps, "", "") { } /// /// Check whether the fields are valid diff --git a/ConsoleUI/RepoEditScreen.cs b/ConsoleUI/RepoEditScreen.cs index 9a8b1e05ae..84a3b16f1c 100644 --- a/ConsoleUI/RepoEditScreen.cs +++ b/ConsoleUI/RepoEditScreen.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using CKAN.Games; namespace CKAN.ConsoleUI { @@ -11,10 +12,11 @@ public class RepoEditScreen : RepoScreen { /// /// Construct the Screen /// + /// Game from which to get repos /// Collection of Repository objects /// The object to edit - public RepoEditScreen(SortedDictionary reps, Repository repo) - : base(reps, repo.name, repo.uri.ToString()) + public RepoEditScreen(IGame game, SortedDictionary reps, Repository repo) + : base(game, reps, repo.name, repo.uri.ToString()) { repository = repo; } diff --git a/ConsoleUI/RepoScreen.cs b/ConsoleUI/RepoScreen.cs index 85133e297d..72f86e327d 100644 --- a/ConsoleUI/RepoScreen.cs +++ b/ConsoleUI/RepoScreen.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using CKAN.ConsoleUI.Toolkit; +using CKAN.Games; namespace CKAN.ConsoleUI { @@ -12,12 +13,14 @@ public abstract class RepoScreen : ConsoleScreen { /// /// Construct the screens /// + /// Game from which to get repos /// Collection of Repository objects /// Initial value of the Name field /// Iniital value of the URL field - protected RepoScreen(SortedDictionary reps, string initName, string initUrl) : base() + protected RepoScreen(IGame game, SortedDictionary reps, string initName, string initUrl) : base() { editList = reps; + defaultRepos = RepositoryList.DefaultRepositories(game); name = new ConsoleField(labelWidth, nameRow, -1, initName) { GhostText = () => "" @@ -149,7 +152,7 @@ protected bool urlValid() /// protected SortedDictionary editList; - private static RepositoryList defaultRepos = RepositoryList.DefaultRepositories(); + private RepositoryList defaultRepos; private const int labelWidth = 8; private const int nameRow = 3; diff --git a/ConsoleUI/SplashScreen.cs b/ConsoleUI/SplashScreen.cs index 663f7c73cf..f43a3d2982 100644 --- a/ConsoleUI/SplashScreen.cs +++ b/ConsoleUI/SplashScreen.cs @@ -12,8 +12,8 @@ public class SplashScreen { /// /// Initialize the screen /// - /// KSP manager object for getting instances - public SplashScreen(KSPManager mgr) + /// Game instance manager object for getting instances + public SplashScreen(GameInstanceManager mgr) { manager = mgr; } @@ -24,8 +24,8 @@ public SplashScreen(KSPManager mgr) public bool Run() { // If there's a default instance, try to get the lock for it. - KSP ksp = manager.CurrentInstance ?? manager.GetPreferredInstance(); - if (ksp != null && !KSPListScreen.TryGetInstance(ksp, () => Draw(false))) { + GameInstance ksp = manager.CurrentInstance ?? manager.GetPreferredInstance(); + if (ksp != null && !GameInstanceListScreen.TryGetInstance(ksp, () => Draw(false))) { Console.ResetColor(); Console.Clear(); Console.CursorVisible = true; @@ -93,7 +93,7 @@ private void drawCentered(int y, string val) } catch { } } - private KSPManager manager; + private GameInstanceManager manager; } } diff --git a/Core/KSPPathUtils.cs b/Core/CKANPathUtils.cs similarity index 63% rename from Core/KSPPathUtils.cs rename to Core/CKANPathUtils.cs index 61b956e9b0..08ab99c28c 100644 --- a/Core/KSPPathUtils.cs +++ b/Core/CKANPathUtils.cs @@ -5,9 +5,9 @@ namespace CKAN { - public class KSPPathUtils + public class CKANPathUtils { - private static readonly ILog log = LogManager.GetLogger(typeof(KSPPathUtils)); + private static readonly ILog log = LogManager.GetLogger(typeof(CKANPathUtils)); /// /// Finds Steam on the current machine. @@ -69,7 +69,7 @@ public static string SteamPath() steam = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Personal), Path.Combine("Library", "Application Support", "Steam") - ); + ); log.DebugFormat("Looking for Steam in {0}", steam); @@ -83,110 +83,6 @@ public static string SteamPath() return null; } - /// - /// Finds the KSP path under a Steam Libary. Returns null if the folder cannot be located. - /// - /// Steam Libary Path - /// The KSP path. - public static string KSPDirectory(string steamPath) - { - // There are several possibilities for the path under Linux. - // Try with the uppercase version. - string installPath = Path.Combine(steamPath, "SteamApps", "common", "Kerbal Space Program"); - - if (Directory.Exists(installPath)) - { - return installPath; - } - - // Try with the lowercase version. - installPath = Path.Combine(steamPath, "steamapps", "common", "Kerbal Space Program"); - - if (Directory.Exists(installPath)) - { - return installPath; - } - - return null; - - } - - /// - /// Finds the Steam KSP path. Returns null if the folder cannot be located. - /// - /// The KSP path. - public static string KSPSteamPath() - { - // Attempt to get the Steam path. - string steamPath = SteamPath(); - - if (steamPath == null) - { - return null; - } - - //Default steam libary - string installPath = KSPDirectory(steamPath); - if (installPath != null) - { - return installPath; - } - - //Attempt to find through config file - string configPath = Path.Combine(steamPath, "config", "config.vdf"); - if (File.Exists(configPath)) - { - log.InfoFormat("Found Steam config file at {0}", configPath); - StreamReader reader = new StreamReader(configPath); - string line; - while ((line = reader.ReadLine()) != null) - { - // Found Steam library - if (line.Contains("BaseInstallFolder")) - { - - // This assumes config file is valid, we just skip it if it looks funny. - string[] split_line = line.Split('"'); - - if (split_line.Length > 3) - { - log.DebugFormat("Found a Steam Libary Location at {0}", split_line[3]); - - installPath = KSPDirectory(split_line[3]); - if (installPath != null) - { - log.InfoFormat("Found a KSP install at {0}", installPath); - return installPath; - } - } - } - } - } - - // Could not locate the folder. - return null; - } - - /// - /// Get the default non-Steam path to KSP on macOS - /// - /// - /// "/Applications/Kerbal Space Program" if it exists and we're on a Mac, else null - /// - public static string KSPMacPath() - { - if (Platform.IsMac) - { - string installPath = Path.Combine( - // This is "/Applications" in Mono on Mac - Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), - "Kerbal Space Program" - ); - return Directory.Exists(installPath) ? installPath : null; - } - return null; - } - /// /// Normalizes the path by replacing all \ with / and removing any trailing slash. /// diff --git a/Core/CompatibleGameVersions.cs b/Core/CompatibleGameVersions.cs new file mode 100644 index 0000000000..c54e0a92a7 --- /dev/null +++ b/Core/CompatibleGameVersions.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace CKAN +{ + [JsonConverter(typeof(CompatibleGameVersionsConverter))] + class CompatibleGameVersions + { + public string GameVersionWhenWritten { get; set; } + + public List Versions { get; set; } = new List(); + } + + public class CompatibleGameVersionsConverter : JsonPropertyNamesChangedConverter + { + protected override Dictionary mapping + { + get + { + return new Dictionary + { + { "VersionOfKspWhenWritten", "GameVersionWhenWritten" }, + { "CompatibleKspVersions", "Versions" } + }; + } + } + } +} diff --git a/Core/CompatibleKspVersionsDto.cs b/Core/CompatibleKspVersionsDto.cs deleted file mode 100644 index 4fcb27bb96..0000000000 --- a/Core/CompatibleKspVersionsDto.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace CKAN -{ - // - //This is DTO object to be serialized/deserialized as JSON - // - class CompatibleKspVersionsDto - { - public CompatibleKspVersionsDto() - { - this.CompatibleKspVersions = new List(); - } - - public String VersionOfKspWhenWritten { get; set; } - - public List CompatibleKspVersions { get; set; } - } -} diff --git a/Core/Configuration/IConfiguration.cs b/Core/Configuration/IConfiguration.cs index 1479d6b99e..50c025c44e 100644 --- a/Core/Configuration/IConfiguration.cs +++ b/Core/Configuration/IConfiguration.cs @@ -6,7 +6,6 @@ namespace CKAN.Configuration { public interface IConfiguration { - string AutoStartInstance { get; set; } /// @@ -53,25 +52,7 @@ public interface IConfiguration /// Token to set, or null to delete void SetAuthToken(string host, string token); - JBuilds GetKSPBuilds(); - void SetKSPBuilds(JBuilds buildMap); - - void SetRegistryToInstances(SortedList instances); - IEnumerable> GetInstances(); - } - - // - // THIS IS NOT THE BUILD MAP! If you are trying to access the build map, - // you want to use IKspBuildMap. - // - // This class represents the internal JSON structure of the build map, - // and should only be used by implementations of IKspBuildMap and - // IConfiguration. - // - public sealed class JBuilds - { - [JsonProperty("builds")] - // ReSharper disable once UnusedAutoPropertyAccessor.Local - public Dictionary Builds { get; set; } + void SetRegistryToInstances(SortedList instances); + IEnumerable> GetInstances(); } } diff --git a/Core/Configuration/JsonConfiguration.cs b/Core/Configuration/JsonConfiguration.cs index 43b70ebaa2..5f02498f30 100644 --- a/Core/Configuration/JsonConfiguration.cs +++ b/Core/Configuration/JsonConfiguration.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using Newtonsoft.Json; +using CKAN.Games; namespace CKAN.Configuration { @@ -11,6 +12,7 @@ public class JsonConfiguration : IConfiguration #region JSON Structures + [JsonConverter(typeof(ConfigConverter))] private class Config { public string AutoStartInstance { get; set; } @@ -18,15 +20,29 @@ private class Config public long? CacheSizeLimit { get; set; } public int? RefreshRate { get; set; } public string Language { get; set; } - public JBuilds KSPBuilds { get; set; } - public IList KspInstances = new List(); - public IDictionary AuthTokens = new Dictionary(); + public IList GameInstances { get; set; } = new List(); + public IDictionary AuthTokens { get; set; } = new Dictionary(); } - private class KspInstance + public class ConfigConverter : JsonPropertyNamesChangedConverter + { + protected override Dictionary mapping + { + get + { + return new Dictionary + { + { "KspInstances", "GameInstances" } + }; + } + } + } + + private class GameInstanceEntry { public string Name { get; set; } public string Path { get; set; } + public string Game { get; set; } } #endregion @@ -207,22 +223,6 @@ public string AutoStartInstance } } - // - // Create a new instance of JsonConfiguration. ServiceLocator maintains a - // singleton instance, so in general you should use that. However, the - // core state is static, so creating multiple instances is not an issue. - // - public JsonConfiguration() - { - lock (_lock) - { - if (config != null) - return; - - LoadConfig(); - } - } - // // For testing purposes only. This constructor discards the global configuration // state, and recreates it from the specified file. @@ -233,52 +233,38 @@ public JsonConfiguration() // doesn't get loaded from the default location first, as that might end up // creating files and directories that the user is trying to avoid creating by // specifying the configuration file on the command line. - public JsonConfiguration(string newConfig) + public JsonConfiguration(string newConfig = null) { lock (_lock) { - configFile = newConfig; - + configFile = newConfig ?? defaultConfigFile; LoadConfig(); } } - public JBuilds GetKSPBuilds() + public IEnumerable> GetInstances() { lock (_lock) { - return config.KSPBuilds; + return config.GameInstances.Select(instance => + new Tuple( + instance.Name, + instance.Path, + instance.Game) + ); } } - public void SetKSPBuilds(JBuilds buildMap) + public void SetRegistryToInstances(SortedList instances) { lock (_lock) { - config.KSPBuilds = buildMap; - - SaveConfig(); - } - } - - public IEnumerable> GetInstances() - { - lock (_lock) - { - return config.KspInstances.Select(instance => - new Tuple(instance.Name, instance.Path)); - } - } - - public void SetRegistryToInstances(SortedList instances) - { - lock (_lock) - { - config.KspInstances = instances.Select(instance => new KspInstance + config.GameInstances = instances.Select(instance => new GameInstanceEntry { Name = instance.Key, - Path = instance.Value.GameDir() + Path = instance.Value.GameDir(), + Game = instance.Value.game.ShortName }).ToList(); SaveConfig(); @@ -351,9 +337,20 @@ private void LoadConfig() config = new Config(); } - if (config.KspInstances == null) + if (config.GameInstances == null) { - config.KspInstances = new List(); + config.GameInstances = new List(); + } + else + { + var game = new KerbalSpaceProgram(); + foreach (GameInstanceEntry e in config.GameInstances) + { + if (e.Game == null) + { + e.Game = game.ShortName; + } + } } if (config.AuthTokens == null) @@ -396,14 +393,13 @@ private void Migrate() lock (_lock) { var instances = registry.GetInstances(); - config.KspInstances = instances.Select(instance => new KspInstance + config.GameInstances = instances.Select(instance => new GameInstanceEntry { Name = instance.Item1, - Path = instance.Item2 + Path = instance.Item2, + Game = instance.Item3 }).ToList(); - config.KSPBuilds = registry.GetKSPBuilds(); - config.AutoStartInstance = registry.AutoStartInstance; config.DownloadCacheDir = registry.DownloadCacheDir; config.CacheSizeLimit = registry.CacheSizeLimit; diff --git a/Core/Configuration/Win32RegistryConfiguration.cs b/Core/Configuration/Win32RegistryConfiguration.cs index 928c9d278d..69de5fd3dc 100644 --- a/Core/Configuration/Win32RegistryConfiguration.cs +++ b/Core/Configuration/Win32RegistryConfiguration.cs @@ -109,13 +109,16 @@ public Win32RegistryConfiguration() ConstructKey(CKAN_KEY_NO_PREFIX); } - private Tuple GetInstance(int i) + private Tuple GetInstance(int i) { - return new Tuple(GetRegistryValue("KSPInstanceName_" + i, string.Empty), - GetRegistryValue("KSPInstancePath_" + i, string.Empty)); + return new Tuple( + GetRegistryValue("KSPInstanceName_" + i, string.Empty), + GetRegistryValue("KSPInstancePath_" + i, string.Empty), + GetRegistryValue("KSPInstanceGame_" + i, string.Empty) + ); } - public void SetRegistryToInstances(SortedList instances) + public void SetRegistryToInstances(SortedList instances) { SetNumberOfInstances(instances.Count); @@ -126,32 +129,11 @@ public void SetRegistryToInstances(SortedList instances) } } - public IEnumerable> GetInstances() + public IEnumerable> GetInstances() { return Enumerable.Range(0, InstanceCount).Select(GetInstance).ToList(); } - public JBuilds GetKSPBuilds() - { - var raw = GetRegistryValue("KSPBuilds", null as string); - try - { - return JsonConvert.DeserializeObject(raw); - } - catch (Exception e) - { - Log.WarnFormat("Could not parse cached build map"); - Log.DebugFormat("{0}\n{1}", raw, e); - return null; - } - } - - public void SetKSPBuilds(JBuilds buildMap) - { - string json = JsonConvert.SerializeObject(buildMap); - SetRegistryValue(@"KSPBuilds", json); - } - public bool TryGetAuthToken(string host, out string token) { try @@ -232,7 +214,7 @@ private void SetNumberOfInstances(int count) SetRegistryValue(@"KSPInstanceCount", count); } - private void SetInstanceKeysTo(int instanceIndex, string name, KSP ksp) + private void SetInstanceKeysTo(int instanceIndex, string name, GameInstance ksp) { SetRegistryValue(@"KSPInstanceName_" + instanceIndex, name); SetRegistryValue(@"KSPInstancePath_" + instanceIndex, ksp.GameDir()); diff --git a/Core/Converters/JsonPropertyNamesChangedConverter.cs b/Core/Converters/JsonPropertyNamesChangedConverter.cs new file mode 100644 index 0000000000..ec1a0c5240 --- /dev/null +++ b/Core/Converters/JsonPropertyNamesChangedConverter.cs @@ -0,0 +1,50 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace CKAN +{ + public abstract class JsonPropertyNamesChangedConverter : JsonConverter + { + public override bool CanWrite => false; + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + + public override bool CanConvert(Type objectType) + { + return objectType.GetTypeInfo().IsClass; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + object instance = Activator.CreateInstance(objectType); + var props = objectType.GetTypeInfo().DeclaredProperties.ToList(); + JObject jo = JObject.Load(reader); + var changes = mapping; + foreach (JProperty jp in jo.Properties()) + { + string name; + if (!changes.TryGetValue(jp.Name, out name)) + { + name = jp.Name; + } + PropertyInfo prop = props.FirstOrDefault(pi => pi.CanWrite && ( + pi.GetCustomAttribute()?.PropertyName == name + || pi.Name == name)); + prop?.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer)); + } + return instance; + } + + // This is what you need to override in the child class + protected abstract Dictionary mapping + { + get; + } + } +} diff --git a/Core/DLC/BreakingGroundDlcDetector.cs b/Core/DLC/BreakingGroundDlcDetector.cs index 320cfa0dde..f8ecd6d6b0 100644 --- a/Core/DLC/BreakingGroundDlcDetector.cs +++ b/Core/DLC/BreakingGroundDlcDetector.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using CKAN.Games; namespace CKAN.DLC { @@ -8,6 +9,11 @@ namespace CKAN.DLC public sealed class BreakingGroundDlcDetector : StandardDlcDetectorBase { public BreakingGroundDlcDetector() - : base("BreakingGround", "Serenity", new Versioning.KspVersion(1, 7, 1)) { } + : base( + new KerbalSpaceProgram(), + "BreakingGround", + "Serenity", + new Versioning.GameVersion(1, 7, 1)) + { } } } diff --git a/Core/DLC/IDlcDetector.cs b/Core/DLC/IDlcDetector.cs index 92589a17fc..944ed55d74 100644 --- a/Core/DLC/IDlcDetector.cs +++ b/Core/DLC/IDlcDetector.cs @@ -1,4 +1,5 @@ using CKAN.Versioning; +using CKAN.Games; namespace CKAN.DLC { @@ -8,12 +9,12 @@ namespace CKAN.DLC public interface IDlcDetector { string IdentifierBaseName { get; } - KspVersion ReleaseGameVersion { get; } + GameVersion ReleaseGameVersion { get; } /// /// Checks if the relevant DLC is installed in the specific KSP installation. /// - /// The KSP installation to check. + /// The KSP installation to check. /// /// The identifier to use for the DLC's psuedo-module. Value is undefined if this method is undefined. /// @@ -26,18 +27,18 @@ public interface IDlcDetector /// /// true /// - /// When the relevant DLC is installed in the installation specified by . + /// When the relevant DLC is installed in the installation specified by . /// /// /// /// false /// - /// When the relevant DLC is not installed in the installation specified by . + /// When the relevant DLC is not installed in the installation specified by . /// /// /// /// - bool IsInstalled(KSP ksp, out string identifier, out UnmanagedModuleVersion version); + bool IsInstalled(GameInstance inst, out string identifier, out UnmanagedModuleVersion version); /// /// Path to the DLC directory relative to GameDir. @@ -50,6 +51,6 @@ public interface IDlcDetector /// Determines whether the DLC is allowed to be installed (or faked) /// on the specified base version (i.e. the game version of the KSP instance.) /// - bool AllowedOnBaseVersion(KspVersion baseVersion); + bool AllowedOnBaseVersion(GameVersion baseVersion); } } diff --git a/Core/DLC/MakingHistoryDlcDetector.cs b/Core/DLC/MakingHistoryDlcDetector.cs index bd87ce3381..40f54e05fd 100644 --- a/Core/DLC/MakingHistoryDlcDetector.cs +++ b/Core/DLC/MakingHistoryDlcDetector.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using CKAN.Games; namespace CKAN.DLC { @@ -8,10 +9,14 @@ namespace CKAN.DLC public sealed class MakingHistoryDlcDetector : StandardDlcDetectorBase { public MakingHistoryDlcDetector() - : base("MakingHistory", new Versioning.KspVersion(1, 4, 1), new Dictionary() + : base( + new KerbalSpaceProgram(), + "MakingHistory", + new Versioning.GameVersion(1, 4, 1), + new Dictionary() { { "1.0", "1.0.0" } - } - ) { } + }) + { } } } diff --git a/Core/DLC/StandardDlcDetectorBase.cs b/Core/DLC/StandardDlcDetectorBase.cs index 5d95e10b6d..ae6dc0916d 100644 --- a/Core/DLC/StandardDlcDetectorBase.cs +++ b/Core/DLC/StandardDlcDetectorBase.cs @@ -3,6 +3,7 @@ using System.IO; using System.Text.RegularExpressions; using CKAN.Versioning; +using CKAN.Games; namespace CKAN.DLC { @@ -16,21 +17,23 @@ namespace CKAN.DLC /// public abstract class StandardDlcDetectorBase : IDlcDetector { - public KspVersion ReleaseGameVersion { get; } + public GameVersion ReleaseGameVersion { get; } public string IdentifierBaseName { get; } private readonly string DirectoryBaseName; private readonly Dictionary CanonicalVersions; + private IGame game; + private static readonly Regex VersionPattern = new Regex( @"^Version\s+(?\S+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase ); - protected StandardDlcDetectorBase(string identifierBaseName, KspVersion releaseGameVersion, Dictionary canonicalVersions = null) - : this(identifierBaseName, identifierBaseName, releaseGameVersion, canonicalVersions) { } + protected StandardDlcDetectorBase(IGame game, string identifierBaseName, GameVersion releaseGameVersion, Dictionary canonicalVersions = null) + : this(game, identifierBaseName, identifierBaseName, releaseGameVersion, canonicalVersions) { } - protected StandardDlcDetectorBase(string identifierBaseName, string directoryBaseName, KspVersion releaseGameVersion, Dictionary canonicalVersions = null) + protected StandardDlcDetectorBase(IGame game, string identifierBaseName, string directoryBaseName, GameVersion releaseGameVersion, Dictionary canonicalVersions = null) { if (string.IsNullOrWhiteSpace(identifierBaseName)) throw new ArgumentException("Value must be provided.", nameof(identifierBaseName)); @@ -38,18 +41,19 @@ protected StandardDlcDetectorBase(string identifierBaseName, string directoryBas if (string.IsNullOrWhiteSpace(directoryBaseName)) throw new ArgumentException("Value must be provided.", nameof(directoryBaseName)); + this.game = game; IdentifierBaseName = identifierBaseName; DirectoryBaseName = directoryBaseName; ReleaseGameVersion = releaseGameVersion; CanonicalVersions = canonicalVersions ?? new Dictionary(); } - public virtual bool IsInstalled(KSP ksp, out string identifier, out UnmanagedModuleVersion version) + public virtual bool IsInstalled(GameInstance ksp, out string identifier, out UnmanagedModuleVersion version) { identifier = $"{IdentifierBaseName}-DLC"; version = null; - var directoryPath = Path.Combine(ksp.GameData(), "SquadExpansion", DirectoryBaseName); + var directoryPath = Path.Combine(game.PrimaryModDirectory(ksp), "SquadExpansion", DirectoryBaseName); if (Directory.Exists(directoryPath)) { var readmeFilePath = Path.Combine(directoryPath, "readme.txt"); @@ -86,7 +90,7 @@ public virtual string InstallPath() return Path.Combine("GameData", "SquadExpansion", DirectoryBaseName); } - public bool AllowedOnBaseVersion(KspVersion baseVersion) + public bool AllowedOnBaseVersion(GameVersion baseVersion) { return baseVersion >= ReleaseGameVersion; } diff --git a/Core/KSP.cs b/Core/GameInstance.cs similarity index 50% rename from Core/KSP.cs rename to Core/GameInstance.cs index 0e2f05083d..fea506f80e 100644 --- a/Core/KSP.cs +++ b/Core/GameInstance.cs @@ -8,43 +8,35 @@ using System.Transactions; using Autofac; using ChinhDo.Transactions.FileManager; -using CKAN.GameVersionProviders; -using CKAN.Versioning; using log4net; using Newtonsoft.Json; -[assembly: InternalsVisibleTo("CKAN.Tests")] +using CKAN.Games; +using CKAN.GameVersionProviders; +using CKAN.Versioning; namespace CKAN { /// - /// Everything for dealing with KSP itself. + /// Everything for dealing with a game folder. /// - public class KSP : IEquatable + public class GameInstance : IEquatable { - /// - /// List of DLLs that should never be added to the autodetect list. - /// - private static readonly HashSet DllIgnoreList = new HashSet - { - "GameData/Squad/Plugins/KSPSteamCtrlr.dll", - "GameData/Squad/Plugins/Steamworks.NET.dll" - }; - - public IUser User { get; set; } - #region Fields and Properties - private static readonly ILog log = LogManager.GetLogger(typeof(KSP)); + public IUser User { get; private set; } private readonly string gameDir; - private KspVersion version; - private List _compatibleVersions = new List(); + public readonly IGame game; + private GameVersion version; + private List _compatibleVersions = new List(); - public string Name { get; internal set; } - public KspVersion VersionOfKspWhenCompatibleVersionsWereStored { get; private set; } - public bool CompatibleVersionsAreFromDifferentKsp { get { return _compatibleVersions.Count > 0 && VersionOfKspWhenCompatibleVersionsWereStored != Version(); } } + public string Name { get; set; } + public GameVersion GameVersionWhenCompatibleVersionsWereStored { get; private set; } + public bool CompatibleVersionsAreFromDifferentGameVersion { get { return _compatibleVersions.Count > 0 && GameVersionWhenCompatibleVersionsWereStored != Version(); } } + + private static readonly ILog log = LogManager.GetLogger(typeof(GameInstance)); #endregion #region Construction and Initialisation @@ -54,12 +46,13 @@ public class KSP : IEquatable /// Will initialise a CKAN instance in the KSP dir if it does not already exist, /// if the directory contains a valid KSP install. /// - public KSP(string gameDir, string name, IUser user, bool scanGameData = true) + public GameInstance(IGame game, string gameDir, string name, IUser user, bool scan = true) { + this.game = game; Name = name; User = user; // Make sure our path is absolute and has normalised slashes. - this.gameDir = KSPPathUtils.NormalizePath(Path.GetFullPath(gameDir)); + this.gameDir = CKANPathUtils.NormalizePath(Path.GetFullPath(gameDir)); if (Platform.IsWindows) { // Normalized slashes are bad for pure drive letters, @@ -72,12 +65,19 @@ public KSP(string gameDir, string name, IUser user, bool scanGameData = true) } if (Valid) { - SetupCkanDirectories(scanGameData); + SetupCkanDirectories(scan); LoadCompatibleVersions(); } } - public bool Valid { get { return IsKspDir(gameDir) && Version() != null; } } + public bool Valid + { + get + { + return game.GameInFolder(new DirectoryInfo(gameDir)) + && Version() != null; + } + } /// /// Create the CKAN directory and any supporting files. @@ -98,7 +98,7 @@ private void SetupCkanDirectories(bool scan = true) if (scan) { User.RaiseMessage("Scanning for installed mods..."); - ScanGameData(); + Scan(); } } @@ -124,7 +124,7 @@ private void SetupCkanDirectories(bool scan = true) log.InfoFormat("Initialised {0}", CkanDir()); } - public void SetCompatibleVersions(List compatibleVersions) + public void SetCompatibleVersions(List compatibleVersions) { this._compatibleVersions = compatibleVersions.Distinct().ToList(); SaveCompatibleVersions(); @@ -132,50 +132,46 @@ public void SetCompatibleVersions(List compatibleVersions) private void SaveCompatibleVersions() { - CompatibleKspVersionsDto compatibleKspVersionsDto = new CompatibleKspVersionsDto(); - - compatibleKspVersionsDto.VersionOfKspWhenWritten = Version()?.ToString(); - compatibleKspVersionsDto.CompatibleKspVersions = _compatibleVersions.Select(v => v.ToString()).ToList(); - - String json = JsonConvert.SerializeObject(compatibleKspVersionsDto); - File.WriteAllText(CompatibleKspVersionsFile(), json); - - this.VersionOfKspWhenCompatibleVersionsWereStored = Version(); + File.WriteAllText( + CompatibleGameVersionsFile(), + JsonConvert.SerializeObject(new CompatibleGameVersions() + { + GameVersionWhenWritten = Version()?.ToString(), + Versions = _compatibleVersions.Select(v => v.ToString()).ToList() + }) + ); + GameVersionWhenCompatibleVersionsWereStored = Version(); } private void LoadCompatibleVersions() { - String path = CompatibleKspVersionsFile(); + String path = CompatibleGameVersionsFile(); if (File.Exists(path)) { - string json = File.ReadAllText(path); - CompatibleKspVersionsDto compatibleKspVersionsDto = JsonConvert.DeserializeObject(json); + CompatibleGameVersions compatibleGameVersions = JsonConvert.DeserializeObject(File.ReadAllText(path)); - _compatibleVersions = compatibleKspVersionsDto.CompatibleKspVersions.Select(v => KspVersion.Parse(v)).ToList(); + _compatibleVersions = compatibleGameVersions.Versions + .Select(v => GameVersion.Parse(v)).ToList(); // Get version without throwing exceptions for null - KspVersion mainVer = null; - KspVersion.TryParse(compatibleKspVersionsDto.VersionOfKspWhenWritten, out mainVer); - this.VersionOfKspWhenCompatibleVersionsWereStored = mainVer; + GameVersion mainVer = null; + GameVersion.TryParse(compatibleGameVersions.GameVersionWhenWritten, out mainVer); + GameVersionWhenCompatibleVersionsWereStored = mainVer; } } - private string CompatibleKspVersionsFile() + private string CompatibleGameVersionsFile() { - return Path.Combine(CkanDir(), "compatible_ksp_versions.json"); + return Path.Combine(CkanDir(), game.CompatibleVersionsFile); } - public List GetCompatibleVersions() + public List GetCompatibleVersions() { - return new List(this._compatibleVersions); + return new List(this._compatibleVersions); } #endregion - #region Destructors and Disposal - - #endregion - #region KSP Directory Detection and Versioning /// @@ -183,27 +179,28 @@ public List GetCompatibleVersions() /// directory as the game, or if the game is in the current directory. /// Otherwise, returns null. /// - public static string PortableDir() + public static string PortableDir(IGame game) { string curDir = Directory.GetCurrentDirectory(); - log.DebugFormat("Checking if KSP is in my current dir: {0}", curDir); + log.DebugFormat("Checking if {0} is in my current dir: {1}", + game.ShortName, curDir); - if (IsKspDir(curDir)) + if (game.GameInFolder(new DirectoryInfo(curDir))) { - log.InfoFormat("KSP found at {0}", curDir); + log.InfoFormat("{0} found at {1}", game.ShortName, curDir); return curDir; } // Find the directory our executable is stored in. - // In Perl, this is just `use FindBin qw($Bin);` Verbose enough, C#? string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - log.DebugFormat("Checking if KSP is in my exe dir: {0}", exeDir); + log.DebugFormat("Checking if {0} is in my exe dir: {1}", + game.ShortName, exeDir); - if (curDir != exeDir && IsKspDir(exeDir)) + if (curDir != exeDir && game.GameInFolder(new DirectoryInfo(exeDir))) { - log.InfoFormat("KSP found at {0}", exeDir); + log.InfoFormat("{0} found at {1}", game.ShortName, exeDir); return exeDir; } @@ -215,30 +212,33 @@ public static string PortableDir() /// Returns the path to the install on success. /// Throws a DirectoryNotFoundException on failure. /// - public static string FindGameDir() + public static string FindGameDir(IGame game) { // See if we can find KSP as part of a Steam install. - string kspSteamPath = KSPPathUtils.KSPSteamPath(); - if (kspSteamPath != null) + string gameSteamPath = game.SteamPath(); + if (gameSteamPath != null) { - if (IsKspDir(kspSteamPath)) + if (game.GameInFolder(new DirectoryInfo(gameSteamPath))) { - return kspSteamPath; + return gameSteamPath; } - log.DebugFormat("Have Steam, but KSP is not at \"{0}\".", kspSteamPath); + log.DebugFormat("Have Steam, but {0} is not at \"{1}\".", + game.ShortName, gameSteamPath); } // See if we can find a non-Steam Mac KSP install - string kspMacPath = KSPPathUtils.KSPMacPath(); + string kspMacPath = game.MacPath(); if (kspMacPath != null) { - if (IsKspDir(kspMacPath)) + if (game.GameInFolder(new DirectoryInfo(kspMacPath))) { - log.InfoFormat("Found a KSP install at {0}", kspMacPath); + log.InfoFormat("Found a {0} install at {1}", + game.ShortName, kspMacPath); return kspMacPath; } - log.DebugFormat("Default Mac KSP folder exists at \"{0}\", but KSP is not installed there.", kspMacPath); + log.DebugFormat("Default Mac {0} folder exists at \"{1}\", but {0} is not installed there.", + game.ShortName, kspMacPath); } // Oh noes! We can't find KSP! @@ -246,67 +246,16 @@ public static string FindGameDir() } /// - /// Checks if the specified directory looks like a KSP directory. - /// Returns true if found, false if not. - /// Checking for a GameData directory probably isn't the best way to - /// detect KSP, but it works. More robust implementations welcome. - /// - public static bool IsKspDir(string directory) - { - return Directory.Exists(Path.Combine(directory, "GameData")); - } - - - /// - /// Detects the version of KSP in a given directory. - /// Throws a NotKSPDirKraken if anything goes wrong. + /// Detects the version of a game in a given directory. /// - private static KspVersion DetectVersion(string directory) + private GameVersion DetectVersion(string directory) { - KspVersion version = DetectVersionInternal(directory); - + GameVersion version = game.DetectVersion(new DirectoryInfo(directory)); if (version != null) { log.DebugFormat("Found version {0}", version); - return version; - } - else - { - return null; - } - } - - private static KspVersion DetectVersionInternal(string directory) - { - var buildIdVersionProvider = ServiceLocator.Container - .ResolveKeyed(KspVersionSource.BuildId); - - KspVersion version; - if (buildIdVersionProvider.TryGetVersion(directory, out version)) - { - return version; - } - else - { - var readmeVersionProvider = ServiceLocator.Container - .ResolveKeyed(KspVersionSource.Readme); - - return readmeVersionProvider.TryGetVersion(directory, out version) ? version : null; - } - } - - /// - /// Rebuilds the "Ships" directory inside the current KSP instance - /// - public void RebuildKSPSubDir() - { - string[] FoldersToCheck = { "Ships/VAB", "Ships/SPH", "Ships/@thumbs/VAB", "Ships/@thumbs/SPH" }; - foreach (string sRelativePath in FoldersToCheck) - { - string sAbsolutePath = ToAbsoluteGameDir(sRelativePath); - if (!Directory.Exists(sAbsolutePath)) - Directory.CreateDirectory(sAbsolutePath); } + return version; } #endregion @@ -318,13 +267,6 @@ public string GameDir() return gameDir; } - public string GameData() - { - return KSPPathUtils.NormalizePath( - Path.Combine(GameDir(), "GameData") - ); - } - public string CkanDir() { if (!Valid) @@ -332,103 +274,31 @@ public string CkanDir() log.Error("Could not find KSP version"); throw new NotKSPDirKraken(gameDir, "Could not find KSP version in buildID.txt or readme.txt"); } - return KSPPathUtils.NormalizePath( - Path.Combine(GameDir(), "CKAN") - ); + return CKANPathUtils.NormalizePath( + Path.Combine(GameDir(), "CKAN")); } public string DownloadCacheDir() { - return KSPPathUtils.NormalizePath( - Path.Combine(CkanDir(), "downloads") - ); + return CKANPathUtils.NormalizePath( + Path.Combine(CkanDir(), "downloads")); } public string InstallHistoryDir() { - return KSPPathUtils.NormalizePath( + return CKANPathUtils.NormalizePath( Path.Combine(CkanDir(), "history") ); } - public string Missions() - { - return KSPPathUtils.NormalizePath( - Path.Combine(GameDir(), "Missions") - ); - } - - public string Ships() - { - return KSPPathUtils.NormalizePath( - Path.Combine(GameDir(), "Ships") - ); - } - - public string ShipsVab() - { - return KSPPathUtils.NormalizePath( - Path.Combine(Ships(), "VAB") - ); - } - - public string ShipsSph() - { - return KSPPathUtils.NormalizePath( - Path.Combine(Ships(), "SPH") - ); - } - - public string ShipsThumbs() - { - return KSPPathUtils.NormalizePath( - Path.Combine(Ships(), "@thumbs") - ); - } - - public string ShipsThumbsSPH() - { - return KSPPathUtils.NormalizePath( - Path.Combine(ShipsThumbs(), "SPH") - ); - } - - public string ShipsThumbsVAB() - { - return KSPPathUtils.NormalizePath( - Path.Combine(ShipsThumbs(), "VAB") - ); - } - - public string ShipsScript() - { - return KSPPathUtils.NormalizePath( - Path.Combine(Ships(), "Script") - ); - } - - public string Tutorial() - { - return KSPPathUtils.NormalizePath( - Path.Combine(GameDir(), "saves", "training") - ); - } - - public string Scenarios() - { - return KSPPathUtils.NormalizePath( - Path.Combine(GameDir(), "saves", "scenarios") - ); - } - public string TempDir() { - return KSPPathUtils.NormalizePath( + return CKANPathUtils.NormalizePath( Path.Combine(CkanDir(), "temp") ); } - public KspVersion Version() + public GameVersion Version() { if (version == null) { @@ -437,10 +307,9 @@ public KspVersion Version() return version; } - - public KspVersionCriteria VersionCriteria() + public GameVersionCriteria VersionCriteria() { - return new KspVersionCriteria(Version(), _compatibleVersions); + return new GameVersionCriteria(Version(), _compatibleVersions); } #endregion @@ -456,7 +325,7 @@ public KspVersionCriteria VersionCriteria() /// /// True if found anything different, false if same as before /// - public bool ScanGameData() + public bool Scan() { var manager = RegistryManager.Instance(this); using (TransactionScope tx = CkanTransaction.CreateTransactionScope()) @@ -473,10 +342,11 @@ public bool ScanGameData() // // The least evil is to walk it once, and filter it ourselves. IEnumerable files = Directory - .EnumerateFiles(GameData(), "*", SearchOption.AllDirectories) + .EnumerateFiles(game.PrimaryModDirectory(this), "*", SearchOption.AllDirectories) .Where(file => dllRegex.IsMatch(file)) - .Select(KSPPathUtils.NormalizePath) - .Where(absPath => !DllIgnoreList.Contains(ToRelativeGameDir(absPath))); + .Select(CKANPathUtils.NormalizePath) + .Where(absPath => !game.StockFolders.Any(f => + ToRelativeGameDir(absPath).StartsWith($"{f}/"))); foreach (string dll in files) { @@ -506,7 +376,7 @@ public bool ScanGameData() /// public string ToRelativeGameDir(string path) { - return KSPPathUtils.ToRelative(path, GameDir()); + return CKANPathUtils.ToRelative(path, GameDir()); } /// @@ -515,22 +385,22 @@ public string ToRelativeGameDir(string path) /// public string ToAbsoluteGameDir(string path) { - return KSPPathUtils.ToAbsolute(path, GameDir()); + return CKANPathUtils.ToAbsolute(path, GameDir()); } public override string ToString() { - return "KSP Install: " + gameDir; + return $"{game.ShortName} Install: {gameDir}"; } - public bool Equals(KSP other) + public bool Equals(GameInstance other) { return other != null && gameDir.Equals(other.GameDir()); } public override bool Equals(object obj) { - return Equals(obj as KSP); + return Equals(obj as GameInstance); } public override int GetHashCode() diff --git a/Core/KSPManager.cs b/Core/GameInstanceManager.cs similarity index 73% rename from Core/KSPManager.cs rename to Core/GameInstanceManager.cs index f70042c00d..70e1cdd287 100644 --- a/Core/KSPManager.cs +++ b/Core/GameInstanceManager.cs @@ -5,26 +5,37 @@ using System.Transactions; using Autofac; using ChinhDo.Transactions.FileManager; +using log4net; using CKAN.Versioning; using CKAN.Configuration; -using log4net; +using CKAN.Games; namespace CKAN { /// /// Manage multiple KSP installs. /// - public class KSPManager : IDisposable + public class GameInstanceManager : IDisposable { + private static IGame[] knownGames = new IGame[] + { + new KerbalSpaceProgram() + }; + public IUser User { get; set; } public IConfiguration Configuration { get; set; } - public KSP CurrentInstance { get; set; } + public GameInstance CurrentInstance { get; set; } public NetModuleCache Cache { get; private set; } - private static readonly ILog log = LogManager.GetLogger(typeof (KSPManager)); + private static readonly ILog log = LogManager.GetLogger(typeof (GameInstanceManager)); - private readonly SortedList instances = new SortedList(); + private readonly SortedList instances = new SortedList(); + + public string[] AllBuildIDFiles => knownGames + .SelectMany(g => g.BuildIDFiles) + .Distinct() + .ToArray(); public string AutoStartInstance { @@ -44,12 +55,12 @@ private set } } - public SortedList Instances + public SortedList Instances { - get { return new SortedList(instances); } + get { return new SortedList(instances); } } - public KSPManager(IUser user, IConfiguration configuration = null) + public GameInstanceManager(IUser user, IConfiguration configuration = null) { User = user; Configuration = configuration ?? ServiceLocator.Container.Resolve(); @@ -71,25 +82,30 @@ public KSPManager(IUser user, IConfiguration configuration = null) /// /// Returns null if we have multiple instances, but none of them are preferred. /// - public KSP GetPreferredInstance() + public GameInstance GetPreferredInstance() { CurrentInstance = _GetPreferredInstance(); return CurrentInstance; } // Actual worker for GetPreferredInstance() - internal KSP _GetPreferredInstance() + internal GameInstance _GetPreferredInstance() { - // First check if we're part of a portable install - // Note that this *does not* register in the registry. - string path = KSP.PortableDir(); - - if (path != null) + foreach (IGame game in knownGames) { - KSP portableInst = new KSP(path, "portable", User); - if (portableInst.Valid) + // TODO: Check which ones match, prompt user if >1 + + // First check if we're part of a portable install + // Note that this *does not* register in the registry. + string path = GameInstance.PortableDir(game); + + if (path != null) { - return portableInst; + GameInstance portableInst = new GameInstance(game, path, "portable", User); + if (portableInst.Valid) + { + return portableInst; + } } } @@ -115,37 +131,48 @@ internal KSP _GetPreferredInstance() } /// - /// Find and register a default instance by running - /// game autodetection code. + /// Find and register default instances by running + /// game autodetection code. Registers one per known game, + /// uses first found as default. /// - /// Returns the resulting KSP object if found. + /// Returns the resulting game instance if found. /// - public KSP FindAndRegisterDefaultInstance() + public GameInstance FindAndRegisterDefaultInstance() { if (instances.Any()) - throw new KSPManagerKraken("Attempted to scan for defaults with instances in registry"); - - try { - string gamedir = KSP.FindGameDir(); - KSP foundInst = new KSP(gamedir, "auto", User); - return foundInst.Valid ? AddInstance(foundInst) : null; - } - catch (DirectoryNotFoundException) - { - return null; + throw new KSPManagerKraken("Attempted to scan for defaults with instances in registry"); } - catch (NotKSPDirKraken) + GameInstance val = null; + foreach (IGame game in knownGames) { - return null; + try + { + string gamedir = GameInstance.FindGameDir(game); + GameInstance foundInst = new GameInstance( + game, gamedir, $"Auto {game.ShortName}", User); + if (foundInst.Valid) + { + var inst = AddInstance(foundInst); + val = val ?? inst; + } + } + catch (DirectoryNotFoundException) + { + // Thrown if no folder found for a game + } + catch (NotKSPDirKraken) + { + } } + return val; } /// /// Adds a KSP instance to registry. /// Returns the resulting KSP object. /// - public KSP AddInstance(KSP ksp_instance) + public GameInstance AddInstance(GameInstance ksp_instance) { if (ksp_instance.Valid) { @@ -160,6 +187,29 @@ public KSP AddInstance(KSP ksp_instance) return ksp_instance; } + public GameInstance AddInstance(string path, string name, IUser user) + { + var matchingGames = knownGames + .Where(g => g.GameInFolder(new DirectoryInfo(path))) + .ToList(); + switch (matchingGames.Count) + { + case 0: + throw new NotKSPDirKraken(path); + + case 1: + return AddInstance(new GameInstance( + matchingGames.First(), + path, name, user + )); + + default: + // TODO: Prompt user to choose + return null; + + } + } + /// /// Clones an existing KSP installation. /// @@ -171,7 +221,7 @@ public KSP AddInstance(KSP ksp_instance) /// Thrown by CopyDirectory() if directory doesn't exist. Should never be thrown here. /// Thrown by CopyDirectory() if the target folder already exists and is not empty. /// Thrown by CopyDirectory() if something goes wrong during the process. - public void CloneInstance(KSP existingInstance, string newName, string newPath) + public void CloneInstance(GameInstance existingInstance, string newName, string newPath) { if (HasInstance(newName)) { @@ -186,7 +236,7 @@ public void CloneInstance(KSP existingInstance, string newName, string newPath) Utilities.CopyDirectory(existingInstance.GameDir(), newPath, true); // Add the new instance to the registry - KSP new_instance = new KSP(newPath, newName, User); + GameInstance new_instance = new GameInstance(existingInstance.game, newPath, newName, User); AddInstance(new_instance); } @@ -199,7 +249,7 @@ public void CloneInstance(KSP existingInstance, string newName, string newPath) /// The IDlcDetector implementations for the DLCs that should be faked and the requested dlc version as a dictionary. /// Thrown if the instance name is already in use. /// Thrown by AddInstance() if created instance is not valid, e.g. if a write operation didn't complete for whatever reason. - public void FakeInstance(string newName, string newPath, KspVersion version, Dictionary dlcs = null) + public void FakeInstance(IGame game, string newName, string newPath, GameVersion version, Dictionary dlcs = null) { TxFileManager fileMgr = new TxFileManager(); using (TransactionScope transaction = CkanTransaction.CreateTransactionScope()) @@ -210,9 +260,9 @@ public void FakeInstance(string newName, string newPath, KspVersion version, Dic } - if (!version.InBuildMap()) + if (!version.InBuildMap(game)) { - throw new BadKSPVersionKraken(String.Format("The specified KSP version is not a known version: {0}", version.ToString())); + throw new BadGameVersionKraken(String.Format("The specified KSP version is not a known version: {0}", version.ToString())); } if (Directory.Exists(newPath) && (Directory.GetFiles(newPath).Length != 0 || Directory.GetDirectories(newPath).Length != 0)) { @@ -242,18 +292,18 @@ public void FakeInstance(string newName, string newPath, KspVersion version, Dic } // Create the readme.txt WITHOUT build number. - fileMgr.WriteAllText(Path.Combine(newPath, "readme.txt"), String.Format("Version {0}", new KspVersion(version.Major, version.Minor, version.Patch).ToString())); + fileMgr.WriteAllText(Path.Combine(newPath, "readme.txt"), String.Format("Version {0}", new GameVersion(version.Major, version.Minor, version.Patch).ToString())); // Create the needed folder structure and the readme.txt for DLCs that should be simulated. if (dlcs != null) { - foreach (KeyValuePair dlc in dlcs) + foreach (KeyValuePair dlc in dlcs) { DLC.IDlcDetector dlcDetector = dlc.Key; - KspVersion dlcVersion = dlc.Value; + GameVersion dlcVersion = dlc.Value; if (!dlcDetector.AllowedOnBaseVersion(version)) - throw new WrongKSPVersionKraken( + throw new WrongGameVersionKraken( version, String.Format("KSP version {0} or above is needed for {1} DLC.", dlcDetector.ReleaseGameVersion, @@ -269,7 +319,7 @@ public void FakeInstance(string newName, string newPath, KspVersion version, Dic } // Add the new instance to the registry - KSP new_instance = new KSP(newPath, newName, User, false); + GameInstance new_instance = new GameInstance(game, newPath, newName, User, false); AddInstance(new_instance); transaction.Complete(); } @@ -337,7 +387,7 @@ public void RemoveInstance(string name) public void RenameInstance(string from, string to) { // TODO: What should we do if our target name already exists? - KSP ksp = instances[from]; + GameInstance ksp = instances[from]; instances.Remove(from); ksp.Name = to; instances.Add(to, ksp); @@ -370,14 +420,51 @@ public void SetCurrentInstance(string name) public void SetCurrentInstanceByPath(string path) { - KSP ksp = new KSP(path, "custom", User); - if (ksp.Valid) + var matchingGames = knownGames + .Where(g => g.GameInFolder(new DirectoryInfo(path))) + .ToList(); + switch (matchingGames.Count) { - CurrentInstance = ksp; + case 0: + throw new NotKSPDirKraken(path); + + case 1: + GameInstance ksp = new GameInstance( + matchingGames.First(), path, "custom", User); + if (ksp.Valid) + { + CurrentInstance = ksp; + } + else + { + throw new NotKSPDirKraken(ksp.GameDir()); + } + break; + + default: + // TODO: Prompt user to choose + break; } - else + } + + public GameInstance InstanceAt(string path, string name) + { + var matchingGames = knownGames + .Where(g => g.GameInFolder(new DirectoryInfo(path))) + .ToList(); + switch (matchingGames.Count) { - throw new NotKSPDirKraken(ksp.GameDir()); + case 0: + return null; + + case 1: + return new GameInstance( + matchingGames.First(), path, "custom", User); + + default: + // TODO: Prompt user to choose + return null; + } } @@ -402,6 +489,11 @@ public bool HasInstance(string name) return instances.ContainsKey(name); } + public IGame GameOfInstance(string name) + { + return instances[name].game; + } + public void ClearAutoStart() { Configuration.AutoStartInstance = null; @@ -413,13 +505,16 @@ public void LoadInstancesFromRegistry() instances.Clear(); - foreach (Tuple instance in Configuration.GetInstances()) + foreach (Tuple instance in Configuration.GetInstances()) { var name = instance.Item1; var path = instance.Item2; + var gameName = instance.Item3; + var game = knownGames.FirstOrDefault(g => g.ShortName == gameName) + ?? knownGames[0]; log.DebugFormat("Loading {0} from {1}", name, path); // Add unconditionally, sort out invalid instances downstream - instances.Add(name, new KSP(path, name, User)); + instances.Add(name, new GameInstance(game, path, name, User)); } if (!Directory.Exists(Configuration.DownloadCacheDir)) @@ -492,5 +587,10 @@ public void Dispose() // Attempting to dispose of the related RegistryManager object here is a bad idea, it cause loads of failures } + public static bool IsGameInstanceDir(DirectoryInfo path) + { + return knownGames.Any(g => g.GameInFolder(path)); + } + } } diff --git a/Core/GameVersionProviders/IGameVersionProvider.cs b/Core/GameVersionProviders/IGameVersionProvider.cs index 96204ec4eb..1025c03c33 100644 --- a/Core/GameVersionProviders/IGameVersionProvider.cs +++ b/Core/GameVersionProviders/IGameVersionProvider.cs @@ -4,6 +4,6 @@ namespace CKAN.GameVersionProviders { public interface IGameVersionProvider { - bool TryGetVersion(string directory, out KspVersion result); + bool TryGetVersion(string directory, out GameVersion result); } } diff --git a/Core/GameVersionProviders/IKspBuildMap.cs b/Core/GameVersionProviders/IKspBuildMap.cs index a383e3b58e..3cfac38e4d 100644 --- a/Core/GameVersionProviders/IKspBuildMap.cs +++ b/Core/GameVersionProviders/IKspBuildMap.cs @@ -3,19 +3,12 @@ namespace CKAN.GameVersionProviders { - public enum BuildMapSource - { - Embedded, - Remote, - Cache, - }; - public interface IKspBuildMap { - KspVersion this[string buildId] { get; } + GameVersion this[string buildId] { get; } - List KnownVersions { get; } + List KnownVersions { get; } - void Refresh(BuildMapSource source = BuildMapSource.Remote); + void Refresh(); } } diff --git a/Core/GameVersionProviders/KspBuildIdVersionProvider.cs b/Core/GameVersionProviders/KspBuildIdVersionProvider.cs index 050f66cead..1b8941e8e5 100644 --- a/Core/GameVersionProviders/KspBuildIdVersionProvider.cs +++ b/Core/GameVersionProviders/KspBuildIdVersionProvider.cs @@ -22,17 +22,17 @@ public KspBuildIdVersionProvider(IKspBuildMap kspBuildMap) _kspBuildMap = kspBuildMap; } - public bool TryGetVersion(string directory, out KspVersion result) + public bool TryGetVersion(string directory, out GameVersion result) { - KspVersion buildIdVersion; + GameVersion buildIdVersion; var hasBuildId = TryGetVersionFromFile(Path.Combine(directory, "buildID.txt"), out buildIdVersion); - KspVersion buildId64Version; + GameVersion buildId64Version; var hasBuildId64 = TryGetVersionFromFile(Path.Combine(directory, "buildID64.txt"), out buildId64Version); if (hasBuildId && hasBuildId64) { - result = KspVersion.Max(buildIdVersion, buildId64Version); + result = GameVersion.Max(buildIdVersion, buildId64Version); if (buildIdVersion != buildId64Version) { @@ -58,12 +58,12 @@ public bool TryGetVersion(string directory, out KspVersion result) } else { - result = default(KspVersion); + result = default(GameVersion); return false; } } - private bool TryGetVersionFromFile(string file, out KspVersion result) + private bool TryGetVersionFromFile(string file, out GameVersion result) { if (File.Exists(file)) { @@ -84,7 +84,7 @@ private bool TryGetVersionFromFile(string file, out KspVersion result) } } - result = default(KspVersion); + result = default(GameVersion); return false; } } diff --git a/Core/GameVersionProviders/KspBuildMap.cs b/Core/GameVersionProviders/KspBuildMap.cs index 59ea123a9f..a4bce2c9f7 100644 --- a/Core/GameVersionProviders/KspBuildMap.cs +++ b/Core/GameVersionProviders/KspBuildMap.cs @@ -9,6 +9,21 @@ namespace CKAN.GameVersionProviders { + // + // THIS IS NOT THE BUILD MAP! If you are trying to access the build map, + // you want to use IKspBuildMap. + // + // This class represents the internal JSON structure of the build map, + // and should only be used by implementations of IKspBuildMap and + // IConfiguration. + // + public sealed class JBuilds + { + [JsonProperty("builds")] + // ReSharper disable once UnusedAutoPropertyAccessor.Local + public Dictionary Builds { get; set; } + } + // ReSharper disable once ClassNeverInstantiated.Global public sealed class KspBuildMap : IKspBuildMap { @@ -22,26 +37,26 @@ public sealed class KspBuildMap : IKspBuildMap private readonly IConfiguration _configuration; private JBuilds _jBuilds; - public KspVersion this[string buildId] + public GameVersion this[string buildId] { get { EnsureBuildMap(); string version; - return _jBuilds.Builds.TryGetValue(buildId, out version) ? KspVersion.Parse(version) : null; + return _jBuilds.Builds.TryGetValue(buildId, out version) ? GameVersion.Parse(version) : null; } } - public List KnownVersions + public List KnownVersions { get { EnsureBuildMap(); - List knownVersions = new List(); + List knownVersions = new List(); foreach (var version in _jBuilds.Builds) { - knownVersions.Add(KspVersion.Parse(version.Value)); + knownVersions.Add(GameVersion.Parse(version.Value)); } return knownVersions; } @@ -60,7 +75,7 @@ private void EnsureBuildMap() { if (ReferenceEquals(_jBuilds, null)) { - Refresh(BuildMapSource.Cache); + Refresh(); } } } @@ -69,21 +84,9 @@ private void EnsureBuildMap() /// /// Load a build map /// - /// Remote to download builds.json from GitHub (default), Cache to use the data from the last remote refresh, Embedded to use the builds.json built into the exe - public void Refresh(BuildMapSource source = BuildMapSource.Remote) + public void Refresh() { - switch (source) - { - case BuildMapSource.Cache: - if (TrySetRegistryBuildMap()) return; - if (TrySetRemoteBuildMap()) return; - break; - - case BuildMapSource.Remote: - if (TrySetRemoteBuildMap()) return; - if (TrySetRegistryBuildMap()) return; - break; - } + if (TrySetRemoteBuildMap()) return; if (TrySetEmbeddedBuildMap()) return; Log.Warn("Could not refresh the build map from any source"); @@ -111,7 +114,6 @@ private bool TrySetRemoteBuildMap() if (TrySetBuildMap(json)) { - _configuration.SetKSPBuilds(_jBuilds); return true; } else @@ -127,29 +129,6 @@ private bool TrySetRemoteBuildMap() } } - private bool TrySetRegistryBuildMap() - { - try - { - var json = _configuration.GetKSPBuilds(); - if (json != null) - { - _jBuilds = json; - return true; - } - else - { - return false; - } - } - catch (Exception e) - { - Log.WarnFormat("Could not retrieve build map from configuration"); - Log.Debug(e); - return false; - } - } - private bool TrySetEmbeddedBuildMap() { try diff --git a/Core/GameVersionProviders/KspReadmeVersionProvider.cs b/Core/GameVersionProviders/KspReadmeVersionProvider.cs index f1024b8819..40371272c2 100644 --- a/Core/GameVersionProviders/KspReadmeVersionProvider.cs +++ b/Core/GameVersionProviders/KspReadmeVersionProvider.cs @@ -12,7 +12,7 @@ public sealed class KspReadmeVersionProvider : IGameVersionProvider RegexOptions.IgnoreCase | RegexOptions.Compiled ); - public bool TryGetVersion(string directory, out KspVersion result) + public bool TryGetVersion(string directory, out GameVersion result) { var readmePath = Path.Combine(directory, "readme.txt"); @@ -25,12 +25,12 @@ public bool TryGetVersion(string directory, out KspVersion result) if (match != null) { - result = KspVersion.Parse(match.Groups["version"].Value); + result = GameVersion.Parse(match.Groups["version"].Value); return true; } } - result = default(KspVersion); + result = default(GameVersion); return false; } } diff --git a/Core/GameVersionProviders/KspVersionSource.cs b/Core/GameVersionProviders/KspVersionSource.cs index 637e21997e..503d894e28 100644 --- a/Core/GameVersionProviders/KspVersionSource.cs +++ b/Core/GameVersionProviders/KspVersionSource.cs @@ -1,6 +1,6 @@ namespace CKAN.GameVersionProviders { - public enum KspVersionSource + public enum GameVersionSource { BuildId = 1, Readme = 2 diff --git a/Core/Games/IGame.cs b/Core/Games/IGame.cs new file mode 100644 index 0000000000..3ef2d15310 --- /dev/null +++ b/Core/Games/IGame.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using System.Collections.Generic; +using Newtonsoft.Json; +using CKAN.GameVersionProviders; +using CKAN.Versioning; + +namespace CKAN.Games +{ + public interface IGame + { + // Identification, used for display and saved/loaded in settings JSON + // Must be unique! + string ShortName { get; } + + // Where are we? + bool GameInFolder(DirectoryInfo where); + string SteamPath(); + string MacPath(); + + // What do we contain? + string PrimaryModDirectoryRelative { get; } + string PrimaryModDirectory(GameInstance inst); + string[] StockFolders { get; } + bool IsReservedDirectory(GameInstance inst, string path); + bool AllowInstallationIn(string name, out string path); + void RebuildSubdirectories(GameInstance inst); + string DefaultCommandLine { get; } + string[] AdjustCommandLine(string[] args, GameVersion installedVersion); + + // Which versions exist and which is present? + List KnownVersions { get; } + GameVersion DetectVersion(DirectoryInfo where); + string CompatibleVersionsFile { get; } + string[] BuildIDFiles { get; } + + // How to get metadata + Uri DefaultRepositoryURL { get; } + Uri RepositoryListURL { get; } + } + +} diff --git a/Core/Games/KerbalSpaceProgram.cs b/Core/Games/KerbalSpaceProgram.cs new file mode 100644 index 0000000000..8fe9f77a33 --- /dev/null +++ b/Core/Games/KerbalSpaceProgram.cs @@ -0,0 +1,323 @@ +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Autofac; +using log4net; +using CKAN.GameVersionProviders; +using CKAN.Versioning; + +namespace CKAN.Games +{ + public class KerbalSpaceProgram : IGame + { + public string ShortName => "KSP"; + + public bool GameInFolder(DirectoryInfo where) + { + return Directory.Exists(Path.Combine(where.FullName, "GameData")); + } + + /// + /// Finds the Steam KSP path. Returns null if the folder cannot be located. + /// + /// The KSP path. + public string SteamPath() + { + // Attempt to get the Steam path. + string steamPath = CKANPathUtils.SteamPath(); + + if (steamPath == null) + { + return null; + } + + // Default steam libary + string installPath = KSPDirectory(steamPath); + if (installPath != null) + { + return installPath; + } + + // Attempt to find through config file + string configPath = Path.Combine(steamPath, "config", "config.vdf"); + if (File.Exists(configPath)) + { + log.InfoFormat("Found Steam config file at {0}", configPath); + StreamReader reader = new StreamReader(configPath); + string line; + while ((line = reader.ReadLine()) != null) + { + // Found Steam library + if (line.Contains("BaseInstallFolder")) + { + // This assumes config file is valid, we just skip it if it looks funny. + string[] split_line = line.Split('"'); + + if (split_line.Length > 3) + { + log.DebugFormat("Found a Steam Libary Location at {0}", split_line[3]); + + installPath = KSPDirectory(split_line[3]); + if (installPath != null) + { + log.InfoFormat("Found a KSP install at {0}", installPath); + return installPath; + } + } + } + } + } + + // Could not locate the folder. + return null; + } + + /// + /// Get the default non-Steam path to KSP on macOS + /// + /// + /// "/Applications/Kerbal Space Program" if it exists and we're on a Mac, else null + /// + public string MacPath() + { + if (Platform.IsMac) + { + string installPath = Path.Combine( + // This is "/Applications" in Mono on Mac + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), + "Kerbal Space Program" + ); + return Directory.Exists(installPath) ? installPath : null; + } + return null; + } + + public string PrimaryModDirectoryRelative => "GameData"; + + public string PrimaryModDirectory(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(inst.GameDir(), PrimaryModDirectoryRelative)); + } + + public string[] StockFolders => new string[] + { + "GameData/Squad", + "GameData/SquadExpansion" + }; + + /// + /// Checks the path against a list of reserved game directories + /// + /// + /// + public bool IsReservedDirectory(GameInstance inst, string path) + { + return path == inst.GameDir() || path == inst.CkanDir() + || path == PrimaryModDirectory(inst) + || path == Missions(inst) + || path == Scenarios(inst) || path == Tutorial(inst) + || path == Ships(inst) || path == ShipsThumbs(inst) + || path == ShipsVab(inst) || path == ShipsThumbsVAB(inst) + || path == ShipsSph(inst) || path == ShipsThumbsSPH(inst) + || path == ShipsScript(inst); + } + + public bool AllowInstallationIn(string name, out string path) + { + return allowedFolders.TryGetValue(name, out path); + } + + public void RebuildSubdirectories(GameInstance inst) + { + string[] FoldersToCheck = { "Ships/VAB", "Ships/SPH", "Ships/@thumbs/VAB", "Ships/@thumbs/SPH" }; + foreach (string sRelativePath in FoldersToCheck) + { + string sAbsolutePath = inst.ToAbsoluteGameDir(sRelativePath); + if (!Directory.Exists(sAbsolutePath)) + Directory.CreateDirectory(sAbsolutePath); + } + } + + public string DefaultCommandLine => + Platform.IsUnix ? "./KSP.x86_64 -single-instance" + : Platform.IsMac ? "./KSP.app/Contents/MacOS/KSP" + : "KSP_x64.exe -single-instance"; + + public string[] AdjustCommandLine(string[] args, GameVersion installedVersion) + { + // -single-instance crashes KSP 1.8 to KSP 1.11 on Linux + // https://issuetracker.unity3d.com/issues/linux-segmentation-fault-when-running-a-built-project-with-single-instance-argument + if (Platform.IsUnix) + { + var brokenVersionRange = new GameVersionRange( + new GameVersion(1, 8), + new GameVersion(1, 11) + ); + args = filterCmdLineArgs(args, installedVersion, brokenVersionRange, "-single-instance"); + } + return args; + } + + public List KnownVersions => + ServiceLocator.Container.Resolve().KnownVersions; + + public GameVersion DetectVersion(DirectoryInfo where) + { + var buildIdVersionProvider = ServiceLocator.Container + .ResolveKeyed(GameVersionSource.BuildId); + GameVersion version; + if (buildIdVersionProvider.TryGetVersion(where.FullName, out version)) + { + return version; + } + else + { + var readmeVersionProvider = ServiceLocator.Container + .ResolveKeyed(GameVersionSource.Readme); + return readmeVersionProvider.TryGetVersion(where.FullName, out version) ? version : null; + } + } + + public string CompatibleVersionsFile => "compatible_ksp_versions.json"; + + public string[] BuildIDFiles => new string[] + { + "buildID.txt", + "buildID64.txt" + }; + + public Uri DefaultRepositoryURL => new Uri("https://github.com/KSP-CKAN/CKAN-meta/archive/master.tar.gz"); + + public Uri RepositoryListURL => new Uri("https://raw.githubusercontent.com/KSP-CKAN/CKAN-meta/master/repositories.json"); + + private string Missions(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(inst.GameDir(), "Missions")); + } + + private string Ships(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(inst.GameDir(), "Ships")); + } + + private string ShipsVab(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(Ships(inst), "VAB")); + } + + private string ShipsSph(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(Ships(inst), "SPH")); + } + + private string ShipsThumbs(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(Ships(inst), "@thumbs")); + } + + private string ShipsThumbsSPH(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(ShipsThumbs(inst), "SPH")); + } + + private string ShipsThumbsVAB(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(ShipsThumbs(inst), "VAB")); + } + + private string ShipsScript(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(Ships(inst), "Script")); + } + + private string Tutorial(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(inst.GameDir(), "saves", "training")); + } + + private string Scenarios(GameInstance inst) + { + return CKANPathUtils.NormalizePath( + Path.Combine(inst.GameDir(), "saves", "scenarios")); + } + + private Dictionary allowedFolders = new Dictionary + { + { "Tutorial", "saves/training" }, + { "Scenarios", "saves/scenarios" }, + { "Missions", "Missions" }, + { "Ships", "Ships" }, + { "Ships/VAB", "Ships/VAB" }, + { "Ships/SPH", "Ships/SPH" }, + { "Ships/@thumbs", "Ships/@thumbs" }, + { "Ships/@thumbs/VAB", "Ships/@thumbs/VAB" }, + { "Ships/@thumbs/SPH", "Ships/@thumbs/SPH" }, + { "Ships/Script", "Ships/Script" } + }; + + /// + /// Finds the KSP path under a Steam Libary. Returns null if the folder cannot be located. + /// + /// Steam Libary Path + /// The KSP path. + private static string KSPDirectory(string steamPath) + { + // There are several possibilities for the path under Linux. + // Try with the uppercase version. + string installPath = Path.Combine(steamPath, "SteamApps", "common", "Kerbal Space Program"); + + if (Directory.Exists(installPath)) + { + return installPath; + } + + // Try with the lowercase version. + installPath = Path.Combine(steamPath, "steamapps", "common", "Kerbal Space Program"); + + if (Directory.Exists(installPath)) + { + return installPath; + } + return null; + } + + /// + /// If the installed game version is in the given range, + /// return the given array without the given parameter, + /// otherwise return the array as-is. + /// + /// Command line parameters to check + /// Game versions that should not use this parameter + /// The parameter to remove on version match + /// + /// args or args minus parameter + /// + private string[] filterCmdLineArgs(string[] args, GameVersion installedVersion, GameVersionRange crashyKspRange, string parameter) + { + var installedRange = installedVersion.ToVersionRange(); + if (crashyKspRange.IntersectWith(installedRange) != null + && args.Contains(parameter)) + { + log.DebugFormat( + "Parameter {0} found on incompatible KSP version {1}, pruning", + parameter, + installedVersion.ToString()); + return args.Where(s => s != parameter).ToArray(); + } + return args; + } + + private static readonly ILog log = LogManager.GetLogger(typeof(KerbalSpaceProgram)); + } +} diff --git a/Core/ModuleInstaller.cs b/Core/ModuleInstaller.cs index a1aa73aff8..1511348796 100644 --- a/Core/ModuleInstaller.cs +++ b/Core/ModuleInstaller.cs @@ -33,14 +33,14 @@ public class ModuleInstaller private static readonly ILog log = LogManager.GetLogger(typeof(ModuleInstaller)); - private KSP ksp; + private GameInstance ksp; private NetModuleCache Cache; public ModuleInstallerReportModInstalled onReportModInstalled = null; // Constructor - private ModuleInstaller(KSP ksp, NetModuleCache cache, IUser user) + private ModuleInstaller(GameInstance ksp, NetModuleCache cache, IUser user) { User = user; Cache = cache; @@ -54,7 +54,7 @@ private ModuleInstaller(KSP ksp, NetModuleCache cache, IUser user) /// The ModuleInstaller instance. /// Current KSP instance. /// IUser implementation. - public static ModuleInstaller GetInstance(KSP ksp_instance, NetModuleCache cache, IUser user) + public static ModuleInstaller GetInstance(GameInstance ksp_instance, NetModuleCache cache, IUser user) { ModuleInstaller instance; @@ -224,7 +224,7 @@ public void InstallList(ICollection modules, RelationshipResolverOpt // leaves everything consistent, and this is just gravy. (And ScanGameData // acts as a Tx, anyway, so we don't need to provide our own.) User.RaiseProgress("Rescanning GameData", 90); - ksp.ScanGameData(); + ksp.Scan(); } User.RaiseProgress("Done!", 100); @@ -485,22 +485,6 @@ private void DeleteConflictingFiles(IEnumerable files) } } - /// - /// Checks the path against a list of reserved game directories - /// - /// - /// - private bool IsReservedDirectory(string path) - { - return path == ksp.Tutorial() || path == ksp.ShipsVab() - || path == ksp.ShipsSph() || path == ksp.Ships() - || path == ksp.Scenarios() || path == ksp.GameData() - || path == ksp.GameDir() || path == ksp.CkanDir() - || path == ksp.ShipsThumbs() || path == ksp.ShipsThumbsVAB() - || path == ksp.ShipsThumbsSPH() || path == ksp.ShipsScript() - || path == ksp.Missions(); - } - /// /// Given a module and an open zipfile, return all the files that would be installed /// for this module. @@ -509,7 +493,7 @@ private bool IsReservedDirectory(string path) /// /// Throws a BadMetadataKraken if the stanza resulted in no files being returned. /// - public static List FindInstallableFiles(CkanModule module, ZipFile zipfile, KSP ksp) + public static List FindInstallableFiles(CkanModule module, ZipFile zipfile, GameInstance ksp) { var files = new List(); @@ -552,7 +536,7 @@ public static List FindInstallableFiles(CkanModule module, ZipF /// If a KSP instance is provided, it will be used to generate output paths, otherwise these will be null. /// // TODO: Document which exception! - public static List FindInstallableFiles(CkanModule module, string zip_filename, KSP ksp) + public static List FindInstallableFiles(CkanModule module, string zip_filename, GameInstance ksp) { // `using` makes sure our zipfile gets closed when we exit this block. using (ZipFile zipfile = new ZipFile(zip_filename)) @@ -789,7 +773,7 @@ private void Uninstall(string modName, ref HashSet possibleConfigOnlyDir // It is bad if any of this directories gets removed // So we protect them // A few string comparisons will be cheaper than hitting the disk, so do this first - if (IsReservedDirectory(directory)) + if (ksp.game.IsReservedDirectory(ksp, directory)) { log.DebugFormat("Directory {0} is reserved, skipping", directory); continue; @@ -847,11 +831,11 @@ public HashSet AddParentDirectories(HashSet directories) return new HashSet(); } - var gameDir = KSPPathUtils.NormalizePath(ksp.GameDir()); + var gameDir = CKANPathUtils.NormalizePath(ksp.GameDir()); return directories .Where(dir => !string.IsNullOrWhiteSpace(dir)) // Normalize all paths before deduplicate - .Select(KSPPathUtils.NormalizePath) + .Select(CKANPathUtils.NormalizePath) // Remove any duplicate paths .Distinct() .SelectMany(dir => @@ -871,11 +855,11 @@ public HashSet AddParentDirectories(HashSet directories) if (!dir.StartsWith(gameDir, StringComparison.CurrentCultureIgnoreCase)) { - dir = KSPPathUtils.ToAbsolute(dir, gameDir); + dir = CKANPathUtils.ToAbsolute(dir, gameDir); } // Remove the system paths, leaving the path under the instance directory - var relativeHead = KSPPathUtils.ToRelative(dir, gameDir); + var relativeHead = CKANPathUtils.ToRelative(dir, gameDir); // Don't try to remove GameRoot if (!string.IsNullOrEmpty(relativeHead)) { @@ -884,13 +868,13 @@ public HashSet AddParentDirectories(HashSet directories) foreach (var path in pathArray) { builtPath += path + '/'; - results.Add(KSPPathUtils.ToAbsolute(builtPath, gameDir)); + results.Add(CKANPathUtils.ToAbsolute(builtPath, gameDir)); } } return results; }) - .Where(dir => !IsReservedDirectory(dir)) + .Where(dir => !ksp.game.IsReservedDirectory(ksp, dir)) .ToHashSet(); } diff --git a/Core/Net/NetFileCache.cs b/Core/Net/NetFileCache.cs index 87a2360660..3c91a02211 100644 --- a/Core/Net/NetFileCache.cs +++ b/Core/Net/NetFileCache.cs @@ -31,15 +31,15 @@ public class NetFileCache : IDisposable // hash => full file path private Dictionary cachedFiles; private string cachePath; - private KSPManager manager; + private GameInstanceManager manager; private static readonly Regex cacheFileRegex = new Regex("^[0-9A-F]{8}-", RegexOptions.Compiled); private static readonly ILog log = LogManager.GetLogger(typeof (NetFileCache)); /// - /// Initialize a cache given a KSPManager + /// Initialize a cache given a GameInstanceManager /// - /// KSPManager object containing the Instances that might have old caches - public NetFileCache(KSPManager mgr, string path) + /// GameInstanceManager object containing the Instances that might have old caches + public NetFileCache(GameInstanceManager mgr, string path) : this(path) { manager = mgr; @@ -308,12 +308,12 @@ public void EnforceSizeLimit(long bytes, Registry registry) if (curBytes > bytes) { // This object will let us determine whether a module is compatible with any of our instances - KspVersionCriteria aggregateCriteria = manager?.Instances.Values + GameVersionCriteria aggregateCriteria = manager?.Instances.Values .Where(ksp => ksp.Valid) .Select(ksp => ksp.VersionCriteria()) .Aggregate( manager?.CurrentInstance?.VersionCriteria() - ?? new KspVersionCriteria(null), + ?? new GameVersionCriteria(null), (combinedCrit, nextCrit) => combinedCrit.Union(nextCrit) ); @@ -352,7 +352,7 @@ public void EnforceSizeLimit(long bytes, Registry registry) } } - private int compareFiles(Dictionary> hashMap, KspVersionCriteria crit, FileInfo a, FileInfo b) + private int compareFiles(Dictionary> hashMap, GameVersionCriteria crit, FileInfo a, FileInfo b) { // Compatible modules for file A List modulesA; diff --git a/Core/Net/NetModuleCache.cs b/Core/Net/NetModuleCache.cs index 7b865029e8..6075255b81 100644 --- a/Core/Net/NetModuleCache.cs +++ b/Core/Net/NetModuleCache.cs @@ -18,8 +18,8 @@ public class NetModuleCache : IDisposable /// /// Initialize the cache /// - /// KSPManager containing instances that might have legacy caches - public NetModuleCache(KSPManager mgr, string path) + /// GameInstanceManager containing instances that might have legacy caches + public NetModuleCache(GameInstanceManager mgr, string path) { cache = new NetFileCache(mgr, path); } diff --git a/Core/Net/Repo.cs b/Core/Net/Repo.cs index 37fef644a6..ce7ad091ff 100644 --- a/Core/Net/Repo.cs +++ b/Core/Net/Repo.cs @@ -34,7 +34,7 @@ public static class Repo /// Download and update the local CKAN meta-info. /// Optionally takes a URL to the zipfile repo to download. /// - public static RepoUpdateResult UpdateAllRepositories(RegistryManager registry_manager, KSP ksp, NetModuleCache cache, IUser user) + public static RepoUpdateResult UpdateAllRepositories(RegistryManager registry_manager, GameInstance ksp, NetModuleCache cache, IUser user) { SortedDictionary sortedRepositories = registry_manager.registry.Repositories; user.RaiseProgress("Checking for updates", 0); @@ -105,14 +105,11 @@ public static RepoUpdateResult UpdateAllRepositories(RegistryManager registry_ma /// /// Retrieve available modules from the URL given. /// - private static List UpdateRegistry(Uri repo, KSP ksp, IUser user, out SortedDictionary downloadCounts, out string currentETag) + private static List UpdateRegistry(Uri repo, GameInstance ksp, IUser user, out SortedDictionary downloadCounts, out string currentETag) { TxFileManager file_transaction = new TxFileManager(); downloadCounts = null; - // Use this opportunity to also update the build mappings... kind of hacky - ServiceLocator.Container.Resolve().Refresh(); - log.InfoFormat("Downloading {0}", repo); string repo_file = String.Empty; @@ -195,7 +192,7 @@ private static List GetChangedInstalledModules(Registry registry) /// Game instance /// Cacne object for mod downloads /// Manager that holds our game instances - private static void HandleModuleChanges(List metadataChanges, IUser user, KSP ksp, NetModuleCache cache, RegistryManager registry_manager) + private static void HandleModuleChanges(List metadataChanges, IUser user, GameInstance ksp, NetModuleCache cache, RegistryManager registry_manager) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < metadataChanges.Count; i++) @@ -327,7 +324,7 @@ private static bool RelationshipsAreEquivalent(List a, L /// /// Number of modules found in repo /// - public static bool Update(RegistryManager registry_manager, KSP ksp, IUser user, string repo = null) + public static bool Update(RegistryManager registry_manager, GameInstance ksp, IUser user, string repo = null) { if (repo == null) { @@ -338,12 +335,12 @@ public static bool Update(RegistryManager registry_manager, KSP ksp, IUser user, } // Same as above, just with a Uri instead of string for the repo - public static bool Update(RegistryManager registry_manager, KSP ksp, IUser user, Uri repo = null) + public static bool Update(RegistryManager registry_manager, GameInstance ksp, IUser user, Uri repo = null) { // Use our default repo, unless we've been told otherwise. if (repo == null) { - repo = CKAN.Repository.default_ckan_repo_uri; + repo = ksp.game.DefaultRepositoryURL; } SortedDictionary downloadCounts; diff --git a/Core/Properties/AssemblyInfo.cs b/Core/Properties/AssemblyInfo.cs index 4c04fa05ac..9b100a5b1b 100644 --- a/Core/Properties/AssemblyInfo.cs +++ b/Core/Properties/AssemblyInfo.cs @@ -5,3 +5,4 @@ [assembly: AssemblyDescription("CKAN Core")] [assembly: InternalsVisibleTo("Tests")] +[assembly: InternalsVisibleTo("CKAN.Tests")] diff --git a/Core/Registry/AvailableModule.cs b/Core/Registry/AvailableModule.cs index af3d77e45e..66ffaa88d1 100644 --- a/Core/Registry/AvailableModule.cs +++ b/Core/Registry/AvailableModule.cs @@ -81,7 +81,7 @@ public void Remove(ModuleVersion version) /// Modules that are planned to be installed /// public CkanModule Latest( - KspVersionCriteria ksp_version = null, + GameVersionCriteria ksp_version = null, RelationshipDescriptor relationship = null, IEnumerable installed = null, IEnumerable toInstall = null @@ -142,12 +142,12 @@ private static bool DependsAndConflictsOK(CkanModule module, IEnumerable - public KspVersion LatestCompatibleKSP() + public GameVersion LatestCompatibleKSP() { - KspVersion best = null; + GameVersion best = null; foreach (var pair in module_version) { - KspVersion v = pair.Value.LatestCompatibleKSP(); + GameVersion v = pair.Value.LatestCompatibleKSP(); if (v.IsAny) // Can't get later than Any, so stop return v; diff --git a/Core/Registry/CompatibilitySorter.cs b/Core/Registry/CompatibilitySorter.cs index 0f1163a2d5..efa15b0b5c 100644 --- a/Core/Registry/CompatibilitySorter.cs +++ b/Core/Registry/CompatibilitySorter.cs @@ -21,7 +21,7 @@ public class CompatibilitySorter /// Collection of found dlls /// Collection of installed DLCs public CompatibilitySorter( - KspVersionCriteria crit, + GameVersionCriteria crit, Dictionary available, Dictionary> providers, Dictionary installed, @@ -39,7 +39,7 @@ IDictionary dlc /// /// Version criteria that this partition represents /// - public readonly KspVersionCriteria CompatibleVersions; + public readonly GameVersionCriteria CompatibleVersions; /// /// Mods that are compatible with our versions @@ -76,7 +76,7 @@ public readonly SortedDictionary Incompatible /// /// Mapping from identifiers to compatible mods providing those identifiers /// - private Dictionary> CompatibleProviders(KspVersionCriteria crit, Dictionary> providers) + private Dictionary> CompatibleProviders(GameVersionCriteria crit, Dictionary> providers) { var compat = new Dictionary>(); foreach (var kvp in providers) diff --git a/Core/Registry/IRegistryQuerier.cs b/Core/Registry/IRegistryQuerier.cs index a03311de60..1a4e6e87bb 100644 --- a/Core/Registry/IRegistryQuerier.cs +++ b/Core/Registry/IRegistryQuerier.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using CKAN.Versioning; +using CKAN.Games; namespace CKAN { @@ -21,7 +22,7 @@ public interface IRegistryQuerier /// Returns a simple array of the latest compatible module for each identifier for /// the specified version of KSP. /// - IEnumerable CompatibleModules(KspVersionCriteria ksp_version); + IEnumerable CompatibleModules(GameVersionCriteria ksp_version); /// /// Get full JSON metadata string for a mod's available versions @@ -38,13 +39,13 @@ public interface IRegistryQuerier /// If no ksp_version is provided, the latest module for *any* KSP version is returned. /// Throws if asked for a non-existent module. /// - CkanModule LatestAvailable(string identifier, KspVersionCriteria ksp_version, RelationshipDescriptor relationship_descriptor = null); + CkanModule LatestAvailable(string identifier, GameVersionCriteria ksp_version, RelationshipDescriptor relationship_descriptor = null); /// /// Returns the max game version that is compatible with the given mod. /// /// Name of mod to check - KspVersion LatestCompatibleKSP(string identifier); + GameVersion LatestCompatibleKSP(string identifier); /// /// Returns all available versions of a module. @@ -61,7 +62,7 @@ public interface IRegistryQuerier /// List LatestAvailableWithProvides( string identifier, - KspVersionCriteria ksp_version, + GameVersionCriteria ksp_version, RelationshipDescriptor relationship_descriptor = null, IEnumerable toInstall = null ); @@ -108,7 +109,7 @@ IEnumerable FindReverseDependencies( /// Returns a simple array of all incompatible modules for /// the specified version of KSP. /// - IEnumerable IncompatibleModules(KspVersionCriteria ksp_version); + IEnumerable IncompatibleModules(GameVersionCriteria ksp_version); /// /// Returns a dictionary of all modules installed, along with their @@ -171,7 +172,7 @@ public static bool IsAutodetected(this IRegistryQuerier querier, string identifi /// Is the mod installed and does it have a newer version compatible with version /// We can't update AD mods /// - public static bool HasUpdate(this IRegistryQuerier querier, string identifier, KspVersionCriteria version) + public static bool HasUpdate(this IRegistryQuerier querier, string identifier, GameVersionCriteria version) { CkanModule newest_version; try @@ -218,14 +219,14 @@ public static bool HasUpdate(this IRegistryQuerier querier, string identifier, K /// /// String describing range of compatible game versions. /// - public static string CompatibleGameVersions(this IRegistryQuerier querier, string identifier) + public static string CompatibleGameVersions(this IRegistryQuerier querier, IGame game, string identifier) { List releases = querier.AvailableByIdentifier(identifier).ToList(); if (releases != null && releases.Count > 0) { ModuleVersion minMod = null, maxMod = null; - KspVersion minKsp = null, maxKsp = null; + GameVersion minKsp = null, maxKsp = null; Registry.GetMinMaxVersions(releases, out minMod, out maxMod, out minKsp, out maxKsp); - return KspVersionRange.VersionSpan(minKsp, maxKsp); + return GameVersionRange.VersionSpan(game, minKsp, maxKsp); } return ""; } @@ -238,16 +239,16 @@ public static string CompatibleGameVersions(this IRegistryQuerier querier, strin /// /// String describing range of compatible game versions. /// - public static string CompatibleGameVersions(this IRegistryQuerier querier, CkanModule module) + public static string CompatibleGameVersions(this IRegistryQuerier querier, IGame game, CkanModule module) { ModuleVersion minMod = null, maxMod = null; - KspVersion minKsp = null, maxKsp = null; + GameVersion minKsp = null, maxKsp = null; Registry.GetMinMaxVersions( new CkanModule[] { module }, out minMod, out maxMod, out minKsp, out maxKsp ); - return KspVersionRange.VersionSpan(minKsp, maxKsp); + return GameVersionRange.VersionSpan(game, minKsp, maxKsp); } /// @@ -257,7 +258,7 @@ public static string CompatibleGameVersions(this IRegistryQuerier querier, CkanM /// Given a mod identifier, return a ModuleReplacement containing the relevant replacement /// if compatibility matches. /// - public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, string identifier, KspVersionCriteria version) + public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, string identifier, GameVersionCriteria version) { // We only care about the installed version CkanModule installedVersion; @@ -272,7 +273,7 @@ public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, st return querier.GetReplacement(installedVersion, version); } - public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, CkanModule installedVersion, KspVersionCriteria version) + public static ModuleReplacement GetReplacement(this IRegistryQuerier querier, CkanModule installedVersion, GameVersionCriteria version) { // Mod is not installed, so we don't care about replacements if (installedVersion == null) diff --git a/Core/Registry/InstalledModule.cs b/Core/Registry/InstalledModule.cs index f64765014c..cb928d7120 100644 --- a/Core/Registry/InstalledModule.cs +++ b/Core/Registry/InstalledModule.cs @@ -25,7 +25,7 @@ public string Sha1 } } - public InstalledModuleFile(string path, KSP ksp) + public InstalledModuleFile(string path, GameInstance ksp) { string absolute_path = ksp.ToAbsoluteGameDir(path); sha1_sum = Sha1Sum(absolute_path); @@ -124,7 +124,7 @@ public bool AutoInstalled #region Constructors - public InstalledModule(KSP ksp, CkanModule module, IEnumerable relative_files, bool autoInstalled) + public InstalledModule(GameInstance ksp, CkanModule module, IEnumerable relative_files, bool autoInstalled) { install_time = DateTime.Now; source_module = module; @@ -158,13 +158,13 @@ private InstalledModule() /// Ensures all files for this module have relative paths. /// Called when upgrading registry versions. Should be a no-op /// if called on newer registries. - public void Renormalise(KSP ksp) + public void Renormalise(GameInstance ksp) { var normalised_installed_files = new Dictionary(); foreach (KeyValuePair tuple in installed_files) { - string path = KSPPathUtils.NormalizePath(tuple.Key); + string path = CKANPathUtils.NormalizePath(tuple.Key); if (Path.IsPathRooted(path)) { diff --git a/Core/Registry/Registry.cs b/Core/Registry/Registry.cs index 08554a7bfb..6e40a13400 100644 --- a/Core/Registry/Registry.cs +++ b/Core/Registry/Registry.cs @@ -5,10 +5,11 @@ using System.Runtime.Serialization; using System.Text.RegularExpressions; using System.Transactions; -using CKAN.Extensions; -using CKAN.Versioning; using log4net; using Newtonsoft.Json; +using CKAN.Extensions; +using CKAN.Versioning; +using CKAN.Games; namespace CKAN { @@ -125,7 +126,7 @@ [JsonIgnore] public IDictionary InstalledDlc /// /// Installed modules that are incompatible, if any /// - public IEnumerable IncompatibleInstalled(KspVersionCriteria crit) + public IEnumerable IncompatibleInstalled(GameVersionCriteria crit) { return installed_modules.Values .Where(im => !im.Module.IsCompatibleKSP(crit)); @@ -136,8 +137,8 @@ public IEnumerable IncompatibleInstalled(KspVersionCriteria cri [OnDeserialized] private void DeSerialisationFixes(StreamingContext context) { - // Our context is our KSP install. - KSP ksp = (KSP)context.Context; + // Our context is our game instance. + GameInstance ksp = (GameInstance)context.Context; // Older registries didn't have the installed_files list, so we create one // if absent. @@ -158,7 +159,7 @@ private void DeSerialisationFixes(StreamingContext context) foreach (KeyValuePair tuple in installed_files) { - string path = KSPPathUtils.NormalizePath(tuple.Key); + string path = CKANPathUtils.NormalizePath(tuple.Key); if (Path.IsPathRooted(path)) { @@ -237,8 +238,8 @@ private void DeSerialisationFixes(StreamingContext context) var oldDefaultRepo = new Uri("https://github.com/KSP-CKAN/CKAN-meta/archive/master.zip"); if (repositories != null && repositories.TryGetValue(Repository.default_ckan_repo_name, out default_repo) && default_repo.uri == oldDefaultRepo) { - log.InfoFormat("Updating default metadata URL from {0} to {1}", oldDefaultRepo, Repository.default_ckan_repo_uri); - repositories["default"].uri = Repository.default_ckan_repo_uri; + log.InfoFormat("Updating default metadata URL from {0} to {1}", oldDefaultRepo, ksp.game.DefaultRepositoryURL); + repositories["default"].uri = ksp.game.DefaultRepositoryURL; } registry_version = LATEST_REGISTRY_VERSION; @@ -494,7 +495,7 @@ public void RemoveAvailable(CkanModule module) /// /// /// - public IEnumerable CompatibleModules(KspVersionCriteria ksp_version) + public IEnumerable CompatibleModules(GameVersionCriteria ksp_version) { // Set up our compatibility partition SetCompatibleVersion(ksp_version); @@ -504,7 +505,7 @@ public IEnumerable CompatibleModules(KspVersionCriteria ksp_version) /// /// /// - public IEnumerable IncompatibleModules(KspVersionCriteria ksp_version) + public IEnumerable IncompatibleModules(GameVersionCriteria ksp_version) { // Set up our compatibility partition SetCompatibleVersion(ksp_version); @@ -516,7 +517,7 @@ public IEnumerable IncompatibleModules(KspVersionCriteria ksp_versio /// public CkanModule LatestAvailable( string module, - KspVersionCriteria ksp_version, + GameVersionCriteria ksp_version, RelationshipDescriptor relationship_descriptor = null) { // TODO: Consider making this internal, because practically everything should @@ -578,7 +579,7 @@ public string GetAvailableMetadata(string identifier) /// Return the latest game version compatible with the given mod. /// /// Name of mod to check - public KspVersion LatestCompatibleKSP(string identifier) + public GameVersion LatestCompatibleKSP(string identifier) { return available_modules.ContainsKey(identifier) ? available_modules[identifier].LatestCompatibleKSP() @@ -596,7 +597,7 @@ public KspVersion LatestCompatibleKSP(string identifier) /// Return parameter for the highest game version public static void GetMinMaxVersions(IEnumerable modVersions, out ModuleVersion minMod, out ModuleVersion maxMod, - out KspVersion minKsp, out KspVersion maxKsp) + out GameVersion minKsp, out GameVersion maxKsp) { minMod = maxMod = null; minKsp = maxKsp = null; @@ -610,8 +611,8 @@ public static void GetMinMaxVersions(IEnumerable modVersions, { maxMod = rel.version; } - KspVersion relMin = rel.EarliestCompatibleKSP(); - KspVersion relMax = rel.LatestCompatibleKSP(); + GameVersion relMin = rel.EarliestCompatibleKSP(); + GameVersion relMax = rel.LatestCompatibleKSP(); if (minKsp == null || !minKsp.IsAny && (minKsp > relMin || relMin.IsAny)) { minKsp = relMin; @@ -667,7 +668,7 @@ public void BuildTagIndex(ModuleTagList tags) /// public List LatestAvailableWithProvides( string identifier, - KspVersionCriteria ksp_version, + GameVersionCriteria ksp_version, RelationshipDescriptor relationship_descriptor = null, IEnumerable toInstall = null) { @@ -713,7 +714,7 @@ public CkanModule GetModuleByVersion(string ident, ModuleVersion version) /// Register the supplied module as having been installed, thereby keeping /// track of its metadata and files. /// - public void RegisterModule(CkanModule mod, IEnumerable absolute_files, KSP ksp, bool autoInstalled) + public void RegisterModule(CkanModule mod, IEnumerable absolute_files, GameInstance ksp, bool autoInstalled) { EnlistWithTransaction(); @@ -775,7 +776,7 @@ public void RegisterModule(CkanModule mod, IEnumerable absolute_files, K /// /// Throws an InconsistentKraken if not all files have been removed. /// - public void DeregisterModule(KSP ksp, string module) + public void DeregisterModule(GameInstance ksp, string module) { EnlistWithTransaction(); @@ -817,7 +818,7 @@ public void DeregisterModule(KSP ksp, string module) /// /// Does nothing if the DLL is already part of an installed module. /// - public void RegisterDll(KSP ksp, string absolute_path) + public void RegisterDll(GameInstance ksp, string absolute_path) { EnlistWithTransaction(); @@ -1033,7 +1034,7 @@ public CkanModule GetInstalledVersion(string mod_identifier) /// public string FileOwner(string file) { - file = KSPPathUtils.NormalizePath(file); + file = CKANPathUtils.NormalizePath(file); if (Path.IsPathRooted(file)) { @@ -1262,7 +1263,7 @@ public Dictionary> GetDownloadHashIndex() /// compatible and incompatible groups. /// /// Version criteria to determine compatibility - public void SetCompatibleVersion(KspVersionCriteria versCrit) + public void SetCompatibleVersion(GameVersionCriteria versCrit) { if (!versCrit.Equals(sorter?.CompatibleVersions)) { diff --git a/Core/Registry/RegistryManager.cs b/Core/Registry/RegistryManager.cs index bccb0bac37..a95788cb63 100644 --- a/Core/Registry/RegistryManager.cs +++ b/Core/Registry/RegistryManager.cs @@ -29,13 +29,13 @@ public class RegistryManager : IDisposable // when deserialising, and *it* only needs it to do registry upgrades. // We could get rid of all of this if we declare we no longer wish to support // older registry formats. - private readonly KSP ksp; + private readonly GameInstance ksp; public Registry registry; // We require our constructor to be private so we can // enforce this being an instance (via Instance() above) - private RegistryManager(string path, KSP ksp) + private RegistryManager(string path, GameInstance ksp) { this.ksp = ksp; @@ -245,7 +245,7 @@ public void ReleaseLock() /// Returns an instance of the registry manager for the KSP install. /// The file `registry.json` is assumed. /// - public static RegistryManager Instance(KSP ksp) + public static RegistryManager Instance(GameInstance ksp) { string directory = ksp.CkanDir(); if (!registryCache.ContainsKey(directory)) @@ -333,7 +333,7 @@ private void AscertainDefaultRepo() if (repositories.Count == 0) { repositories.Add(Repository.default_ckan_repo_name, - new Repository(Repository.default_ckan_repo_name, Repository.default_ckan_repo_uri)); + new Repository(Repository.default_ckan_repo_name, ksp.game.DefaultRepositoryURL)); } registry.Repositories = repositories; diff --git a/Core/Relationships/RelationshipResolver.cs b/Core/Relationships/RelationshipResolver.cs index 57d4a05891..feadbd9f4f 100644 --- a/Core/Relationships/RelationshipResolver.cs +++ b/Core/Relationships/RelationshipResolver.cs @@ -99,7 +99,7 @@ public class RelationshipResolver new Dictionary(new NameComparer()); private readonly IRegistryQuerier registry; - private readonly KspVersionCriteria kspversion; + private readonly GameVersionCriteria GameVersion; private readonly RelationshipResolverOptions options; private readonly HashSet installed_modules; @@ -108,11 +108,11 @@ public class RelationshipResolver /// /// Options for the RelationshipResolver /// CKAN registry object for current game instance - /// The current KSP version criteria to consider - public RelationshipResolver(RelationshipResolverOptions options, IRegistryQuerier registry, KspVersionCriteria kspversion) + /// The current KSP version criteria to consider + public RelationshipResolver(RelationshipResolverOptions options, IRegistryQuerier registry, GameVersionCriteria GameVersion) { this.registry = registry; - this.kspversion = kspversion; + this.GameVersion = GameVersion; this.options = options; installed_modules = new HashSet(registry.InstalledModules.Select(i_module => i_module.Module)); @@ -124,17 +124,17 @@ public RelationshipResolver(RelationshipResolverOptions options, IRegistryQuerie } /// - /// Attempts to convert the identifiers to CkanModules and then calls RelationshipResolver.ctor(IEnumerable{CkanModule}, IEnumerable{CkanModule}, Registry, KSPVersion)"/> + /// Attempts to convert the identifiers to CkanModules and then calls RelationshipResolver.ctor(IEnumerable{CkanModule}, IEnumerable{CkanModule}, Registry, GameVersion)"/> /// /// Identifiers of modules to install, will be converted to CkanModules using CkanModule.FromIDandVersion /// Identifiers of modules to remove, will be converted to CkanModules using Registry.InstalledModule /// Options for the RelationshipResolver /// CKAN registry object for current game instance - /// The current KSP version criteria to consider + /// The current KSP version criteria to consider public RelationshipResolver(IEnumerable modulesToInstall, IEnumerable modulesToRemove, RelationshipResolverOptions options, IRegistryQuerier registry, - KspVersionCriteria kspversion) : + GameVersionCriteria GameVersion) : this( - modulesToInstall?.Select(mod => TranslateModule(mod, options, registry, kspversion)), + modulesToInstall?.Select(mod => TranslateModule(mod, options, registry, GameVersion)), modulesToRemove? .Select(mod => { @@ -143,7 +143,7 @@ public RelationshipResolver(IEnumerable modulesToInstall, IEnumerable registry.InstalledModule(identifier) != null) .Select(identifier => registry.InstalledModule(identifier).Module), - options, registry, kspversion) + options, registry, GameVersion) { // Does nothing, just calls the other overloaded constructor } @@ -155,15 +155,15 @@ public RelationshipResolver(IEnumerable modulesToInstall, IEnumerableThe identifier or identifier=version of the module /// If options.allow_incompatible is set, fall back to searching incompatible modules if no compatible has been found /// CKAN registry object for current game instance - /// The current KSP version criteria to consider + /// The current KSP version criteria to consider /// A CkanModule - private static CkanModule TranslateModule(string name, RelationshipResolverOptions options, IRegistryQuerier registry, KspVersionCriteria kspversion) + private static CkanModule TranslateModule(string name, RelationshipResolverOptions options, IRegistryQuerier registry, GameVersionCriteria GameVersion) { if (options.allow_incompatible) { try { - return CkanModule.FromIDandVersion(registry, name, kspversion); + return CkanModule.FromIDandVersion(registry, name, GameVersion); } catch (ModuleNotFoundKraken) { @@ -174,7 +174,7 @@ private static CkanModule TranslateModule(string name, RelationshipResolverOptio } else { - return CkanModule.FromIDandVersion(registry, name, kspversion); + return CkanModule.FromIDandVersion(registry, name, GameVersion); } } @@ -185,10 +185,10 @@ private static CkanModule TranslateModule(string name, RelationshipResolverOptio /// Modules to remove /// Options for the RelationshipResolver /// CKAN registry object for current game instance - /// The current KSP version criteria to consider + /// The current KSP version criteria to consider public RelationshipResolver(IEnumerable modulesToInstall, IEnumerable modulesToRemove, RelationshipResolverOptions options, IRegistryQuerier registry, - KspVersionCriteria kspversion) - : this(options, registry, kspversion) + GameVersionCriteria GameVersion) + : this(options, registry, GameVersion) { if (modulesToRemove != null) { @@ -424,7 +424,7 @@ private void ResolveStanza(IEnumerable stanza, Selection // Pass mod list in case an older version of a module is conflict-free while later versions have conflicts var descriptor1 = descriptor; List candidates = descriptor - .LatestAvailableWithProvides(registry, kspversion, modlist.Values) + .LatestAvailableWithProvides(registry, GameVersion, modlist.Values) .Where(mod => !modlist.ContainsKey(mod.identifier) && descriptor1.WithinBounds(mod) && MightBeInstallable(mod)) @@ -434,7 +434,7 @@ private void ResolveStanza(IEnumerable stanza, Selection // Nothing found, try again without mod list // (conflicts will still be caught below) candidates = descriptor - .LatestAvailableWithProvides(registry, kspversion) + .LatestAvailableWithProvides(registry, GameVersion) .Where(mod => !modlist.ContainsKey(mod.identifier) && descriptor1.WithinBounds(mod) && MightBeInstallable(mod)) @@ -595,7 +595,7 @@ private bool MightBeInstallable(CkanModule module, List compatible = nul var needed = module.depends // Skip dependencies satisfied by installed modules .Where(depend => !depend.MatchesAny(installed_modules, null, null)) - .Select(depend => depend.LatestAvailableWithProvides(registry, kspversion)); + .Select(depend => depend.LatestAvailableWithProvides(registry, GameVersion)); log.DebugFormat("Trying to satisfy: {0}", string.Join("; ", needed.Select(need => diff --git a/Core/ServiceLocator.cs b/Core/ServiceLocator.cs index 4571d3b919..2c0ff55736 100644 --- a/Core/ServiceLocator.cs +++ b/Core/ServiceLocator.cs @@ -48,11 +48,11 @@ private static void Init() builder.RegisterType() .As() - .Keyed(KspVersionSource.BuildId); + .Keyed(GameVersionSource.BuildId); builder.RegisterType() .As() - .Keyed(KspVersionSource.Readme); + .Keyed(GameVersionSource.Readme); _container = builder.Build(); } diff --git a/Core/Types/CkanModule.cs b/Core/Types/CkanModule.cs index ec8378689c..584e40d4d0 100644 --- a/Core/Types/CkanModule.cs +++ b/Core/Types/CkanModule.cs @@ -144,13 +144,13 @@ public class CkanModule : IEquatable public string identifier; [JsonProperty("ksp_version", Order = 9, NullValueHandling = NullValueHandling.Ignore)] - public KspVersion ksp_version; + public GameVersion ksp_version; [JsonProperty("ksp_version_max", Order = 11, NullValueHandling = NullValueHandling.Ignore)] - public KspVersion ksp_version_max; + public GameVersion ksp_version_max; [JsonProperty("ksp_version_min", Order = 10, NullValueHandling = NullValueHandling.Ignore)] - public KspVersion ksp_version_min; + public GameVersion ksp_version_min; [JsonProperty("ksp_version_strict", Order = 12, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(false)] @@ -392,7 +392,7 @@ private void DeSerialisationFixes(StreamingContext like_i_could_care) /// The current KSP version criteria to consider /// A CkanModule /// Thrown if no matching module could be found - public static CkanModule FromIDandVersion(IRegistryQuerier registry, string mod, KspVersionCriteria ksp_version) + public static CkanModule FromIDandVersion(IRegistryQuerier registry, string mod, GameVersionCriteria ksp_version) { CkanModule module; @@ -496,7 +496,7 @@ internal static bool UniConflicts(CkanModule mod1, CkanModule mod2) /// /// Returns true if our mod is compatible with the KSP version specified. /// - public bool IsCompatibleKSP(KspVersionCriteria version) + public bool IsCompatibleKSP(GameVersionCriteria version) { log.DebugFormat("Testing if {0} is compatible with KSP {1}", this, version.ToString()); @@ -514,7 +514,7 @@ public bool IsCompatibleKSP(KspVersionCriteria version) /// public string HighestCompatibleKSP() { - KspVersion v = LatestCompatibleKSP(); + GameVersion v = LatestCompatibleKSP(); if (v.IsAny) return "All versions"; else @@ -525,7 +525,7 @@ public string HighestCompatibleKSP() /// Returns machine readable object indicating the highest compatible /// version of KSP this module will run with. /// - public KspVersion LatestCompatibleKSP() + public GameVersion LatestCompatibleKSP() { // Find the highest compatible KSP version if (ksp_version_max != null) @@ -534,14 +534,14 @@ public KspVersion LatestCompatibleKSP() return ksp_version; else // No upper limit. - return KspVersion.Any; + return GameVersion.Any; } /// /// Returns machine readable object indicating the lowest compatible /// version of KSP this module will run with. /// - public KspVersion EarliestCompatibleKSP() + public GameVersion EarliestCompatibleKSP() { // Find the lowest compatible KSP version if (ksp_version_min != null) @@ -550,7 +550,7 @@ public KspVersion EarliestCompatibleKSP() return ksp_version; else // No lower limit. - return KspVersion.Any; + return GameVersion.Any; } /// diff --git a/Core/Types/GameComparator/BaseGameComparator.cs b/Core/Types/GameComparator/BaseGameComparator.cs index 7118fcef06..4942af712d 100644 --- a/Core/Types/GameComparator/BaseGameComparator.cs +++ b/Core/Types/GameComparator/BaseGameComparator.cs @@ -6,13 +6,13 @@ public abstract class BaseGameComparator : IGameComparator { public BaseGameComparator() { } - public virtual bool Compatible(KspVersionCriteria gameVersionCriteria, CkanModule module) + public virtual bool Compatible(GameVersionCriteria gameVersionCriteria, CkanModule module) { if (gameVersionCriteria.Versions.Count == 0) { return true; } - foreach (KspVersion gameVersion in gameVersionCriteria.Versions) + foreach (GameVersion gameVersion in gameVersionCriteria.Versions) { if (SingleVersionsCompatible (gameVersion, module)) { @@ -22,6 +22,6 @@ public virtual bool Compatible(KspVersionCriteria gameVersionCriteria, CkanModul return false; } - public abstract bool SingleVersionsCompatible(KspVersion gameVersionCriteria, CkanModule module); + public abstract bool SingleVersionsCompatible(GameVersion gameVersionCriteria, CkanModule module); } } diff --git a/Core/Types/GameComparator/GrasGameComparator.cs b/Core/Types/GameComparator/GrasGameComparator.cs index 88f4cbbf1f..f80b239ae5 100644 --- a/Core/Types/GameComparator/GrasGameComparator.cs +++ b/Core/Types/GameComparator/GrasGameComparator.cs @@ -10,10 +10,10 @@ namespace CKAN public class GrasGameComparator : BaseGameComparator { static readonly StrictGameComparator strict = new StrictGameComparator(); - static readonly KspVersion v103 = KspVersion.Parse("1.0.3"); - static readonly KspVersion v104 = KspVersion.Parse("1.0.4"); + static readonly GameVersion v103 = GameVersion.Parse("1.0.3"); + static readonly GameVersion v104 = GameVersion.Parse("1.0.4"); - public override bool Compatible(KspVersionCriteria gameVersionCriteria, CkanModule module) + public override bool Compatible(GameVersionCriteria gameVersionCriteria, CkanModule module) { // If it's strictly compatible, then it's compatible. if (strict.Compatible(gameVersionCriteria, module)) @@ -27,7 +27,7 @@ public override bool Compatible(KspVersionCriteria gameVersionCriteria, CkanModu return base.Compatible(gameVersionCriteria, module); } - public override bool SingleVersionsCompatible (KspVersion gameVersion, CkanModule module) + public override bool SingleVersionsCompatible (GameVersion gameVersion, CkanModule module) { // Otherwise, check if it's "generally recognise as safe". diff --git a/Core/Types/GameComparator/IGameComparator.cs b/Core/Types/GameComparator/IGameComparator.cs index c8ca2cfb1c..ab0ce0150d 100644 --- a/Core/Types/GameComparator/IGameComparator.cs +++ b/Core/Types/GameComparator/IGameComparator.cs @@ -11,7 +11,7 @@ public interface IGameComparator /// Returns true if the given module is compatible with the supplied /// gameVersion, false otherwise. /// - bool Compatible(KspVersionCriteria gameVersion, CkanModule module); + bool Compatible(GameVersionCriteria gameVersion, CkanModule module); } } diff --git a/Core/Types/GameComparator/StrictGameComparator.cs b/Core/Types/GameComparator/StrictGameComparator.cs index a95c3abf4a..db194d3be0 100644 --- a/Core/Types/GameComparator/StrictGameComparator.cs +++ b/Core/Types/GameComparator/StrictGameComparator.cs @@ -10,11 +10,11 @@ namespace CKAN /// public class StrictGameComparator : BaseGameComparator { - public override bool SingleVersionsCompatible(KspVersion gameVersion, CkanModule module) + public override bool SingleVersionsCompatible(GameVersion gameVersion, CkanModule module) { var gameVersionRange = gameVersion.ToVersionRange(); - var moduleRange = KspVersionRange.Any; + var moduleRange = GameVersionRange.Any; if (module.ksp_version != null) { @@ -24,7 +24,7 @@ public override bool SingleVersionsCompatible(KspVersion gameVersion, CkanModule { if (module.ksp_version_min != null && module.ksp_version_max != null) { - moduleRange = new KspVersionRange(module.ksp_version_min, module.ksp_version_max); + moduleRange = new GameVersionRange(module.ksp_version_min, module.ksp_version_max); if (moduleRange.Lower.Value > moduleRange.Upper.Value) { log.WarnFormat("{0} is not less or equal to {1}", @@ -34,11 +34,11 @@ public override bool SingleVersionsCompatible(KspVersion gameVersion, CkanModule } else if (module.ksp_version_min != null) { - moduleRange = new KspVersionRange(module.ksp_version_min, KspVersion.Any); + moduleRange = new GameVersionRange(module.ksp_version_min, GameVersion.Any); } else if (module.ksp_version_max != null) { - moduleRange = new KspVersionRange(KspVersion.Any, module.ksp_version_max); + moduleRange = new GameVersionRange(GameVersion.Any, module.ksp_version_max); } } else diff --git a/Core/Types/GameComparator/YoyoGameComparator.cs b/Core/Types/GameComparator/YoyoGameComparator.cs index 77d18d8280..121fa84620 100644 --- a/Core/Types/GameComparator/YoyoGameComparator.cs +++ b/Core/Types/GameComparator/YoyoGameComparator.cs @@ -8,7 +8,7 @@ namespace CKAN /// public class YoyoGameComparator : IGameComparator { - public bool Compatible(KspVersionCriteria gameVersion, CkanModule module) + public bool Compatible(GameVersionCriteria gameVersion, CkanModule module) { return true; } diff --git a/Core/Types/Kraken.cs b/Core/Types/Kraken.cs index 2bbc93c433..34936892fe 100644 --- a/Core/Types/Kraken.cs +++ b/Core/Types/Kraken.cs @@ -498,9 +498,9 @@ public InvalidModuleFileKraken(CkanModule module, string path, string reason = n /// /// The version is either not in the build map, or incomplete or something like this. /// - public class BadKSPVersionKraken : Kraken + public class BadGameVersionKraken : Kraken { - public BadKSPVersionKraken(string reason = null, Exception inner_exception = null) + public BadGameVersionKraken(string reason = null, Exception inner_exception = null) : base(reason, inner_exception) { } @@ -510,11 +510,11 @@ public BadKSPVersionKraken(string reason = null, Exception inner_exception = nul /// The version is a known and per se a valid KSP version, but is not allowed to be used for an action. /// For example the given base game version is too low to fake a DLC in instance faking. /// - public class WrongKSPVersionKraken : Kraken + public class WrongGameVersionKraken : Kraken { - public readonly Versioning.KspVersion version; + public readonly Versioning.GameVersion version; - public WrongKSPVersionKraken(Versioning.KspVersion version, string reason = null, Exception inner_exception = null) + public WrongGameVersionKraken(Versioning.GameVersion version, string reason = null, Exception inner_exception = null) : base(reason, inner_exception) { this.version = version; diff --git a/Core/Types/ModuleInstallDescriptor.cs b/Core/Types/ModuleInstallDescriptor.cs index 4675f0f096..8b24e31a63 100644 --- a/Core/Types/ModuleInstallDescriptor.cs +++ b/Core/Types/ModuleInstallDescriptor.cs @@ -105,7 +105,7 @@ internal void DeSerialisationFixes(StreamingContext like_i_could_care) } // Normalize paths on load (note, doesn't cover assignment like in tests) - install_to = KSPPathUtils.NormalizePath(install_to); + install_to = CKANPathUtils.NormalizePath(install_to); } #endregion @@ -152,13 +152,13 @@ public bool Equals(ModuleInstallDescriptor otherStanza) if (otherStanza == null) // Not even the right type! return false; - if (KSPPathUtils.NormalizePath(file) != KSPPathUtils.NormalizePath(otherStanza.file)) + if (CKANPathUtils.NormalizePath(file) != CKANPathUtils.NormalizePath(otherStanza.file)) return false; - if (KSPPathUtils.NormalizePath(find) != KSPPathUtils.NormalizePath(otherStanza.find)) + if (CKANPathUtils.NormalizePath(find) != CKANPathUtils.NormalizePath(otherStanza.find)) return false; if (find_regexp != otherStanza.find_regexp) return false; - if (KSPPathUtils.NormalizePath(install_to) != KSPPathUtils.NormalizePath(otherStanza.install_to)) + if (CKANPathUtils.NormalizePath(install_to) != CKANPathUtils.NormalizePath(otherStanza.install_to)) return false; if (@as != otherStanza.@as) return false; @@ -231,13 +231,13 @@ private void EnsurePattern() { if (file != null) { - file = KSPPathUtils.NormalizePath(file); + file = CKANPathUtils.NormalizePath(file); inst_pattern = new Regex(@"^" + Regex.Escape(file) + @"(/|$)", RegexOptions.IgnoreCase | RegexOptions.Compiled); } else if (find != null) { - find = KSPPathUtils.NormalizePath(find); + find = CKANPathUtils.NormalizePath(find); inst_pattern = new Regex(@"(?:^|/)" + Regex.Escape(find) + @"(/|$)", RegexOptions.IgnoreCase | RegexOptions.Compiled); } @@ -330,78 +330,50 @@ private bool IsWanted(string path, int? matchWhere) /// Throws a BadMetadataKraken if the stanza resulted in no files being returned. /// /// Thrown when the installation path is not valid according to the spec. - public List FindInstallableFiles(ZipFile zipfile, KSP ksp) + public List FindInstallableFiles(ZipFile zipfile, GameInstance ksp) { string installDir; var files = new List(); // Normalize the path before doing everything else - string install_to = KSPPathUtils.NormalizePath(this.install_to); + string install_to = CKANPathUtils.NormalizePath(this.install_to); - if (install_to == "GameData" || install_to.StartsWith("GameData/")) + // The installation path cannot contain updirs + if (install_to.Contains("/../") || install_to.EndsWith("/..")) + throw new BadInstallLocationKraken("Invalid installation path: " + install_to); + + if (ksp == null) + { + installDir = null; + } + else if (install_to == ksp.game.PrimaryModDirectoryRelative + || install_to.StartsWith($"{ksp.game.PrimaryModDirectoryRelative}/")) { // The installation path can be either "GameData" or a sub-directory of "GameData" - // but it cannot contain updirs - if (install_to.Contains("/../") || install_to.EndsWith("/..")) - throw new BadInstallLocationKraken("Invalid installation path: " + install_to); - - string subDir = install_to.Substring("GameData".Length); // remove "GameData" + string subDir = install_to.Substring(ksp.game.PrimaryModDirectoryRelative.Length); // remove "GameData" subDir = subDir.StartsWith("/") ? subDir.Substring(1) : subDir; // remove a "/" at the beginning, if present // Add the extracted subdirectory to the path of KSP's GameData - installDir = ksp == null ? null : (KSPPathUtils.NormalizePath(ksp.GameData() + "/" + subDir)); - } - else if (install_to.StartsWith("Ships")) - { - switch (install_to) - { - case "Ships": - installDir = ksp?.Ships(); - break; - case "Ships/VAB": - installDir = ksp?.ShipsVab(); - break; - case "Ships/SPH": - installDir = ksp?.ShipsSph(); - break; - case "Ships/@thumbs": - installDir = ksp?.ShipsThumbs(); - break; - case "Ships/@thumbs/VAB": - installDir = ksp?.ShipsThumbsVAB(); - break; - case "Ships/@thumbs/SPH": - installDir = ksp?.ShipsThumbsSPH(); - break; - case "Ships/Script": - installDir = ksp?.ShipsScript(); - break; - default: - throw new BadInstallLocationKraken("Unknown install_to " + install_to); - } + installDir = CKANPathUtils.NormalizePath(ksp.game.PrimaryModDirectory(ksp) + "/" + subDir); } else { switch (install_to) { - case "Tutorial": - installDir = ksp?.Tutorial(); - break; - - case "Scenarios": - installDir = ksp?.Scenarios(); - break; - - case "Missions": - installDir = ksp?.Missions(); - break; - case "GameRoot": - installDir = ksp?.GameDir(); + installDir = ksp.GameDir(); break; default: - throw new BadInstallLocationKraken("Unknown install_to " + install_to); + if (ksp.game.AllowInstallationIn(install_to, out string path)) + { + installDir = ksp.ToAbsoluteGameDir(path); + } + else + { + throw new BadInstallLocationKraken("Unknown install_to " + install_to); + } + break; } } @@ -524,7 +496,7 @@ internal string TransformOutputName(string outputName, string installDir, string } // Return our snipped, normalised, and ready to go output filename! - return KSPPathUtils.NormalizePath( + return CKANPathUtils.NormalizePath( Path.Combine(installDir, outputName) ); } diff --git a/Core/Types/RelationshipDescriptor.cs b/Core/Types/RelationshipDescriptor.cs index e89402b13d..e66219d7e3 100644 --- a/Core/Types/RelationshipDescriptor.cs +++ b/Core/Types/RelationshipDescriptor.cs @@ -17,7 +17,7 @@ IDictionary dlc public abstract bool WithinBounds(CkanModule otherModule); - public abstract List LatestAvailableWithProvides(IRegistryQuerier registry, KspVersionCriteria crit, IEnumerable toInstall = null); + public abstract List LatestAvailableWithProvides(IRegistryQuerier registry, GameVersionCriteria crit, IEnumerable toInstall = null); public abstract bool Equals(RelationshipDescriptor other); @@ -138,7 +138,7 @@ IDictionary dlc return false; } - public override List LatestAvailableWithProvides(IRegistryQuerier registry, KspVersionCriteria crit, IEnumerable toInstall = null) + public override List LatestAvailableWithProvides(IRegistryQuerier registry, GameVersionCriteria crit, IEnumerable toInstall = null) { return registry.LatestAvailableWithProvides(name, crit, this, toInstall); } @@ -225,7 +225,7 @@ IDictionary dlc ?? false; } - public override List LatestAvailableWithProvides(IRegistryQuerier registry, KspVersionCriteria crit, IEnumerable toInstall = null) + public override List LatestAvailableWithProvides(IRegistryQuerier registry, GameVersionCriteria crit, IEnumerable toInstall = null) { return any_of?.SelectMany(r => r.LatestAvailableWithProvides(registry, crit, toInstall)).ToList(); } diff --git a/Core/Types/Repository.cs b/Core/Types/Repository.cs index 6923c3dc79..b0ebb6e661 100644 --- a/Core/Types/Repository.cs +++ b/Core/Types/Repository.cs @@ -1,14 +1,13 @@ using System; using System.Net; using Newtonsoft.Json; +using CKAN.Games; namespace CKAN { public class Repository { [JsonIgnore] public static readonly string default_ckan_repo_name = "default"; - [JsonIgnore] public static readonly Uri default_ckan_repo_uri = new Uri("https://github.com/KSP-CKAN/CKAN-meta/archive/master.tar.gz"); - [JsonIgnore] public static readonly Uri default_repo_master_list = new Uri("https://raw.githubusercontent.com/KSP-CKAN/CKAN-meta/master/repositories.json"); public string name; public Uri uri; @@ -49,12 +48,12 @@ public struct RepositoryList { public Repository[] repositories; - public static RepositoryList DefaultRepositories() + public static RepositoryList DefaultRepositories(IGame game) { try { return JsonConvert.DeserializeObject( - Net.DownloadText(Repository.default_repo_master_list) + Net.DownloadText(game.RepositoryListURL) ); } catch diff --git a/Core/Versioning/KspVersion.cs b/Core/Versioning/GameVersion.cs similarity index 73% rename from Core/Versioning/KspVersion.cs rename to Core/Versioning/GameVersion.cs index 3710ac7c16..fd98a94a74 100644 --- a/Core/Versioning/KspVersion.cs +++ b/Core/Versioning/GameVersion.cs @@ -4,16 +4,17 @@ using System.Text.RegularExpressions; using System.Collections.Generic; using Newtonsoft.Json; -using CKAN.GameVersionProviders; using Autofac; +using CKAN.GameVersionProviders; +using CKAN.Games; namespace CKAN.Versioning { /// /// Represents the version number of a Kerbal Space Program (KSP) installation. /// - [JsonConverter(typeof(KspVersionJsonConverter))] - public sealed partial class KspVersion + [JsonConverter(typeof(GameVersionJsonConverter))] + public sealed partial class GameVersion { private static readonly Regex Pattern = new Regex( @"^(?\d+)(?:\.(?\d+)(?:\.(?\d+)(?:\.(?\d+))?)?)?$", @@ -22,7 +23,7 @@ public sealed partial class KspVersion private const int Undefined = -1; - public static readonly KspVersion Any = new KspVersion(); + public static readonly GameVersion Any = new GameVersion(); private readonly int _major; private readonly int _minor; @@ -32,55 +33,55 @@ public sealed partial class KspVersion private readonly string _string; /// - /// Gets the value of the major component of the version number for the current + /// Gets the value of the major component of the version number for the current /// object. /// public int Major { get { return _major; } } /// - /// Gets the value of the minor component of the version number for the current + /// Gets the value of the minor component of the version number for the current /// object. /// public int Minor { get { return _minor; } } /// - /// Gets the value of the patch component of the version number for the current + /// Gets the value of the patch component of the version number for the current /// object. /// public int Patch { get { return _patch; } } /// - /// Gets the value of the build component of the version number for the current + /// Gets the value of the build component of the version number for the current /// object. /// public int Build { get { return _build; } } /// - /// Gets whether or not the major component of the version number for the current + /// Gets whether or not the major component of the version number for the current /// object is defined. /// public bool IsMajorDefined { get { return _major != Undefined; } } /// - /// Gets whether or not the minor component of the version number for the current + /// Gets whether or not the minor component of the version number for the current /// object is defined. /// public bool IsMinorDefined { get { return _minor != Undefined; } } /// - /// Gets whether or not the patch component of the version number for the current + /// Gets whether or not the patch component of the version number for the current /// object is defined. /// public bool IsPatchDefined { get { return _patch != Undefined; } } /// - /// Gets whether or not the build component of the version number for the current + /// Gets whether or not the build component of the version number for the current /// object is defined. /// public bool IsBuildDefined { get { return _build != Undefined; } } /// - /// Indicates whether or not all components of the current are defined. + /// Indicates whether or not all components of the current are defined. /// public bool IsFullyDefined { @@ -88,7 +89,7 @@ public bool IsFullyDefined } /// - /// Indicates wheter or not all the components of the current are undefined. + /// Indicates wheter or not all the components of the current are undefined. /// public bool IsAny { @@ -103,15 +104,15 @@ public bool IsAny /// /// True if null or Any, false otherwise /// - public static bool IsNullOrAny(KspVersion v) + public static bool IsNullOrAny(GameVersion v) { return v == null || v.IsAny; } /// - /// Initialize a new instance of the class with all components unspecified. + /// Initialize a new instance of the class with all components unspecified. /// - public KspVersion() + public GameVersion() { _major = Undefined; _minor = Undefined; @@ -122,10 +123,10 @@ public KspVersion() } /// - /// Initialize a new instance of the class using the specified major value. + /// Initialize a new instance of the class using the specified major value. /// /// The major version number. - public KspVersion(int major) + public GameVersion(int major) { if (major < 0) throw new ArgumentOutOfRangeException("major"); @@ -139,12 +140,12 @@ public KspVersion(int major) } /// - /// Initialize a new instance of the class using the specified major and minor + /// Initialize a new instance of the class using the specified major and minor /// values. /// /// The major version number. /// The minor version number. - public KspVersion(int major, int minor) + public GameVersion(int major, int minor) { if (major < 0) throw new ArgumentOutOfRangeException("major"); @@ -161,13 +162,13 @@ public KspVersion(int major, int minor) } /// - /// Initialize a new instance of the class using the specified major, minor, and + /// Initialize a new instance of the class using the specified major, minor, and /// patch values. /// /// The major version number. /// The minor version number. /// The patch version number. - public KspVersion(int major, int minor, int patch) + public GameVersion(int major, int minor, int patch) { if (major < 0) throw new ArgumentOutOfRangeException("major"); @@ -187,14 +188,14 @@ public KspVersion(int major, int minor, int patch) } /// - /// Initialize a new instance of the class using the specified major, minor, patch, + /// Initialize a new instance of the class using the specified major, minor, patch, /// and build values. /// /// The major version number. /// The minor version number. /// The patch version number. /// The build verison number. - public KspVersion(int major, int minor, int patch, int build) + public GameVersion(int major, int minor, int patch, int build) { if (major < 0) throw new ArgumentOutOfRangeException("major"); @@ -217,13 +218,13 @@ public KspVersion(int major, int minor, int patch, int build) } /// - /// Converts the value of the current to its equivalent + /// Converts the value of the current to its equivalent /// representation. /// /// /// /// The representation of the values of the major, minor, patch, and build components of - /// the current object as depicted in the following format. Each component is + /// the current object as depicted in the following format. Each component is /// separated by a period character ('.'). Square brackets ('[' and ']') indicate a component that will not /// appear in the return value if the component is not defined: /// @@ -231,12 +232,12 @@ public KspVersion(int major, int minor, int patch, int build) /// [major[.minor[.patch[.build]]]] /// /// - /// For example, if you create a object using the constructor KspVersion(1,1), - /// the returned string is "1.1". If you create a using the constructor (1,3,4,2), + /// For example, if you create a object using the constructor GameVersion(1,1), + /// the returned string is "1.1". If you create a using the constructor (1,3,4,2), /// the returned string is "1.3.4.2". /// /// - /// If the current is totally undefined the return value will null. + /// If the current is totally undefined the return value will null. /// /// public override string ToString() @@ -244,15 +245,15 @@ public override string ToString() return _string; } - private static Dictionary VersionsMax = new Dictionary(); + private static Dictionary VersionsMax = new Dictionary(); /// /// Generate version mapping table once for all instances to share /// - static KspVersion() + static GameVersion() { // Should be sorted - List versions = ServiceLocator.Container.Resolve().KnownVersions; + List versions = ServiceLocator.Container.Resolve().KnownVersions; VersionsMax[""] = versions.Last(); foreach (var v in versions) { @@ -271,7 +272,7 @@ static KspVersion() /// public string ToYalovString() { - KspVersion value; + GameVersion value; if (!IsMajorDefined // 2.0.0 @@ -304,13 +305,13 @@ private static int UptoNines(int num) } /// - /// Converts the value of the current to its equivalent - /// . + /// Converts the value of the current to its equivalent + /// . /// /// /// - /// A which specifies a set of versions equivalent to the current - /// . + /// A which specifies a set of versions equivalent to the current + /// . /// /// /// For example, the version "1.0.0.0" would be equivalent to the range ["1.0.0.0", "1.0.0.0"], while the @@ -318,54 +319,54 @@ private static int UptoNines(int num) /// inclusive bounds and '(' and ')' represent exclusive bounds. /// /// - public KspVersionRange ToVersionRange() + public GameVersionRange ToVersionRange() { - KspVersionBound lower; - KspVersionBound upper; + GameVersionBound lower; + GameVersionBound upper; if (IsBuildDefined) { - lower = new KspVersionBound(this, inclusive: true); - upper = new KspVersionBound(this, inclusive: true); + lower = new GameVersionBound(this, inclusive: true); + upper = new GameVersionBound(this, inclusive: true); } else if (IsPatchDefined) { - lower = new KspVersionBound(new KspVersion(Major, Minor, Patch, 0), inclusive: true); - upper = new KspVersionBound(new KspVersion(Major, Minor, Patch + 1, 0), inclusive: false); + lower = new GameVersionBound(new GameVersion(Major, Minor, Patch, 0), inclusive: true); + upper = new GameVersionBound(new GameVersion(Major, Minor, Patch + 1, 0), inclusive: false); } else if (IsMinorDefined) { - lower = new KspVersionBound(new KspVersion(Major, Minor, 0, 0), inclusive: true); - upper = new KspVersionBound(new KspVersion(Major, Minor + 1, 0, 0), inclusive: false); + lower = new GameVersionBound(new GameVersion(Major, Minor, 0, 0), inclusive: true); + upper = new GameVersionBound(new GameVersion(Major, Minor + 1, 0, 0), inclusive: false); } else if (IsMajorDefined) { - lower = new KspVersionBound(new KspVersion(Major, 0, 0, 0), inclusive: true); - upper = new KspVersionBound(new KspVersion(Major + 1, 0, 0, 0), inclusive: false); + lower = new GameVersionBound(new GameVersion(Major, 0, 0, 0), inclusive: true); + upper = new GameVersionBound(new GameVersion(Major + 1, 0, 0, 0), inclusive: false); } else { - lower = KspVersionBound.Unbounded; - upper = KspVersionBound.Unbounded; + lower = GameVersionBound.Unbounded; + upper = GameVersionBound.Unbounded; } - return new KspVersionRange(lower, upper); + return new GameVersionRange(lower, upper); } /// - /// Converts the string representation of a version number to an equivalent object. + /// Converts the string representation of a version number to an equivalent object. /// /// A string that contains a version number to convert. /// - /// A object that is equivalent to the version number specified in the + /// A object that is equivalent to the version number specified in the /// parameter. /// - public static KspVersion Parse(string input) + public static GameVersion Parse(string input) { if (ReferenceEquals(input, null)) throw new ArgumentNullException("input"); - KspVersion result; + GameVersion result; if (TryParse(input, out result)) return result; else @@ -373,20 +374,20 @@ public static KspVersion Parse(string input) } /// - /// Tries to convert the string representation of a version number to an equivalent + /// Tries to convert the string representation of a version number to an equivalent /// object and returns a value that indicates whether the conversion succeeded. /// /// /// A string that contains a version number to convert. /// /// - /// When this method returns true, contains the equivalent of the number that + /// When this method returns true, contains the equivalent of the number that /// is contained in . When this method returns false, the value is unspecified. /// /// /// true if the parameter was converted successfully; otherwise, false. /// - public static bool TryParse(string input, out KspVersion result) + public static bool TryParse(string input, out GameVersion result) { result = null; @@ -395,7 +396,7 @@ public static bool TryParse(string input, out KspVersion result) if (input == "any") { - result = KspVersion.Any; + result = GameVersion.Any; return true; } @@ -430,13 +431,13 @@ public static bool TryParse(string input, out KspVersion result) return false; if (minor == Undefined) - result = new KspVersion(major); + result = new GameVersion(major); else if (patch == Undefined) - result = new KspVersion(major, minor); + result = new GameVersion(major, minor); else if (build == Undefined) - result = new KspVersion(major, minor, patch); + result = new GameVersion(major, minor, patch); else - result = new KspVersion(major, minor, patch, build); + result = new GameVersion(major, minor, patch, build); return true; } @@ -450,11 +451,11 @@ public static bool TryParse(string input, out KspVersion result) /// Searches the build map if the version is a valid, known KSP version. /// /// true, if version is in the build map, false otherwise. - public bool InBuildMap() + public bool InBuildMap(IGame game) { - List knownVersions = ServiceLocator.Container.Resolve().KnownVersions; + List knownVersions = game.KnownVersions; - foreach (KspVersion ver in knownVersions) + foreach (GameVersion ver in knownVersions) { if (ver.Major == Major && ver.Minor == Minor && ver.Patch == Patch) { @@ -476,11 +477,11 @@ public bool InBuildMap() /// of the patch range. /// Needs at least a Major and Minor (doesn't make sense else). /// - /// A complete KspVersion object + /// A complete GameVersion object /// A IUser instance, to raise the corresponding dialog. - public KspVersion RaiseVersionSelectionDialog (IUser user) + public GameVersion RaiseVersionSelectionDialog (IGame game, IUser user) { - if (IsFullyDefined && InBuildMap()) + if (IsFullyDefined && InBuildMap(game)) { // The specified version is complete and known :hooray:. Return this instance. return this; @@ -488,19 +489,19 @@ public KspVersion RaiseVersionSelectionDialog (IUser user) } else if (!IsMajorDefined || !IsMinorDefined) { - throw new BadKSPVersionKraken("Needs at least Major and Minor"); + throw new BadGameVersionKraken("Needs at least Major and Minor"); } else { // Get all known versions out of the build map. - KspVersion[] knownVersions = ServiceLocator.Container.Resolve().KnownVersions.ToArray(); - List possibleVersions = new List(); + var knownVersions = game.KnownVersions; + List possibleVersions = new List(); // Default message passed to RaiseSelectionDialog. string message = "The specified version is not unique, please select one:"; // Find the versions which are part of the range. - foreach (KspVersion ver in knownVersions) + foreach (GameVersion ver in knownVersions) { // If we only have Major and Minor -> compare these two. if (!IsPatchDefined) @@ -534,7 +535,7 @@ public KspVersion RaiseVersionSelectionDialog (IUser user) if (possibleVersions.Count == 0) { // No version found in the map. Happens for future or other unknown versions. - throw new BadKSPVersionKraken("The version is not known to CKAN."); + throw new BadGameVersionKraken("The version is not known to CKAN."); } else if (possibleVersions.Count == 1) { @@ -562,21 +563,21 @@ public KspVersion RaiseVersionSelectionDialog (IUser user) } } - public sealed partial class KspVersion : IEquatable + public sealed partial class GameVersion : IEquatable { /// - /// Returns a value indicating whether the current object and specified - /// object represent the same value. + /// Returns a value indicating whether the current object and specified + /// object represent the same value. /// /// - /// A object to compare to the current object, or + /// A object to compare to the current object, or /// null. /// /// - /// true if every component of the current matches the corresponding component + /// true if every component of the current matches the corresponding component /// of the parameter; otherwise, false. /// - public bool Equals(KspVersion obj) + public bool Equals(GameVersion obj) { if (ReferenceEquals(obj, null)) return false; if (ReferenceEquals(obj, this)) return true; @@ -584,26 +585,26 @@ public bool Equals(KspVersion obj) } /// - /// Returns a value indicating whether the current object is equal to a specified + /// Returns a value indicating whether the current object is equal to a specified /// object. /// /// - /// An object to compare with the current object, or null. + /// An object to compare with the current object, or null. /// /// - /// true if the current object and are both - /// objects and every component of the current object + /// true if the current object and are both + /// objects and every component of the current object /// matches the corresponding component of ; otherwise, false. /// public override bool Equals(object obj) { if (ReferenceEquals(obj, null)) return false; if (ReferenceEquals(obj, this)) return true; - return obj is KspVersion && Equals((KspVersion) obj); + return obj is GameVersion && Equals((GameVersion) obj); } /// - /// Returns a hash code for the current object. + /// Returns a hash code for the current object. /// /// A 32-bit signed integer hash code. public override int GetHashCode() @@ -619,34 +620,34 @@ public override int GetHashCode() } /// - /// Determines whether two specified objects are equal. + /// Determines whether two specified objects are equal. /// - /// The first object. - /// The second object. + /// The first object. + /// The second object. /// true if equals ; otherwise, false. - public static bool operator ==(KspVersion v1, KspVersion v2) + public static bool operator ==(GameVersion v1, GameVersion v2) { return Equals(v1, v2); } /// - /// Determines whether two specified objects are not equal. + /// Determines whether two specified objects are not equal. /// - /// The first object. - /// The second object. + /// The first object. + /// The second object. /// /// true if does not equal ; otherwise, false. /// - public static bool operator !=(KspVersion v1, KspVersion v2) + public static bool operator !=(GameVersion v1, GameVersion v2) { return !Equals(v1, v2); } } - public sealed partial class KspVersion : IComparable, IComparable + public sealed partial class GameVersion : IComparable, IComparable { /// - /// Compares the current object to a specified object and returns an indication of + /// Compares the current object to a specified object and returns an indication of /// their relative values. /// /// An object to compare, or null. @@ -660,20 +661,20 @@ public sealed partial class KspVersion : IComparable, IComparable /// /// Less than zero /// - /// The current object is a version before . + /// The current object is a version before . /// /// /// /// Zero /// - /// The current object is the same version as . + /// The current object is the same version as . /// /// /// /// Greater than zero /// /// - /// The current object is a version subsequent to . + /// The current object is a version subsequent to . /// /// /// @@ -684,16 +685,16 @@ public int CompareTo(object obj) if (ReferenceEquals(obj, null)) throw new ArgumentNullException("obj"); - var objKspVersion = obj as KspVersion; + var objGameVersion = obj as GameVersion; - if (objKspVersion != null) - return CompareTo(objKspVersion); + if (objGameVersion != null) + return CompareTo(objGameVersion); else - throw new ArgumentException("Object must be of type KspVersion."); + throw new ArgumentException("Object must be of type GameVersion."); } /// - /// Compares the current object to a specified object and returns an indication of + /// Compares the current object to a specified object and returns an indication of /// their relative values. /// /// An object to compare. @@ -707,26 +708,26 @@ public int CompareTo(object obj) /// /// Less than zero /// - /// The current object is a version before . + /// The current object is a version before . /// /// /// /// Zero /// - /// The current object is the same version as . + /// The current object is the same version as . /// /// /// /// Greater than zero /// /// - /// The current object is a version subsequent to . + /// The current object is a version subsequent to . /// /// /// /// /// - public int CompareTo(KspVersion other) + public int CompareTo(GameVersion other) { if (ReferenceEquals(other, null)) throw new ArgumentNullException("other"); @@ -758,15 +759,15 @@ public int CompareTo(KspVersion other) } /// - /// Determines whether the first specified object is less than the second specified - /// object. + /// Determines whether the first specified object is less than the second specified + /// object. /// - /// The first object. - /// The second object. + /// The first object. + /// The second object. /// /// true if is less than ; otherwise, flase. /// - public static bool operator <(KspVersion left, KspVersion right) + public static bool operator <(GameVersion left, GameVersion right) { if (ReferenceEquals(left, null)) throw new ArgumentNullException("left"); @@ -778,15 +779,15 @@ public int CompareTo(KspVersion other) } /// - /// Determines whether the first specified object is greater than the second + /// Determines whether the first specified object is greater than the second /// specified object. /// - /// The first object. - /// The second object. + /// The first object. + /// The second object. /// /// true if is greater than ; otherwise, flase. /// - public static bool operator >(KspVersion left, KspVersion right) + public static bool operator >(GameVersion left, GameVersion right) { if (ReferenceEquals(left, null)) throw new ArgumentNullException("left"); @@ -798,15 +799,15 @@ public int CompareTo(KspVersion other) } /// - /// Determines whether the first specified object is less than or equal to the second - /// specified object. + /// Determines whether the first specified object is less than or equal to the second + /// specified object. /// - /// The first object. - /// The second object. + /// The first object. + /// The second object. /// /// true if is less than or equal to ; otherwise, flase. /// - public static bool operator <=(KspVersion left, KspVersion right) + public static bool operator <=(GameVersion left, GameVersion right) { if (ReferenceEquals(left, null)) throw new ArgumentNullException("left"); @@ -818,15 +819,15 @@ public int CompareTo(KspVersion other) } /// - /// Determines whether the first specified object is greater than or equal to the - /// second specified object. + /// Determines whether the first specified object is greater than or equal to the + /// second specified object. /// - /// The first object. - /// The second object. + /// The first object. + /// The second object. /// /// true if is greater than or equal to ; otherwise, flase. /// - public static bool operator >=(KspVersion left, KspVersion right) + public static bool operator >=(GameVersion left, GameVersion right) { if (ReferenceEquals(left, null)) throw new ArgumentNullException("left"); @@ -838,9 +839,9 @@ public int CompareTo(KspVersion other) } } - public sealed partial class KspVersion + public sealed partial class GameVersion { - public static KspVersion Min(params KspVersion[] versions) + public static GameVersion Min(params GameVersion[] versions) { if (versions == null) throw new ArgumentNullException("versions"); @@ -854,7 +855,7 @@ public static KspVersion Min(params KspVersion[] versions) return versions.Min(); } - public static KspVersion Max(params KspVersion[] versions) + public static GameVersion Max(params GameVersion[] versions) { if (versions == null) throw new ArgumentNullException("versions"); @@ -869,7 +870,7 @@ public static KspVersion Max(params KspVersion[] versions) } } - public sealed partial class KspVersion + public sealed partial class GameVersion { private static string DeriveString(int major, int minor, int patch, int build) { @@ -904,7 +905,7 @@ private static string DeriveString(int major, int minor, int patch, int build) } } - public sealed class KspVersionJsonConverter : JsonConverter + public sealed class GameVersionJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -920,7 +921,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist case null: return null; default: - KspVersion result; + GameVersion result; // For a little while, AVC files which didn't specify a full three-part // version number could result in versions like `1.1.`, which cause our @@ -929,7 +930,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist value = Regex.Replace(value, @"\.$", ""); - if (KspVersion.TryParse(value, out result)) + if (GameVersion.TryParse(value, out result)) return result; else throw new JsonException(string.Format("Could not parse KSP version: {0}", value)); @@ -938,7 +939,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist public override bool CanConvert(Type objectType) { - return objectType == typeof(KspVersion); + return objectType == typeof(GameVersion); } } } diff --git a/Core/Versioning/KspVersionBound.cs b/Core/Versioning/GameVersionBound.cs similarity index 68% rename from Core/Versioning/KspVersionBound.cs rename to Core/Versioning/GameVersionBound.cs index 05b01e812b..4c48d20f6d 100644 --- a/Core/Versioning/KspVersionBound.cs +++ b/Core/Versioning/GameVersionBound.cs @@ -3,19 +3,19 @@ namespace CKAN.Versioning { - public sealed partial class KspVersionBound + public sealed partial class GameVersionBound { - public static readonly KspVersionBound Unbounded = new KspVersionBound(); + public static readonly GameVersionBound Unbounded = new GameVersionBound(); - public KspVersion Value { get; private set; } + public GameVersion Value { get; private set; } public bool Inclusive { get; private set; } private readonly string _string; - public KspVersionBound() - : this(KspVersion.Any, true) { } + public GameVersionBound() + : this(GameVersion.Any, true) { } - public KspVersionBound(KspVersion value, bool inclusive) + public GameVersionBound(GameVersion value, bool inclusive) { if (ReferenceEquals(value, null)) throw new ArgumentNullException("value"); @@ -39,9 +39,9 @@ public override string ToString() } } - public sealed partial class KspVersionBound : IEquatable + public sealed partial class GameVersionBound : IEquatable { - public bool Equals(KspVersionBound other) + public bool Equals(GameVersionBound other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; @@ -52,7 +52,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is KspVersionBound && Equals((KspVersionBound) obj); + return obj is GameVersionBound && Equals((GameVersionBound) obj); } public override int GetHashCode() @@ -63,27 +63,27 @@ public override int GetHashCode() } } - public static bool operator ==(KspVersionBound left, KspVersionBound right) + public static bool operator ==(GameVersionBound left, GameVersionBound right) { return Equals(left, right); } - public static bool operator !=(KspVersionBound left, KspVersionBound right) + public static bool operator !=(GameVersionBound left, GameVersionBound right) { return !Equals(left, right); } } - public sealed partial class KspVersionBound + public sealed partial class GameVersionBound { /// - /// Returns the lowest of a set of objects. Analagous to - /// but does not produce a stable sort because in the event of a + /// Returns the lowest of a set of objects. Analagous to + /// but does not produce a stable sort because in the event of a /// tie inclusive bounds are treated as both lower and higher than equivalent exclusive bounds. /// - /// The set of objects to compare. + /// The set of objects to compare. /// The lowest value in . - public static KspVersionBound Lowest(params KspVersionBound[] versionBounds) + public static GameVersionBound Lowest(params GameVersionBound[] versionBounds) { if (versionBounds == null) throw new ArgumentNullException("versionBounds"); @@ -102,13 +102,13 @@ public static KspVersionBound Lowest(params KspVersionBound[] versionBounds) } /// - /// Returns the highest of a set of objects. Analagous to - /// but does not produce a stable sort because in the event of a + /// Returns the highest of a set of objects. Analagous to + /// but does not produce a stable sort because in the event of a /// tie inclusive bounds are treated as both lower and higher than equivalent exclusive bounds. /// - /// The set of objects to compare. + /// The set of objects to compare. /// The highest value in . - public static KspVersionBound Highest(params KspVersionBound[] versionBounds) + public static GameVersionBound Highest(params GameVersionBound[] versionBounds) { if (versionBounds == null) throw new ArgumentNullException("versionBounds"); diff --git a/Core/Versioning/KspVersionCriteria.cs b/Core/Versioning/GameVersionCriteria.cs similarity index 68% rename from Core/Versioning/KspVersionCriteria.cs rename to Core/Versioning/GameVersionCriteria.cs index 9d94b7f679..0b603d3cf5 100644 --- a/Core/Versioning/KspVersionCriteria.cs +++ b/Core/Versioning/GameVersionCriteria.cs @@ -4,11 +4,11 @@ namespace CKAN.Versioning { - public class KspVersionCriteria : IEquatable + public class GameVersionCriteria : IEquatable { - private List _versions = new List(); + private List _versions = new List(); - public KspVersionCriteria(KspVersion v) + public GameVersionCriteria(GameVersion v) { if (v != null) { @@ -16,7 +16,7 @@ public KspVersionCriteria(KspVersion v) } } - public KspVersionCriteria(KspVersion v, List compatibleVersions) + public GameVersionCriteria(GameVersion v, List compatibleVersions) { if (v != null) { @@ -26,7 +26,7 @@ public KspVersionCriteria(KspVersion v, List compatibleVersions) this._versions = this._versions.Distinct().ToList(); } - public IList Versions + public IList Versions { get { @@ -34,9 +34,9 @@ public IList Versions } } - public KspVersionCriteria Union(KspVersionCriteria other) + public GameVersionCriteria Union(GameVersionCriteria other) { - return new KspVersionCriteria( + return new GameVersionCriteria( null, _versions.Union(other.Versions).ToList() ); @@ -44,11 +44,11 @@ public KspVersionCriteria Union(KspVersionCriteria other) public override bool Equals(object obj) { - return Equals(obj as KspVersionCriteria); + return Equals(obj as GameVersionCriteria); } - // From IEquatable - public bool Equals(KspVersionCriteria other) + // From IEquatable + public bool Equals(GameVersionCriteria other) { return other == null ? false @@ -64,7 +64,7 @@ public override int GetHashCode() public override String ToString() { List versionList = new List(); - foreach (KspVersion version in _versions) + foreach (GameVersion version in _versions) { versionList.Add(version.ToString()); } diff --git a/Core/Versioning/KspVersionRange.cs b/Core/Versioning/GameVersionRange.cs similarity index 64% rename from Core/Versioning/KspVersionRange.cs rename to Core/Versioning/GameVersionRange.cs index 0d7466af59..a115139186 100644 --- a/Core/Versioning/KspVersionRange.cs +++ b/Core/Versioning/GameVersionRange.cs @@ -1,19 +1,20 @@ using System; using System.Text; +using CKAN.Games; namespace CKAN.Versioning { - public sealed partial class KspVersionRange + public sealed partial class GameVersionRange { private readonly string _string; - public static readonly KspVersionRange Any = - new KspVersionRange(KspVersionBound.Unbounded, KspVersionBound.Unbounded); + public static readonly GameVersionRange Any = + new GameVersionRange(GameVersionBound.Unbounded, GameVersionBound.Unbounded); - public KspVersionBound Lower { get; private set; } - public KspVersionBound Upper { get; private set; } + public GameVersionBound Lower { get; private set; } + public GameVersionBound Upper { get; private set; } - public KspVersionRange(KspVersionBound lower, KspVersionBound upper) + public GameVersionRange(GameVersionBound lower, GameVersionBound upper) { if (ReferenceEquals(lower, null)) throw new ArgumentNullException("lower"); @@ -27,7 +28,7 @@ public KspVersionRange(KspVersionBound lower, KspVersionBound upper) _string = DeriveString(this); } - public KspVersionRange(KspVersion lower, KspVersion upper) + public GameVersionRange(GameVersion lower, GameVersion upper) : this(lower?.ToVersionRange().Lower, upper?.ToVersionRange().Upper) { } public override string ToString() @@ -35,18 +36,18 @@ public override string ToString() return _string; } - public KspVersionRange IntersectWith(KspVersionRange other) + public GameVersionRange IntersectWith(GameVersionRange other) { if (ReferenceEquals(other, null)) throw new ArgumentNullException("other"); - var highestLow = KspVersionBound.Highest(Lower, other.Lower); - var lowestHigh = KspVersionBound.Lowest(Upper, other.Upper); + var highestLow = GameVersionBound.Highest(Lower, other.Lower); + var lowestHigh = GameVersionBound.Lowest(Upper, other.Upper); - return IsEmpty(highestLow, lowestHigh) ? null : new KspVersionRange(highestLow, lowestHigh); + return IsEmpty(highestLow, lowestHigh) ? null : new GameVersionRange(highestLow, lowestHigh); } - public bool IsSupersetOf(KspVersionRange other) + public bool IsSupersetOf(GameVersionRange other) { if (ReferenceEquals(other, null)) throw new ArgumentNullException("other"); @@ -62,13 +63,13 @@ public bool IsSupersetOf(KspVersionRange other) return lowerIsOkay && upperIsOkay; } - private static bool IsEmpty(KspVersionBound lower, KspVersionBound upper) + private static bool IsEmpty(GameVersionBound lower, GameVersionBound upper) { return upper.Value < lower.Value || (lower.Value == upper.Value && (!lower.Inclusive || !upper.Inclusive)); } - private static string DeriveString(KspVersionRange versionRange) + private static string DeriveString(GameVersionRange versionRange) { var sb = new StringBuilder(); @@ -87,7 +88,7 @@ private static string DeriveString(KspVersionRange versionRange) return sb.ToString(); } - private static string SameVersionString(KspVersion v) + private static string SameVersionString(GameVersion v) { return v == null ? "???" : v.IsAny ? "all versions" @@ -103,19 +104,19 @@ private static string SameVersionString(KspVersion v) /// /// Human readable string describing the versions. /// - public static string VersionSpan(KspVersion minKsp, KspVersion maxKsp) + public static string VersionSpan(IGame game, GameVersion minKsp, GameVersion maxKsp) { - return minKsp == maxKsp ? $"KSP {SameVersionString(minKsp)}" - : minKsp.IsAny ? $"KSP {maxKsp} and earlier" - : maxKsp.IsAny ? $"KSP {minKsp} and later" - : $"KSP {minKsp} - {maxKsp}"; + return minKsp == maxKsp ? $"{game.ShortName} {SameVersionString(minKsp)}" + : minKsp.IsAny ? $"{game.ShortName} {maxKsp} and earlier" + : maxKsp.IsAny ? $"{game.ShortName} {minKsp} and later" + : $"{game.ShortName} {minKsp} - {maxKsp}"; } } - public sealed partial class KspVersionRange : IEquatable + public sealed partial class GameVersionRange : IEquatable { - public bool Equals(KspVersionRange other) + public bool Equals(GameVersionRange other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; @@ -126,7 +127,7 @@ public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - return obj is KspVersionRange && Equals((KspVersionRange) obj); + return obj is GameVersionRange && Equals((GameVersionRange) obj); } public override int GetHashCode() @@ -137,12 +138,12 @@ public override int GetHashCode() } } - public static bool operator ==(KspVersionRange left, KspVersionRange right) + public static bool operator ==(GameVersionRange left, GameVersionRange right) { return Equals(left, right); } - public static bool operator !=(KspVersionRange left, KspVersionRange right) + public static bool operator !=(GameVersionRange left, GameVersionRange right) { return !Equals(left, right); } diff --git a/GUI/CKAN-GUI.csproj b/GUI/CKAN-GUI.csproj index 901873e614..35402f2545 100644 --- a/GUI/CKAN-GUI.csproj +++ b/GUI/CKAN-GUI.csproj @@ -62,23 +62,23 @@ AskUserForAutoUpdatesDialog.cs - + Form - - ManageKspInstancesDialog.cs + + ManageGameInstancesDialog.cs - + Form - - CloneFakeKspDialog.cs + + CloneFakeGameDialog.cs - + Form - - CompatibleKspVersionsDialog.cs + + CompatibleGameVersionsDialog.cs Form @@ -92,11 +92,11 @@ ErrorDialog.cs - + Form - - KSPCommandLineOptionsDialog.cs + + GameCommandLineOptionsDialog.cs Form @@ -343,23 +343,23 @@ ..\..\Dialogs\AskUserForAutoUpdatesDialog.cs - - CloneFakeKspDialog.cs + + CloneFakeGameDialog.cs - - ..\..\Dialogs\CloneFakeKspDialog.cs + + ..\..\Dialogs\CloneFakeGameDialog.cs - - ..\..\Dialogs\CloneFakeKspDialog.cs + + ..\..\Dialogs\CloneFakeGameDialog.cs - - CompatibleKspVersionsDialog.cs + + CompatibleGameVersionsDialog.cs - - ..\..\Dialogs\CompatibleKspVersionsDialog.cs + + ..\..\Dialogs\CompatibleGameVersionsDialog.cs - - ..\..\Dialogs\CompatibleKspVersionsDialog.cs + + ..\..\Dialogs\CompatibleGameVersionsDialog.cs Changeset.cs @@ -439,14 +439,14 @@ HintTextBox.cs - - KSPCommandLineOptionsDialog.cs + + GameCommandLineOptionsDialog.cs - - ..\..\Dialogs\KSPCommandLineOptionsDialog.cs + + ..\..\Dialogs\GameCommandLineOptionsDialog.cs - - ..\..\Dialogs\KSPCommandLineOptionsDialog.cs + + ..\..\Dialogs\GameCommandLineOptionsDialog.cs Main.cs @@ -506,14 +506,14 @@ ..\..\Controls\ModInfo.cs - - ManageKspInstancesDialog.cs + + ManageGameInstancesDialog.cs - - ..\..\Dialogs\ManageKspInstancesDialog.cs + + ..\..\Dialogs\ManageGameInstancesDialog.cs - - ..\..\Dialogs\ManageKspInstancesDialog.cs + + ..\..\Dialogs\ManageGameInstancesDialog.cs NewRepoDialog.cs diff --git a/GUI/Controls/AllModVersions.Designer.cs b/GUI/Controls/AllModVersions.Designer.cs index dfc8b7895b..8674faf55e 100644 --- a/GUI/Controls/AllModVersions.Designer.cs +++ b/GUI/Controls/AllModVersions.Designer.cs @@ -36,7 +36,7 @@ private void InitializeComponent() "i2"}, -1); this.label1 = new System.Windows.Forms.Label(); this.ModVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); - this.CompatibleKSPVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.CompatibleGameVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.VersionsListView = new ThemedListView(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); @@ -60,10 +60,10 @@ private void InitializeComponent() this.ModVersion.Width = 98; resources.ApplyResources(this.ModVersion, "ModVersion"); // - // CompatibleKSPVersion + // CompatibleGameVersion // - this.CompatibleKSPVersion.Width = 160; - resources.ApplyResources(this.CompatibleKSPVersion, "CompatibleKSPVersion"); + this.CompatibleGameVersion.Width = 190; + resources.ApplyResources(this.CompatibleGameVersion, "CompatibleGameVersion"); // // VersionsListView // @@ -72,7 +72,7 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Right))); this.VersionsListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.ModVersion, - this.CompatibleKSPVersion}); + this.CompatibleGameVersion}); this.VersionsListView.CheckBoxes = true; this.VersionsListView.FullRowSelect = true; this.VersionsListView.Items.AddRange(new System.Windows.Forms.ListViewItem[] { @@ -164,7 +164,7 @@ private void InitializeComponent() private System.Windows.Forms.Label label1; private System.Windows.Forms.ColumnHeader ModVersion; - private System.Windows.Forms.ColumnHeader CompatibleKSPVersion; + private System.Windows.Forms.ColumnHeader CompatibleGameVersion; private System.Windows.Forms.ListView VersionsListView; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; diff --git a/GUI/Controls/AllModVersions.cs b/GUI/Controls/AllModVersions.cs index 135ca5bde2..71ed952ead 100644 --- a/GUI/Controls/AllModVersions.cs +++ b/GUI/Controls/AllModVersions.cs @@ -140,7 +140,7 @@ public GUIMod SelectedModule // Only show checkboxes for non-DLC modules VersionsListView.CheckBoxes = !value.ToModule().IsDLC; - KSP currentInstance = Main.Instance.Manager.CurrentInstance; + GameInstance currentInstance = Main.Instance.Manager.CurrentInstance; IRegistryQuerier registry = RegistryManager.Instance(currentInstance).registry; List allAvailableVersions; @@ -162,12 +162,12 @@ public GUIMod SelectedModule VersionsListView.Items.AddRange(allAvailableVersions.Select(module => { ModuleVersion minMod = null, maxMod = null; - KspVersion minKsp = null, maxKsp = null; + GameVersion minKsp = null, maxKsp = null; Registry.GetMinMaxVersions(new List() {module}, out minMod, out maxMod, out minKsp, out maxKsp); ListViewItem toRet = new ListViewItem(new string[] { module.version.ToString(), - KspVersionRange.VersionSpan(minKsp, maxKsp).ToString() + GameVersionRange.VersionSpan(currentInstance.game, minKsp, maxKsp) }) { Tag = module diff --git a/GUI/Controls/AllModVersions.resx b/GUI/Controls/AllModVersions.resx index 64617de16c..1a78ffea84 100644 --- a/GUI/Controls/AllModVersions.resx +++ b/GUI/Controls/AllModVersions.resx @@ -119,11 +119,11 @@ All available versions of selected mod Mod Version - Compatible KSP Versions + Compatible Game Versions Green Light green Bold - latest compatible version (likely to be installed) - - version is compatible with your KSP + - version is compatible with your game - currently installed version diff --git a/GUI/Controls/ChooseRecommendedMods.cs b/GUI/Controls/ChooseRecommendedMods.cs index fe25c84f0b..9c76dab7ba 100644 --- a/GUI/Controls/ChooseRecommendedMods.cs +++ b/GUI/Controls/ChooseRecommendedMods.cs @@ -17,14 +17,14 @@ public ChooseRecommendedMods() } public void LoadRecommendations( - IRegistryQuerier registry, KspVersionCriteria kspVersion, NetModuleCache cache, + IRegistryQuerier registry, GameVersionCriteria GameVersion, NetModuleCache cache, Dictionary>> recommendations, Dictionary> suggestions, Dictionary> supporters ) { this.registry = registry; - this.kspVersion = kspVersion; + this.GameVersion = GameVersion; Util.Invoke(this, () => { RecommendedModsToggleCheckbox.Checked = true; @@ -118,7 +118,7 @@ private Dictionary FindConflicts() .Select(item => item.Tag as CkanModule) .Distinct(), new CkanModule[] { }, - conflictOptions, registry, kspVersion + conflictOptions, registry, GameVersion ).ConflictList; } @@ -196,7 +196,7 @@ private void RecommendedModsContinueButton_Click(object sender, EventArgs e) } private IRegistryQuerier registry; - private KspVersionCriteria kspVersion; + private GameVersionCriteria GameVersion; private TaskCompletionSource> task; } diff --git a/GUI/Controls/DeleteDirectories.cs b/GUI/Controls/DeleteDirectories.cs index 64e793521d..a3bd14f012 100644 --- a/GUI/Controls/DeleteDirectories.cs +++ b/GUI/Controls/DeleteDirectories.cs @@ -21,7 +21,7 @@ public DeleteDirectories() /// before the calling code switches to the tab. /// /// Directories that the user may want to delete - public void LoadDirs(KSP ksp, HashSet possibleConfigOnlyDirs) + public void LoadDirs(GameInstance ksp, HashSet possibleConfigOnlyDirs) { instance = ksp; var items = possibleConfigOnlyDirs @@ -120,6 +120,6 @@ private void KeepAllButton_Click(object sender, EventArgs e) } private TaskCompletionSource task = null; - private KSP instance = null; + private GameInstance instance = null; } } diff --git a/GUI/Controls/EditModpack.Designer.cs b/GUI/Controls/EditModpack.Designer.cs index 6901bdb45c..e6f8b91f1d 100644 --- a/GUI/Controls/EditModpack.Designer.cs +++ b/GUI/Controls/EditModpack.Designer.cs @@ -40,9 +40,9 @@ private void InitializeComponent() this.AbstractTextBox = new System.Windows.Forms.TextBox(); this.VersionLabel = new System.Windows.Forms.Label(); this.VersionTextBox = new System.Windows.Forms.TextBox(); - this.KspVersionLabel = new System.Windows.Forms.Label(); - this.KspVersionMinComboBox = new System.Windows.Forms.ComboBox(); - this.KspVersionMaxComboBox = new System.Windows.Forms.ComboBox(); + this.GameVersionLabel = new System.Windows.Forms.Label(); + this.GameVersionMinComboBox = new System.Windows.Forms.ComboBox(); + this.GameVersionMaxComboBox = new System.Windows.Forms.ComboBox(); this.LicenseLabel = new System.Windows.Forms.Label(); this.LicenseComboBox = new System.Windows.Forms.ComboBox(); this.IncludeVersionsCheckbox = new System.Windows.Forms.CheckBox(); @@ -80,9 +80,9 @@ private void InitializeComponent() this.TopEditPanel.Controls.Add(this.AbstractTextBox); this.TopEditPanel.Controls.Add(this.VersionLabel); this.TopEditPanel.Controls.Add(this.VersionTextBox); - this.TopEditPanel.Controls.Add(this.KspVersionLabel); - this.TopEditPanel.Controls.Add(this.KspVersionMinComboBox); - this.TopEditPanel.Controls.Add(this.KspVersionMaxComboBox); + this.TopEditPanel.Controls.Add(this.GameVersionLabel); + this.TopEditPanel.Controls.Add(this.GameVersionMinComboBox); + this.TopEditPanel.Controls.Add(this.GameVersionMaxComboBox); this.TopEditPanel.Controls.Add(this.LicenseLabel); this.TopEditPanel.Controls.Add(this.LicenseComboBox); this.TopEditPanel.Controls.Add(this.IncludeVersionsCheckbox); @@ -167,35 +167,35 @@ private void InitializeComponent() this.VersionTextBox.TabIndex = 7; resources.ApplyResources(this.VersionTextBox, "VersionTextBox"); // - // KspVersionLabel + // GameVersionLabel // - this.KspVersionLabel.AutoSize = true; - this.KspVersionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)); - this.KspVersionLabel.Location = new System.Drawing.Point(400, 40); - this.KspVersionLabel.Name = "KspVersionLabel"; - this.KspVersionLabel.Size = new System.Drawing.Size(75, 23); - this.KspVersionLabel.TabIndex = 8; - resources.ApplyResources(this.KspVersionLabel, "KspVersionLabel"); + this.GameVersionLabel.AutoSize = true; + this.GameVersionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)); + this.GameVersionLabel.Location = new System.Drawing.Point(400, 40); + this.GameVersionLabel.Name = "GameVersionLabel"; + this.GameVersionLabel.Size = new System.Drawing.Size(75, 23); + this.GameVersionLabel.TabIndex = 8; + resources.ApplyResources(this.GameVersionLabel, "GameVersionLabel"); // - // KspVersionMinComboBox + // GameVersionMinComboBox // - this.KspVersionMinComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)); - this.KspVersionMinComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.KspVersionMinComboBox.Location = new System.Drawing.Point(515, 40); - this.KspVersionMinComboBox.Name = "KspVersionMinComboBox"; - this.KspVersionMinComboBox.Size = new System.Drawing.Size(70, 23); - this.KspVersionMinComboBox.TabIndex = 9; - resources.ApplyResources(this.KspVersionMinComboBox, "KspVersionMinComboBox"); + this.GameVersionMinComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)); + this.GameVersionMinComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.GameVersionMinComboBox.Location = new System.Drawing.Point(515, 40); + this.GameVersionMinComboBox.Name = "GameVersionMinComboBox"; + this.GameVersionMinComboBox.Size = new System.Drawing.Size(70, 23); + this.GameVersionMinComboBox.TabIndex = 9; + resources.ApplyResources(this.GameVersionMinComboBox, "GameVersionMinComboBox"); // - // KspVersionMaxComboBox + // GameVersionMaxComboBox // - this.KspVersionMaxComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)); - this.KspVersionMaxComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.KspVersionMaxComboBox.Location = new System.Drawing.Point(595, 40); - this.KspVersionMaxComboBox.Name = "KspVersionMaxComboBox"; - this.KspVersionMaxComboBox.Size = new System.Drawing.Size(70, 23); - this.KspVersionMaxComboBox.TabIndex = 10; - resources.ApplyResources(this.KspVersionMaxComboBox, "KspVersionMaxComboBox"); + this.GameVersionMaxComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)); + this.GameVersionMaxComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.GameVersionMaxComboBox.Location = new System.Drawing.Point(595, 40); + this.GameVersionMaxComboBox.Name = "GameVersionMaxComboBox"; + this.GameVersionMaxComboBox.Size = new System.Drawing.Size(70, 23); + this.GameVersionMaxComboBox.TabIndex = 10; + resources.ApplyResources(this.GameVersionMaxComboBox, "GameVersionMaxComboBox"); // // LicenseLabel // @@ -413,9 +413,9 @@ private void InitializeComponent() private System.Windows.Forms.TextBox AbstractTextBox; private System.Windows.Forms.Label VersionLabel; private System.Windows.Forms.TextBox VersionTextBox; - private System.Windows.Forms.Label KspVersionLabel; - private System.Windows.Forms.ComboBox KspVersionMinComboBox; - private System.Windows.Forms.ComboBox KspVersionMaxComboBox; + private System.Windows.Forms.Label GameVersionLabel; + private System.Windows.Forms.ComboBox GameVersionMinComboBox; + private System.Windows.Forms.ComboBox GameVersionMaxComboBox; private System.Windows.Forms.Label LicenseLabel; private System.Windows.Forms.ComboBox LicenseComboBox; private System.Windows.Forms.CheckBox IncludeVersionsCheckbox; diff --git a/GUI/Controls/EditModpack.cs b/GUI/Controls/EditModpack.cs index 3776c001fd..2d6e0d1d5d 100644 --- a/GUI/Controls/EditModpack.cs +++ b/GUI/Controls/EditModpack.cs @@ -20,8 +20,8 @@ public EditModpack() this.ToolTip.SetToolTip(NameTextBox, Properties.Resources.EditModpackTooltipName); this.ToolTip.SetToolTip(AbstractTextBox, Properties.Resources.EditModpackTooltipAbstract); this.ToolTip.SetToolTip(VersionTextBox, Properties.Resources.EditModpackTooltipVersion); - this.ToolTip.SetToolTip(KspVersionMinComboBox, Properties.Resources.EditModpackTooltipKspVersionMin); - this.ToolTip.SetToolTip(KspVersionMaxComboBox, Properties.Resources.EditModpackTooltipKspVersionMax); + this.ToolTip.SetToolTip(GameVersionMinComboBox, Properties.Resources.EditModpackTooltipGameVersionMin); + this.ToolTip.SetToolTip(GameVersionMaxComboBox, Properties.Resources.EditModpackTooltipGameVersionMax); this.ToolTip.SetToolTip(LicenseComboBox, Properties.Resources.EditModpackTooltipLicense); this.ToolTip.SetToolTip(IncludeVersionsCheckbox, Properties.Resources.EditModpackTooltipIncludeVersions); this.ToolTip.SetToolTip(DependsRadioButton, Properties.Resources.EditModpackTooltipDepends); @@ -41,19 +41,19 @@ public void LoadModule(CkanModule module, IRegistryQuerier registry) NameTextBox.Text = module.name; AbstractTextBox.Text = module.@abstract; VersionTextBox.Text = module.version.ToString(); - var options = new string[] { "" }.Concat(ServiceLocator.Container.Resolve().KnownVersions - .SelectMany(v => new KspVersion[] { - new KspVersion(v.Major, v.Minor, v.Patch), - new KspVersion(v.Major, v.Minor) + var options = new string[] { "" }.Concat(Main.Instance.CurrentInstance.game.KnownVersions + .SelectMany(v => new GameVersion[] { + new GameVersion(v.Major, v.Minor, v.Patch), + new GameVersion(v.Major, v.Minor) }) .Distinct() .OrderByDescending(v => v) .Select(v => v.ToString()) ); - KspVersionMinComboBox.DataSource = options.ToArray(); - KspVersionMinComboBox.Text = (module.ksp_version_min ?? module.ksp_version)?.ToString(); - KspVersionMaxComboBox.DataSource = options.ToArray(); - KspVersionMaxComboBox.Text = (module.ksp_version_max ?? module.ksp_version)?.ToString(); + GameVersionMinComboBox.DataSource = options.ToArray(); + GameVersionMinComboBox.Text = (module.ksp_version_min ?? module.ksp_version)?.ToString(); + GameVersionMaxComboBox.DataSource = options.ToArray(); + GameVersionMaxComboBox.Text = (module.ksp_version_max ?? module.ksp_version)?.ToString(); LicenseComboBox.DataSource = License.valid_licenses.OrderBy(l => l).ToArray(); LicenseComboBox.Text = module.license?.FirstOrDefault()?.ToString(); LoadRelationships(registry); @@ -162,11 +162,11 @@ private bool TryFieldsToModule(out string error, out Control badField) badField = VersionTextBox; return false; } - if (!string.IsNullOrEmpty(KspVersionMinComboBox.Text) && !string.IsNullOrEmpty(KspVersionMaxComboBox.Text) - && KspVersion.Parse(KspVersionMinComboBox.Text) > KspVersion.Parse(KspVersionMaxComboBox.Text)) + if (!string.IsNullOrEmpty(GameVersionMinComboBox.Text) && !string.IsNullOrEmpty(GameVersionMaxComboBox.Text) + && GameVersion.Parse(GameVersionMinComboBox.Text) > GameVersion.Parse(GameVersionMaxComboBox.Text)) { - error = Properties.Resources.EditModpackBadKspVersions; - badField = KspVersionMinComboBox; + error = Properties.Resources.EditModpackBadGameVersions; + badField = GameVersionMinComboBox; return false; } @@ -177,12 +177,12 @@ private bool TryFieldsToModule(out string error, out Control badField) module.@abstract = AbstractTextBox.Text; module.version = new ModuleVersion(VersionTextBox.Text); module.license = new List() { new License(LicenseComboBox.Text) }; - module.ksp_version_min = string.IsNullOrEmpty(KspVersionMinComboBox.Text) + module.ksp_version_min = string.IsNullOrEmpty(GameVersionMinComboBox.Text) ? null - : KspVersion.Parse(KspVersionMinComboBox.Text); - module.ksp_version_max = string.IsNullOrEmpty(KspVersionMaxComboBox.Text) + : GameVersion.Parse(GameVersionMinComboBox.Text); + module.ksp_version_max = string.IsNullOrEmpty(GameVersionMaxComboBox.Text) ? null - : KspVersion.Parse(KspVersionMaxComboBox.Text); + : GameVersion.Parse(GameVersionMaxComboBox.Text); return true; } diff --git a/GUI/Controls/EditModpack.resx b/GUI/Controls/EditModpack.resx index 37219b9c18..48ea15ec10 100644 --- a/GUI/Controls/EditModpack.resx +++ b/GUI/Controls/EditModpack.resx @@ -121,7 +121,7 @@ Name: Abstract: Version: - KSP versions: + Game versions: Licence: Save mod versions Mod diff --git a/GUI/Controls/ManageMods.Designer.cs b/GUI/Controls/ManageMods.Designer.cs index 4fd4cc9160..3f379653ef 100644 --- a/GUI/Controls/ManageMods.Designer.cs +++ b/GUI/Controls/ManageMods.Designer.cs @@ -31,7 +31,7 @@ private void InitializeComponent() this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(ManageMods)); this.menuStrip2 = new System.Windows.Forms.MenuStrip(); - this.launchKSPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.launchGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RefreshToolButton = new System.Windows.Forms.ToolStripMenuItem(); this.UpdateAllToolButton = new System.Windows.Forms.ToolStripMenuItem(); this.ApplyToolButton = new System.Windows.Forms.ToolStripMenuItem(); @@ -61,7 +61,7 @@ private void InitializeComponent() this.Author = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.InstalledVersion = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.LatestVersion = new System.Windows.Forms.DataGridViewTextBoxColumn(); - this.KSPCompatibility = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.GameCompatibility = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.SizeCol = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ReleaseDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.InstallDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); @@ -91,7 +91,7 @@ private void InitializeComponent() this.menuStrip2.Dock = System.Windows.Forms.DockStyle.Top; this.menuStrip2.ImageScalingSize = new System.Drawing.Size(24, 24); this.menuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.launchKSPToolStripMenuItem, + this.launchGameToolStripMenuItem, this.RefreshToolButton, this.UpdateAllToolButton, this.ApplyToolButton, @@ -104,14 +104,14 @@ private void InitializeComponent() this.menuStrip2.TabIndex = 4; this.menuStrip2.Text = "menuStrip2"; // - // launchKSPToolStripMenuItem + // launchGameToolStripMenuItem // - this.launchKSPToolStripMenuItem.Image = global::CKAN.Properties.Resources.ksp; - this.launchKSPToolStripMenuItem.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; - this.launchKSPToolStripMenuItem.Name = "launchKSPToolStripMenuItem"; - this.launchKSPToolStripMenuItem.Size = new System.Drawing.Size(146, 56); - this.launchKSPToolStripMenuItem.Click += new System.EventHandler(this.launchKSPToolStripMenuItem_Click); - resources.ApplyResources(this.launchKSPToolStripMenuItem, "launchKSPToolStripMenuItem"); + this.launchGameToolStripMenuItem.Image = global::CKAN.Properties.Resources.ksp; + this.launchGameToolStripMenuItem.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; + this.launchGameToolStripMenuItem.Name = "launchGameToolStripMenuItem"; + this.launchGameToolStripMenuItem.Size = new System.Drawing.Size(146, 56); + this.launchGameToolStripMenuItem.Click += new System.EventHandler(this.launchGameToolStripMenuItem_Click); + resources.ApplyResources(this.launchGameToolStripMenuItem, "launchGameToolStripMenuItem"); // // RefreshToolButton // @@ -294,7 +294,7 @@ private void InitializeComponent() this.Author, this.InstalledVersion, this.LatestVersion, - this.KSPCompatibility, + this.GameCompatibility, this.SizeCol, this.ReleaseDate, this.InstallDate, @@ -385,13 +385,13 @@ private void InitializeComponent() this.LatestVersion.Width = 70; resources.ApplyResources(this.LatestVersion, "LatestVersion"); // - // KSPCompatibility + // GameCompatibility // - this.KSPCompatibility.Name = "KSPCompatibility"; - this.KSPCompatibility.ReadOnly = true; - this.KSPCompatibility.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; - this.KSPCompatibility.Width = 78; - resources.ApplyResources(this.KSPCompatibility, "KSPCompatibility"); + this.GameCompatibility.Name = "GameCompatibility"; + this.GameCompatibility.ReadOnly = true; + this.GameCompatibility.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; + this.GameCompatibility.Width = 78; + resources.ApplyResources(this.GameCompatibility, "GameCompatibility"); // // SizeCol // @@ -528,7 +528,7 @@ private void InitializeComponent() #endregion private System.Windows.Forms.MenuStrip menuStrip2; - private System.Windows.Forms.ToolStripMenuItem launchKSPToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem launchGameToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem RefreshToolButton; private System.Windows.Forms.ToolStripMenuItem UpdateAllToolButton; private System.Windows.Forms.ToolStripMenuItem ApplyToolButton; @@ -557,7 +557,7 @@ private void InitializeComponent() private System.Windows.Forms.DataGridViewTextBoxColumn Author; private System.Windows.Forms.DataGridViewTextBoxColumn InstalledVersion; private System.Windows.Forms.DataGridViewTextBoxColumn LatestVersion; - private System.Windows.Forms.DataGridViewTextBoxColumn KSPCompatibility; + private System.Windows.Forms.DataGridViewTextBoxColumn GameCompatibility; private System.Windows.Forms.DataGridViewTextBoxColumn SizeCol; private System.Windows.Forms.DataGridViewTextBoxColumn ReleaseDate; private System.Windows.Forms.DataGridViewTextBoxColumn InstallDate; diff --git a/GUI/Controls/ManageMods.cs b/GUI/Controls/ManageMods.cs index 2ae9ae4925..d7079480e8 100644 --- a/GUI/Controls/ManageMods.cs +++ b/GUI/Controls/ManageMods.cs @@ -21,7 +21,7 @@ public ManageMods() mainModList = new ModList(source => UpdateFilters()); FilterToolButton.MouseHover += (sender, args) => FilterToolButton.ShowDropDown(); - launchKSPToolStripMenuItem.MouseHover += (sender, args) => launchKSPToolStripMenuItem.ShowDropDown(); + launchGameToolStripMenuItem.MouseHover += (sender, args) => launchGameToolStripMenuItem.ShowDropDown(); ApplyToolButton.MouseHover += (sender, args) => ApplyToolButton.ShowDropDown(); ApplyToolButton.Enabled = false; @@ -440,9 +440,9 @@ private void _MarkModForUpdate(string identifier, bool value) mod.SetUpgradeChecked(row, UpdateCol, value); } - private void launchKSPToolStripMenuItem_Click(object sender, EventArgs e) + private void launchGameToolStripMenuItem_Click(object sender, EventArgs e) { - Main.Instance.LaunchKSP(); + Main.Instance.LaunchGame(); } private void NavBackwardToolButton_Click(object sender, EventArgs e) @@ -1019,7 +1019,7 @@ private void _UpdateModsList(Dictionary old_modules = null) } Main.Instance.Wait.AddLogMessage(Properties.Resources.MainModListLoadingRegistry); - KspVersionCriteria versionCriteria = Main.Instance.CurrentInstance.VersionCriteria(); + GameVersionCriteria versionCriteria = Main.Instance.CurrentInstance.VersionCriteria(); IRegistryQuerier registry = RegistryManager.Instance(Main.Instance.CurrentInstance).registry; Main.Instance.Wait.AddLogMessage(Properties.Resources.MainModListLoadingInstalled); @@ -1256,8 +1256,8 @@ private int CompareColumn(DataGridViewRow a, DataGridViewRow b, DataGridViewColu { case "ModName": return gmodA.Name.CompareTo(gmodB.Name); - case "KSPCompatibility": - return KSPCompatComparison(a, b); + case "GameCompatibility": + return GameCompatComparison(a, b); case "InstallDate": if (gmodA.InstallDate.HasValue) { @@ -1302,8 +1302,8 @@ private int CompareColumn(DataGridViewRow a, DataGridViewRow b, DataGridViewColu } /// - /// Compare two rows' KspVersions as max versions. - /// KspVersion.CompareTo sorts IsAny to the beginning instead + /// Compare two rows' GameVersions as max versions. + /// GameVersion.CompareTo sorts IsAny to the beginning instead /// of the end, and we can't change that without breaking many things. /// Similarly, 1.8 should sort after 1.8.0. /// @@ -1312,10 +1312,10 @@ private int CompareColumn(DataGridViewRow a, DataGridViewRow b, DataGridViewColu /// /// Positive to sort as a lessthan b, negative to sort as b lessthan a /// - private int KSPCompatComparison(DataGridViewRow a, DataGridViewRow b) + private int GameCompatComparison(DataGridViewRow a, DataGridViewRow b) { - KspVersion verA = ((GUIMod)a.Tag)?.KSPCompatibilityVersion; - KspVersion verB = ((GUIMod)b.Tag)?.KSPCompatibilityVersion; + GameVersion verA = ((GUIMod)a.Tag)?.GameCompatibilityVersion; + GameVersion verB = ((GUIMod)b.Tag)?.GameCompatibilityVersion; if (verA == null) { return verB == null ? 0 : -1; @@ -1499,13 +1499,13 @@ public bool AllowClose() return true; } - public void InstanceUpdated(KSP ksp) + public void InstanceUpdated(GameInstance inst) { ChangeSet = null; Conflicts = null; } - public async Task UpdateChangeSetAndConflicts(KSP ksp, IRegistryQuerier registry) + public async Task UpdateChangeSetAndConflicts(GameInstance inst, IRegistryQuerier registry) { IEnumerable full_change_set = null; Dictionary new_conflicts = null; @@ -1514,15 +1514,15 @@ public async Task UpdateChangeSetAndConflicts(KSP ksp, IRegistryQuerier registry var user_change_set = mainModList.ComputeUserChangeSet(registry); try { - var module_installer = ModuleInstaller.GetInstance(ksp, Main.Instance.Manager.Cache, Main.Instance.currentUser); - full_change_set = mainModList.ComputeChangeSetFromModList(registry, user_change_set, module_installer, ksp.VersionCriteria()); + var module_installer = ModuleInstaller.GetInstance(inst, Main.Instance.Manager.Cache, Main.Instance.currentUser); + full_change_set = mainModList.ComputeChangeSetFromModList(registry, user_change_set, module_installer, inst.VersionCriteria()); } catch (InconsistentKraken k) { // Need to be recomputed due to ComputeChangeSetFromModList possibly changing it with too many provides handling. Main.Instance.AddStatusMessage(k.ShortDescription); user_change_set = mainModList.ComputeUserChangeSet(registry); - new_conflicts = ModList.ComputeConflictsFromModList(registry, user_change_set, ksp.VersionCriteria()); + new_conflicts = ModList.ComputeConflictsFromModList(registry, user_change_set, inst.VersionCriteria()); full_change_set = null; } catch (TooManyModsProvideKraken) @@ -1545,7 +1545,7 @@ public async Task UpdateChangeSetAndConflicts(KSP ksp, IRegistryQuerier registry if (too_many_provides_thrown) { - await UpdateChangeSetAndConflicts(ksp, registry); + await UpdateChangeSetAndConflicts(inst, registry); new_conflicts = Conflicts; full_change_set = ChangeSet; } diff --git a/GUI/Controls/ManageMods.resx b/GUI/Controls/ManageMods.resx index 2dcef4a6fb..b0b30bacd2 100644 --- a/GUI/Controls/ManageMods.resx +++ b/GUI/Controls/ManageMods.resx @@ -147,7 +147,7 @@ True - Launch KSP + Launch Game Refresh Add available updates Apply changes @@ -174,7 +174,7 @@ Author Installed version Latest version - Max KSP version + Max game version Download Release date Install date diff --git a/GUI/Controls/ModInfo.Designer.cs b/GUI/Controls/ModInfo.Designer.cs index 9ee34fc7c4..6b8d9cd246 100644 --- a/GUI/Controls/ModInfo.Designer.cs +++ b/GUI/Controls/ModInfo.Designer.cs @@ -43,7 +43,7 @@ private void InitializeComponent() this.MetadataIdentifierTextBox = new TransparentTextBox(); this.ReplacementLabel = new System.Windows.Forms.Label(); this.ReplacementTextBox = new TransparentTextBox(); - this.KSPCompatibilityLabel = new System.Windows.Forms.Label(); + this.GameCompatibilityLabel = new System.Windows.Forms.Label(); this.ReleaseLabel = new System.Windows.Forms.Label(); this.AuthorLabel = new System.Windows.Forms.Label(); this.LicenseLabel = new System.Windows.Forms.Label(); @@ -52,7 +52,7 @@ private void InitializeComponent() this.MetadataModuleAuthorTextBox = new TransparentTextBox(); this.VersionLabel = new System.Windows.Forms.Label(); this.MetadataModuleReleaseStatusTextBox = new TransparentTextBox(); - this.MetadataModuleKSPCompatibilityTextBox = new TransparentTextBox(); + this.MetadataModuleGameCompatibilityTextBox = new TransparentTextBox(); this.RelationshipTabPage = new System.Windows.Forms.TabPage(); this.DependsGraphTree = new System.Windows.Forms.TreeView(); this.LegendDependsImage = new System.Windows.Forms.PictureBox(); @@ -211,14 +211,14 @@ private void InitializeComponent() this.MetaDataLowerLayoutPanel.Controls.Add(this.LicenseLabel, 0, 1); this.MetaDataLowerLayoutPanel.Controls.Add(this.AuthorLabel, 0, 2); this.MetaDataLowerLayoutPanel.Controls.Add(this.ReleaseLabel, 0, 3); - this.MetaDataLowerLayoutPanel.Controls.Add(this.KSPCompatibilityLabel, 0, 4); + this.MetaDataLowerLayoutPanel.Controls.Add(this.GameCompatibilityLabel, 0, 4); this.MetaDataLowerLayoutPanel.Controls.Add(this.IdentifierLabel, 0, 5); this.MetaDataLowerLayoutPanel.Controls.Add(this.ReplacementLabel, 0, 6); this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataModuleVersionTextBox, 1, 0); this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataModuleLicenseTextBox, 1, 1); this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataModuleAuthorTextBox, 1, 2); this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataModuleReleaseStatusTextBox, 1, 3); - this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataModuleKSPCompatibilityTextBox, 1, 4); + this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataModuleGameCompatibilityTextBox, 1, 4); this.MetaDataLowerLayoutPanel.Controls.Add(this.MetadataIdentifierTextBox, 1, 5); this.MetaDataLowerLayoutPanel.Controls.Add(this.ReplacementTextBox, 1, 6); this.MetaDataLowerLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; @@ -291,16 +291,16 @@ private void InitializeComponent() this.ReplacementTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.ReplacementTextBox, "ReplacementTextBox"); // - // KSPCompatibilityLabel + // GameCompatibilityLabel // - this.KSPCompatibilityLabel.AutoSize = true; - this.KSPCompatibilityLabel.Dock = System.Windows.Forms.DockStyle.Fill; - this.KSPCompatibilityLabel.ForeColor = System.Drawing.SystemColors.GrayText; - this.KSPCompatibilityLabel.Location = new System.Drawing.Point(3, 180); - this.KSPCompatibilityLabel.Name = "KSPCompatibilityLabel"; - this.KSPCompatibilityLabel.Size = new System.Drawing.Size(84, 30); - this.KSPCompatibilityLabel.TabIndex = 13; - resources.ApplyResources(this.KSPCompatibilityLabel, "KSPCompatibilityLabel"); + this.GameCompatibilityLabel.AutoSize = true; + this.GameCompatibilityLabel.Dock = System.Windows.Forms.DockStyle.Fill; + this.GameCompatibilityLabel.ForeColor = System.Drawing.SystemColors.GrayText; + this.GameCompatibilityLabel.Location = new System.Drawing.Point(3, 180); + this.GameCompatibilityLabel.Name = "GameCompatibilityLabel"; + this.GameCompatibilityLabel.Size = new System.Drawing.Size(84, 30); + this.GameCompatibilityLabel.TabIndex = 13; + resources.ApplyResources(this.GameCompatibilityLabel, "GameCompatibilityLabel"); // // ReleaseLabel // @@ -402,19 +402,19 @@ private void InitializeComponent() this.MetadataModuleReleaseStatusTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.MetadataModuleReleaseStatusTextBox, "MetadataModuleReleaseStatusTextBox"); // - // MetadataModuleKSPCompatibilityTextBox + // MetadataModuleGameCompatibilityTextBox // - this.MetadataModuleKSPCompatibilityTextBox.AutoSize = true; - this.MetadataModuleKSPCompatibilityTextBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.MetadataModuleKSPCompatibilityTextBox.Location = new System.Drawing.Point(93, 180); - this.MetadataModuleKSPCompatibilityTextBox.Name = "MetadataModuleKSPCompatibilityTextBox"; - this.MetadataModuleKSPCompatibilityTextBox.Size = new System.Drawing.Size(250, 30); - this.MetadataModuleKSPCompatibilityTextBox.TabIndex = 14; - this.MetadataModuleKSPCompatibilityTextBox.ReadOnly = true; - this.MetadataModuleKSPCompatibilityTextBox.BackColor = MetadataTabPage.BackColor; - this.MetadataModuleKSPCompatibilityTextBox.ForeColor = System.Drawing.SystemColors.ControlText; - this.MetadataModuleKSPCompatibilityTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; - resources.ApplyResources(this.MetadataModuleKSPCompatibilityTextBox, "MetadataModuleKSPCompatibilityTextBox"); + this.MetadataModuleGameCompatibilityTextBox.AutoSize = true; + this.MetadataModuleGameCompatibilityTextBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.MetadataModuleGameCompatibilityTextBox.Location = new System.Drawing.Point(93, 180); + this.MetadataModuleGameCompatibilityTextBox.Name = "MetadataModuleGameCompatibilityTextBox"; + this.MetadataModuleGameCompatibilityTextBox.Size = new System.Drawing.Size(250, 30); + this.MetadataModuleGameCompatibilityTextBox.TabIndex = 14; + this.MetadataModuleGameCompatibilityTextBox.ReadOnly = true; + this.MetadataModuleGameCompatibilityTextBox.BackColor = MetadataTabPage.BackColor; + this.MetadataModuleGameCompatibilityTextBox.ForeColor = System.Drawing.SystemColors.ControlText; + this.MetadataModuleGameCompatibilityTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; + resources.ApplyResources(this.MetadataModuleGameCompatibilityTextBox, "MetadataModuleGameCompatibilityTextBox"); // // RelationshipTabPage // @@ -652,7 +652,7 @@ private void InitializeComponent() private TransparentTextBox MetadataIdentifierTextBox; private System.Windows.Forms.Label ReplacementLabel; private TransparentTextBox ReplacementTextBox; - private System.Windows.Forms.Label KSPCompatibilityLabel; + private System.Windows.Forms.Label GameCompatibilityLabel; private System.Windows.Forms.Label ReleaseLabel; private System.Windows.Forms.Label AuthorLabel; private System.Windows.Forms.Label LicenseLabel; @@ -661,7 +661,7 @@ private void InitializeComponent() private TransparentTextBox MetadataModuleAuthorTextBox; private System.Windows.Forms.Label VersionLabel; private TransparentTextBox MetadataModuleReleaseStatusTextBox; - private TransparentTextBox MetadataModuleKSPCompatibilityTextBox; + private TransparentTextBox MetadataModuleGameCompatibilityTextBox; private System.Windows.Forms.TabPage RelationshipTabPage; private System.Windows.Forms.TreeView DependsGraphTree; private System.Windows.Forms.PictureBox LegendDependsImage; diff --git a/GUI/Controls/ModInfo.cs b/GUI/Controls/ModInfo.cs index 4d0caa5133..ff80e0563a 100644 --- a/GUI/Controls/ModInfo.cs +++ b/GUI/Controls/ModInfo.cs @@ -80,7 +80,7 @@ public int ModMetaSplitPosition public event Action OnDownloadClick; - private KSPManager manager + private GameInstanceManager manager { get { @@ -139,7 +139,7 @@ private void UpdateModInfo(GUIMod gui_module) Util.Invoke(MetadataIdentifierTextBox, () => MetadataIdentifierTextBox.Text = gui_module.Identifier); Util.Invoke(MetadataModuleReleaseStatusTextBox, () => MetadataModuleReleaseStatusTextBox.Text = module.release_status?.ToString() ?? Properties.Resources.ModInfoNSlashA); - Util.Invoke(MetadataModuleKSPCompatibilityTextBox, () => MetadataModuleKSPCompatibilityTextBox.Text = gui_module.KSPCompatibilityLong); + Util.Invoke(MetadataModuleGameCompatibilityTextBox, () => MetadataModuleGameCompatibilityTextBox.Text = gui_module.GameCompatibilityLong); Util.Invoke(ReplacementTextBox, () => ReplacementTextBox.Text = gui_module.ToModule()?.replaced_by?.ToString() ?? Properties.Resources.ModInfoNSlashA); Util.Invoke(MetaDataLowerLayoutPanel, () => @@ -428,7 +428,7 @@ private void AddChildren(IRegistryQuerier registry, TreeNode node) } } - private TreeNode findDependencyShallow(IRegistryQuerier registry, RelationshipDescriptor relDescr, RelationshipType relationship, KspVersionCriteria crit) + private TreeNode findDependencyShallow(IRegistryQuerier registry, RelationshipDescriptor relDescr, RelationshipType relationship, GameVersionCriteria crit) { // Maybe it's a DLC? if (relDescr.MatchesAny( @@ -476,7 +476,7 @@ private TreeNode indexedNode(IRegistryQuerier registry, CkanModule module, Relat { int icon = (int)relationship + 1; string suffix = compatible ? "" - : $" ({registry.CompatibleGameVersions(module.identifier)})"; + : $" ({registry.CompatibleGameVersions(manager.CurrentInstance.game, module.identifier)})"; return new TreeNode($"{module.name} {module.version}{suffix}", icon, icon) { Name = module.identifier, diff --git a/GUI/Controls/ModInfo.resx b/GUI/Controls/ModInfo.resx index 223b78c7d6..5ac2c3b9b8 100644 --- a/GUI/Controls/ModInfo.resx +++ b/GUI/Controls/ModInfo.resx @@ -123,7 +123,7 @@ - Replaced by: - - Max KSP ver.: + Max game ver.: Release status: Author: Licence: @@ -132,7 +132,7 @@ Nobody Version: Stable - 0.0.0 + 0.0.0 Relationships Depends Recommends diff --git a/GUI/Dialogs/CloneFakeKspDialog.Designer.cs b/GUI/Dialogs/CloneFakeGameDialog.Designer.cs similarity index 95% rename from GUI/Dialogs/CloneFakeKspDialog.Designer.cs rename to GUI/Dialogs/CloneFakeGameDialog.Designer.cs index 4dea24c2a8..aa17ea9ade 100644 --- a/GUI/Dialogs/CloneFakeKspDialog.Designer.cs +++ b/GUI/Dialogs/CloneFakeGameDialog.Designer.cs @@ -1,6 +1,6 @@ namespace CKAN { - partial class CloneFakeKspDialog + partial class CloneFakeGameDialog { /// /// Required designer variable. @@ -29,7 +29,7 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(CloneFakeKspDialog)); + System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(CloneFakeGameDialog)); this.radioButtonClone = new System.Windows.Forms.RadioButton(); this.cloneGroupBox = new System.Windows.Forms.GroupBox(); this.labelOldInstance = new System.Windows.Forms.Label(); @@ -40,7 +40,7 @@ private void InitializeComponent() this.radioButtonFake = new System.Windows.Forms.RadioButton(); this.fakeGroupBox = new System.Windows.Forms.GroupBox(); this.labelVersion = new System.Windows.Forms.Label(); - this.comboBoxKspVersion = new System.Windows.Forms.ComboBox(); + this.comboBoxGameVersion = new System.Windows.Forms.ComboBox(); this.labelDlcVersions = new System.Windows.Forms.Label(); this.textBoxMHDlcVersion = new System.Windows.Forms.TextBox(); this.labelMakingHistory = new System.Windows.Forms.Label(); @@ -148,7 +148,7 @@ private void InitializeComponent() this.fakeGroupBox.Controls.Add(this.textBoxBGDlcVersion); this.fakeGroupBox.Controls.Add(this.labelBreakingGround); this.fakeGroupBox.Controls.Add(this.labelVersion); - this.fakeGroupBox.Controls.Add(this.comboBoxKspVersion); + this.fakeGroupBox.Controls.Add(this.comboBoxGameVersion); this.fakeGroupBox.Location = new System.Drawing.Point(13, 130); this.fakeGroupBox.Name = "fakeGroupBox"; this.fakeGroupBox.Size = new System.Drawing.Size(400, 104); @@ -177,17 +177,17 @@ private void InitializeComponent() this.labelVersion.Text = "Version:"; resources.ApplyResources(this.labelVersion, "labelVersion"); // - // comboBoxKspVersion + // comboBoxGameVersion // - this.comboBoxKspVersion.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; - this.comboBoxKspVersion.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; - this.comboBoxKspVersion.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.comboBoxKspVersion.FormattingEnabled = true; - this.comboBoxKspVersion.Location = new System.Drawing.Point(168, 20); - this.comboBoxKspVersion.MaxDropDownItems = 6; - this.comboBoxKspVersion.Name = "comboBoxKspVersion"; - this.comboBoxKspVersion.Size = new System.Drawing.Size(83, 21); - this.comboBoxKspVersion.TabIndex = 10; + this.comboBoxGameVersion.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; + this.comboBoxGameVersion.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource; + this.comboBoxGameVersion.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBoxGameVersion.FormattingEnabled = true; + this.comboBoxGameVersion.Location = new System.Drawing.Point(168, 20); + this.comboBoxGameVersion.MaxDropDownItems = 6; + this.comboBoxGameVersion.Name = "comboBoxGameVersion"; + this.comboBoxGameVersion.Size = new System.Drawing.Size(83, 21); + this.comboBoxGameVersion.TabIndex = 10; // // labelDlcVersions // @@ -377,7 +377,7 @@ private void InitializeComponent() private System.Windows.Forms.RadioButton radioButtonFake; private System.Windows.Forms.GroupBox fakeGroupBox; private System.Windows.Forms.Label labelVersion; - private System.Windows.Forms.ComboBox comboBoxKspVersion; + private System.Windows.Forms.ComboBox comboBoxGameVersion; private System.Windows.Forms.Label labelDlcVersions; private System.Windows.Forms.TextBox textBoxMHDlcVersion; private System.Windows.Forms.Label labelMakingHistory; diff --git a/GUI/Dialogs/CloneFakeKspDialog.cs b/GUI/Dialogs/CloneFakeGameDialog.cs similarity index 87% rename from GUI/Dialogs/CloneFakeKspDialog.cs rename to GUI/Dialogs/CloneFakeGameDialog.cs index cbdb9efce7..1153631329 100644 --- a/GUI/Dialogs/CloneFakeKspDialog.cs +++ b/GUI/Dialogs/CloneFakeGameDialog.cs @@ -6,6 +6,7 @@ using System.Windows.Forms; using Autofac; using CKAN.Versioning; +using CKAN.Games; namespace CKAN { @@ -13,12 +14,12 @@ namespace CKAN /// The GUI implementation of clone and fake. /// It's a separate window, handling the whole process. /// - public partial class CloneFakeKspDialog : Form + public partial class CloneFakeGameDialog : Form { - private KSPManager manager; + private GameInstanceManager manager; private IUser user; - public CloneFakeKspDialog(KSPManager manager, IUser user) + public CloneFakeGameDialog(GameInstanceManager manager, IUser user) : base() { this.manager = manager; @@ -27,9 +28,9 @@ public CloneFakeKspDialog(KSPManager manager, IUser user) InitializeComponent(); // Populate the version combobox for fake instance. - List knownVersions = ServiceLocator.Container.Resolve().KnownVersions; + List knownVersions = new KerbalSpaceProgram().KnownVersions; knownVersions.Reverse(); - comboBoxKspVersion.DataSource = knownVersions; + comboBoxGameVersion.DataSource = knownVersions; // Populate the instances combobox with names of known instances comboBoxKnownInstance.DataSource = new string[] { "" } @@ -63,12 +64,12 @@ private void buttonInstancePathSelection_Click(object sender, EventArgs e) // Create a new FileDialog object OpenFileDialog instanceDialog = new OpenFileDialog() { - AddExtension = false, - CheckFileExists = false, - CheckPathExists = false, + AddExtension = false, + CheckFileExists = false, + CheckPathExists = false, InitialDirectory = Environment.CurrentDirectory, - Filter = Properties.Resources.CloneFakeKspDialogOpenFilter, - Multiselect = false + Filter = ManageGameInstancesDialog.GameFolderFilter(manager), + Multiselect = false }; // Show the FileDialog and let the user search for the KSP directory. @@ -145,7 +146,14 @@ private async void buttonOK_Click(object sender, EventArgs e) { await Task.Run(() => { - KSP instanceToClone = new KSP(textBoxClonePath.Text, "irrelevant", user); + GameInstance sourceInstance = manager.Instances.Values + .FirstOrDefault(i => i.GameDir() == textBoxClonePath.Text); + GameInstance instanceToClone = new GameInstance( + sourceInstance.game, + textBoxClonePath.Text, + "irrelevant", + user + ); if (instanceToClone.Valid) { @@ -208,12 +216,12 @@ await Task.Run(() => // Also in a separate task. else if (radioButtonFake.Checked) { - KspVersion kspVersion = KspVersion.Parse(comboBoxKspVersion.Text); + GameVersion GameVersion = GameVersion.Parse(comboBoxGameVersion.Text); - Dictionary dlcs = new Dictionary(); + Dictionary dlcs = new Dictionary(); if (!String.IsNullOrWhiteSpace(textBoxMHDlcVersion.Text) && textBoxMHDlcVersion.Text.ToLower() != "none") { - if (KspVersion.TryParse(textBoxMHDlcVersion.Text, out KspVersion ver)) + if (GameVersion.TryParse(textBoxMHDlcVersion.Text, out GameVersion ver)) { dlcs.Add(new DLC.MakingHistoryDlcDetector(), ver); } @@ -226,7 +234,7 @@ await Task.Run(() => } if (!String.IsNullOrWhiteSpace(textBoxBGDlcVersion.Text) && textBoxBGDlcVersion.Text.ToLower() != "none") { - if (KspVersion.TryParse(textBoxBGDlcVersion.Text, out KspVersion ver)) + if (GameVersion.TryParse(textBoxBGDlcVersion.Text, out GameVersion ver)) { dlcs.Add(new DLC.BreakingGroundDlcDetector(), ver); } @@ -244,7 +252,7 @@ await Task.Run(() => { await Task.Run(() => { - manager.FakeInstance(newName, newPath, kspVersion, dlcs); + manager.FakeInstance(new KerbalSpaceProgram(), newName, newPath, GameVersion, dlcs); }); } catch (InstanceNameTakenKraken) diff --git a/GUI/Dialogs/CloneFakeKspDialog.resx b/GUI/Dialogs/CloneFakeGameDialog.resx similarity index 100% rename from GUI/Dialogs/CloneFakeKspDialog.resx rename to GUI/Dialogs/CloneFakeGameDialog.resx diff --git a/GUI/Dialogs/CompatibleKspVersionsDialog.Designer.cs b/GUI/Dialogs/CompatibleGameVersionsDialog.Designer.cs similarity index 98% rename from GUI/Dialogs/CompatibleKspVersionsDialog.Designer.cs rename to GUI/Dialogs/CompatibleGameVersionsDialog.Designer.cs index 4fd29bed5b..d2670394e0 100644 --- a/GUI/Dialogs/CompatibleKspVersionsDialog.Designer.cs +++ b/GUI/Dialogs/CompatibleGameVersionsDialog.Designer.cs @@ -1,6 +1,6 @@ namespace CKAN { - partial class CompatibleKspVersionsDialog + partial class CompatibleGameVersionsDialog { /// /// Required designer variable. @@ -29,7 +29,7 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(CompatibleKspVersionsDialog)); + System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(CompatibleGameVersionsDialog)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); @@ -195,7 +195,7 @@ private void InitializeComponent() this.CancelChooseCompatibleVersionsButton.Click += new System.EventHandler(this.CancelButton_Click); resources.ApplyResources(this.CancelChooseCompatibleVersionsButton, "CancelChooseCompatibleVersionsButton"); // - // CompatibleKspVersionsDialog + // CompatibleGameVersionsDialog // this.AcceptButton = this.SaveButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); @@ -220,9 +220,9 @@ private void InitializeComponent() this.Icon = Properties.Resources.AppIcon; this.MaximizeBox = false; this.MinimizeBox = false; - this.Name = "CompatibleKspVersionsDialog"; + this.Name = "CompatibleGameVersionsDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Shown += new System.EventHandler(this.CompatibleKspVersionsDialog_Shown); + this.Shown += new System.EventHandler(this.CompatibleGameVersionsDialog_Shown); resources.ApplyResources(this, "$this"); this.ResumeLayout(false); this.PerformLayout(); diff --git a/GUI/Dialogs/CompatibleKspVersionsDialog.cs b/GUI/Dialogs/CompatibleGameVersionsDialog.cs similarity index 57% rename from GUI/Dialogs/CompatibleKspVersionsDialog.cs rename to GUI/Dialogs/CompatibleGameVersionsDialog.cs index a5442cc952..56fb84a9ad 100644 --- a/GUI/Dialogs/CompatibleKspVersionsDialog.cs +++ b/GUI/Dialogs/CompatibleGameVersionsDialog.cs @@ -8,18 +8,18 @@ namespace CKAN { - public partial class CompatibleKspVersionsDialog : Form + public partial class CompatibleGameVersionsDialog : Form { - private KSP _ksp; + private GameInstance _inst; /// /// Initialize the compatible game versions dialog /// - /// Game instance + /// Game instance /// true to center the dialog on the screen, false to center on the parent - public CompatibleKspVersionsDialog(KSP ksp, bool centerScreen) + public CompatibleGameVersionsDialog(GameInstance inst, bool centerScreen) { - this._ksp = ksp; + this._inst = inst; InitializeComponent(); if (centerScreen) @@ -27,13 +27,13 @@ public CompatibleKspVersionsDialog(KSP ksp, bool centerScreen) StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; } - List compatibleVersions = ksp.GetCompatibleVersions(); + List compatibleVersions = inst.GetCompatibleVersions(); - GameVersionLabel.Text = ksp.Version()?.ToString() ?? Properties.Resources.CompatibleKspVersionsDialogNone; - GameLocationLabel.Text = ksp.GameDir(); - List knownVersions = new List(ServiceLocator.Container.Resolve().KnownVersions); - List majorVersionsList = CreateMajorVersionsList(knownVersions); - List compatibleVersionsLeftOthers = new List(compatibleVersions); + GameVersionLabel.Text = inst.Version()?.ToString() ?? Properties.Resources.CompatibleGameVersionsDialogNone; + GameLocationLabel.Text = inst.GameDir(); + List knownVersions = inst.game.KnownVersions; + List majorVersionsList = CreateMajorVersionsList(knownVersions); + List compatibleVersionsLeftOthers = new List(compatibleVersions); compatibleVersionsLeftOthers.RemoveAll((el)=>knownVersions.Contains(el) || majorVersionsList.Contains(el)); SortAndAddVersionsToList(compatibleVersionsLeftOthers, compatibleVersions); @@ -41,43 +41,43 @@ public CompatibleKspVersionsDialog(KSP ksp, bool centerScreen) SortAndAddVersionsToList(knownVersions, compatibleVersions); } - private void CompatibleKspVersionsDialog_Shown(object sender, EventArgs e) + private void CompatibleGameVersionsDialog_Shown(object sender, EventArgs e) { - if (_ksp.CompatibleVersionsAreFromDifferentKsp) + if (_inst.CompatibleVersionsAreFromDifferentGameVersion) { - MessageBox.Show(Properties.Resources.CompatibleKspVersionsDialogKSPUpdated); + MessageBox.Show(Properties.Resources.CompatibleGameVersionsDialogGameUpdated); CancelChooseCompatibleVersionsButton.Visible = false; GameVersionLabel.Text = string.Format( - Properties.Resources.CompatibleKspVersionsDialogVersionDetails, - _ksp.Version(), - _ksp.VersionOfKspWhenCompatibleVersionsWereStored + Properties.Resources.CompatibleGameVersionsDialogVersionDetails, + _inst.Version(), + _inst.GameVersionWhenCompatibleVersionsWereStored ); GameVersionLabel.ForeColor = System.Drawing.Color.Red; } } - private static List CreateMajorVersionsList(List knownVersions) + private static List CreateMajorVersionsList(List knownVersions) { - Dictionary majorVersions = new Dictionary(); + Dictionary majorVersions = new Dictionary(); foreach (var version in knownVersions) { - KspVersion fullKnownVersion = version.ToVersionRange().Lower.Value; - KspVersion toAdd = new KspVersion(fullKnownVersion.Major, fullKnownVersion.Minor); + GameVersion fullKnownVersion = version.ToVersionRange().Lower.Value; + GameVersion toAdd = new GameVersion(fullKnownVersion.Major, fullKnownVersion.Minor); if (!majorVersions.ContainsKey(toAdd)) { majorVersions.Add(toAdd, true); } } - return new List(majorVersions.Keys); + return new List(majorVersions.Keys); } - private void SortAndAddVersionsToList(List versions, List compatibleVersions) + private void SortAndAddVersionsToList(List versions, List compatibleVersions) { versions.Sort(); versions.Reverse(); - foreach (KspVersion version in versions) + foreach (GameVersion version in versions) { - if (!version.Equals(_ksp.Version())) + if (!version.Equals(_inst.Version())) { SelectedVersionsCheckedListBox.Items.Add(version, compatibleVersions.Contains(version)); } @@ -93,8 +93,8 @@ private void AddVersionToListButton_Click(object sender, EventArgs e) if (AddVersionToListTextBox.Text.ToLower() == "any") { MessageBox.Show( - Properties.Resources.CompatibleKspVersionsDialogInvalidFormat, - Properties.Resources.CompatibleKspVersionsDialogErrorTitle, + Properties.Resources.CompatibleGameVersionsDialogInvalidFormat, + Properties.Resources.CompatibleGameVersionsDialogErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error ); @@ -102,14 +102,14 @@ private void AddVersionToListButton_Click(object sender, EventArgs e) } try { - var version = KspVersion.Parse(AddVersionToListTextBox.Text); + var version = GameVersion.Parse(AddVersionToListTextBox.Text); SelectedVersionsCheckedListBox.Items.Insert(0, version); } catch (FormatException) { MessageBox.Show( - Properties.Resources.CompatibleKspVersionsDialogInvalidFormat, - Properties.Resources.CompatibleKspVersionsDialogErrorTitle, + Properties.Resources.CompatibleGameVersionsDialogInvalidFormat, + Properties.Resources.CompatibleGameVersionsDialogErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error ); @@ -132,8 +132,8 @@ private void CancelButton_Click(object sender, EventArgs e) private void SaveButton_Click(object sender, EventArgs e) { - _ksp.SetCompatibleVersions( - SelectedVersionsCheckedListBox.CheckedItems.Cast().ToList() + _inst.SetCompatibleVersions( + SelectedVersionsCheckedListBox.CheckedItems.Cast().ToList() ); DialogResult = DialogResult.OK; diff --git a/GUI/Dialogs/CompatibleKspVersionsDialog.resx b/GUI/Dialogs/CompatibleGameVersionsDialog.resx similarity index 95% rename from GUI/Dialogs/CompatibleKspVersionsDialog.resx rename to GUI/Dialogs/CompatibleGameVersionsDialog.resx index 04aff61ecb..cf312443d7 100644 --- a/GUI/Dialogs/CompatibleKspVersionsDialog.resx +++ b/GUI/Dialogs/CompatibleGameVersionsDialog.resx @@ -117,18 +117,18 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Additionally install mods compatible with following KSP versions: + Additionally install mods compatible with following game versions: Game version: Warning! There is no way to check if mod is truly compatible with versions selected here! Please act carefully. <version> Clear selection Add Add version to list: - Note: if you add version like "1.2" you will force all mods compatible with 1.2.xx (1.2.0, 1.2.1, etc) to be compatible with this KSP installation. - If KSP is updated this dialog will be shown again so you can adjust your settings. + Note: if you add version like "1.2" you will force all mods compatible with 1.2.xx (1.2.0, 1.2.1, etc) to be compatible with this game instance. + If the game is updated this dialog will be shown again so you can adjust your settings. Accept Installation: <location> Cancel - Compatible KSP Versions + Compatible Game Versions diff --git a/GUI/Dialogs/EditLabelsDialog.cs b/GUI/Dialogs/EditLabelsDialog.cs index dc2d43cddc..d7f145f85c 100644 --- a/GUI/Dialogs/EditLabelsDialog.cs +++ b/GUI/Dialogs/EditLabelsDialog.cs @@ -8,7 +8,7 @@ namespace CKAN { public partial class EditLabelsDialog : Form { - public EditLabelsDialog(IUser user, KSPManager manager, ModuleLabelList labels) + public EditLabelsDialog(IUser user, GameInstanceManager manager, ModuleLabelList labels) { InitializeComponent(); this.user = user; diff --git a/GUI/Dialogs/KSPCommandLineOptionsDialog.Designer.cs b/GUI/Dialogs/GameCommandLineOptionsDialog.Designer.cs similarity index 95% rename from GUI/Dialogs/KSPCommandLineOptionsDialog.Designer.cs rename to GUI/Dialogs/GameCommandLineOptionsDialog.Designer.cs index 8c6ece3467..8f4cea8217 100644 --- a/GUI/Dialogs/KSPCommandLineOptionsDialog.Designer.cs +++ b/GUI/Dialogs/GameCommandLineOptionsDialog.Designer.cs @@ -1,6 +1,6 @@ namespace CKAN { - partial class KSPCommandLineOptionsDialog + partial class GameCommandLineOptionsDialog { /// /// Required designer variable. @@ -29,7 +29,7 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(KSPCommandLineOptionsDialog)); + System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(GameCommandLineOptionsDialog)); this.AdditionalArguments = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.AcceptChangesButton = new System.Windows.Forms.Button(); @@ -74,7 +74,7 @@ private void InitializeComponent() this.CancelChangesButton.UseVisualStyleBackColor = true; resources.ApplyResources(this.CancelChangesButton, "CancelChangesButton"); // - // KSPCommandLineOptionsDialog + // GameCommandLineOptionsDialog // this.AcceptButton = this.AcceptChangesButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); @@ -88,7 +88,7 @@ private void InitializeComponent() this.Controls.Add(this.AdditionalArguments); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = Properties.Resources.AppIcon; - this.Name = "KSPCommandLineOptionsDialog"; + this.Name = "GameCommandLineOptionsDialog"; resources.ApplyResources(this, "$this"); this.ResumeLayout(false); this.PerformLayout(); diff --git a/GUI/Dialogs/KSPCommandLineOptionsDialog.cs b/GUI/Dialogs/GameCommandLineOptionsDialog.cs similarity index 67% rename from GUI/Dialogs/KSPCommandLineOptionsDialog.cs rename to GUI/Dialogs/GameCommandLineOptionsDialog.cs index 7b8f6b6e7d..3d85b80595 100644 --- a/GUI/Dialogs/KSPCommandLineOptionsDialog.cs +++ b/GUI/Dialogs/GameCommandLineOptionsDialog.cs @@ -3,16 +3,16 @@ namespace CKAN { - public partial class KSPCommandLineOptionsDialog : Form + public partial class GameCommandLineOptionsDialog : Form { - public KSPCommandLineOptionsDialog() + public GameCommandLineOptionsDialog() { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; } - public DialogResult ShowKSPCommandLineOptionsDialog(string arguments) + public DialogResult ShowGameCommandLineOptionsDialog(string arguments) { AdditionalArguments.Text = arguments; return ShowDialog(); diff --git a/GUI/Dialogs/KSPCommandLineOptionsDialog.resx b/GUI/Dialogs/GameCommandLineOptionsDialog.resx similarity index 98% rename from GUI/Dialogs/KSPCommandLineOptionsDialog.resx rename to GUI/Dialogs/GameCommandLineOptionsDialog.resx index be3b3f8895..ec66cbd835 100644 --- a/GUI/Dialogs/KSPCommandLineOptionsDialog.resx +++ b/GUI/Dialogs/GameCommandLineOptionsDialog.resx @@ -121,5 +121,5 @@ Arguments: OK Cancel - KSP command-line arguments + Command-line arguments diff --git a/GUI/Dialogs/ManageKspInstancesDialog.Designer.cs b/GUI/Dialogs/ManageGameInstancesDialog.Designer.cs similarity index 74% rename from GUI/Dialogs/ManageKspInstancesDialog.Designer.cs rename to GUI/Dialogs/ManageGameInstancesDialog.Designer.cs index 7fb7523437..0d969f0565 100644 --- a/GUI/Dialogs/ManageKspInstancesDialog.Designer.cs +++ b/GUI/Dialogs/ManageGameInstancesDialog.Designer.cs @@ -1,6 +1,6 @@ namespace CKAN { - partial class ManageKspInstancesDialog + partial class ManageGameInstancesDialog { /// /// Required designer variable. @@ -29,15 +29,16 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(ManageKspInstancesDialog)); + System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(ManageGameInstancesDialog)); System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { "dsadsa", "", ""}, -1); - this.KSPInstancesListView = new ThemedListView(); - this.KSPInstallName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); - this.KSPInstallVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); - this.KSPInstallPath = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.GameInstancesListView = new ThemedListView(); + this.GameInstallName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.Game = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.GameInstallVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.GameInstallPath = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.SelectButton = new System.Windows.Forms.Button(); this.AddNewButton = new CKAN.DropdownMenuButton(); this.AddNewMenu = new System.Windows.Forms.ContextMenuStrip(this.components); @@ -51,30 +52,31 @@ private void InitializeComponent() this.AddNewMenu.SuspendLayout(); this.SuspendLayout(); // - // KSPInstancesListView + // GameInstancesListView // - this.KSPInstancesListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + this.GameInstancesListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); - this.KSPInstancesListView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.KSPInstancesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { - this.KSPInstallName, - this.KSPInstallVersion, - this.KSPInstallPath}); - this.KSPInstancesListView.FullRowSelect = true; - this.KSPInstancesListView.HideSelection = false; - this.KSPInstancesListView.Items.AddRange(new System.Windows.Forms.ListViewItem[] { + this.GameInstancesListView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.GameInstancesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.GameInstallName, + this.Game, + this.GameInstallVersion, + this.GameInstallPath}); + this.GameInstancesListView.FullRowSelect = true; + this.GameInstancesListView.HideSelection = false; + this.GameInstancesListView.Items.AddRange(new System.Windows.Forms.ListViewItem[] { listViewItem1}); - this.KSPInstancesListView.Location = new System.Drawing.Point(12, 13); - this.KSPInstancesListView.MultiSelect = false; - this.KSPInstancesListView.Name = "KSPInstancesListView"; - this.KSPInstancesListView.Size = new System.Drawing.Size(522, 301); - this.KSPInstancesListView.TabIndex = 0; - this.KSPInstancesListView.UseCompatibleStateImageBehavior = false; - this.KSPInstancesListView.View = System.Windows.Forms.View.Details; - this.KSPInstancesListView.SelectedIndexChanged += new System.EventHandler(this.KSPInstancesListView_SelectedIndexChanged); - this.KSPInstancesListView.DoubleClick += new System.EventHandler(this.KSPInstancesListView_DoubleClick); - this.KSPInstancesListView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.KSPInstancesListView_Click); + this.GameInstancesListView.Location = new System.Drawing.Point(12, 13); + this.GameInstancesListView.MultiSelect = false; + this.GameInstancesListView.Name = "GameInstancesListView"; + this.GameInstancesListView.Size = new System.Drawing.Size(522, 301); + this.GameInstancesListView.TabIndex = 0; + this.GameInstancesListView.UseCompatibleStateImageBehavior = false; + this.GameInstancesListView.View = System.Windows.Forms.View.Details; + this.GameInstancesListView.SelectedIndexChanged += new System.EventHandler(this.GameInstancesListView_SelectedIndexChanged); + this.GameInstancesListView.DoubleClick += new System.EventHandler(this.GameInstancesListView_DoubleClick); + this.GameInstancesListView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.GameInstancesListView_Click); // // InstanceListContextMenuStrip // @@ -89,20 +91,25 @@ private void InitializeComponent() this.openDirectoryMenuItem.Click += new System.EventHandler(this.OpenDirectoryMenuItem_Click); resources.ApplyResources(this.openDirectoryMenuItem, "openDirectoryMenuItem"); // - // KSPInstallName + // GameInstallName // - this.KSPInstallName.Width = 130; - resources.ApplyResources(this.KSPInstallName, "KSPInstallName"); + this.GameInstallName.Width = 130; + resources.ApplyResources(this.GameInstallName, "GameInstallName"); // - // KSPInstallVersion + // Game // - this.KSPInstallVersion.Width = 70; - resources.ApplyResources(this.KSPInstallVersion, "KSPInstallVersion"); + this.Game.Width = 70; + resources.ApplyResources(this.Game, "Game"); // - // KSPInstallPath + // GameInstallVersion // - this.KSPInstallPath.Width = 370; - resources.ApplyResources(this.KSPInstallPath, "KSPInstallPath"); + this.GameInstallVersion.Width = 70; + resources.ApplyResources(this.GameInstallVersion, "GameInstallVersion"); + // + // GameInstallPath + // + this.GameInstallPath.Width = 370; + resources.ApplyResources(this.GameInstallPath, "GameInstallPath"); // // SelectButton // @@ -188,7 +195,7 @@ private void InitializeComponent() this.ForgetButton.Click += new System.EventHandler(this.Forget_Click); resources.ApplyResources(this.ForgetButton, "ForgetButton"); // - // ManageKspInstancesDialog + // ManageGameInstancesDialog // this.AcceptButton = this.SelectButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); @@ -199,10 +206,10 @@ private void InitializeComponent() this.Controls.Add(this.RenameButton); this.Controls.Add(this.AddNewButton); this.Controls.Add(this.SelectButton); - this.Controls.Add(this.KSPInstancesListView); + this.Controls.Add(this.GameInstancesListView); this.Icon = Properties.Resources.AppIcon; this.MinimumSize = new System.Drawing.Size(560, 200); - this.Name = "ManageKspInstancesDialog"; + this.Name = "ManageGameInstancesDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; resources.ApplyResources(this, "$this"); this.InstanceListContextMenuStrip.ResumeLayout(false); @@ -214,10 +221,11 @@ private void InitializeComponent() #endregion - private System.Windows.Forms.ListView KSPInstancesListView; - private System.Windows.Forms.ColumnHeader KSPInstallName; - private System.Windows.Forms.ColumnHeader KSPInstallPath; - private System.Windows.Forms.ColumnHeader KSPInstallVersion; + private System.Windows.Forms.ListView GameInstancesListView; + private System.Windows.Forms.ColumnHeader GameInstallName; + private System.Windows.Forms.ColumnHeader Game; + private System.Windows.Forms.ColumnHeader GameInstallVersion; + private System.Windows.Forms.ColumnHeader GameInstallPath; private System.Windows.Forms.Button SelectButton; private DropdownMenuButton AddNewButton; private System.Windows.Forms.ContextMenuStrip AddNewMenu; diff --git a/GUI/Dialogs/ManageKspInstancesDialog.cs b/GUI/Dialogs/ManageGameInstancesDialog.cs similarity index 62% rename from GUI/Dialogs/ManageKspInstancesDialog.cs rename to GUI/Dialogs/ManageGameInstancesDialog.cs index 327d755de1..2158b625d7 100644 --- a/GUI/Dialogs/ManageKspInstancesDialog.cs +++ b/GUI/Dialogs/ManageGameInstancesDialog.cs @@ -5,30 +5,42 @@ namespace CKAN { - public partial class ManageKspInstancesDialog : Form + public partial class ManageGameInstancesDialog : Form { - private readonly KSPManager _manager; + private readonly GameInstanceManager _manager = Main.Instance.Manager; private readonly IUser _user; private RenameInstanceDialog _renameInstanceDialog; private readonly OpenFileDialog _instanceDialog = new OpenFileDialog() { - AddExtension = false, - CheckFileExists = false, - CheckPathExists = false, + AddExtension = false, + CheckFileExists = false, + CheckPathExists = false, InitialDirectory = Environment.CurrentDirectory, - Filter = Properties.Resources.CloneFakeKspDialogOpenFilter, - Multiselect = false + Filter = GameFolderFilter(Main.Instance.Manager), + Multiselect = false }; + + /// + /// Generate filter string for OpenFileDialog + /// + /// Game instance manager that can tell us about the build ID files + /// + /// "Build metadata files (buildID.txt;buildID64.txt)|buildID.txt;buildID64.txt" + /// + public static string GameFolderFilter(GameInstanceManager mgr) + { + return Properties.Resources.BuildIDFilterDescription + + "|" + string.Join(";", mgr.AllBuildIDFiles); + } - public bool HasSelections => KSPInstancesListView.SelectedItems.Count > 0; + public bool HasSelections => GameInstancesListView.SelectedItems.Count > 0; /// /// Initialize the game instance selection window /// /// true to center the window on the screen, false to center it on the parent - public ManageKspInstancesDialog(bool centerScreen, IUser user) + public ManageGameInstancesDialog(bool centerScreen, IUser user) { - _manager = Main.Instance.Manager; _user = user; InitializeComponent(); @@ -55,22 +67,23 @@ public ManageKspInstancesDialog(bool centerScreen, IUser user) public void UpdateInstancesList() { - KSPInstancesListView.Items.Clear(); + GameInstancesListView.Items.Clear(); UpdateButtonState(); - foreach (var instance in _manager.Instances) - { - KSPInstancesListView.Items.Add( - new ListViewItem(new string[] - { - instance.Key, - instance.Value.Version()?.ToString() ?? Properties.Resources.CompatibleKspVersionsDialogNone, - instance.Value.GameDir().Replace('/', Path.DirectorySeparatorChar) - }) - { - Tag = instance.Key - }); - } + GameInstancesListView.Items.AddRange(_manager.Instances + .OrderByDescending(instance => instance.Value.Version()) + .Select(instance => new ListViewItem(new string[] + { + instance.Key, + instance.Value.game.ShortName, + instance.Value.Version()?.ToString() ?? Properties.Resources.CompatibleGameVersionsDialogNone, + instance.Value.GameDir().Replace('/', Path.DirectorySeparatorChar) + }) + { + Tag = instance.Key + }) + .ToArray() + ); } private void AddToCKANMenuItem_Click(object sender, EventArgs e) @@ -88,13 +101,12 @@ private void AddToCKANMenuItem_Click(object sender, EventArgs e) instanceName = path; } instanceName = _manager.GetNextValidInstanceName(instanceName); - KSP instance = new KSP(path, instanceName, _user); - _manager.AddInstance(instance); + _manager.AddInstance(path, instanceName, _user); UpdateInstancesList(); } catch (NotKSPDirKraken k) { - _user.RaiseError(Properties.Resources.ManageKspInstancesNotValid, + _user.RaiseError(Properties.Resources.ManageGameInstancesNotValid, new object[] { k.path }); return; } @@ -104,7 +116,7 @@ private void CloneFakeInstanceMenuItem_Click(object sender, EventArgs e) { var old_instance = Main.Instance.CurrentInstance; - var result = new CloneFakeKspDialog(_manager, _user).ShowDialog(); + var result = new CloneFakeGameDialog(_manager, _user).ShowDialog(); if (result == DialogResult.OK && !Equals(old_instance, Main.Instance.CurrentInstance)) { DialogResult = DialogResult.OK; @@ -121,12 +133,12 @@ private void SelectButton_Click(object sender, EventArgs e) private void UseSelectedInstance() { - if (KSPInstancesListView.SelectedItems.Count == 0) + if (GameInstancesListView.SelectedItems.Count == 0) { return; } - var selected = KSPInstancesListView.SelectedItems[0]; + var selected = GameInstancesListView.SelectedItems[0]; var instName = selected?.Tag as string; if (instName == null) { @@ -141,7 +153,7 @@ private void UseSelectedInstance() } catch (NotKSPDirKraken k) { - _user.RaiseError(Properties.Resources.ManageKspInstancesNotValid, k.path); + _user.RaiseError(Properties.Resources.ManageGameInstancesNotValid, k.path); } } @@ -154,7 +166,7 @@ private void SetAsDefaultCheckbox_Click(object sender, EventArgs e) return; } - var selected = KSPInstancesListView.SelectedItems[0]; + var selected = GameInstancesListView.SelectedItems[0]; string instName = selected?.Tag as string; if (instName == null) { @@ -168,22 +180,22 @@ private void SetAsDefaultCheckbox_Click(object sender, EventArgs e) } catch (NotKSPDirKraken k) { - _user.RaiseError(Properties.Resources.ManageKspInstancesNotValid, k.path); + _user.RaiseError(Properties.Resources.ManageGameInstancesNotValid, k.path); } } - private void KSPInstancesListView_SelectedIndexChanged(object sender, EventArgs e) + private void GameInstancesListView_SelectedIndexChanged(object sender, EventArgs e) { UpdateButtonState(); - if (KSPInstancesListView.SelectedItems.Count == 0) + if (GameInstancesListView.SelectedItems.Count == 0) return; - string instName = (string)KSPInstancesListView.SelectedItems[0].Tag; + string instName = (string)GameInstancesListView.SelectedItems[0].Tag; SetAsDefaultCheckbox.Checked = _manager.AutoStartInstance?.Equals(instName) ?? false; } - private void KSPInstancesListView_DoubleClick(object sender, EventArgs r) + private void GameInstancesListView_DoubleClick(object sender, EventArgs r) { if (HasSelections) { @@ -191,7 +203,7 @@ private void KSPInstancesListView_DoubleClick(object sender, EventArgs r) } } - private void KSPInstancesListView_Click(object sender, MouseEventArgs e) + private void GameInstancesListView_Click(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { @@ -201,11 +213,11 @@ private void KSPInstancesListView_Click(object sender, MouseEventArgs e) private void OpenDirectoryMenuItem_Click(object sender, EventArgs e) { - string path = KSPInstancesListView.SelectedItems[0].SubItems[2].Text; + string path = GameInstancesListView.SelectedItems[0].SubItems[2].Text; if (!Directory.Exists(path)) { - _user.RaiseError(Properties.Resources.ManageKspInstancesDirectoryDeleted, path); + _user.RaiseError(Properties.Resources.ManageGameInstancesDirectoryDeleted, path); return; } @@ -214,7 +226,7 @@ private void OpenDirectoryMenuItem_Click(object sender, EventArgs e) private void RenameButton_Click(object sender, EventArgs e) { - var instance = (string)KSPInstancesListView.SelectedItems[0].Tag; + var instance = (string)GameInstancesListView.SelectedItems[0].Tag; // show the dialog, and only continue if the user selected "OK" _renameInstanceDialog = new RenameInstanceDialog(); @@ -228,7 +240,7 @@ private void RenameButton_Click(object sender, EventArgs e) private void Forget_Click(object sender, EventArgs e) { - foreach (var instance in KSPInstancesListView.SelectedItems.OfType().Select(item => item.Tag as string)) + foreach (var instance in GameInstancesListView.SelectedItems.OfType().Select(item => item.Tag as string)) { _manager.RemoveInstance(instance); UpdateInstancesList(); @@ -238,7 +250,7 @@ private void Forget_Click(object sender, EventArgs e) private void UpdateButtonState() { RenameButton.Enabled = SelectButton.Enabled = SetAsDefaultCheckbox.Enabled = HasSelections; - ForgetButton.Enabled = HasSelections && (string)KSPInstancesListView.SelectedItems[0].Tag != _manager.CurrentInstance?.Name; + ForgetButton.Enabled = HasSelections && (string)GameInstancesListView.SelectedItems[0].Tag != _manager.CurrentInstance?.Name; } } } diff --git a/GUI/Dialogs/ManageKSPInstancesDialog.resx b/GUI/Dialogs/ManageGameInstancesDialog.resx similarity index 93% rename from GUI/Dialogs/ManageKSPInstancesDialog.resx rename to GUI/Dialogs/ManageGameInstancesDialog.resx index 8e252a8838..2dfcf69472 100644 --- a/GUI/Dialogs/ManageKSPInstancesDialog.resx +++ b/GUI/Dialogs/ManageGameInstancesDialog.resx @@ -111,15 +111,16 @@ Open directory - Name - Version - Path + Name + Game + Version + Path Select - New KSP instance + New game instance Add instance to CKAN Clone or fake new instance Rename Set as default Forget - Manage KSP Instances + Manage Game Instances diff --git a/GUI/Localization/de-DE/AllModVersions.de-DE.resx b/GUI/Localization/de-DE/AllModVersions.de-DE.resx index 88157a4e1e..8a66a6c123 100644 --- a/GUI/Localization/de-DE/AllModVersions.de-DE.resx +++ b/GUI/Localization/de-DE/AllModVersions.de-DE.resx @@ -119,7 +119,7 @@ Alle verfügbaren Versionen der ausgewählten Mod Mod-Version - Kompatible KSP-Versionen + Kompatible Spielversionen Grün Hellgrün Fett diff --git a/GUI/Localization/de-DE/CloneFakeKspDialog.de-DE.resx b/GUI/Localization/de-DE/CloneFakeGameDialog.de-DE.resx similarity index 100% rename from GUI/Localization/de-DE/CloneFakeKspDialog.de-DE.resx rename to GUI/Localization/de-DE/CloneFakeGameDialog.de-DE.resx diff --git a/GUI/Localization/de-DE/CompatibleKspVersionsDialog.de-DE.resx b/GUI/Localization/de-DE/CompatibleGameVersionsDialog.de-DE.resx similarity index 96% rename from GUI/Localization/de-DE/CompatibleKspVersionsDialog.de-DE.resx rename to GUI/Localization/de-DE/CompatibleGameVersionsDialog.de-DE.resx index 5283c60b1b..2b05326fe7 100644 --- a/GUI/Localization/de-DE/CompatibleKspVersionsDialog.de-DE.resx +++ b/GUI/Localization/de-DE/CompatibleGameVersionsDialog.de-DE.resx @@ -117,16 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Erlaube außerdem die Installation von Mods, die mit folgenden KSP-Versionen kompatibel sind: + Erlaube außerdem die Installation von Mods, die mit folgenden Spielversionen kompatibel sind: Spielversion: Achtung! Ob Mods tatsächlich mit den ausgewählten Versionen kompatibel sind, ist nicht überprüfbar! Sei vorsichtig. Auswahl löschen Hinzufügen Version hinzufügen: Beachte: Wenn du Versionen wie "1.2" hinzufügst, werden alle Versionen im Bereich 1.2.xx (also 1.2.0, 1.2.1, etc.) als kompatibel markiert. - Nach jedem Update von KSP wird dir dieser Dialog wieder angezeigt, damit du deine Auswahl überprüfen kannst. + Nach jedem Spielupdate wird dir dieser Dialog wieder angezeigt, damit du deine Auswahl überprüfen kannst. Annehmen Installationspfad: Abbrechen - Kompatible KSP-Versionen + Kompatible Spielversionen diff --git a/GUI/Localization/de-DE/EditModpack.de-DE.resx b/GUI/Localization/de-DE/EditModpack.de-DE.resx index 60cc2f61bc..ebfc9b5f78 100644 --- a/GUI/Localization/de-DE/EditModpack.de-DE.resx +++ b/GUI/Localization/de-DE/EditModpack.de-DE.resx @@ -121,7 +121,7 @@ Name: Abstrakt: Modpack-Version: - KSP-Versionen: + Spielversionen: Lizenz: Mod-Versionen im Pack auf die hier angezeigten festsetzen Mod diff --git a/GUI/Localization/de-DE/KSPCommandLineOptionsDialog.de-DE.resx b/GUI/Localization/de-DE/GameCommandLineOptionsDialog.de-DE.resx similarity index 98% rename from GUI/Localization/de-DE/KSPCommandLineOptionsDialog.de-DE.resx rename to GUI/Localization/de-DE/GameCommandLineOptionsDialog.de-DE.resx index cd8379543e..7a8c850152 100644 --- a/GUI/Localization/de-DE/KSPCommandLineOptionsDialog.de-DE.resx +++ b/GUI/Localization/de-DE/GameCommandLineOptionsDialog.de-DE.resx @@ -120,5 +120,5 @@ Argumente: Abbrechen - KSP Befehlszeilenargumente + Befehlszeilenargumente diff --git a/GUI/Localization/de-DE/Main.de-DE.resx b/GUI/Localization/de-DE/Main.de-DE.resx index 3696bda2da..b217b607fd 100644 --- a/GUI/Localization/de-DE/Main.de-DE.resx +++ b/GUI/Localization/de-DE/Main.de-DE.resx @@ -164,8 +164,8 @@ True Datei - KSP-Instanzen verwalten - Spieleverzeichnis öffnen + Spielinstanzen verwalten + Spieleverzeichnis öffnen Von .ckan installieren Liste installierter Mods speichern... Modpack exportieren ... @@ -175,8 +175,8 @@ Einstellungen CKAN Einstellungen CKAN Plugins - KSP Befehlszeile - Kompatible KSP-Versionen + Spielstart-Befehlszeile + Kompatible Spielversionen Hilfe Fehler mit dem CKAN Client melden Fehler mit Mod-Metadaten melden @@ -191,8 +191,8 @@ Aktualisieren Anhalten CKAN öffnen - KSP starten - KSP-Verzeichnis öffnen + Spiel starten + Spielverzeichnis öffnen CKAN Einstellungen Beenden diff --git a/GUI/Localization/de-DE/ManageKSPInstancesDialog.de-DE.resx b/GUI/Localization/de-DE/ManageGameInstancesDialog.de-DE.resx similarity index 95% rename from GUI/Localization/de-DE/ManageKSPInstancesDialog.de-DE.resx rename to GUI/Localization/de-DE/ManageGameInstancesDialog.de-DE.resx index 33916a919a..0e1bb1bec1 100644 --- a/GUI/Localization/de-DE/ManageKSPInstancesDialog.de-DE.resx +++ b/GUI/Localization/de-DE/ManageGameInstancesDialog.de-DE.resx @@ -122,14 +122,14 @@ Verzeichnis öffnen - Name - Pfad + Name + Pfad Wählen - Neue KSP-Instanz + Neue Spielinstanz Instanz hinzufügen Instanz klonen oder fälschen Umbenennen Als Standardinstanz setzen Vergessen - KSP-Instanzen verwalten + Spielinstanzen verwalten diff --git a/GUI/Localization/de-DE/ManageMods.de-DE.resx b/GUI/Localization/de-DE/ManageMods.de-DE.resx index bf05344f1e..c272ebb238 100644 --- a/GUI/Localization/de-DE/ManageMods.de-DE.resx +++ b/GUI/Localization/de-DE/ManageMods.de-DE.resx @@ -147,7 +147,7 @@ True - KSP starten + Spiel starten Aktualisieren Verfügbare Updates auswählen Annehmen @@ -170,7 +170,7 @@ Autor Installierte Version Neueste Version - Max. KSP Version + Max. Spielversion Downloadgröße Veröffentlichungsdatum Installationsdatum diff --git a/GUI/Localization/de-DE/ModInfo.de-DE.resx b/GUI/Localization/de-DE/ModInfo.de-DE.resx index 5fe8b02d44..a76458ec45 100644 --- a/GUI/Localization/de-DE/ModInfo.de-DE.resx +++ b/GUI/Localization/de-DE/ModInfo.de-DE.resx @@ -121,7 +121,7 @@ Modname Kennung: Ersetzt durch: - Max. KSP-Version: + Max. Spielversion: Releasestatus: Autor: Lizenz: diff --git a/GUI/Localization/de-DE/RenameInstanceDialog.de-DE.resx b/GUI/Localization/de-DE/RenameInstanceDialog.de-DE.resx index 3798cb20c7..601d3ab3de 100644 --- a/GUI/Localization/de-DE/RenameInstanceDialog.de-DE.resx +++ b/GUI/Localization/de-DE/RenameInstanceDialog.de-DE.resx @@ -119,5 +119,5 @@ OK Abbrechen - KSP-Instanz umbenennen + Spielinstanz umbenennen diff --git a/GUI/Localization/zh-CN/AllModVersions.zh-CN.resx b/GUI/Localization/zh-CN/AllModVersions.zh-CN.resx index 30dee97a8b..3effd249a8 100644 --- a/GUI/Localization/zh-CN/AllModVersions.zh-CN.resx +++ b/GUI/Localization/zh-CN/AllModVersions.zh-CN.resx @@ -119,11 +119,11 @@ 选中Mod的所有可用版本 Mod版本 - 兼容的KSP版本 + 兼容的游戏版本 绿色 浅绿色 粗体 - 最新的兼容版本(很可能安装) - - 兼容您的KSP的版本 + - 兼容您的游戏的版本 - 当前已安装版本 diff --git a/GUI/Localization/zh-CN/CloneFakeKspDialog.zh-CN.resx b/GUI/Localization/zh-CN/CloneFakeGameDialog.zh-CN.resx similarity index 100% rename from GUI/Localization/zh-CN/CloneFakeKspDialog.zh-CN.resx rename to GUI/Localization/zh-CN/CloneFakeGameDialog.zh-CN.resx diff --git a/GUI/Localization/zh-CN/CompatibleKspVersionsDialog.zh-CN.resx b/GUI/Localization/zh-CN/CompatibleGameVersionsDialog.zh-CN.resx similarity index 95% rename from GUI/Localization/zh-CN/CompatibleKspVersionsDialog.zh-CN.resx rename to GUI/Localization/zh-CN/CompatibleGameVersionsDialog.zh-CN.resx index 9ba12c07ba..ed98c29b8e 100644 --- a/GUI/Localization/zh-CN/CompatibleKspVersionsDialog.zh-CN.resx +++ b/GUI/Localization/zh-CN/CompatibleGameVersionsDialog.zh-CN.resx @@ -117,7 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - 此外,安装兼容以下KSP版本的Mod: + 此外,安装兼容以下游戏版本的Mod: 游戏版本: 警告!无法检查Mod是否真正与所选版本兼容!请小心操作。 <版本> @@ -125,10 +125,10 @@ 添加 向列表中添加版本: 注意:如果您添加类似于“1.2”的版本您将会强制所有兼容1.2.xx(例如1.2.0、1.2.1等等)的Mod与该版本兼容 - 如果KSP被更新,此对话框将重新弹出以便您调整设置。 + 如果游戏被更新,此对话框将重新弹出以便您调整设置。 确认 当前安装: <地址> 取消 - 兼容的KSP版本 + 兼容的游戏版本 diff --git a/GUI/Localization/zh-CN/EditModpack.zh-CN.resx b/GUI/Localization/zh-CN/EditModpack.zh-CN.resx index 6b237eb1ae..7e9e50194e 100644 --- a/GUI/Localization/zh-CN/EditModpack.zh-CN.resx +++ b/GUI/Localization/zh-CN/EditModpack.zh-CN.resx @@ -121,7 +121,7 @@ 名称: 概要: 版本: - KSP版本: + 游戏版本: 协议: 保存mod版本 Mod diff --git a/GUI/Localization/zh-CN/KSPCommandLineOptionsDialog.zh-CN.resx b/GUI/Localization/zh-CN/GameCommandLineOptionsDialog.zh-CN.resx similarity index 98% rename from GUI/Localization/zh-CN/KSPCommandLineOptionsDialog.zh-CN.resx rename to GUI/Localization/zh-CN/GameCommandLineOptionsDialog.zh-CN.resx index aa048a72a4..ef0f257c62 100644 --- a/GUI/Localization/zh-CN/KSPCommandLineOptionsDialog.zh-CN.resx +++ b/GUI/Localization/zh-CN/GameCommandLineOptionsDialog.zh-CN.resx @@ -121,5 +121,5 @@ 变量: 确认 取消 - KSP启动选项 + 启动选项 diff --git a/GUI/Localization/zh-CN/Main.zh-CN.resx b/GUI/Localization/zh-CN/Main.zh-CN.resx index d128c04302..c562375a83 100644 --- a/GUI/Localization/zh-CN/Main.zh-CN.resx +++ b/GUI/Localization/zh-CN/Main.zh-CN.resx @@ -163,8 +163,8 @@ True 文件 - 管理KSP实例 - 打开KSP目录 + 管理游戏实例 + 打开游戏目录 从.ckan安装... &保存已安装的Mod列表... 导出Mod包... @@ -174,8 +174,8 @@ 设置 CKAN设置 CKAN插件 - KSP启动选项 - 兼容的KSP版本 + 游戏启动选项 + 兼容的游戏版本 帮助 报告CKAN客户端的问题 报告Mod元数据的问题 @@ -192,8 +192,8 @@ 刷新 暂停 打开CKAN - 启动KSP - 打开KSP目录 + 启动游戏 + 打开游戏目录 CKAN设置 退出 diff --git a/GUI/Localization/zh-CN/ManageKSPInstancesDialog.zh-CN.resx b/GUI/Localization/zh-CN/ManageGameInstancesDialog.zh-CN.resx similarity index 94% rename from GUI/Localization/zh-CN/ManageKSPInstancesDialog.zh-CN.resx rename to GUI/Localization/zh-CN/ManageGameInstancesDialog.zh-CN.resx index e7c8707f18..03b6090fa5 100644 --- a/GUI/Localization/zh-CN/ManageKSPInstancesDialog.zh-CN.resx +++ b/GUI/Localization/zh-CN/ManageGameInstancesDialog.zh-CN.resx @@ -111,15 +111,15 @@ 打开目录 - 名称 - 版本 - 路径 + 名称 + 版本 + 路径 选择 - 新KSP实例 + 新游戏实例 添加实例到CKAN 克隆或伪装新实例 重命名 设为默认 忽略 - 管理KSP实例 + 管理游戏实例 diff --git a/GUI/Localization/zh-CN/ManageMods.zh-CN.resx b/GUI/Localization/zh-CN/ManageMods.zh-CN.resx index 4722edca26..9c8753db68 100644 --- a/GUI/Localization/zh-CN/ManageMods.zh-CN.resx +++ b/GUI/Localization/zh-CN/ManageMods.zh-CN.resx @@ -147,7 +147,7 @@ True - 启动KSP + 启动游戏 刷新 添加可用更新 应用更改 @@ -174,7 +174,7 @@ 作者 已安装版本 最新版本 - 最高KSP版本 + 最高游戏版本 下载大小 安装日期 下载量 diff --git a/GUI/Localization/zh-CN/ModInfo.zh-CN.resx b/GUI/Localization/zh-CN/ModInfo.zh-CN.resx index 1443090917..047e5be419 100644 --- a/GUI/Localization/zh-CN/ModInfo.zh-CN.resx +++ b/GUI/Localization/zh-CN/ModInfo.zh-CN.resx @@ -123,18 +123,16 @@ - 替换为: - - 最高KSP版本: + 最高游戏版本: 发布状态: 源代码: 主页: 作者: 协议: - 0.0.0 无协议 无作者 版本: 稳定 - 0.0.0 关系 依赖 推荐 diff --git a/GUI/Main/Main.Designer.cs b/GUI/Main/Main.Designer.cs index 3e657f07a1..4506b26af6 100644 --- a/GUI/Main/Main.Designer.cs +++ b/GUI/Main/Main.Designer.cs @@ -32,8 +32,8 @@ private void InitializeComponent() System.ComponentModel.ComponentResourceManager resources = new SingleAssemblyComponentResourceManager(typeof(Main)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.manageKspInstancesMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.openKspDirectoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.manageGameInstancesMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.openGameDirectoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.installFromckanToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportModListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -46,8 +46,8 @@ private void InitializeComponent() this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cKANSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pluginsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.kSPCommandlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.compatibleKSPVersionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.GameCommandlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.compatibleGameVersionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reportClientIssueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reportMetadataIssueToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); @@ -83,8 +83,8 @@ private void InitializeComponent() this.pauseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.openCKANToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.openKSPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.openKSPDirectoryToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); + this.openGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.openGameDirectoryToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.cKANSettingsToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); @@ -127,8 +127,8 @@ private void InitializeComponent() // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.manageKspInstancesMenuItem, - this.openKspDirectoryToolStripMenuItem, + this.manageGameInstancesMenuItem, + this.openGameDirectoryToolStripMenuItem, this.toolStripSeparator1, this.installFromckanToolStripMenuItem, this.importDownloadsToolStripMenuItem, @@ -143,19 +143,19 @@ private void InitializeComponent() this.fileToolStripMenuItem.Size = new System.Drawing.Size(50, 29); resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem"); // - // manageKspInstancesMenuItem + // manageGameInstancesMenuItem // - this.manageKspInstancesMenuItem.Name = "manageKspInstancesMenuItem"; - this.manageKspInstancesMenuItem.Size = new System.Drawing.Size(281, 30); - this.manageKspInstancesMenuItem.Click += new System.EventHandler(this.manageKspInstancesMenuItem_Click); - resources.ApplyResources(this.manageKspInstancesMenuItem, "manageKspInstancesMenuItem"); + this.manageGameInstancesMenuItem.Name = "manageGameInstancesMenuItem"; + this.manageGameInstancesMenuItem.Size = new System.Drawing.Size(281, 30); + this.manageGameInstancesMenuItem.Click += new System.EventHandler(this.manageGameInstancesMenuItem_Click); + resources.ApplyResources(this.manageGameInstancesMenuItem, "manageGameInstancesMenuItem"); // - // openKspDirectoryToolStripMenuItem + // openGameDirectoryToolStripMenuItem // - this.openKspDirectoryToolStripMenuItem.Name = "openKspDirectoryToolStripMenuItem"; - this.openKspDirectoryToolStripMenuItem.Size = new System.Drawing.Size(281, 30); - this.openKspDirectoryToolStripMenuItem.Click += new System.EventHandler(this.openKspDirectoryToolStripMenuItem_Click); - resources.ApplyResources(this.openKspDirectoryToolStripMenuItem, "openKspDirectoryToolStripMenuItem"); + this.openGameDirectoryToolStripMenuItem.Name = "openGameDirectoryToolStripMenuItem"; + this.openGameDirectoryToolStripMenuItem.Size = new System.Drawing.Size(281, 30); + this.openGameDirectoryToolStripMenuItem.Click += new System.EventHandler(this.openGameDirectoryToolStripMenuItem_Click); + resources.ApplyResources(this.openGameDirectoryToolStripMenuItem, "openGameDirectoryToolStripMenuItem"); // // toolStripSeparator1 // @@ -225,8 +225,8 @@ private void InitializeComponent() this.settingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.cKANSettingsToolStripMenuItem, this.pluginsToolStripMenuItem, - this.kSPCommandlineToolStripMenuItem, - this.compatibleKSPVersionsToolStripMenuItem}); + this.GameCommandlineToolStripMenuItem, + this.compatibleGameVersionsToolStripMenuItem}); this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; this.settingsToolStripMenuItem.Size = new System.Drawing.Size(88, 29); resources.ApplyResources(this.settingsToolStripMenuItem, "settingsToolStripMenuItem"); @@ -245,19 +245,19 @@ private void InitializeComponent() this.pluginsToolStripMenuItem.Click += new System.EventHandler(this.pluginsToolStripMenuItem_Click); resources.ApplyResources(this.pluginsToolStripMenuItem, "pluginsToolStripMenuItem"); // - // kSPCommandlineToolStripMenuItem + // GameCommandlineToolStripMenuItem // - this.kSPCommandlineToolStripMenuItem.Name = "kSPCommandlineToolStripMenuItem"; - this.kSPCommandlineToolStripMenuItem.Size = new System.Drawing.Size(247, 30); - this.kSPCommandlineToolStripMenuItem.Click += new System.EventHandler(this.KSPCommandlineToolStripMenuItem_Click); - resources.ApplyResources(this.kSPCommandlineToolStripMenuItem, "kSPCommandlineToolStripMenuItem"); + this.GameCommandlineToolStripMenuItem.Name = "GameCommandlineToolStripMenuItem"; + this.GameCommandlineToolStripMenuItem.Size = new System.Drawing.Size(247, 30); + this.GameCommandlineToolStripMenuItem.Click += new System.EventHandler(this.GameCommandlineToolStripMenuItem_Click); + resources.ApplyResources(this.GameCommandlineToolStripMenuItem, "GameCommandlineToolStripMenuItem"); // - // compatibleKSPVersionsToolStripMenuItem + // compatibleGameVersionsToolStripMenuItem // - this.compatibleKSPVersionsToolStripMenuItem.Name = "compatibleKSPVersionsToolStripMenuItem"; - this.compatibleKSPVersionsToolStripMenuItem.Size = new System.Drawing.Size(233, 24); - this.compatibleKSPVersionsToolStripMenuItem.Click += new System.EventHandler(this.CompatibleKspVersionsToolStripMenuItem_Click); - resources.ApplyResources(this.compatibleKSPVersionsToolStripMenuItem, "compatibleKSPVersionsToolStripMenuItem"); + this.compatibleGameVersionsToolStripMenuItem.Name = "compatibleGameVersionsToolStripMenuItem"; + this.compatibleGameVersionsToolStripMenuItem.Size = new System.Drawing.Size(233, 24); + this.compatibleGameVersionsToolStripMenuItem.Click += new System.EventHandler(this.CompatibleGameVersionsToolStripMenuItem_Click); + resources.ApplyResources(this.compatibleGameVersionsToolStripMenuItem, "compatibleGameVersionsToolStripMenuItem"); // // helpToolStripMenuItem // @@ -577,8 +577,8 @@ private void InitializeComponent() this.pauseToolStripMenuItem, this.toolStripSeparator5, this.openCKANToolStripMenuItem, - this.openKSPToolStripMenuItem, - this.openKSPDirectoryToolStripMenuItem1, + this.openGameToolStripMenuItem, + this.openGameDirectoryToolStripMenuItem1, this.cKANSettingsToolStripMenuItem1, this.toolStripSeparator6, this.quitToolStripMenuItem}); @@ -624,19 +624,19 @@ private void InitializeComponent() this.openCKANToolStripMenuItem.Click += new System.EventHandler(this.openCKANToolStripMenuItem_Click); resources.ApplyResources(this.openCKANToolStripMenuItem, "openCKANToolStripMenuItem"); // - // openKSPToolStripMenuItem + // openGameToolStripMenuItem // - this.openKSPToolStripMenuItem.Name = "launchKSPToolStripMenuItem"; - this.openKSPToolStripMenuItem.Size = new System.Drawing.Size(180, 22); - this.openKSPToolStripMenuItem.Click += new System.EventHandler(this.openKSPToolStripMenuItem_Click); - resources.ApplyResources(this.openKSPToolStripMenuItem, "openKSPToolStripMenuItem"); + this.openGameToolStripMenuItem.Name = "openGameToolStripMenuItem"; + this.openGameToolStripMenuItem.Size = new System.Drawing.Size(180, 22); + this.openGameToolStripMenuItem.Click += new System.EventHandler(this.openGameToolStripMenuItem_Click); + resources.ApplyResources(this.openGameToolStripMenuItem, "openGameToolStripMenuItem"); // - // openKSPDirectoryToolStripMenuItem1 + // openGameDirectoryToolStripMenuItem1 // - this.openKSPDirectoryToolStripMenuItem1.Name = "openKSPDirectoryToolStripMenuItem1"; - this.openKSPDirectoryToolStripMenuItem1.Size = new System.Drawing.Size(180, 22); - this.openKSPDirectoryToolStripMenuItem1.Click += new System.EventHandler(this.openKspDirectoryToolStripMenuItem_Click); - resources.ApplyResources(this.openKSPDirectoryToolStripMenuItem1, "openKSPDirectoryToolStripMenuItem1"); + this.openGameDirectoryToolStripMenuItem1.Name = "openGameDirectoryToolStripMenuItem1"; + this.openGameDirectoryToolStripMenuItem1.Size = new System.Drawing.Size(180, 22); + this.openGameDirectoryToolStripMenuItem1.Click += new System.EventHandler(this.openGameDirectoryToolStripMenuItem_Click); + resources.ApplyResources(this.openGameDirectoryToolStripMenuItem1, "openGameDirectoryToolStripMenuItem1"); // // cKANSettingsToolStripMenuItem1 // @@ -707,8 +707,8 @@ private void InitializeComponent() private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem manageKspInstancesMenuItem; - private System.Windows.Forms.ToolStripMenuItem openKspDirectoryToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem manageGameInstancesMenuItem; + private System.Windows.Forms.ToolStripMenuItem openGameDirectoryToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem installFromckanToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exportModListToolStripMenuItem; @@ -721,8 +721,8 @@ private void InitializeComponent() public System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem cKANSettingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pluginsToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem kSPCommandlineToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem compatibleKSPVersionsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem GameCommandlineToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem compatibleGameVersionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reportClientIssueToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reportMetadataIssueToolStripMenuItem; @@ -762,8 +762,8 @@ private void InitializeComponent() public System.Windows.Forms.ToolStripMenuItem pauseToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem openCKANToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem openKSPToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem openKSPDirectoryToolStripMenuItem1; + private System.Windows.Forms.ToolStripMenuItem openGameToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem openGameDirectoryToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem cKANSettingsToolStripMenuItem1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; diff --git a/GUI/Main/Main.cs b/GUI/Main/Main.cs index 94d96b3617..20d692d9b5 100644 --- a/GUI/Main/Main.cs +++ b/GUI/Main/Main.cs @@ -34,14 +34,14 @@ public partial class Main : Form public PluginController pluginController; - public volatile KSPManager manager; + public volatile GameInstanceManager manager; - public KSP CurrentInstance + public GameInstance CurrentInstance { get { return manager.CurrentInstance; } } - public KSPManager Manager + public GameInstanceManager Manager { get { return manager; } set { manager = value; } @@ -56,7 +56,7 @@ public KSPManager Manager private bool enableTrayIcon; private bool minimizeToTray; - public Main(string[] cmdlineArgs, KSPManager mgr, bool showConsole) + public Main(string[] cmdlineArgs, GameInstanceManager mgr, bool showConsole) { log.Info("Starting the GUI"); commandLineArgs = cmdlineArgs; @@ -82,7 +82,7 @@ public Main(string[] cmdlineArgs, KSPManager mgr, bool showConsole) Instance = this; currentUser = new GUIUser(this, this.Wait); - manager = mgr ?? new KSPManager(currentUser); + manager = mgr ?? new GameInstanceManager(currentUser); controlFactory = new ControlFactory(); @@ -108,7 +108,7 @@ public Main(string[] cmdlineArgs, KSPManager mgr, bool showConsole) { Hide(); - var result = new ManageKspInstancesDialog(!actuallyVisible, currentUser).ShowDialog(); + var result = new ManageGameInstancesDialog(!actuallyVisible, currentUser).ShowDialog(); if (result == DialogResult.Cancel || result == DialogResult.Abort) { Application.Exit(); @@ -314,7 +314,7 @@ protected override void OnLoad(EventArgs e) pluginController = new PluginController(pluginsPath); - CurrentInstance.RebuildKSPSubDir(); + CurrentInstance.game.RebuildSubdirectories(CurrentInstance); log.Info("GUI started"); base.OnLoad(e); @@ -376,13 +376,14 @@ protected override void OnFormClosing(FormClosingEventArgs e) /// true if a repo update is allowed if needed (e.g. on initial load), false otherwise private void CurrentInstanceUpdated(bool allowRepoUpdate) { - CurrentInstance.ScanGameData(); + CurrentInstance.Scan(); Util.Invoke(this, () => { - Text = $"CKAN {Meta.GetVersion()} - KSP {CurrentInstance.Version()} -- {CurrentInstance.GameDir().Replace('/', Path.DirectorySeparatorChar)}"; + Text = $"CKAN {Meta.GetVersion()} - {CurrentInstance.game.ShortName} {CurrentInstance.Version()} -- {CurrentInstance.GameDir().Replace('/', Path.DirectorySeparatorChar)}"; StatusInstanceLabel.Text = string.Format( Properties.Resources.StatusInstanceLabelText, CurrentInstance.Name, + CurrentInstance.game.ShortName, CurrentInstance.Version()?.ToString() ); }); @@ -391,9 +392,9 @@ private void CurrentInstanceUpdated(bool allowRepoUpdate) Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml") ); - if (CurrentInstance.CompatibleVersionsAreFromDifferentKsp) + if (CurrentInstance.CompatibleVersionsAreFromDifferentGameVersion) { - new CompatibleKspVersionsDialog(CurrentInstance, !actuallyVisible) + new CompatibleGameVersionsDialog(CurrentInstance, !actuallyVisible) .ShowDialog(); } @@ -466,10 +467,10 @@ private void aboutToolStripMenuItem_Click(object sender, EventArgs e) new AboutDialog().ShowDialog(); } - private void KSPCommandlineToolStripMenuItem_Click(object sender, EventArgs e) + private void GameCommandlineToolStripMenuItem_Click(object sender, EventArgs e) { - var dialog = new KSPCommandLineOptionsDialog(); - if (dialog.ShowKSPCommandLineOptionsDialog(configuration.CommandLineArguments) == DialogResult.OK) + var dialog = new GameCommandLineOptionsDialog(); + if (dialog.ShowGameCommandLineOptionsDialog(configuration.CommandLineArguments) == DialogResult.OK) { configuration.CommandLineArguments = dialog.GetResult(); configuration.Save(); @@ -540,10 +541,10 @@ private void installFromckanToolStripMenuItem_Click(object sender, EventArgs e) } } - private void manageKspInstancesMenuItem_Click(object sender, EventArgs e) + private void manageGameInstancesMenuItem_Click(object sender, EventArgs e) { var old_instance = Instance.CurrentInstance; - var result = new ManageKspInstancesDialog(!actuallyVisible, currentUser).ShowDialog(); + var result = new ManageGameInstancesDialog(!actuallyVisible, currentUser).ShowDialog(); if (result == DialogResult.OK && !Equals(old_instance, Instance.CurrentInstance)) { ManageMods.ModGrid.ClearSelection(); @@ -551,9 +552,9 @@ private void manageKspInstancesMenuItem_Click(object sender, EventArgs e) } } - private void CompatibleKspVersionsToolStripMenuItem_Click(object sender, EventArgs e) + private void CompatibleGameVersionsToolStripMenuItem_Click(object sender, EventArgs e) { - CompatibleKspVersionsDialog dialog = new CompatibleKspVersionsDialog( + CompatibleGameVersionsDialog dialog = new CompatibleGameVersionsDialog( Instance.manager.CurrentInstance, !actuallyVisible ); @@ -661,17 +662,17 @@ private void Main_Resize(object sender, EventArgs e) UpdateTrayState(); } - private void openKspDirectoryToolStripMenuItem_Click(object sender, EventArgs e) + private void openGameDirectoryToolStripMenuItem_Click(object sender, EventArgs e) { Utilities.ProcessStartURL(Instance.manager.CurrentInstance.GameDir()); } - private void openKSPToolStripMenuItem_Click(object sender, EventArgs e) + private void openGameToolStripMenuItem_Click(object sender, EventArgs e) { - LaunchKSP(); + LaunchGame(); } - public void LaunchKSP() + public void LaunchGame() { var split = configuration.CommandLineArguments.Split(' '); if (split.Length == 0) @@ -681,9 +682,9 @@ public void LaunchKSP() var incomp = registry.IncompatibleInstalled(CurrentInstance.VersionCriteria()); if (incomp.Any()) { - // Warn that it might not be safe to run KSP with incompatible modules installed + // Warn that it might not be safe to run Game with incompatible modules installed string incompatDescrip = incomp - .Select(m => $"{m.Module} ({registry.CompatibleGameVersions(m.Module)})") + .Select(m => $"{m.Module} ({registry.CompatibleGameVersions(CurrentInstance.game, m.Module)})") .Aggregate((a, b) => $"{a}, {b}"); if (!YesNoDialog(string.Format(Properties.Resources.MainLaunchWithIncompatible, incompatDescrip), Properties.Resources.MainLaunch, @@ -693,17 +694,8 @@ public void LaunchKSP() } } - // -single-instance crashes KSP 1.8 to KSP 1.9 on Linux - // https://issuetracker.unity3d.com/issues/linux-segmentation-fault-when-running-a-built-project-with-single-instance-argument - if (Platform.IsUnix) - { - var brokenVersionRange = new KspVersionRange( - new KspVersion(1, 8), - new KspVersion(1, 11) - ); - split = filterCmdLineArgs(split, brokenVersionRange, "-single-instance"); - } - + split = CurrentInstance.game.AdjustCommandLine(split, + Main.Instance.CurrentInstance.Version()); var binary = split[0]; var args = string.Join(" ", split.Skip(1)); @@ -718,32 +710,6 @@ public void LaunchKSP() } } - /// - /// If the installed game version is in the given range, - /// return the given array without the given parameter, - /// otherwise return the array as-is. - /// - /// Command line parameters to check - /// Game versions that should not use this parameter - /// The parameter to remove on version match - /// - /// args or args minus parameter - /// - private string[] filterCmdLineArgs(string[] args, KspVersionRange crashyKspRange, string parameter) - { - var installedRange = Main.Instance.CurrentInstance.Version().ToVersionRange(); - if (crashyKspRange.IntersectWith(installedRange) != null - && args.Contains(parameter)) - { - log.DebugFormat( - "Parameter {0} found on incompatible KSP version {1}, pruning", - parameter, - Main.Instance.CurrentInstance.Version().ToString()); - return args.Where(s => s != parameter).ToArray(); - } - return args; - } - private void ManageMods_StartChangeSet(List changeset) { // Hand off to centralized [un]installer code diff --git a/GUI/Main/Main.resx b/GUI/Main/Main.resx index a8c7d08fe3..9954b27540 100644 --- a/GUI/Main/Main.resx +++ b/GUI/Main/Main.resx @@ -136,8 +136,8 @@ True File - Manage KSP Instances - Open KSP Directory + Manage game instances + Open game directory Install from .ckan... &Save installed mod list... Export modpack... @@ -147,8 +147,8 @@ Settings CKAN settings CKAN plugins - KSP command-line - Compatible KSP versions + Game command-line + Compatible game versions Help Report an issue with the CKAN client Report an issue with mod metadata @@ -165,8 +165,8 @@ Refresh Pause Open CKAN - Launch KSP - Open KSP Directory + Launch Game + Open Game Directory CKAN Settings Quit diff --git a/GUI/Main/MainImport.cs b/GUI/Main/MainImport.cs index 97c60d32ea..8511c0fafa 100644 --- a/GUI/Main/MainImport.cs +++ b/GUI/Main/MainImport.cs @@ -68,7 +68,7 @@ private HashSet GetFiles(string[] filenames) Environment.GetFolderPath(Environment.SpecialFolder.Desktop) }; - private static string FindDownloadsPath(KSP gameInst) + private static string FindDownloadsPath(GameInstance gameInst) { foreach (string p in downloadPaths) { diff --git a/GUI/Main/MainRecommendations.cs b/GUI/Main/MainRecommendations.cs index 2c37ea6fb3..b9f946de31 100644 --- a/GUI/Main/MainRecommendations.cs +++ b/GUI/Main/MainRecommendations.cs @@ -31,7 +31,7 @@ private void auditRecommendationsMenuItem_Click(object sender, EventArgs e) )); } - private void AuditRecommendations(IRegistryQuerier registry, KspVersionCriteria versionCriteria) + private void AuditRecommendations(IRegistryQuerier registry, GameVersionCriteria versionCriteria) { var installer = ModuleInstaller.GetInstance(CurrentInstance, Manager.Cache, currentUser); if (installer.FindRecommendations( diff --git a/GUI/Main/MainRepo.cs b/GUI/Main/MainRepo.cs index 9201a18348..bc62858b9a 100644 --- a/GUI/Main/MainRepo.cs +++ b/GUI/Main/MainRepo.cs @@ -19,7 +19,7 @@ public static RepositoryList FetchMasterRepositoryList(Uri master_uri = null) { if (master_uri == null) { - master_uri = Repository.default_repo_master_list; + master_uri = Main.Instance.CurrentInstance.game.RepositoryListURL; } string json = Net.DownloadText(master_uri); @@ -65,12 +65,12 @@ private void UpdateRepo(object sender, DoWorkEventArgs e) try { AddStatusMessage(Properties.Resources.MainRepoScanning); - bool scanChanged = CurrentInstance.ScanGameData(); + bool scanChanged = CurrentInstance.Scan(); AddStatusMessage(Properties.Resources.MainRepoUpdating); // Note the current mods' compatibility for the NewlyCompatible filter - KspVersionCriteria versionCriteria = CurrentInstance.VersionCriteria(); + GameVersionCriteria versionCriteria = CurrentInstance.VersionCriteria(); IRegistryQuerier registry = RegistryManager.Instance(CurrentInstance).registry; Dictionary oldModules = registry.CompatibleModules(versionCriteria) .ToDictionary(m => m.identifier, m => false); diff --git a/GUI/Model/GUIConfiguration.cs b/GUI/Model/GUIConfiguration.cs index 1750884dbd..c16fcc6300 100644 --- a/GUI/Model/GUIConfiguration.cs +++ b/GUI/Model/GUIConfiguration.cs @@ -108,9 +108,7 @@ public static GUIConfiguration LoadOrCreateConfiguration(string path) var configuration = new GUIConfiguration { path = path, - CommandLineArguments = Platform.IsUnix ? "./KSP.x86_64 -single-instance" : - Platform.IsMac ? "./KSP.app/Contents/MacOS/KSP" : - "KSP_x64.exe -single-instance" + CommandLineArguments = Main.Instance.CurrentInstance.game.DefaultCommandLine }; SaveConfiguration(configuration); diff --git a/GUI/Model/GUIMod.cs b/GUI/Model/GUIMod.cs index 9a140b7e58..b45152d09d 100644 --- a/GUI/Model/GUIMod.cs +++ b/GUI/Model/GUIMod.cs @@ -77,12 +77,12 @@ private void OnPropertyChanged([CallerMemberName] string name = null) public int? DownloadCount { get; private set; } public bool IsCached { get; private set; } - // These indicate the maximum KSP version that the maximum available + // These indicate the maximum game version that the maximum available // version of this mod can handle. The "Long" version also indicates // to the user if a mod upgrade would be required. (#1270) - public KspVersion KSPCompatibilityVersion { get; private set; } - public string KSPCompatibility { get; private set; } - public string KSPCompatibilityLong { get; private set; } + public GameVersion GameCompatibilityVersion { get; private set; } + public string GameCompatibility { get; private set; } + public string GameCompatibilityLong { get; private set; } public string Abstract { get; private set; } public string Description { get; private set; } @@ -125,10 +125,10 @@ public string Version /// /// The installed module to represent /// CKAN registry object for current game instance - /// Current game version + /// Current game version /// If true, mark this module as incompatible - public GUIMod(InstalledModule instMod, IRegistryQuerier registry, KspVersionCriteria current_ksp_version, bool? incompatible = null) - : this(instMod.Module, registry, current_ksp_version, incompatible) + public GUIMod(InstalledModule instMod, IRegistryQuerier registry, GameVersionCriteria current_game_version, bool? incompatible = null) + : this(instMod.Module, registry, current_game_version, incompatible) { IsInstalled = true; IsInstallChecked = true; @@ -148,10 +148,10 @@ public GUIMod(InstalledModule instMod, IRegistryQuerier registry, KspVersionCrit /// /// The module to represent /// CKAN registry object for current game instance - /// Current game version + /// Current game version /// If true, mark this module as incompatible - public GUIMod(CkanModule mod, IRegistryQuerier registry, KspVersionCriteria current_ksp_version, bool? incompatible = null) - : this(mod.identifier, registry, current_ksp_version, incompatible) + public GUIMod(CkanModule mod, IRegistryQuerier registry, GameVersionCriteria current_game_version, bool? incompatible = null) + : this(mod.identifier, registry, current_game_version, incompatible) { Mod = mod; IsCKAN = mod is CkanModule; @@ -162,8 +162,8 @@ public GUIMod(CkanModule mod, IRegistryQuerier registry, KspVersionCriteria curr Abbrevation = new string(Name.Split(' ').Where(s => s.Length > 0).Select(s => s[0]).ToArray()); Authors = mod.author == null ? Properties.Resources.GUIModNSlashA : String.Join(",", mod.author); - HasUpdate = registry.HasUpdate(mod.identifier, current_ksp_version); - HasReplacement = registry.GetReplacement(mod, current_ksp_version) != null; + HasUpdate = registry.HasUpdate(mod.identifier, current_game_version); + HasReplacement = registry.GetReplacement(mod, current_game_version) != null; DownloadSize = mod.download_size == 0 ? Properties.Resources.GUIModNSlashA : CkanModule.FmtSize(mod.download_size); // Get the Searchables. @@ -174,13 +174,13 @@ public GUIMod(CkanModule mod, IRegistryQuerier registry, KspVersionCriteria curr // If not set in GUIMod(identifier, ...) (because the mod is not known to the registry), // set based on the the data we have from the CkanModule. - if (KSPCompatibilityVersion == null) + if (GameCompatibilityVersion == null) { - KSPCompatibilityVersion = mod.LatestCompatibleKSP(); - KSPCompatibility = KSPCompatibilityVersion?.ToYalovString() ?? Properties.Resources.GUIModUnknown; - KSPCompatibilityLong = string.Format( - Properties.Resources.GUIModKSPCompatibilityLong, - KSPCompatibility, + GameCompatibilityVersion = mod.LatestCompatibleKSP(); + GameCompatibility = GameCompatibilityVersion?.ToYalovString() ?? Properties.Resources.GUIModUnknown; + GameCompatibilityLong = string.Format( + Properties.Resources.GUIModGameCompatibilityLong, + GameCompatibility, mod.version ); } @@ -193,9 +193,9 @@ public GUIMod(CkanModule mod, IRegistryQuerier registry, KspVersionCriteria curr /// /// The id of the module to represent /// CKAN registry object for current game instance - /// Current game version + /// Current game version /// If true, mark this module as incompatible - public GUIMod(string identifier, IRegistryQuerier registry, KspVersionCriteria current_ksp_version, bool? incompatible = null) + public GUIMod(string identifier, IRegistryQuerier registry, GameVersionCriteria current_game_version, bool? incompatible = null) { Identifier = identifier; IsAutodetected = registry.IsAutodetected(identifier); @@ -208,7 +208,7 @@ public GUIMod(string identifier, IRegistryQuerier registry, KspVersionCriteria c ModuleVersion latest_version = null; try { - LatestCompatibleMod = registry.LatestAvailable(identifier, current_ksp_version); + LatestCompatibleMod = registry.LatestAvailable(identifier, current_game_version); latest_version = LatestCompatibleMod?.version; } catch (ModuleNotFoundKraken) @@ -233,10 +233,10 @@ public GUIMod(string identifier, IRegistryQuerier registry, KspVersionCriteria c // KSP. if (latest_available_for_any_ksp != null) { - KSPCompatibilityVersion = registry.LatestCompatibleKSP(identifier); - KSPCompatibility = KSPCompatibilityVersion?.ToYalovString() + GameCompatibilityVersion = registry.LatestCompatibleKSP(identifier); + GameCompatibility = GameCompatibilityVersion?.ToYalovString() ?? Properties.Resources.GUIModUnknown; - KSPCompatibilityLong = string.Format(Properties.Resources.GUIModKSPCompatibilityLong, KSPCompatibility, latest_available_for_any_ksp.version); + GameCompatibilityLong = string.Format(Properties.Resources.GUIModGameCompatibilityLong, GameCompatibility, latest_available_for_any_ksp.version); } if (latest_version != null) diff --git a/GUI/Model/ModList.cs b/GUI/Model/ModList.cs index 4eb58a3f2f..c88828cfcd 100644 --- a/GUI/Model/ModList.cs +++ b/GUI/Model/ModList.cs @@ -109,11 +109,11 @@ public void SetSearch(ModSearch newSearch) /// /// /// - /// A module installer for the current KSP install - /// The version of the current KSP install + /// A module installer for the current game instance + /// The version of the current game instance public IEnumerable ComputeChangeSetFromModList( IRegistryQuerier registry, HashSet changeSet, ModuleInstaller installer, - KspVersionCriteria version) + GameVersionCriteria version) { var modules_to_install = new HashSet(); var modules_to_remove = new HashSet(); @@ -342,7 +342,7 @@ private DataGridViewRow MakeRow(GUIMod mod, List changes, string inst }; var downloadCount = new DataGridViewTextBoxCell { Value = $"{mod.DownloadCount:N0}" }; - var compat = new DataGridViewTextBoxCell { Value = mod.KSPCompatibility }; + var compat = new DataGridViewTextBoxCell { Value = mod.GameCompatibility }; var size = new DataGridViewTextBoxCell { Value = mod.DownloadSize }; var releaseDate = new DataGridViewTextBoxCell { Value = mod.ToModule().release_date }; var installDate = new DataGridViewTextBoxCell { Value = mod.InstallDate }; @@ -429,7 +429,7 @@ private bool IsModInFilter(GUIModFilter filter, ModuleTag tag, ModuleLabel label } public static Dictionary ComputeConflictsFromModList(IRegistryQuerier registry, - IEnumerable change_set, KspVersionCriteria ksp_version) + IEnumerable change_set, GameVersionCriteria ksp_version) { var modules_to_install = new HashSet(); var modules_to_remove = new HashSet(); diff --git a/GUI/Program.cs b/GUI/Program.cs index 751f36b4d8..56b229b18b 100644 --- a/GUI/Program.cs +++ b/GUI/Program.cs @@ -15,7 +15,7 @@ public static void Main(string[] args) Main_(args); } - public static void Main_(string[] args, KSPManager manager = null, bool showConsole = false) + public static void Main_(string[] args, GameInstanceManager manager = null, bool showConsole = false) { Logging.Initialize(); diff --git a/GUI/Properties/Resources.Designer.cs b/GUI/Properties/Resources.Designer.cs index f25b7be4c9..e6645c54a1 100644 --- a/GUI/Properties/Resources.Designer.cs +++ b/GUI/Properties/Resources.Designer.cs @@ -258,8 +258,8 @@ internal static string AboutDialogLabel2Text { get { return (string)(ResourceManager.GetObject("AboutDialogLabel2Text", resourceCulture)); } } - internal static string CloneFakeKspDialogOpenFilter { - get { return (string)(ResourceManager.GetObject("CloneFakeKspDialogOpenFilter", resourceCulture)); } + internal static string BuildIDFilterDescription { + get { return (string)(ResourceManager.GetObject("BuildIDFilterDescription", resourceCulture)); } } internal static string CloneFakeKspDialogEnterName { get { return (string)(ResourceManager.GetObject("CloneFakeKspDialogEnterName", resourceCulture)); } @@ -298,20 +298,20 @@ internal static string CloneFakeKspDialogSuccessfulCreate { get { return (string)(ResourceManager.GetObject("CloneFakeKspDialogSuccessfulCreate", resourceCulture)); } } - internal static string CompatibleKspVersionsDialogNone { - get { return (string)(ResourceManager.GetObject("CompatibleKspVersionsDialogNone", resourceCulture)); } + internal static string CompatibleGameVersionsDialogNone { + get { return (string)(ResourceManager.GetObject("CompatibleGameVersionsDialogNone", resourceCulture)); } } - internal static string CompatibleKspVersionsDialogKSPUpdated { - get { return (string)(ResourceManager.GetObject("CompatibleKspVersionsDialogKSPUpdated", resourceCulture)); } + internal static string CompatibleGameVersionsDialogGameUpdated { + get { return (string)(ResourceManager.GetObject("CompatibleGameVersionsDialogGameUpdated", resourceCulture)); } } - internal static string CompatibleKspVersionsDialogVersionDetails { - get { return (string)(ResourceManager.GetObject("CompatibleKspVersionsDialogVersionDetails", resourceCulture)); } + internal static string CompatibleGameVersionsDialogVersionDetails { + get { return (string)(ResourceManager.GetObject("CompatibleGameVersionsDialogVersionDetails", resourceCulture)); } } - internal static string CompatibleKspVersionsDialogInvalidFormat { - get { return (string)(ResourceManager.GetObject("CompatibleKspVersionsDialogInvalidFormat", resourceCulture)); } + internal static string CompatibleGameVersionsDialogInvalidFormat { + get { return (string)(ResourceManager.GetObject("CompatibleGameVersionsDialogInvalidFormat", resourceCulture)); } } - internal static string CompatibleKspVersionsDialogErrorTitle { - get { return (string)(ResourceManager.GetObject("CompatibleKspVersionsDialogErrorTitle", resourceCulture)); } + internal static string CompatibleGameVersionsDialogErrorTitle { + get { return (string)(ResourceManager.GetObject("CompatibleGameVersionsDialogErrorTitle", resourceCulture)); } } internal static string ConfigurationParseError { @@ -327,8 +327,8 @@ internal static string GUIModUnknown { internal static string GUIModMethodNotCKAN { get { return (string)(ResourceManager.GetObject("GUIModMethodNotCKAN", resourceCulture)); } } - internal static string GUIModKSPCompatibilityLong { - get { return (string)(ResourceManager.GetObject("GUIModKSPCompatibilityLong", resourceCulture)); } + internal static string GUIModGameCompatibilityLong { + get { return (string)(ResourceManager.GetObject("GUIModGameCompatibilityLong", resourceCulture)); } } internal static string MainAutoUpdateFailed { @@ -722,12 +722,12 @@ internal static string MainWaitDone { get { return (string)(ResourceManager.GetObject("MainWaitDone", resourceCulture)); } } - internal static string ManageKspInstancesNotValid { - get { return (string)(ResourceManager.GetObject("ManageKspInstancesNotValid", resourceCulture)); } + internal static string ManageGameInstancesNotValid { + get { return (string)(ResourceManager.GetObject("ManageGameInstancesNotValid", resourceCulture)); } } - internal static string ManageKspInstancesDirectoryDeleted { - get { return (string)(ResourceManager.GetObject("ManageKspInstancesDirectoryDeleted", resourceCulture)); } + internal static string ManageGameInstancesDirectoryDeleted { + get { return (string)(ResourceManager.GetObject("ManageGameInstancesDirectoryDeleted", resourceCulture)); } } internal static string NewRepoDialogFailed { @@ -875,8 +875,8 @@ internal static string EditModpackBadName { internal static string EditModpackBadVersion { get { return (string)(ResourceManager.GetObject("EditModpackBadVersion", resourceCulture)); } } - internal static string EditModpackBadKspVersions { - get { return (string)(ResourceManager.GetObject("EditModpackBadKspVersions", resourceCulture)); } + internal static string EditModpackBadGameVersions { + get { return (string)(ResourceManager.GetObject("EditModpackBadGameVersions", resourceCulture)); } } internal static string EditModpackTooltipIdentifier { get { return (string)(ResourceManager.GetObject("EditModpackTooltipIdentifier", resourceCulture)); } @@ -890,11 +890,11 @@ internal static string EditModpackTooltipAbstract { internal static string EditModpackTooltipVersion { get { return (string)(ResourceManager.GetObject("EditModpackTooltipVersion", resourceCulture)); } } - internal static string EditModpackTooltipKspVersionMin { - get { return (string)(ResourceManager.GetObject("EditModpackTooltipKspVersionMin", resourceCulture)); } + internal static string EditModpackTooltipGameVersionMin { + get { return (string)(ResourceManager.GetObject("EditModpackTooltipGameVersionMin", resourceCulture)); } } - internal static string EditModpackTooltipKspVersionMax { - get { return (string)(ResourceManager.GetObject("EditModpackTooltipKspVersionMax", resourceCulture)); } + internal static string EditModpackTooltipGameVersionMax { + get { return (string)(ResourceManager.GetObject("EditModpackTooltipGameVersionMax", resourceCulture)); } } internal static string EditModpackTooltipLicense { get { return (string)(ResourceManager.GetObject("EditModpackTooltipLicense", resourceCulture)); } diff --git a/GUI/Properties/Resources.de-DE.resx b/GUI/Properties/Resources.de-DE.resx index db6390eb04..aa0bff7825 100644 --- a/GUI/Properties/Resources.de-DE.resx +++ b/GUI/Properties/Resources.de-DE.resx @@ -112,7 +112,7 @@ CKAN Metadaten (*.ckan)|*.ckan Export der Modliste - Build-Metadatendatei (buildID*.txt)|buildID*.txt + Build-Metadatendatei Bitte gib einen Namen für die neue Instanz an. Bitte gib einen Pfad für die neue Instanz an. Klone Instanz... @@ -125,15 +125,15 @@ Dieser Name wird bereits verwendet. Die Erstellung einer gefälschten Instanz ist fehlgeschlagen: {0} Instanz erfolgreich erstellt. - KSP wurde aktualisiert, seit du zuletzt deine kompatiblen KSP-Versionen überprüft hast. Bitte stelle sicher, dass die Einstellungen noch korrekt sind. - {0} (vorherige Version: {1}) - Ungültiges Versionsformat - Fehler + Das Spiel wurde aktualisiert, seit du zuletzt deine kompatiblen Spielversionen überprüft hast. Bitte stelle sicher, dass die Einstellungen noch korrekt sind. + {0} (vorherige Version: {1}) + Ungültiges Versionsformat + Fehler Fehler beim Parsen von "{0}"{1} Versuche {2} aus {3} zu verschieben und CKAN neu zu starten. Unbekannt - {0} (bei Mod-Version {1}) + {0} (bei Mod-Version {1}) Fehler beim Auto-Update: {0} @@ -153,7 +153,7 @@ Versuche {2} aus {3} zu verschieben und CKAN neu zu starten. Aktualisiere CKAN Aktualisiere CKAN auf {0} - {0} ist abhängig von {1}, das nicht mit der aktuell installierten KSP-Version kompatibel ist. + {0} ist abhängig von {1}, das nicht mit der aktuell installierten Spielversion kompatibel ist. Filter (Alle) Filter (Inkompatibel) Filter (Installiert) @@ -168,13 +168,13 @@ Versuche {2} aus {3} zu verschieben und CKAN neu zu starten. Kategorie ({0}) Kategorie (Keine) - Einige installierte Module sind inkompatibel! Es ist möglicherweise nicht sicher, KSP zu starten. Trotzdem starten? + Einige installierte Module sind inkompatibel! Es ist möglicherweise nicht sicher, das Spiel zu starten. Trotzdem starten? {0} Starten - KSP konnte nicht gestartet werden. + Das Spiel konnte nicht gestartet werden. {0} @@ -193,8 +193,8 @@ Möchten Sie es wirklich installieren? Mod-Import Statuslog Statuslog - {0} erfordert {1}, ist aber nicht im Index aufgeführt oder nicht für die installierte KSP-Version verfügbar. - Modul {0} benötigt, aber es ist nicht im Index aufgeführt oder nicht für dies KSP-Version verfügbar. + {0} erfordert {1}, ist aber nicht im Index aufgeführt oder nicht für die installierte Spielversion verfügbar. + Modul {0} benötigt, aber es ist nicht im Index aufgeführt oder nicht für dies Spielversion verfügbar. Fehlerhafte Metadaten für das Modul {0} erkannt: {1} Oh nein! Wir haben versucht, eine Datei zu überschreiben, die einer anderen Mod gehört! @@ -304,8 +304,8 @@ Wenn du ein Fehler mit dem CKAN Client vermutest: https://github.com/KSP-CKAN/CK {0} Aktualisierung(en) verfügbar Bitte warten Alles erledigt! - "{0}" ist kein gültiges KSP-Verzeichnis. - Das Verzeichnis "{0}" existiert nicht. + "{0}" ist kein gültiges Spielverzeichnis. + Das Verzeichnis "{0}" existiert nicht. Die Master-Liste konnte nicht abgerufen werden. {0} Dateien, {1} Ungültiger Pfad: "{0}" @@ -329,7 +329,7 @@ Möchtest du CKAN dies erlauben? Wenn du auf Nein klickst, siehst du diese Nachricht nicht mehr. &Linkadresse kopieren - Spielinstanz: {0} (KSP {1}) + Spielinstanz: {0} ({1} {2}) Favoriten Versteckt Global @@ -347,7 +347,7 @@ Wenn du auf Nein klickst, siehst du diese Nachricht nicht mehr. Module mit diesem Label werden haben diese Hintergrundfarbe in der Modliste Instanz, für welche dieses Label verfügbar ist. Leerlassen, um es in allen Instanzen verfügbar zu haben Wenn diese Option aktiviert ist, werden Module mit diesem Label ausgeblendet - Wenn diese Option aktiviert ist, wird eine Benachrichtigung angezeigt, sobald das Modul für deine KSP-Version kompatibel wird + Wenn diese Option aktiviert ist, wird eine Benachrichtigung angezeigt, sobald das Modul für deine Spielversion kompatibel wird Wenn diese Option aktiviert ist, wird das Label von Modulen entfernt, sobald sie kompatibel werden Wenn diese Option aktiviert ist, wird eine Warnung angezeigt, wenn das Modul installiert werden soll Wenn diese Option aktiviert ist, wird das Label von dem Modul entfernt, wenn es installiert wurde @@ -359,13 +359,13 @@ Wenn du auf Nein klickst, siehst du diese Nachricht nicht mehr. Die Kennung darf nur aus Buchstaben, Zahlen und Bindestrichen bestehen, muss mindestens zwei Zeichen lang sein und darf nicht mit einem Bindestrich beginnen. Ein Name für das Modpack ist erforderlich. Eine Version für das Modpack ist erforderlich. - Die minimale KSP-Version muss kleiner oder gleich der maximalen KSP-Version sein. + Die minimale Spielversion muss kleiner oder gleich der maximalen Spielversion sein. Interne Kennung dieses Modpacks; Nur Buchstaben, Zahlen und Bindestriche Öffentlich sichtbarer Name dieses Modpacks Kurze Zusammenfassung dieses Modpacks Die Versionsnummer für dieses Modpack, nutze das heutige Datum um es später einfach zuordnen zu können. - Setze die früheste KSP-Version fest, unter der das Modpack installiert werden kann. Leer für unbeschränkt. - Setze die neusete KSP-Version fest, unter der das Modpack installiert werden kann. Leer für unbeschränkt. + Setze die früheste Spielversion fest, unter der das Modpack installiert werden kann. Leer für unbeschränkt. + Setze die neusete Spielversion fest, unter der das Modpack installiert werden kann. Leer für unbeschränkt. Die Lizenz für dieses Modpack Wenn diese Option aktiviert ist, wird bei jeder Mod die unten angezeigte Version mitgespeichert. Beim Importieren des Modpacks werden dann genau diese Versionen installiert. Speichere die ausgewählten Mods als Abhängigkeiten im Modpack. Diese Mods werden bei der Installation des Modpacks auf jeden Fall installiert. diff --git a/GUI/Properties/Resources.resx b/GUI/Properties/Resources.resx index 23cdafe983..4db10d71f9 100644 --- a/GUI/Properties/Resources.resx +++ b/GUI/Properties/Resources.resx @@ -140,7 +140,7 @@ ..\Resources\arrow_forward.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\arrow_upward.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a Version {0} - Build metadata file (buildID*.txt)|buildID*.txt + Build metadata file Please enter a name for the new instance. Please enter a path for the new instance. "Cloning instance..." @@ -153,17 +153,17 @@ This name is already used. Fake instance creation failed: {0} Successfully created instance. - <NONE> - KSP has been updated since you last reviewed your compatible KSP versions. Please make sure that settings are correct. - {0} (previous game version: {1}) - Version has invalid format - Error + <NONE> + The game has been updated since you last reviewed your compatible game versions. Please make sure that settings are correct. + {0} (previous game version: {1}) + Version has invalid format + Error Error trying to parse "{0}"{1} Try to move {2} out of {3} and restart CKAN. N/A Unknown Method can not be called unless IsCKAN - {0} (using mod version {1}) + {0} (using mod version {1}) Error in auto-update: {0} There are conflicts. Really quit? {0} Quit @@ -174,7 +174,7 @@ Try to move {2} out of {3} and restart CKAN. {0} Updating CKAN Upgrading CKAN to {0} - {0} depends on {1}, which is not compatible with the currently installed version of KSP + {0} depends on {1}, which is not compatible with the currently installed game version Filter (All) Filter (Incompatible) Filter (Installed) @@ -188,11 +188,11 @@ Try to move {2} out of {3} and restart CKAN. Label ({0}) Tag ({0}) Tag (Untagged) - Some installed modules are incompatible! It might not be safe to launch KSP. Really launch? + Some installed modules are incompatible! It might not be safe to launch game. Really launch? {0} Launch - Couldn't start KSP. + Couldn't start game. {0} CKAN modpack (*.ckan) @@ -218,8 +218,8 @@ Do you really want to install it? Mods (*.zip)|*.zip Status log Status log - {0} requires {1} but it is not listed in the index, or not available for your version of KSP. - Module {0} required but it is not listed in the index, or not available for your version of KSP. + {0} requires {1} but it is not listed in the index, or not available for your game version. + Module {0} required but it is not listed in the index, or not available for your game version. Bad metadata detected for module {0}: {1} Oh no! We tried to overwrite a file owned by another mod! Please try a `ckan update` and try again. @@ -329,8 +329,8 @@ If you suspect a bug in the client: https://github.com/KSP-CKAN/CKAN/issues/new/ {0} available update(s) Please wait All done! - Directory {0} is not a valid KSP directory. - Directory "{0}" doesn't exist. + Directory {0} is not a valid game directory. + Directory "{0}" doesn't exist. Failed to fetch master list. CKAN Plugins (*.dll)|*.dll {0} files, {1} @@ -351,7 +351,7 @@ Can't update automatically, because ckan.exe is read-only or we are not allowed CKAN requires permission to add a handler for ckan:// URLs. Do you want to allow CKAN to do this? If you click no you won't see this message again. &Copy link address - Game instance: {0} (KSP {1}) + Game instance: {0} ({1} {2}) Favourites Hidden Global @@ -381,13 +381,13 @@ Do you want to allow CKAN to do this? If you click no you won't see this message Identifier must contain ONLY letters, numbers, and dashes, and must start with a letter or number Name is required Version is required - Min KSP version must be less than or equal to max KSP version + Min game version must be less than or equal to max game version Internal name of this modpack; letters, numbers, and dashes only Publicly visible name of this modpack Short description of this modpack The version number for this modpack - Earliest compatible version of KSP, blank for all - Latest compatible version of KSP, blank for all + Earliest compatible game version, blank for all + Latest compatible game version, blank for all The licence for this modpack If checked, the modpack will include the specific versions of the mods shown, otherwise any version will do Move selected mods to the Depends group. These mods will definitely be installed. diff --git a/GUI/Properties/Resources.zh-CN.resx b/GUI/Properties/Resources.zh-CN.resx index 39436d349d..e961d107c9 100644 --- a/GUI/Properties/Resources.zh-CN.resx +++ b/GUI/Properties/Resources.zh-CN.resx @@ -121,7 +121,7 @@ CKAN元数据 (*.ckan)|*.ckan 导出Mod列表 版本 {0} - Build metadata file (buildID*.txt)|buildID*.txt + Build metadata file 请输入新实例名称. 请输入新实例路径. "正在克隆实例..." @@ -134,16 +134,16 @@ 该名称已被占用. 伪装实例创建失败: {0} 成功创建实例. - <NONE> - KSP已经在您上次确认您的兼容KSP版本后更新. 请确认设置是否正确. - {0} (上一个游戏版本: {1}) - 版本格式无效 - Error + <NONE> + 游戏已经在您上次确认您的兼容游戏版本后更新. 请确认设置是否正确. + {0} (上一个游戏版本: {1}) + 版本格式无效 + Error 尝试解析 "{0}"{1}时出现错误. 请尝试将其移出文件夹并重启CKAN. N/A 未知 Method can not be called unless IsCKAN - {0} (正在使用的Mod版本: {1}) + {0} (正在使用的Mod版本: {1}) 自动更新错误: {0} 存在冲突. 真的要退出吗? {0} 退出 @@ -154,7 +154,7 @@ {0} 正在更新CKAN 更新CKAN到 {0} - {0} 依赖于 {1}, 而它并不与当前安装的KSP版本兼容 + {0} 依赖于 {1}, 而它并不与当前安装的游戏版本兼容 筛选 (全部) 筛选 (不兼容) 筛选 (已安装) @@ -168,11 +168,11 @@ 标签 ({0}) 分类 ({0}) 分类 (未分类) - 有一些安装的Mod不兼容!启动KSP可能不安全. 真的要启动吗? + 有一些安装的Mod不兼容!启动游戏可能不安全. 真的要启动吗? {0} 启动 - 无法启动KSP. + 无法启动游戏. {0} CKAN modpack (*.ckan) @@ -197,8 +197,8 @@ Mods (*.zip)|*.zip 状态日志 状态日志 - {0} 需要 {1} 但它未在索引中列出或不兼容您当前的KSP版本. - 需要Mod {0} 但它未在索引中列出或不兼容您当前的KSP版本. + {0} 需要 {1} 但它未在索引中列出或不兼容您当前的游戏版本. + 需要Mod {0} 但它未在索引中列出或不兼容您当前的游戏版本. 检测到损坏的元数据,来自Mod {0}: {1} 哦不! 我们尝试去覆写其它Mod的文件! 请尝试 `ckan更新` 并重试. @@ -293,8 +293,8 @@ CKAN Version(CKAN版本) : {3} {0} 个可用更新 请稍候 已完成! - 目录 {0} 并非有效的KSP目录. - 目录 "{0}" 不存在. + 目录 {0} 并非有效的游戏目录. + 目录 "{0}" 不存在. 同步主列表失败. CKAN Plugins (*.dll)|*.dll {0} 个文件, {1} @@ -315,7 +315,7 @@ CKAN Version(CKAN版本) : {3} CKAN需要处理 ckan:// URLs 的权限. 您想要允许CKAN这么做吗? 如果您点击否您将不会再次看到此消息. &复制链接地址 - 游戏实例: {0} (KSP {1}) + 游戏实例: {0} ({1} {2}) 收藏 隐藏 全局 @@ -345,13 +345,13 @@ CKAN Version(CKAN版本) : {3} 标识符必须包含一个或多个字母、数字及横杠,并必须以字母或数字开头 需要名称 需要版本 - 最低KSP版本必须小于或等于最高KSP版本 + 最低游戏版本必须小于或等于最高游戏版本 该Mod包的内部名称;仅限字母、数字和横杠 该Mod包的公开名称 Mod包的简短描述 Mod包版本号 - 最低兼容KSP版本,留空以应用全部 - 最高兼容KSP版本,留空以应用全部 + 最低兼容游戏版本,留空以应用全部 + 最高兼容游戏版本,留空以应用全部 该Mod包的协议 如果勾选,Mod包将会包括特定版本的Mod,否则任何版本均可用 移动选中Mod到依赖组. 这些Mod一定会被安装. diff --git a/Netkan/CKAN-netkan.csproj b/Netkan/CKAN-netkan.csproj index 9ca48dacf8..016e37467b 100644 --- a/Netkan/CKAN-netkan.csproj +++ b/Netkan/CKAN-netkan.csproj @@ -76,7 +76,7 @@ - + diff --git a/Netkan/Processors/Inflator.cs b/Netkan/Processors/Inflator.cs index 947f49dfa9..22b82bf327 100644 --- a/Netkan/Processors/Inflator.cs +++ b/Netkan/Processors/Inflator.cs @@ -19,7 +19,7 @@ public Inflator(string cacheDir, bool overwriteCache, string githubToken, bool p { log.Debug("Initializing inflator"); cache = FindCache( - new KSPManager(new ConsoleUser(false)), + new GameInstanceManager(new ConsoleUser(false)), ServiceLocator.Container.Resolve(), cacheDir ); @@ -68,7 +68,7 @@ internal void ValidateCkan(Metadata ckan) ckanValidator.Validate(ckan); } - private static NetFileCache FindCache(KSPManager kspManager, IConfiguration cfg, string cacheDir) + private static NetFileCache FindCache(GameInstanceManager kspManager, IConfiguration cfg, string cacheDir) { if (cacheDir != null) { diff --git a/Netkan/Services/IModuleService.cs b/Netkan/Services/IModuleService.cs index cc399309a3..57577ae604 100644 --- a/Netkan/Services/IModuleService.cs +++ b/Netkan/Services/IModuleService.cs @@ -11,9 +11,9 @@ internal interface IModuleService JObject GetInternalCkan(string filePath); bool HasInstallableFiles(CkanModule module, string filePath); - IEnumerable GetConfigFiles(CkanModule module, ZipFile zip, KSP ksp); - IEnumerable GetPlugins(CkanModule module, ZipFile zip, KSP ksp); - IEnumerable GetCrafts(CkanModule module, ZipFile zip, KSP ksp); + IEnumerable GetConfigFiles(CkanModule module, ZipFile zip, GameInstance inst); + IEnumerable GetPlugins(CkanModule module, ZipFile zip, GameInstance inst); + IEnumerable GetCrafts(CkanModule module, ZipFile zip, GameInstance ksp); IEnumerable FileDestinations(CkanModule module, string filePath); } diff --git a/Netkan/Services/ModuleService.cs b/Netkan/Services/ModuleService.cs index fa549c2fdf..39a28ae40a 100644 --- a/Netkan/Services/ModuleService.cs +++ b/Netkan/Services/ModuleService.cs @@ -10,6 +10,7 @@ using CKAN.Extensions; using CKAN.NetKAN.Sources.Avc; +using CKAN.Games; namespace CKAN.NetKAN.Services { @@ -53,7 +54,8 @@ public bool HasInstallableFiles(CkanModule module, string filePath) { try { - ModuleInstaller.FindInstallableFiles(module, filePath, null); + ModuleInstaller.FindInstallableFiles(module, filePath, + new GameInstance(new KerbalSpaceProgram(), "/", "dummy", new NullUser())); } catch (BadMetadataKraken) { @@ -64,22 +66,22 @@ public bool HasInstallableFiles(CkanModule module, string filePath) return true; } - public IEnumerable GetConfigFiles(CkanModule module, ZipFile zip, KSP ksp) + public IEnumerable GetConfigFiles(CkanModule module, ZipFile zip, GameInstance inst) { - return GetFilesBySuffix(module, zip, ".cfg", ksp); + return GetFilesBySuffix(module, zip, ".cfg", inst); } - public IEnumerable GetPlugins(CkanModule module, ZipFile zip, KSP ksp) + public IEnumerable GetPlugins(CkanModule module, ZipFile zip, GameInstance inst) { - return GetFilesBySuffix(module, zip, ".dll", ksp); + return GetFilesBySuffix(module, zip, ".dll", inst); } - public IEnumerable GetCrafts(CkanModule module, ZipFile zip, KSP ksp) + public IEnumerable GetCrafts(CkanModule module, ZipFile zip, GameInstance ksp) { return GetFilesBySuffix(module, zip, ".craft", ksp); } - private IEnumerable GetFilesBySuffix(CkanModule module, ZipFile zip, string suffix, KSP ksp) + private IEnumerable GetFilesBySuffix(CkanModule module, ZipFile zip, string suffix, GameInstance ksp) { return ModuleInstaller .FindInstallableFiles(module, zip, ksp) @@ -89,7 +91,7 @@ private IEnumerable GetFilesBySuffix(CkanModule module, ZipFile public IEnumerable FileDestinations(CkanModule module, string filePath) { - var ksp = new KSP("/", "dummy", null, false); + var ksp = new GameInstance(new KerbalSpaceProgram(), "/", "dummy", null, false); return ModuleInstaller .FindInstallableFiles(module, filePath, ksp) .Where(f => !f.source.IsDirectory) @@ -127,7 +129,8 @@ private static AvcVersion GetInternalAvc(CkanModule module, ZipFile zipfile, str const string versionExt = ".version"; // Get all our version files. - var files = ModuleInstaller.FindInstallableFiles(module, zipfile, null) + var ksp = new GameInstance(new KerbalSpaceProgram(), "/", "dummy", new NullUser()); + var files = ModuleInstaller.FindInstallableFiles(module, zipfile, ksp) .Select(x => x.source) .Where(source => source.Name.EndsWith(versionExt, StringComparison.InvariantCultureIgnoreCase)) diff --git a/Netkan/Sources/Avc/AvcVersion.cs b/Netkan/Sources/Avc/AvcVersion.cs index 696c356d9d..152cdb0ed7 100644 --- a/Netkan/Sources/Avc/AvcVersion.cs +++ b/Netkan/Sources/Avc/AvcVersion.cs @@ -20,14 +20,14 @@ public class AvcVersion [JsonConverter(typeof(JsonAvcToVersion))] public ModuleVersion version; - [JsonConverter(typeof(JsonAvcToKspVersion))] - public KspVersion ksp_version; + [JsonConverter(typeof(JsonAvcToGameVersion))] + public GameVersion ksp_version; - [JsonConverter(typeof(JsonAvcToKspVersion))] - public KspVersion ksp_version_min; + [JsonConverter(typeof(JsonAvcToGameVersion))] + public GameVersion ksp_version_min; - [JsonConverter(typeof(JsonAvcToKspVersion))] - public KspVersion ksp_version_max; + [JsonConverter(typeof(JsonAvcToGameVersion))] + public GameVersion ksp_version_max; } diff --git a/Netkan/Sources/Avc/JsonAvcToKspVersion.cs b/Netkan/Sources/Avc/JsonAvcToGameVersion.cs similarity index 96% rename from Netkan/Sources/Avc/JsonAvcToKspVersion.cs rename to Netkan/Sources/Avc/JsonAvcToGameVersion.cs index 2d222074b4..8b37c07a88 100644 --- a/Netkan/Sources/Avc/JsonAvcToKspVersion.cs +++ b/Netkan/Sources/Avc/JsonAvcToGameVersion.cs @@ -10,9 +10,9 @@ namespace CKAN.NetKAN.Sources.Avc /// /// Converts AVC style KSP versions into CKAN ones. /// - public class JsonAvcToKspVersion : JsonConverter + public class JsonAvcToGameVersion : JsonConverter { - private static readonly ILog Log = LogManager.GetLogger(typeof (JsonAvcToKspVersion)); + private static readonly ILog Log = LogManager.GetLogger(typeof (JsonAvcToGameVersion)); private const int AvcWildcard = -1; public override bool CanConvert(Type objectType) @@ -64,7 +64,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist string version; if (major == null || int.TryParse(major, out integer) && integer == AvcWildcard) { - return KspVersion.Any; + return GameVersion.Any; } else if (minor == null || int.TryParse(minor, out integer) && integer == AvcWildcard) { @@ -80,7 +80,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist } Log.DebugFormat(" extracted version: {0}", version); - var result = KspVersion.Parse(version); + var result = GameVersion.Parse(version); Log.DebugFormat(" generated result: {0}", result); return result; } @@ -101,7 +101,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// public class JsonAvcToVersion : JsonConverter { - private static readonly ILog Log = LogManager.GetLogger(typeof (JsonAvcToKspVersion)); + private static readonly ILog Log = LogManager.GetLogger(typeof (JsonAvcToGameVersion)); public override bool CanConvert(Type objectType) { diff --git a/Netkan/Sources/Curse/CurseFile.cs b/Netkan/Sources/Curse/CurseFile.cs index 707e5de41a..2abfa628aa 100755 --- a/Netkan/Sources/Curse/CurseFile.cs +++ b/Netkan/Sources/Curse/CurseFile.cs @@ -9,11 +9,11 @@ namespace CKAN.NetKAN.Sources.Curse { public class CurseFile { - [JsonConverter(typeof(JsonConvertKSPVersion))] - [JsonProperty] public KspVersion version; + [JsonConverter(typeof(JsonConvertGameVersion))] + [JsonProperty] public GameVersion version; - [JsonConverter(typeof(JsonConvertKSPVersion))] - [JsonProperty] public KspVersion[] versions; + [JsonConverter(typeof(JsonConvertGameVersion))] + [JsonProperty] public GameVersion[] versions; [JsonProperty] public string name = ""; [JsonProperty] public string type; @@ -102,7 +102,7 @@ public void SetFileVersion(string version) /// Curse has versions that don't play nicely with CKAN, for example "1.1-prerelease". /// This transformer strips out the dash and anything after it. /// - internal class JsonConvertKSPVersion : JsonConverter + internal class JsonConvertGameVersion : JsonConverter { public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer @@ -112,7 +112,7 @@ public override object ReadJson( { return JArray.Load(reader) .Values() - .Select(v => KspVersion.Parse(Regex.Replace(v, @"-.*$", ""))) + .Select(v => GameVersion.Parse(Regex.Replace(v, @"-.*$", ""))) .ToArray(); } else @@ -120,7 +120,7 @@ public override object ReadJson( if (reader.Value == null) return null; string raw_version = reader.Value.ToString(); - return KspVersion.Parse(Regex.Replace(raw_version, @"-.*$", "")); + return GameVersion.Parse(Regex.Replace(raw_version, @"-.*$", "")); } } diff --git a/Netkan/Sources/Spacedock/SDVersion.cs b/Netkan/Sources/Spacedock/SDVersion.cs index 6cb90fbcf4..1310af152b 100644 --- a/Netkan/Sources/Spacedock/SDVersion.cs +++ b/Netkan/Sources/Spacedock/SDVersion.cs @@ -12,9 +12,9 @@ public class SDVersion // These all get filled by JSON deserialisation. - [JsonConverter(typeof(JsonConvertKSPVersion))] + [JsonConverter(typeof(JsonConvertGameVersion))] [JsonProperty("game_version")] - public KspVersion KSP_version; + public GameVersion KSP_version; public string changelog; public DateTime? created; @@ -31,7 +31,7 @@ public class SDVersion /// will work with more versions than they actually will. This converter /// puts the .0 back on when appropriate. GH #1156. /// - internal class JsonConvertKSPVersion : JsonConverter + internal class JsonConvertGameVersion : JsonConverter { public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer @@ -42,7 +42,7 @@ public override object ReadJson( string raw_version = reader.Value.ToString(); - return KspVersion.Parse(ExpandVersionIfNeeded(raw_version)); + return GameVersion.Parse(ExpandVersionIfNeeded(raw_version)); } /// diff --git a/Netkan/Transformers/AvcTransformer.cs b/Netkan/Transformers/AvcTransformer.cs index 37cbc36571..1d134c3c49 100644 --- a/Netkan/Transformers/AvcTransformer.cs +++ b/Netkan/Transformers/AvcTransformer.cs @@ -126,8 +126,8 @@ public static void ApplyVersions(JObject json, AvcVersion avc) var existingKspMinStr = (string)json["ksp_version_min"] ?? (string)json["ksp_version"]; var existingKspMaxStr = (string)json["ksp_version_max"] ?? (string)json["ksp_version"]; - var existingKspMin = existingKspMinStr == null ? null : KspVersion.Parse(existingKspMinStr); - var existingKspMax = existingKspMaxStr == null ? null : KspVersion.Parse(existingKspMaxStr); + var existingKspMin = existingKspMinStr == null ? null : GameVersion.Parse(existingKspMinStr); + var existingKspMax = existingKspMaxStr == null ? null : GameVersion.Parse(existingKspMaxStr); // Get the minimum and maximum KSP versions that are in the AVC file. // https://github.com/linuxgurugamer/KSPAddonVersionChecker/blob/master/KSP-AVC.schema.json @@ -136,7 +136,7 @@ public static void ApplyVersions(JObject json, AvcVersion avc) // its equivalent properties as mutually exclusive. // Only fallback if neither min nor max are defined, // for open ranges. - KspVersion avcKspMin, avcKspMax; + GameVersion avcKspMin, avcKspMax; if (avc.ksp_version_min == null && avc.ksp_version_max == null) { // Use specific KSP version if min/max don't exist @@ -150,19 +150,19 @@ public static void ApplyVersions(JObject json, AvcVersion avc) // Now calculate the minimum and maximum KSP versions between both the existing metadata and the // AVC file. - var kspMins = new List(); - var kspMaxes = new List(); + var kspMins = new List(); + var kspMaxes = new List(); - if (!KspVersion.IsNullOrAny(existingKspMin)) + if (!GameVersion.IsNullOrAny(existingKspMin)) kspMins.Add(existingKspMin); - if (!KspVersion.IsNullOrAny(avcKspMin)) + if (!GameVersion.IsNullOrAny(avcKspMin)) kspMins.Add(avcKspMin); - if (!KspVersion.IsNullOrAny(existingKspMax)) + if (!GameVersion.IsNullOrAny(existingKspMax)) kspMaxes.Add(existingKspMax); - if (!KspVersion.IsNullOrAny(avcKspMax)) + if (!GameVersion.IsNullOrAny(avcKspMax)) kspMaxes.Add(avcKspMax); var kspMin = kspMins.Any() ? kspMins.Min() : null; diff --git a/Netkan/Transformers/CurseTransformer.cs b/Netkan/Transformers/CurseTransformer.cs index b74dc772de..bbec42cde2 100755 --- a/Netkan/Transformers/CurseTransformer.cs +++ b/Netkan/Transformers/CurseTransformer.cs @@ -72,8 +72,8 @@ private Metadata TransformOne(JObject json, CurseMod curseMod, CurseFile latestV // Only pre-fill version info if there's none already. GH #199 if (json["ksp_version_min"] == null && json["ksp_version_max"] == null && json["ksp_version"] == null) { - KspVersion minVer = latestVersion.versions.Min(); - KspVersion maxVer = latestVersion.versions.Max(); + GameVersion minVer = latestVersion.versions.Min(); + GameVersion maxVer = latestVersion.versions.Max(); if (minVer == maxVer) { Log.DebugFormat("Writing ksp_version from Curse: {0}", latestVersion.version); diff --git a/Netkan/Transformers/LocalizationsTransformer.cs b/Netkan/Transformers/LocalizationsTransformer.cs index ad7582a4c9..652616ef5a 100644 --- a/Netkan/Transformers/LocalizationsTransformer.cs +++ b/Netkan/Transformers/LocalizationsTransformer.cs @@ -9,6 +9,7 @@ using CKAN.NetKAN.Extensions; using CKAN.NetKAN.Model; using CKAN.NetKAN.Services; +using CKAN.Games; namespace CKAN.NetKAN.Transformers { @@ -51,11 +52,11 @@ public IEnumerable Transform(Metadata metadata, TransformOptions opts) { CkanModule mod = CkanModule.FromJson(json.ToString()); ZipFile zip = new ZipFile(_http.DownloadModule(metadata)); - var ksp = new KSP("/", "dummy", null, false); + GameInstance inst = new GameInstance(new KerbalSpaceProgram(), "/", "dummy", new NullUser()); log.Debug("Extracting locales"); // Extract the locale names from the ZIP's cfg files - var locales = _moduleService.GetConfigFiles(mod, zip, ksp) + var locales = _moduleService.GetConfigFiles(mod, zip, inst) .Select(cfg => new StreamReader(zip.GetInputStream(cfg.source)).ReadToEnd()) .SelectMany(contents => localizationRegex.Matches(contents).Cast() .Select(m => m.Groups["contents"].Value)) diff --git a/Netkan/Transformers/StagingTransformer.cs b/Netkan/Transformers/StagingTransformer.cs index 77ab076ad5..90060e0094 100644 --- a/Netkan/Transformers/StagingTransformer.cs +++ b/Netkan/Transformers/StagingTransformer.cs @@ -6,6 +6,7 @@ using CKAN.Extensions; using CKAN.GameVersionProviders; using CKAN.Versioning; +using CKAN.Games; using CKAN.NetKAN.Model; namespace CKAN.NetKAN.Transformers @@ -14,9 +15,7 @@ internal sealed class StagingTransformer : ITransformer { public StagingTransformer() { - IKspBuildMap builds = ServiceLocator.Container.Resolve(); - builds.Refresh(BuildMapSource.Embedded); - currentRelease = builds.KnownVersions.Max().ToVersionRange(); + currentRelease = new KerbalSpaceProgram().KnownVersions.Max().ToVersionRange(); } public string Name { get { return "staging"; } } @@ -38,11 +37,12 @@ private bool VersionsNeedManualReview(Metadata metadata, out string reason) JObject json = metadata.Json(); var minStr = json["ksp_version_min"] ?? json["ksp_version"]; var maxStr = json["ksp_version_max"] ?? json["ksp_version"]; - var minVer = minStr == null ? KspVersion.Any : KspVersion.Parse((string)minStr); - var maxVer = maxStr == null ? KspVersion.Any : KspVersion.Parse((string)maxStr); - if (currentRelease.IntersectWith(new KspVersionRange(minVer, maxVer)) == null) + var minVer = minStr == null ? GameVersion.Any : GameVersion.Parse((string)minStr); + var maxVer = maxStr == null ? GameVersion.Any : GameVersion.Parse((string)maxStr); + if (currentRelease.IntersectWith(new GameVersionRange(minVer, maxVer)) == null) { - reason = $"Hard-coded game versions not compatible with current release: {KspVersionRange.VersionSpan(minVer, maxVer)}\r\nPlease check that they match the forum thread."; + var game = new KerbalSpaceProgram(); + reason = $"Hard-coded game versions not compatible with current release: {GameVersionRange.VersionSpan(game, minVer, maxVer)}\r\nPlease check that they match the forum thread."; return true; } else @@ -53,7 +53,7 @@ private bool VersionsNeedManualReview(Metadata metadata, out string reason) } } - private static KspVersionRange currentRelease; + private static GameVersionRange currentRelease; private static readonly ILog Log = LogManager.GetLogger(typeof(StagingTransformer)); } } diff --git a/Netkan/Validators/CraftsInShipsValidator.cs b/Netkan/Validators/CraftsInShipsValidator.cs index fe25da4b27..c986962015 100644 --- a/Netkan/Validators/CraftsInShipsValidator.cs +++ b/Netkan/Validators/CraftsInShipsValidator.cs @@ -6,6 +6,7 @@ using log4net; using CKAN.NetKAN.Services; using CKAN.NetKAN.Model; +using CKAN.Games; namespace CKAN.NetKAN.Validators { @@ -29,9 +30,9 @@ public void Validate(Metadata metadata) if (!string.IsNullOrEmpty(package)) { var zip = new ZipFile(package); - var ksp = new KSP("/", "dummy", null, false); - var badCrafts = _moduleService.GetCrafts(mod, zip, ksp) - .Where(f => !AllowedCraftPath(ksp.ToRelativeGameDir(f.destination))) + var inst = new GameInstance(new KerbalSpaceProgram(), "/", "dummy", null, false); + var badCrafts = _moduleService.GetCrafts(mod, zip, inst) + .Where(f => !AllowedCraftPath(inst.ToRelativeGameDir(f.destination))) .ToList(); if (badCrafts.Any()) @@ -39,7 +40,7 @@ public void Validate(Metadata metadata) Log.WarnFormat( "Craft files installed outside Ships folder: {0}", string.Join(", ", badCrafts.Select(f => - ksp.ToRelativeGameDir(f.destination) + inst.ToRelativeGameDir(f.destination) )) ); } diff --git a/Netkan/Validators/InstallValidator.cs b/Netkan/Validators/InstallValidator.cs index 1b4715177a..6e8a414568 100644 --- a/Netkan/Validators/InstallValidator.cs +++ b/Netkan/Validators/InstallValidator.cs @@ -52,7 +52,7 @@ public void Validate(Metadata metadata) if (stanza.ContainsKey(propName)) { string val = (string)stanza[propName]; - string norm = KSPPathUtils.NormalizePath(val); + string norm = CKANPathUtils.NormalizePath(val); if (val != norm) { throw new Kraken($"Path \"{val}\" in '{propName}' is not normalized, should be \"{norm}\""); diff --git a/Netkan/Validators/MatchesKnownGameVersionsValidator.cs b/Netkan/Validators/MatchesKnownGameVersionsValidator.cs index 7cbd6cde34..cc309198d4 100644 --- a/Netkan/Validators/MatchesKnownGameVersionsValidator.cs +++ b/Netkan/Validators/MatchesKnownGameVersionsValidator.cs @@ -2,6 +2,7 @@ using Autofac; using CKAN.GameVersionProviders; using CKAN.Versioning; +using CKAN.Games; using CKAN.NetKAN.Model; namespace CKAN.NetKAN.Validators @@ -10,21 +11,21 @@ internal sealed class MatchesKnownGameVersionsValidator : IValidator { public MatchesKnownGameVersionsValidator() { - buildMap = ServiceLocator.Container.Resolve(); - buildMap.Refresh(BuildMapSource.Embedded); + knownVersions = new KerbalSpaceProgram().KnownVersions; } public void Validate(Metadata metadata) { var mod = CkanModule.FromJson(metadata.Json().ToString()); - if (!mod.IsCompatibleKSP(new KspVersionCriteria(null, buildMap.KnownVersions))) + if (!mod.IsCompatibleKSP(new GameVersionCriteria(null, knownVersions))) { - KspVersion minKsp = null, maxKsp = null; + GameVersion minKsp = null, maxKsp = null; Registry.GetMinMaxVersions(new List() {mod}, out _, out _, out minKsp, out maxKsp); - throw new Kraken($"{metadata.Identifier} doesn't match any valid game version: {KspVersionRange.VersionSpan(minKsp, maxKsp)}"); + var game = new KerbalSpaceProgram(); + throw new Kraken($"{metadata.Identifier} doesn't match any valid game version: {GameVersionRange.VersionSpan(game, minKsp, maxKsp)}"); } } - private IKspBuildMap buildMap; + private List knownVersions; } } diff --git a/Netkan/Validators/ModuleManagerDependsValidator.cs b/Netkan/Validators/ModuleManagerDependsValidator.cs index 8364e6d19b..42a0304f35 100644 --- a/Netkan/Validators/ModuleManagerDependsValidator.cs +++ b/Netkan/Validators/ModuleManagerDependsValidator.cs @@ -7,6 +7,7 @@ using CKAN.NetKAN.Services; using CKAN.NetKAN.Model; using CKAN.Extensions; +using CKAN.Games; namespace CKAN.NetKAN.Validators { @@ -30,9 +31,8 @@ public void Validate(Metadata metadata) if (!string.IsNullOrEmpty(package)) { ZipFile zip = new ZipFile(package); - var ksp = new KSP("/", "dummy", null, false); - - var mmConfigs = _moduleService.GetConfigFiles(mod, zip, ksp) + GameInstance inst = new GameInstance(new KerbalSpaceProgram(), "/", "dummy", new NullUser()); + var mmConfigs = _moduleService.GetConfigFiles(mod, zip, inst) .Where(cfg => moduleManagerRegex.IsMatch( new StreamReader(zip.GetInputStream(cfg.source)).ReadToEnd())) .Memoize(); diff --git a/Netkan/Validators/PluginCompatibilityValidator.cs b/Netkan/Validators/PluginCompatibilityValidator.cs index 60f1828f3f..e29597e8d2 100644 --- a/Netkan/Validators/PluginCompatibilityValidator.cs +++ b/Netkan/Validators/PluginCompatibilityValidator.cs @@ -6,6 +6,7 @@ using log4net; using CKAN.NetKAN.Services; using CKAN.NetKAN.Model; +using CKAN.Games; namespace CKAN.NetKAN.Validators { @@ -28,10 +29,10 @@ public void Validate(Metadata metadata) var package = _http.DownloadModule(metadata); if (!string.IsNullOrEmpty(package)) { - ZipFile zip = new ZipFile(package); - var ksp = new KSP("/", "dummy", null, false); + ZipFile zip = new ZipFile(package); + GameInstance inst = new GameInstance(new KerbalSpaceProgram(), "/", "dummy", new NullUser()); - bool hasPlugin = _moduleService.GetPlugins(mod, zip, ksp).Any(); + bool hasPlugin = _moduleService.GetPlugins(mod, zip, inst).Any(); bool boundedCompatibility = json.ContainsKey("ksp_version") || json.ContainsKey("ksp_version_max"); diff --git a/Tests/Core/Configuration/FakeConfiguration.cs b/Tests/Core/Configuration/FakeConfiguration.cs index c46ea86750..3c2b92d75f 100644 --- a/Tests/Core/Configuration/FakeConfiguration.cs +++ b/Tests/Core/Configuration/FakeConfiguration.cs @@ -3,17 +3,18 @@ using System.IO; using System.Linq; using CKAN.Configuration; +using CKAN.GameVersionProviders; using Tests.Data; namespace Tests.Core.Configuration { public class FakeConfiguration : IConfiguration, IDisposable { - public FakeConfiguration(CKAN.KSP instance, string autostart) + public FakeConfiguration(CKAN.GameInstance instance, string autostart) : this( - new List> + new List> { - new Tuple("test", instance.GameDir()) + new Tuple("test", instance.GameDir(), "KSP") }, autostart ) @@ -25,7 +26,7 @@ public FakeConfiguration(CKAN.KSP instance, string autostart) /// /// List of name/path pairs for the instances /// The auto start instance to use - public FakeConfiguration(List> instances, string auto_start_instance) + public FakeConfiguration(List> instances, string auto_start_instance) { Instances = instances; AutoStartInstance = auto_start_instance; @@ -35,7 +36,7 @@ public FakeConfiguration(List> instances, string auto_star /// /// The instances in the fake registry /// - public List> Instances { get; set; } + public List> Instances { get; set; } /// /// Build map for the fake registry /// @@ -82,7 +83,7 @@ public string AutoStartInstance /// /// Name/path pair for the requested instance /// - public Tuple GetInstance(int i) + public Tuple GetInstance(int i) { return Instances[i]; } @@ -95,16 +96,16 @@ public Tuple GetInstance(int i) /// /// Returns /// - public void SetRegistryToInstances(SortedList instances) + public void SetRegistryToInstances(SortedList instances) { Instances = - instances.Select(kvpair => new Tuple(kvpair.Key, kvpair.Value.GameDir())).ToList(); + instances.Select(kvpair => new Tuple(kvpair.Key, kvpair.Value.GameDir(), "KSP")).ToList(); } /// /// The instances in the fake registry /// - public IEnumerable> GetInstances() + public IEnumerable> GetInstances() { return Instances; } diff --git a/Tests/Core/Configuration/JsonConfiguration.cs b/Tests/Core/Configuration/JsonConfiguration.cs index d5e47e2412..81f64b61a5 100644 --- a/Tests/Core/Configuration/JsonConfiguration.cs +++ b/Tests/Core/Configuration/JsonConfiguration.cs @@ -11,22 +11,6 @@ namespace Tests.Core.Configuration [TestFixture] public class JsonConfigurationTests { - // We want to make sure that the config file is pointed to the - // right place for the other tests. - private string configFileLoc; - - [SetUp] - public void SetUp() - { - configFileLoc = new JsonConfiguration().ConfigFile; - } - - [TearDown] - public void TearDown() - { - _ = new JsonConfiguration(configFileLoc); - } - [Test] public void CreatesNewConfig() { @@ -63,10 +47,10 @@ public void LoadsGoodConfig() var reg = new JsonConfiguration(tmpFile); - CollectionAssert.AreEquivalent(new List>() + CollectionAssert.AreEquivalent(new List>() { - new Tuple("instance1", "instance1_path"), - new Tuple("instance2", "instance2_path") + new Tuple("instance1", "instance1_path", "KSP"), + new Tuple("instance2", "instance2_path", "KSP") }, reg.GetInstances()); CollectionAssert.AreEquivalent(new List() @@ -89,12 +73,6 @@ public void LoadsGoodConfig() Assert.AreEqual(2, reg.CacheSizeLimit); Assert.AreEqual(4, reg.RefreshRate); - CollectionAssert.AreEquivalent(new Dictionary() - { - { "build1", "version1" }, - { "build2", "version2" } - }, reg.GetKSPBuilds().Builds); - File.Delete(tmpFile); } @@ -106,10 +84,10 @@ public void LoadsMissingJsonConfig() var reg = new JsonConfiguration(tmpFile); - CollectionAssert.AreEquivalent(new List>() + CollectionAssert.AreEquivalent(new List>() { - new Tuple("instance1", "instance1_path"), - new Tuple("instance2", "instance2_path") + new Tuple("instance1", "instance1_path", "KSP"), + new Tuple("instance2", "instance2_path", "KSP") }, reg.GetInstances()); CollectionAssert.AreEquivalent(new List(), reg.GetAuthTokenHosts()); @@ -119,12 +97,6 @@ public void LoadsMissingJsonConfig() Assert.AreEqual(null, reg.CacheSizeLimit); Assert.AreEqual(4, reg.RefreshRate); - CollectionAssert.AreEquivalent(new Dictionary() - { - { "build1", "version1" }, - { "build2", "version2" } - }, reg.GetKSPBuilds().Builds); - File.Delete(tmpFile); } @@ -141,7 +113,6 @@ public void LoadsEmptyConfig() Assert.AreEqual(JsonConfiguration.DefaultDownloadCacheDir, reg.DownloadCacheDir); Assert.AreEqual(null, reg.CacheSizeLimit); Assert.AreEqual(0, reg.RefreshRate); - Assert.AreEqual(null, reg.GetKSPBuilds()); File.Delete(tmpFile); } @@ -154,10 +125,10 @@ public void LoadsExtraConfig() var reg = new JsonConfiguration(tmpFile); - CollectionAssert.AreEquivalent(new List>() + CollectionAssert.AreEquivalent(new List>() { - new Tuple("instance1", "instance1_path"), - new Tuple("instance2", "instance2_path") + new Tuple("instance1", "instance1_path", "KSP"), + new Tuple("instance2", "instance2_path", "KSP") }, reg.GetInstances()); CollectionAssert.AreEquivalent(new List() @@ -180,12 +151,6 @@ public void LoadsExtraConfig() Assert.AreEqual(2, reg.CacheSizeLimit); Assert.AreEqual(4, reg.RefreshRate); - CollectionAssert.AreEquivalent(new Dictionary() - { - { "build1", "version1" }, - { "build2", "version2" } - }, reg.GetKSPBuilds().Builds); - File.Delete(tmpFile); } @@ -381,34 +346,6 @@ public void AuthTokensPersist() File.Delete(tmpFile2); } - [Test] - public void KspBuildsPersist() - { - string tmpFile1 = Path.GetTempFileName(); - var reg = new JsonConfiguration(tmpFile1); - - - reg.SetKSPBuilds(new JBuilds - { - Builds = new Dictionary - { - { "test_build", "test_version" } - } - }); - - string tmpFile2 = Path.GetTempFileName(); - File.Copy(tmpFile1, tmpFile2, true); - reg = new JsonConfiguration(tmpFile2); - - CollectionAssert.AreEquivalent(new Dictionary() - { - { "test_build", "test_version" } - }, reg.GetKSPBuilds().Builds); - - File.Delete(tmpFile1); - File.Delete(tmpFile2); - } - [Test] public void InstancesPersist() { @@ -418,7 +355,7 @@ public void InstancesPersist() string tmpFile1 = Path.GetTempFileName(); var reg = new JsonConfiguration(tmpFile1); - var sl = new SortedList(); + var sl = new SortedList(); sl.Add("instance_1", k1.KSP); sl.Add("instance_2", k2.KSP); reg.SetRegistryToInstances(sl); @@ -427,10 +364,10 @@ public void InstancesPersist() File.Copy(tmpFile1, tmpFile2, true); reg = new JsonConfiguration(tmpFile2); - CollectionAssert.AreEquivalent(new List>() + CollectionAssert.AreEquivalent(new List>() { - new Tuple("instance_1", k1.KSP.GameDir()), - new Tuple("instance_2", k2.KSP.GameDir()) + new Tuple("instance_1", k1.KSP.GameDir(), "KSP"), + new Tuple("instance_2", k2.KSP.GameDir(), "KSP") }, reg.GetInstances()); File.Delete(tmpFile1); diff --git a/Tests/Core/KSP.cs b/Tests/Core/KSP.cs index 3bf1004b01..95c9595453 100644 --- a/Tests/Core/KSP.cs +++ b/Tests/Core/KSP.cs @@ -1,16 +1,17 @@ using System; using System.IO; -using CKAN; -using CKAN.Versioning; using NUnit.Framework; using Tests.Data; +using CKAN; +using CKAN.Versioning; +using CKAN.Games; namespace Tests.Core { [TestFixture] public class KSP { - private CKAN.KSP ksp; + private CKAN.GameInstance ksp; private string ksp_dir; private IUser nullUser; @@ -20,7 +21,7 @@ public void Setup() ksp_dir = TestData.NewTempDir(); nullUser = new NullUser(); CKAN.Utilities.CopyDirectory(TestData.good_ksp_dir(), ksp_dir, true); - ksp = new CKAN.KSP(ksp_dir, "test", nullUser); + ksp = new CKAN.GameInstance(new KerbalSpaceProgram(), ksp_dir, "test", nullUser); } [TearDown] @@ -40,42 +41,49 @@ public void TearDown() [Test] public void IsGameDir() { + var game = new KerbalSpaceProgram(); + // Our test data directory should be good. - Assert.IsTrue(CKAN.KSP.IsKspDir(TestData.good_ksp_dir())); + Assert.IsTrue(game.GameInFolder(new DirectoryInfo(TestData.good_ksp_dir()))); // As should our copied folder. - Assert.IsTrue(CKAN.KSP.IsKspDir(ksp_dir)); + Assert.IsTrue(game.GameInFolder(new DirectoryInfo(ksp_dir))); // And the one from our KSP instance. - Assert.IsTrue(CKAN.KSP.IsKspDir(ksp.GameDir())); + Assert.IsTrue(game.GameInFolder(new DirectoryInfo(ksp.GameDir()))); // All these ones should be bad. foreach (string dir in TestData.bad_ksp_dirs()) { - Assert.IsFalse(CKAN.KSP.IsKspDir(dir)); + Assert.IsFalse(game.GameInFolder(new DirectoryInfo(dir))); } } [Test] - public void Training() + public void Tutorial() { //Use Uri to avoid issues with windows vs linux line separators. var canonicalPath = new Uri(Path.Combine(ksp_dir, "saves", "training")).LocalPath; - var training = new Uri(ksp.Tutorial()).LocalPath; - Assert.AreEqual(canonicalPath, training); + var game = new KerbalSpaceProgram(); + string dest; + Assert.IsTrue(game.AllowInstallationIn("Tutorial", out dest)); + Assert.AreEqual( + new DirectoryInfo(ksp.ToAbsoluteGameDir(dest)), + new DirectoryInfo(canonicalPath) + ); } [Test] public void ScanDlls() { - string path = Path.Combine(ksp.GameData(), "Example.dll"); + string path = Path.Combine(ksp.game.PrimaryModDirectory(ksp), "Example.dll"); var registry = CKAN.RegistryManager.Instance(ksp).registry; Assert.IsFalse(registry.IsInstalled("Example"), "Example should start uninstalled"); File.WriteAllText(path, "Not really a DLL, are we?"); - ksp.ScanGameData(); + ksp.Scan(); Assert.IsTrue(registry.IsInstalled("Example"), "Example installed"); @@ -84,12 +92,12 @@ public void ScanDlls() // Now let's do the same with different case. - string path2 = Path.Combine(ksp.GameData(), "NewMod.DLL"); + string path2 = Path.Combine(ksp.game.PrimaryModDirectory(ksp), "NewMod.DLL"); Assert.IsFalse(registry.IsInstalled("NewMod")); File.WriteAllText(path2, "This text is irrelevant. You will be assimilated"); - ksp.ScanGameData(); + ksp.Scan(); Assert.IsTrue(registry.IsInstalled("NewMod")); } @@ -98,7 +106,7 @@ public void ScanDlls() public void ToAbsolute() { Assert.AreEqual( - CKAN.KSPPathUtils.NormalizePath( + CKAN.CKANPathUtils.NormalizePath( Path.Combine(ksp_dir, "GameData/HydrazinePrincess") ), ksp.ToAbsoluteGameDir("GameData/HydrazinePrincess") @@ -127,7 +135,7 @@ public void Valid_MissingVersionData_False() string jsonpath = Path.Combine(ckandir, "compatible_ksp_versions.json"); const string compatible_ksp_versions_json = @"{ ""VersionOfKspWhenWritten"": ""1.4.3"", - ""CompatibleKspVersions"": [""1.4""] + ""CompatibleGameVersions"": [""1.4""] }"; // Generate a valid game dir except for missing buildID.txt and readme.txt @@ -140,7 +148,7 @@ public void Valid_MissingVersionData_False() File.WriteAllText(jsonpath, compatible_ksp_versions_json); // Act - CKAN.KSP my_ksp = new CKAN.KSP(gamedir, "missing-ver-test", nullUser); + CKAN.GameInstance my_ksp = new CKAN.GameInstance(new KerbalSpaceProgram(), gamedir, "missing-ver-test", nullUser); // Assert Assert.IsFalse(my_ksp.Valid); @@ -159,7 +167,7 @@ public void Constructor_NullMainCompatVer_NoCrash() string jsonpath = Path.Combine(ckandir, "compatible_ksp_versions.json"); const string compatible_ksp_versions_json = @"{ ""VersionOfKspWhenWritten"": null, - ""CompatibleKspVersions"": [""1.4""] + ""CompatibleGameVersions"": [""1.4""] }"; // Generate a valid game dir except for missing buildID.txt and readme.txt @@ -174,7 +182,7 @@ public void Constructor_NullMainCompatVer_NoCrash() // Act & Assert Assert.DoesNotThrow(() => { - CKAN.KSP my_ksp = new CKAN.KSP(gamedir, "null-compat-ver-test", nullUser); + CKAN.GameInstance my_ksp = new CKAN.GameInstance(new KerbalSpaceProgram(), gamedir, "null-compat-ver-test", nullUser); }); Directory.Delete(gamedir, true); diff --git a/Tests/Core/KSPManager.cs b/Tests/Core/KSPManager.cs index 64e8affce4..37a1a5657e 100644 --- a/Tests/Core/KSPManager.cs +++ b/Tests/Core/KSPManager.cs @@ -1,11 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; -using CKAN; -using CKAN.Versioning; using NUnit.Framework; using Tests.Core.Configuration; using Tests.Data; +using CKAN; +using CKAN.Versioning; +using CKAN.Games; namespace Tests.Core { @@ -14,14 +15,14 @@ [TestFixture] public class KSPManagerTests private DisposableKSP tidy; private const string nameInReg = "testing"; private FakeConfiguration cfg; - KSPManager manager; + GameInstanceManager manager; [SetUp] public void SetUp() { tidy = new DisposableKSP(); cfg = GetTestCfg(nameInReg); - manager = new KSPManager(new NullUser(), cfg); + manager = new GameInstanceManager(new NullUser(), cfg); } [TearDown] @@ -120,7 +121,7 @@ public void CloneInstance_BadInstance_ThrowsNotKSPDirKraken() { string badName = "badInstance"; string tempdir = TestData.NewTempDir(); - CKAN.KSP badKSP = new CKAN.KSP(TestData.bad_ksp_dirs().First(), "badDir", new NullUser()); + CKAN.GameInstance badKSP = new CKAN.GameInstance(new KerbalSpaceProgram(), TestData.bad_ksp_dirs().First(), "badDir", new NullUser()); Assert.Throws(() => manager.CloneInstance(badKSP, badName, tempdir)); @@ -167,14 +168,14 @@ public void CloneInstance_GoodInstance_ManagerHasValidInstance() // FakeInstance [Test] - public void FakeInstance_InvalidVersion_ThrowsBadKSPVersionKraken() + public void FakeInstance_InvalidVersion_ThrowsBadGameVersionKraken() { string name = "testname"; string tempdir = TestData.NewTempDir(); - KspVersion version = KspVersion.Parse("1.1.99"); + GameVersion version = GameVersion.Parse("1.1.99"); - Assert.Throws(() => - manager.FakeInstance(name, tempdir, version)); + Assert.Throws(() => + manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version)); Assert.IsFalse(manager.HasInstance(name)); // Tidy up. @@ -184,21 +185,21 @@ public void FakeInstance_InvalidVersion_ThrowsBadKSPVersionKraken() [Test, TestCase("1.4.0"), TestCase("1.6.1")] - public void FakeInstance_DlcsWithWrongBaseVersion_ThrowsWrongKSPVersionKraken(string baseVersion) + public void FakeInstance_DlcsWithWrongBaseVersion_ThrowsWrongGameVersionKraken(string baseVersion) { string name = "testname"; - KspVersion mhVersion = KspVersion.Parse("1.1.0"); - KspVersion bgVersion = KspVersion.Parse("1.0.0"); + GameVersion mhVersion = GameVersion.Parse("1.1.0"); + GameVersion bgVersion = GameVersion.Parse("1.0.0"); string tempdir = TestData.NewTempDir(); - KspVersion version = KspVersion.Parse(baseVersion); + GameVersion version = GameVersion.Parse(baseVersion); - Dictionary dlcs = new Dictionary() { + Dictionary dlcs = new Dictionary() { { new CKAN.DLC.MakingHistoryDlcDetector(), mhVersion }, { new CKAN.DLC.BreakingGroundDlcDetector(), bgVersion } }; - Assert.Throws(() => - manager.FakeInstance(name, tempdir, version, dlcs)); + Assert.Throws(() => + manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs)); Assert.IsFalse(manager.HasInstance(name)); // Tidy up. @@ -210,11 +211,11 @@ public void FakeInstance_InNotEmptyFolder_ThrowsBadInstallLocationKraken() { string name = "testname"; string tempdir = TestData.NewTempDir(); - KspVersion version = KspVersion.Parse("1.5.1"); + GameVersion version = GameVersion.Parse("1.5.1"); System.IO.File.Create(System.IO.Path.Combine(tempdir, "shouldntbehere.txt")).Close(); Assert.Throws(() => - manager.FakeInstance(name, tempdir, version)); + manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version)); Assert.IsFalse(manager.HasInstance(name)); // Tidy up. @@ -225,18 +226,18 @@ public void FakeInstance_InNotEmptyFolder_ThrowsBadInstallLocationKraken() public void FakeInstance_ValidArgumentsWithDLCs_ManagerHasValidInstance() { string name = "testname"; - KspVersion mhVersion = KspVersion.Parse("1.1.0"); - KspVersion bgVersion = KspVersion.Parse("1.0.0"); + GameVersion mhVersion = GameVersion.Parse("1.1.0"); + GameVersion bgVersion = GameVersion.Parse("1.0.0"); string tempdir = TestData.NewTempDir(); - KspVersion version = KspVersion.Parse("1.7.1"); + GameVersion version = GameVersion.Parse("1.7.1"); - Dictionary dlcs = new Dictionary() { + Dictionary dlcs = new Dictionary() { { new CKAN.DLC.MakingHistoryDlcDetector(), mhVersion }, { new CKAN.DLC.BreakingGroundDlcDetector(), bgVersion } }; - manager.FakeInstance(name, tempdir, version, dlcs); - CKAN.KSP newKSP = new CKAN.KSP(tempdir, name, new NullUser()); + manager.FakeInstance(new KerbalSpaceProgram(), name, tempdir, version, dlcs); + CKAN.GameInstance newKSP = new CKAN.GameInstance(new KerbalSpaceProgram(), tempdir, name, new NullUser()); CKAN.DLC.MakingHistoryDlcDetector mhDetector = new CKAN.DLC.MakingHistoryDlcDetector(); CKAN.DLC.BreakingGroundDlcDetector bgDetector = new CKAN.DLC.BreakingGroundDlcDetector(); @@ -264,7 +265,7 @@ public void GetPreferredInstance_WithEmptyAutoStartAndMultipleInstances_ReturnsN { using (var tidy2 = new DisposableKSP()) { - cfg.Instances.Add(new Tuple("tidy2",tidy2.KSP.GameDir())); + cfg.Instances.Add(new Tuple("tidy2",tidy2.KSP.GameDir(), "KSP")); manager.LoadInstancesFromRegistry(); manager.ClearAutoStart(); Assert.That(manager.GetPreferredInstance(), Is.Null); @@ -289,7 +290,7 @@ public void SetCurrentInstance_NameNotInRepo_Throws() public void Ctor_InvalidAutoStart_DoesNotThrow() { var config = new FakeConfiguration(tidy.KSP, "invalid"); - Assert.DoesNotThrow(() => new KSPManager(new NullUser(), config)); + Assert.DoesNotThrow(() => new GameInstanceManager(new NullUser(), config)); config.Dispose(); } @@ -299,9 +300,9 @@ public void Ctor_InvalidAutoStart_DoesNotThrow() private FakeConfiguration GetTestCfg(string name) { return new FakeConfiguration( - new List> + new List> { - new Tuple(name, tidy.KSP.GameDir()) + new Tuple(name, tidy.KSP.GameDir(), "KSP") }, null ); diff --git a/Tests/Core/KSPPathUtils.cs b/Tests/Core/KSPPathUtils.cs index d1a0d3128f..1dcdc45674 100644 --- a/Tests/Core/KSPPathUtils.cs +++ b/Tests/Core/KSPPathUtils.cs @@ -4,41 +4,41 @@ namespace Tests.Core { [TestFixture] - public class KSPPathUtils + public class CKANPathUtils { [Test] public void NormalizePath() { - Assert.AreEqual("/a/b/c", CKAN.KSPPathUtils.NormalizePath("/a/b/c"), "Identity function failed"); - Assert.AreEqual("/a/b/c", CKAN.KSPPathUtils.NormalizePath("\\a\\b\\c"), "Actual replace"); - Assert.AreEqual("/a/b/c", CKAN.KSPPathUtils.NormalizePath("\\a/b\\c"), "Mixed slashes"); - Assert.AreEqual("a/b/c", CKAN.KSPPathUtils.NormalizePath("a/b\\c"), "No starting slash"); - Assert.AreEqual("/a/b/c", CKAN.KSPPathUtils.NormalizePath("\\a/b\\c\\"), "Trailing slash"); - Assert.AreEqual("SPACE", CKAN.KSPPathUtils.NormalizePath("SPACE"), "All upper-case, no slashes"); + Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("/a/b/c"), "Identity function failed"); + Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("\\a\\b\\c"), "Actual replace"); + Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("\\a/b\\c"), "Mixed slashes"); + Assert.AreEqual("a/b/c", CKAN.CKANPathUtils.NormalizePath("a/b\\c"), "No starting slash"); + Assert.AreEqual("/a/b/c", CKAN.CKANPathUtils.NormalizePath("\\a/b\\c\\"), "Trailing slash"); + Assert.AreEqual("SPACE", CKAN.CKANPathUtils.NormalizePath("SPACE"), "All upper-case, no slashes"); } [Test] public void GetLastPathElement() { - Assert.AreEqual("c", CKAN.KSPPathUtils.GetLastPathElement("/a/b/c"), "Simple case"); - Assert.AreEqual("c", CKAN.KSPPathUtils.GetLastPathElement("\\a\\b\\c"), "With other slashes"); - Assert.AreEqual("c", CKAN.KSPPathUtils.GetLastPathElement("\\a/b\\c"), "With mixed slashes"); - Assert.AreEqual("c", CKAN.KSPPathUtils.GetLastPathElement("a/b\\c"), "No starting slash"); - Assert.AreEqual("c", CKAN.KSPPathUtils.GetLastPathElement("\\a/b\\c\\"), "Trailing slash"); - Assert.AreEqual("kOS", CKAN.KSPPathUtils.GetLastPathElement("GameData/kOS"), "Real world test"); - Assert.AreEqual("buckethead", CKAN.KSPPathUtils.GetLastPathElement("buckethead"), "No slashes at all"); + Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("/a/b/c"), "Simple case"); + Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("\\a\\b\\c"), "With other slashes"); + Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("\\a/b\\c"), "With mixed slashes"); + Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("a/b\\c"), "No starting slash"); + Assert.AreEqual("c", CKAN.CKANPathUtils.GetLastPathElement("\\a/b\\c\\"), "Trailing slash"); + Assert.AreEqual("kOS", CKAN.CKANPathUtils.GetLastPathElement("GameData/kOS"), "Real world test"); + Assert.AreEqual("buckethead", CKAN.CKANPathUtils.GetLastPathElement("buckethead"), "No slashes at all"); } [Test] public void GetLeadingPathElements() { - Assert.AreEqual("/a/b", CKAN.KSPPathUtils.GetLeadingPathElements("/a/b/c"), "Simple case"); - Assert.AreEqual("/a/b", CKAN.KSPPathUtils.GetLeadingPathElements("\\a\\b\\c"), "With other slashes"); - Assert.AreEqual("/a/b", CKAN.KSPPathUtils.GetLeadingPathElements("\\a/b\\c"), "With mixed slashes"); - Assert.AreEqual("a/b", CKAN.KSPPathUtils.GetLeadingPathElements("a/b\\c"), "No starting slash"); - Assert.AreEqual("/a/b", CKAN.KSPPathUtils.GetLeadingPathElements("\\a/b\\c\\"), "Trailing slash"); + Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("/a/b/c"), "Simple case"); + Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("\\a\\b\\c"), "With other slashes"); + Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("\\a/b\\c"), "With mixed slashes"); + Assert.AreEqual("a/b", CKAN.CKANPathUtils.GetLeadingPathElements("a/b\\c"), "No starting slash"); + Assert.AreEqual("/a/b", CKAN.CKANPathUtils.GetLeadingPathElements("\\a/b\\c\\"), "Trailing slash"); - Assert.IsEmpty(CKAN.KSPPathUtils.GetLeadingPathElements("ModuleManager.2.5.1.dll")); + Assert.IsEmpty(CKAN.CKANPathUtils.GetLeadingPathElements("ModuleManager.2.5.1.dll")); } [Test] @@ -46,31 +46,31 @@ public void ToRelative() { Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP"), + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP"), "Basic operation" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative(@"\home\fionna\KSP\GameData\Cake", "/home/fionna/KSP"), + CKAN.CKANPathUtils.ToRelative(@"\home\fionna\KSP\GameData\Cake", "/home/fionna/KSP"), "Swapped slashes" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP"), + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP"), "Trailing slash in path" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP/"), + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/fionna/KSP/"), "Trailing slash in root" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP/"), + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake/", "/home/fionna/KSP/"), "Trailing slashes for everyone!" ); @@ -79,52 +79,52 @@ public void ToRelative() { Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("K:GameData/Cake", "K:"), + CKAN.CKANPathUtils.ToRelative("K:GameData/Cake", "K:"), "Root of a Windows drive" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("K:GameData/Cake", "K:/"), + CKAN.CKANPathUtils.ToRelative("K:GameData/Cake", "K:/"), "Root of a Windows drive, slash in root" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("K:/GameData/Cake", "K:"), + CKAN.CKANPathUtils.ToRelative("K:/GameData/Cake", "K:"), "Root of a Windows drive, slash in path" ); Assert.AreEqual( "GameData/Cake", - CKAN.KSPPathUtils.ToRelative("K:/GameData/Cake", "K:/"), + CKAN.CKANPathUtils.ToRelative("K:/GameData/Cake", "K:/"), "Root of a Windows drive, slash in both" ); } Assert.Throws(delegate { - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/finn/KSP"); + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "/home/finn/KSP"); }, "Not a sub-path"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToRelative("KSP/GameData/Cake", "/KSP/GameData"); + CKAN.CKANPathUtils.ToRelative("KSP/GameData/Cake", "/KSP/GameData"); }, "Path not absolute"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "home/fionna/KSP"); + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", "home/fionna/KSP"); }, "Root not absolute"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToRelative(null, "/home/fionna/KSP"); + CKAN.CKANPathUtils.ToRelative(null, "/home/fionna/KSP"); }, "null path"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", null); + CKAN.CKANPathUtils.ToRelative("/home/fionna/KSP/GameData/Cake", null); }, "null root"); } @@ -138,7 +138,7 @@ public void ToRelative_PathEqualsRoot_DontCrash() // Act & Assert Assert.DoesNotThrow(() => { - string s = CKAN.KSPPathUtils.ToRelative(path, root); + string s = CKAN.CKANPathUtils.ToRelative(path, root); Assert.IsEmpty(s); }); } @@ -148,52 +148,52 @@ public void ToAbsolute() { Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.KSPPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP"), + CKAN.CKANPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP"), "Basic functionality" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.KSPPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP"), + CKAN.CKANPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP"), "Trailing slashes path" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.KSPPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP/"), + CKAN.CKANPathUtils.ToAbsolute("GameData/Cake","/home/fionna/KSP/"), "Trailing slashes root" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.KSPPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP/"), + CKAN.CKANPathUtils.ToAbsolute("GameData/Cake/","/home/fionna/KSP/"), "Trailing slashes for all" ); Assert.AreEqual( "/home/fionna/KSP/GameData/Cake", - CKAN.KSPPathUtils.ToAbsolute(@"GameData\Cake\","/home/fionna/KSP"), + CKAN.CKANPathUtils.ToAbsolute(@"GameData\Cake\","/home/fionna/KSP"), "Swapped slashes" ); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToAbsolute("/GameData/Cake", "/home/fionna/KSP"); + CKAN.CKANPathUtils.ToAbsolute("/GameData/Cake", "/home/fionna/KSP"); }, "Rooted path"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToAbsolute("GameData/Cake", "home/fionna/KSP"); + CKAN.CKANPathUtils.ToAbsolute("GameData/Cake", "home/fionna/KSP"); }, "Unrooted root"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToAbsolute(null, "/home/fionna/KSP"); + CKAN.CKANPathUtils.ToAbsolute(null, "/home/fionna/KSP"); }, "null path"); Assert.Throws(delegate { - CKAN.KSPPathUtils.ToAbsolute("/home/fionna/KSP/GameData/Cake", null); + CKAN.CKANPathUtils.ToAbsolute("/home/fionna/KSP/GameData/Cake", null); }, "null root"); } diff --git a/Tests/Core/ModuleInstaller.cs b/Tests/Core/ModuleInstaller.cs index 6c4e26a021..ed37235328 100644 --- a/Tests/Core/ModuleInstaller.cs +++ b/Tests/Core/ModuleInstaller.cs @@ -29,6 +29,8 @@ public class ModuleInstaller private IUser nullUser; + private DisposableKSP ksp = new DisposableKSP(); + [SetUp] public void Setup() { @@ -48,6 +50,12 @@ public void Setup() nullUser = new NullUser(); } + [OneTimeTearDown] + public void TearDown() + { + ksp.Dispose(); + } + [Test] public void Sanity() { @@ -89,7 +97,7 @@ public void GenerateDefaultInstall() [TestCaseSource("doge_mods")] public void FindInstallableFiles(CkanModule mod) { - List contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, dogezip, null); + List contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, dogezip, ksp.KSP); List filenames = new List(); Assert.IsNotNull(contents); @@ -99,9 +107,6 @@ public void FindInstallableFiles(CkanModule mod) foreach (var file in contents) { - // Make sure the destination paths are null, because we supplied no KSP instance. - Assert.IsNull(file.destination); - // Make sure the source paths are not null, that would be silly! Assert.IsNotNull(file.source); @@ -212,7 +217,7 @@ public void FindInstallableFilesWithFilter(CkanModule mod) { string extra_doge = TestData.DogeCoinFlagZipWithExtras(); - List contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, extra_doge, null); + List contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, extra_doge, ksp.KSP); var files = contents.Select(x => x.source.Name); @@ -229,7 +234,7 @@ public void FindInstallableFilesWithInclude() string extra_doge = TestData.DogeCoinFlagZipWithExtras(); CkanModule mod = TestData.DogeCoinFlag_101_module_include(); - List contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, extra_doge, null); + List contents = CKAN.ModuleInstaller.FindInstallableFiles(mod, extra_doge, ksp.KSP); var files = contents.Select(x => x.source.Name); @@ -249,12 +254,12 @@ public void No_Installable_Files() Assert.Throws(delegate { - CKAN.ModuleInstaller.FindInstallableFiles(bugged_mod, dogezip, null); + CKAN.ModuleInstaller.FindInstallableFiles(bugged_mod, dogezip, ksp.KSP); }); try { - CKAN.ModuleInstaller.FindInstallableFiles(bugged_mod, dogezip, null); + CKAN.ModuleInstaller.FindInstallableFiles(bugged_mod, dogezip, ksp.KSP); } catch (BadMetadataKraken ex) { @@ -284,7 +289,7 @@ public void FindInstallableFilesWithBadTarget(string location) Assert.Throws(delegate { - CKAN.ModuleInstaller.FindInstallableFiles(dogemod, dogezip, null); + CKAN.ModuleInstaller.FindInstallableFiles(dogemod, dogezip, ksp.KSP); }); } @@ -361,7 +366,7 @@ public void CorruptZip_242() // FindInstallableFiles CkanModule dogemod = TestData.DogeCoinFlag_101_module(); - CKAN.ModuleInstaller.FindInstallableFiles(dogemod, corrupt_dogezip, null); + CKAN.ModuleInstaller.FindInstallableFiles(dogemod, corrupt_dogezip, ksp.KSP); } } @@ -387,7 +392,7 @@ public void UninstallModNotFound() { var config = new FakeConfiguration(tidy.KSP, tidy.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { @@ -417,7 +422,7 @@ public void CanInstallMod() { var config = new FakeConfiguration(ksp.KSP, ksp.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { @@ -425,7 +430,7 @@ public void CanInstallMod() }; // Make sure the mod is not installed. - string mod_file_path = Path.Combine(ksp.KSP.GameData(), mod_file_name); + string mod_file_path = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), mod_file_name); Assert.IsFalse(File.Exists(mod_file_path)); @@ -467,7 +472,7 @@ public void InstallList_IdentifierEqualsVersionSyntax_InstallsModule() // Arrange var config = new FakeConfiguration(ksp.KSP, ksp.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { @@ -477,7 +482,7 @@ public void InstallList_IdentifierEqualsVersionSyntax_InstallsModule() var inst = CKAN.ModuleInstaller.GetInstance(ksp.KSP, manager.Cache, nullUser); const string mod_file_name = "DogeCoinFlag/Flags/dogecoin.png"; - string mod_file_path = Path.Combine(ksp.KSP.GameData(), mod_file_name); + string mod_file_path = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), mod_file_name); CkanModule mod = TestData.DogeCoinFlag_101_module(); registry.AddAvailable(mod); manager.Cache.Store(mod, TestData.DogeCoinFlagZip()); @@ -508,14 +513,14 @@ public void CanUninstallMod() { var config = new FakeConfiguration(ksp.KSP, ksp.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { CurrentInstance = ksp.KSP }; - string mod_file_path = Path.Combine(ksp.KSP.GameData(), mod_file_name); + string mod_file_path = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), mod_file_name); // Install the test mod. var registry = CKAN.RegistryManager.Instance(ksp.KSP).registry; @@ -551,14 +556,14 @@ public void UninstallEmptyDirs() { var config = new FakeConfiguration(ksp.KSP, ksp.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { CurrentInstance = ksp.KSP }; - string directoryPath = Path.Combine(ksp.KSP.GameData(), emptyFolderName); + string directoryPath = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), emptyFolderName); // Install the base test mod. @@ -615,7 +620,7 @@ public void ModuleManagerInstancesAreDecoupled() { var config = new FakeConfiguration(ksp.KSP, ksp.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { @@ -636,7 +641,7 @@ public void ModuleManagerInstancesAreDecoupled() CKAN.ModuleInstaller.GetInstance(ksp.KSP, manager.Cache, nullUser).InstallList(modules, new RelationshipResolverOptions(), CKAN.RegistryManager.Instance(manager.CurrentInstance), ref possibleConfigOnlyDirs); // Check that the module is installed. - string mod_file_path = Path.Combine(ksp.KSP.GameData(), mod_file_name); + string mod_file_path = Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), mod_file_name); Assert.IsTrue(File.Exists(mod_file_path)); @@ -717,8 +722,7 @@ public void AllowInstallsToScenarios() ""install_to"": ""Scenarios"" } ] - }") - ; + }"); List results; using (var ksp = new DisposableKSP()) @@ -726,7 +730,7 @@ public void AllowInstallsToScenarios() results = mod.install.First().FindInstallableFiles(zip, ksp.KSP); Assert.AreEqual( - CKAN.KSPPathUtils.NormalizePath( + CKAN.CKANPathUtils.NormalizePath( Path.Combine(ksp.KSP.GameDir(), "saves/scenarios/AwesomeRace.sfs") ), results.First().destination diff --git a/Tests/Core/ModuleInstallerDirTest.cs b/Tests/Core/ModuleInstallerDirTest.cs index 2db4648a2e..1fbff773fc 100644 --- a/Tests/Core/ModuleInstallerDirTest.cs +++ b/Tests/Core/ModuleInstallerDirTest.cs @@ -18,7 +18,7 @@ namespace Tests.Core [TestFixture] public class ModuleInstallerDirTest { - private KSPManager _manager; + private GameInstanceManager _manager; private DisposableKSP _instance; private FakeConfiguration _config; private CKAN.RegistryManager _registryManager; @@ -41,13 +41,13 @@ public void SetUp() _instance = new DisposableKSP(); _nullUser = new NullUser(); _config = new FakeConfiguration(_instance.KSP, _instance.KSP.Name); - _manager = new KSPManager(_nullUser, _config); + _manager = new GameInstanceManager(_nullUser, _config); _registryManager = CKAN.RegistryManager.Instance(_instance.KSP); _registry = _registryManager.registry; _installer = CKAN.ModuleInstaller.GetInstance(_instance.KSP, _manager.Cache, _nullUser); _gameDir = _instance.KSP.GameDir(); - _gameDataDir = _instance.KSP.GameData(); + _gameDataDir = _instance.KSP.game.PrimaryModDirectory(_instance.KSP); _registry.AddAvailable(_testModule); var testModFile = TestData.DogeCoinFlagZip(); _manager.Cache.Store(_testModule, testModFile); @@ -118,7 +118,7 @@ public void TestNullPath() public void TestSlashVariants() { var rawInstallDir = Path.Combine(_gameDataDir, _testModule.identifier); - var normalizedInstallDir = CKAN.KSPPathUtils.NormalizePath(rawInstallDir); + var normalizedInstallDir = CKAN.CKANPathUtils.NormalizePath(rawInstallDir); var windowsInstallDir = normalizedInstallDir.Replace('/', '\\'); Assert.DoesNotThrow(delegate () diff --git a/Tests/Core/Net/NetAsyncModulesDownloader.cs b/Tests/Core/Net/NetAsyncModulesDownloader.cs index 9755312b2d..6505c27a51 100644 --- a/Tests/Core/Net/NetAsyncModulesDownloader.cs +++ b/Tests/Core/Net/NetAsyncModulesDownloader.cs @@ -13,7 +13,7 @@ namespace Tests.Core.Net [TestFixture] public class NetAsyncModulesDownloader { - private CKAN.KSPManager manager; + private CKAN.GameInstanceManager manager; private CKAN.RegistryManager registry_manager; private CKAN.Registry registry; private DisposableKSP ksp; @@ -25,7 +25,7 @@ public class NetAsyncModulesDownloader [SetUp] public void Setup() { - manager = new KSPManager(new NullUser()); + manager = new GameInstanceManager(new NullUser()); // Give us a registry to play with. ksp = new DisposableKSP(); registry_manager = CKAN.RegistryManager.Instance(ksp.KSP); diff --git a/Tests/Core/Net/Repo.cs b/Tests/Core/Net/Repo.cs index e4f0b3be84..ac07e7c512 100644 --- a/Tests/Core/Net/Repo.cs +++ b/Tests/Core/Net/Repo.cs @@ -34,7 +34,7 @@ public void UpdateRegistryTarGz() CKAN.Repo.Update(manager, ksp.KSP, new NullUser(), TestData.TestKANTarGz()); // Test we've got an expected module. - CkanModule far = registry.LatestAvailable("FerramAerospaceResearch", new KspVersionCriteria(KspVersion.Parse("0.25.0"))); + CkanModule far = registry.LatestAvailable("FerramAerospaceResearch", new GameVersionCriteria(GameVersion.Parse("0.25.0"))); Assert.AreEqual("v0.14.3.2", far.version.ToString()); } @@ -45,7 +45,7 @@ public void UpdateRegistryZip() CKAN.Repo.Update(manager, ksp.KSP, new NullUser(), TestData.TestKANZip()); // Test we've got an expected module. - CkanModule far = registry.LatestAvailable("FerramAerospaceResearch", new KspVersionCriteria(KspVersion.Parse("0.25.0"))); + CkanModule far = registry.LatestAvailable("FerramAerospaceResearch", new GameVersionCriteria(GameVersion.Parse("0.25.0"))); Assert.AreEqual("v0.14.3.2", far.version.ToString()); } diff --git a/Tests/Core/Registry/Registry.cs b/Tests/Core/Registry/Registry.cs index 2b20d52879..77d1b22c3c 100644 --- a/Tests/Core/Registry/Registry.cs +++ b/Tests/Core/Registry/Registry.cs @@ -13,8 +13,8 @@ public class Registry { private static readonly CkanModule module = TestData.kOS_014_module(); private static readonly string identifier = module.identifier; - private static readonly KspVersionCriteria v0_24_2 = new KspVersionCriteria(KspVersion.Parse("0.24.2")); - private static readonly KspVersionCriteria v0_25_0 = new KspVersionCriteria (KspVersion.Parse("0.25.0")); + private static readonly GameVersionCriteria v0_24_2 = new GameVersionCriteria(GameVersion.Parse("0.24.2")); + private static readonly GameVersionCriteria v0_25_0 = new GameVersionCriteria (GameVersion.Parse("0.25.0")); private CKAN.Registry registry; @@ -211,7 +211,7 @@ public void CompatibleModules_PastAndFutureCompatibility_ReturnsCurrentOnly() registry.AddAvailable(modFor181); // Act - KspVersionCriteria v173 = new KspVersionCriteria(KspVersion.Parse("1.7.3")); + GameVersionCriteria v173 = new GameVersionCriteria(GameVersion.Parse("1.7.3")); List compat = registry.CompatibleModules(v173).ToList(); // Assert diff --git a/Tests/Core/Registry/RegistryLive.cs b/Tests/Core/Registry/RegistryLive.cs index be32bcc4fe..e7eaa31947 100644 --- a/Tests/Core/Registry/RegistryLive.cs +++ b/Tests/Core/Registry/RegistryLive.cs @@ -37,7 +37,7 @@ public void TearDown() public void LatestAvailable() { CkanModule module = - registry.LatestAvailable("AGExt", new KspVersionCriteria (temp_ksp.KSP.Version())); + registry.LatestAvailable("AGExt", new GameVersionCriteria (temp_ksp.KSP.Version())); Assert.AreEqual("AGExt", module.identifier); Assert.AreEqual("1.24a", module.version.ToString()); diff --git a/Tests/Core/Registry/RegistryManager.cs b/Tests/Core/Registry/RegistryManager.cs index 4b1d473237..8bf071d16a 100644 --- a/Tests/Core/Registry/RegistryManager.cs +++ b/Tests/Core/Registry/RegistryManager.cs @@ -71,7 +71,7 @@ public void Registry_ZeroByteRegistryJson_EmptyRegistryWithoutCrash() // Arrange string registryPath = TestData.DataDir("zero-byte-registry.json"); DisposableKSP dispksp; - CKAN.KSP ksp; + CKAN.GameInstance ksp; // Act dispksp = new DisposableKSP(null, registryPath); diff --git a/Tests/Core/Relationships/RelationshipResolver.cs b/Tests/Core/Relationships/RelationshipResolver.cs index 759a133762..95d9117852 100644 --- a/Tests/Core/Relationships/RelationshipResolver.cs +++ b/Tests/Core/Relationships/RelationshipResolver.cs @@ -710,7 +710,7 @@ public void Constructor_WithRegistryThatHasRequiredModuleRemoved_Throws() { var list = new List(); var mod = generator.GeneratorRandomModule(); - mod.ksp_version = KspVersion.Parse("0.10"); + mod.ksp_version = GameVersion.Parse("0.10"); list.Add(mod.identifier); registry.AddAvailable(mod); registry.RemoveAvailable(mod); @@ -896,7 +896,7 @@ public void AutodetectedCanSatisfyRelationships() { using (var ksp = new DisposableKSP ()) { - registry.RegisterDll(ksp.KSP, Path.Combine(ksp.KSP.GameData(), "ModuleManager.dll")); + registry.RegisterDll(ksp.KSP, Path.Combine(ksp.KSP.game.PrimaryModDirectory(ksp.KSP), "ModuleManager.dll")); var depends = new List(); depends.Add(new CKAN.ModuleRelationshipDescriptor { name = "ModuleManager" }); @@ -908,7 +908,7 @@ public void AutodetectedCanSatisfyRelationships() null, RelationshipResolver.DefaultOpts(), registry, - new KspVersionCriteria (KspVersion.Parse("1.0.0")) + new GameVersionCriteria (GameVersion.Parse("1.0.0")) ); } } diff --git a/Tests/Core/Types/CkanModuleTests.cs b/Tests/Core/Types/CkanModuleTests.cs index d4a0c50ac1..be5931dbf7 100644 --- a/Tests/Core/Types/CkanModuleTests.cs +++ b/Tests/Core/Types/CkanModuleTests.cs @@ -17,7 +17,7 @@ public void CompatibleWith() { CkanModule module = CkanModule.FromJson(TestData.kOS_014()); - Assert.IsTrue(module.IsCompatibleKSP(new KspVersionCriteria(KspVersion.Parse("0.24.2")))); + Assert.IsTrue(module.IsCompatibleKSP(new GameVersionCriteria(GameVersion.Parse("0.24.2")))); } [Test] diff --git a/Tests/Core/Types/GameComparator.cs b/Tests/Core/Types/GameComparator.cs index 44e9187df5..110e1ebb4f 100644 --- a/Tests/Core/Types/GameComparator.cs +++ b/Tests/Core/Types/GameComparator.cs @@ -10,7 +10,7 @@ namespace Tests.Core.Types [TestFixture] public class GameComparator { - static readonly KspVersion gameVersion = KspVersion.Parse("1.0.4"); + static readonly GameVersion gameVersion = GameVersion.Parse("1.0.4"); CkanModule gameMod; [SetUp] @@ -30,10 +30,10 @@ public void TotallyCompatible(Type type, bool expected) // Mark the mod as being for 1.0.4 gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max - = KspVersion.Parse("1.0.4"); + = GameVersion.Parse("1.0.4"); // Now test! - Assert.AreEqual(expected, comparator.Compatible(new KspVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } [Test] @@ -46,10 +46,10 @@ public void GenerallySafeLax(Type type, bool expected) // We're going to tweak compatibly to mark the mod as being for 1.0.3 gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max - = KspVersion.Parse("1.0.3"); + = GameVersion.Parse("1.0.3"); // Now test! - Assert.AreEqual(expected, comparator.Compatible(new KspVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } [Test] @@ -62,12 +62,12 @@ public void GenerallySafeStrict(Type type, bool expected) // We're going to tweak compatibly to mark the mod as being for 1.0.3 ONLY gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max - = KspVersion.Parse("1.0.3"); + = GameVersion.Parse("1.0.3"); gameMod.ksp_version_strict = true; // Now test! - Assert.AreEqual(expected, comparator.Compatible(new KspVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } [Test] @@ -79,7 +79,7 @@ public void Incompatible(Type type, bool expected) var comparator = (CKAN.IGameComparator) Activator.CreateInstance(type); // The mod already starts off being incompatible, so just do the test. :) - Assert.AreEqual(expected, comparator.Compatible(new KspVersionCriteria (gameVersion), gameMod)); + Assert.AreEqual(expected, comparator.Compatible(new GameVersionCriteria (gameVersion), gameMod)); } public static readonly object[] TestStrictGameComparatorCases = @@ -124,10 +124,10 @@ public void TestStrictGameComparator(String modVersion, String gameVersion, bool var comparator = new CKAN.StrictGameComparator(); // We're going to tweak compatibly of the mod - gameMod.ksp_version = KspVersion.Parse(modVersion); + gameMod.ksp_version = GameVersion.Parse(modVersion); // Now test! - Assert.AreEqual(expectedResult, comparator.Compatible(new KspVersionCriteria(KspVersion.Parse(gameVersion)), gameMod)); + Assert.AreEqual(expectedResult, comparator.Compatible(new GameVersionCriteria(GameVersion.Parse(gameVersion)), gameMod)); } public static readonly object[] TestStrictGameComparatorMinMaxCases = @@ -170,11 +170,11 @@ public void TestStrictGameComparatorMinMax(String modMinVersion, String modMaxVe var comparator = new CKAN.StrictGameComparator(); gameMod.ksp_version = null; - gameMod.ksp_version_min = modMinVersion == null ? null : KspVersion.Parse(modMinVersion); - gameMod.ksp_version_max = modMaxVersion == null ? null : KspVersion.Parse(modMaxVersion); + gameMod.ksp_version_min = modMinVersion == null ? null : GameVersion.Parse(modMinVersion); + gameMod.ksp_version_max = modMaxVersion == null ? null : GameVersion.Parse(modMaxVersion); // Now test! - Assert.AreEqual(expectedResult, comparator.Compatible(new KspVersionCriteria(KspVersion.Parse(gameVersion)), gameMod)); + Assert.AreEqual(expectedResult, comparator.Compatible(new GameVersionCriteria(GameVersion.Parse(gameVersion)), gameMod)); } } } diff --git a/Tests/Core/Versioning/KspVersionBoundTests.cs b/Tests/Core/Versioning/KspVersionBoundTests.cs index 9cb8855858..dc6235b3c3 100644 --- a/Tests/Core/Versioning/KspVersionBoundTests.cs +++ b/Tests/Core/Versioning/KspVersionBoundTests.cs @@ -7,32 +7,32 @@ namespace Tests.Core.Versioning { [TestFixture] - public sealed class KspVersionBoundTests + public sealed class GameVersionBoundTests { private static readonly object[] EqualityCases = { new object[] { - new KspVersionBound(), - new KspVersionBound(), + new GameVersionBound(), + new GameVersionBound(), true }, new object[] { - new KspVersionBound(new KspVersion(), false), - new KspVersionBound(new KspVersion(), true), + new GameVersionBound(new GameVersion(), false), + new GameVersionBound(new GameVersion(), true), false }, new object[] { - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), true }, new object[] { - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 3, 4, 4), true), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 3, 4, 4), true), false } }; @@ -41,10 +41,10 @@ public sealed class KspVersionBoundTests public void ParameterlessCtorWorksCorrectly() { // Act - var result = new KspVersionBound(); + var result = new GameVersionBound(); // Assert - Assert.AreEqual(KspVersion.Any, result.Value); + Assert.AreEqual(GameVersion.Any, result.Value); Assert.IsTrue(result.Inclusive); } @@ -52,10 +52,10 @@ public void ParameterlessCtorWorksCorrectly() public void ParameterfulCtorWorksCorrectly() { // Act - var result = new KspVersionBound(new KspVersion(1, 2, 3, 4), true); + var result = new GameVersionBound(new GameVersion(1, 2, 3, 4), true); // Assert - Assert.AreEqual(new KspVersion(1, 2, 3, 4), result.Value); + Assert.AreEqual(new GameVersion(1, 2, 3, 4), result.Value); Assert.IsTrue(result.Inclusive); } @@ -64,7 +64,7 @@ public void ParameterfulCtorThrowsOnNullParameter() { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => new KspVersionBound(null, false); + TestDelegate act = () => new GameVersionBound(null, false); // Assert Assert.That(act, Throws.Exception.InstanceOf()); @@ -75,14 +75,14 @@ public void ParameterfulCtorThrowsOnPartiallyDefinedParameter() { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => new KspVersionBound(new KspVersion(1, 2, 3), false); + TestDelegate act = () => new GameVersionBound(new GameVersion(1, 2, 3), false); // Assert Assert.That(act, Throws.Exception); } [TestCaseSource("EqualityCases")] - public void EqualityWorksCorrectly(KspVersionBound vb1, KspVersionBound vb2, bool areEqual) + public void EqualityWorksCorrectly(GameVersionBound vb1, GameVersionBound vb2, bool areEqual) { // Act var genericEquals = vb1.Equals(vb2); @@ -106,12 +106,12 @@ public void NullEqualityWorksCorrectly() { // Act // ReSharper disable ConditionIsAlwaysTrueOrFalse - var genericEquals = new KspVersionBound().Equals(null); - var nonGenericEquals = new KspVersionBound().Equals((object)null); - var equalsOperatorNullLeft = null == new KspVersionBound(); - var equalsOperatorNullRight = new KspVersionBound() == null; - var notEqualsOperatorNullLeft = null != new KspVersionBound(); - var notEqualsOperatorNullRight = new KspVersionBound() != null; + var genericEquals = new GameVersionBound().Equals(null); + var nonGenericEquals = new GameVersionBound().Equals((object)null); + var equalsOperatorNullLeft = null == new GameVersionBound(); + var equalsOperatorNullRight = new GameVersionBound() == null; + var notEqualsOperatorNullLeft = null != new GameVersionBound(); + var notEqualsOperatorNullRight = new GameVersionBound() != null; // ReSharper restore ConditionIsAlwaysTrueOrFalse // ASsert @@ -127,7 +127,7 @@ public void NullEqualityWorksCorrectly() public void ReferenceEqualityWorksCorrectly() { // Arrange - var sut = new KspVersionBound(); + var sut = new GameVersionBound(); // Act var genericEquals = sut.Equals(sut); @@ -150,7 +150,7 @@ public void GetHashCodeDoesNotThrow( // Act // ReSharper disable once ReturnValueOfPureMethodIsNotUsed TestDelegate act = - () => new KspVersionBound(new KspVersion(major, minor, patch, build), inclusive).GetHashCode(); + () => new GameVersionBound(new GameVersion(major, minor, patch, build), inclusive).GetHashCode(); // Assert Assert.That(act, Throws.Nothing); diff --git a/Tests/Core/Versioning/KspVersionJsonConverterTests.cs b/Tests/Core/Versioning/KspVersionJsonConverterTests.cs index f32cf0ff7b..74639f4a23 100644 --- a/Tests/Core/Versioning/KspVersionJsonConverterTests.cs +++ b/Tests/Core/Versioning/KspVersionJsonConverterTests.cs @@ -7,54 +7,54 @@ namespace Tests.Core.Versioning { - public sealed class KspVersionJsonConverterTests + public sealed class GameVersionJsonConverterTests { private static readonly object[] WriteJsonCases = { - new object[] { new KspVersion(1), "1" }, - new object[] { new KspVersion(1, 2), "1.2" }, - new object[] { new KspVersion(1, 2, 3), "1.2.3" }, - new object[] { new KspVersion(1, 2, 3, 4), "1.2.3.4" }, + new object[] { new GameVersion(1), "1" }, + new object[] { new GameVersion(1, 2), "1.2" }, + new object[] { new GameVersion(1, 2, 3), "1.2.3" }, + new object[] { new GameVersion(1, 2, 3, 4), "1.2.3.4" }, }; private static readonly object[] ReadJsonCases = { - new object[] { @"{ ""KspVersion"": null }", null }, - new object[] { @"{ ""KspVersion"": ""any"" }", KspVersion.Any }, - new object[] { @"{ ""KspVersion"": ""1""} ", new KspVersion(1) }, - new object[] { @"{ ""KspVersion"": ""1.2""} ", new KspVersion(1, 2) }, - new object[] { @"{ ""KspVersion"": ""1.2.3""} ", new KspVersion(1, 2, 3) }, - new object[] { @"{ ""KspVersion"": ""1.2.3.4""} ", new KspVersion(1, 2, 3, 4) }, - new object[] { @"{ ""KspVersion"": ""1.1.""} ", new KspVersion(1,1) }, // #1780 + new object[] { @"{ ""GameVersion"": null }", null }, + new object[] { @"{ ""GameVersion"": ""any"" }", GameVersion.Any }, + new object[] { @"{ ""GameVersion"": ""1""} ", new GameVersion(1) }, + new object[] { @"{ ""GameVersion"": ""1.2""} ", new GameVersion(1, 2) }, + new object[] { @"{ ""GameVersion"": ""1.2.3""} ", new GameVersion(1, 2, 3) }, + new object[] { @"{ ""GameVersion"": ""1.2.3.4""} ", new GameVersion(1, 2, 3, 4) }, + new object[] { @"{ ""GameVersion"": ""1.1.""} ", new GameVersion(1,1) }, // #1780 }; private static readonly object[] ReadJsonFailureCases = { - new object[] { @"{ ""KspVersion"": "" "" }" }, - new object[] { @"{ ""KspVersion"": ""a.b.c"" }" } + new object[] { @"{ ""GameVersion"": "" "" }" }, + new object[] { @"{ ""GameVersion"": ""a.b.c"" }" } }; [TestCaseSource("WriteJsonCases")] - public void WriteJsonWorksCorrectly(KspVersion version, string expected) + public void WriteJsonWorksCorrectly(GameVersion version, string expected) { // Arrange - var poco = new TestPoco { KspVersion = version }; + var poco = new TestPoco { GameVersion = version }; // Act dynamic result = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(poco)); // Assert - Assert.That((string)result.KspVersion, Is.EqualTo(expected)); + Assert.That((string)result.GameVersion, Is.EqualTo(expected)); } [TestCaseSource("ReadJsonCases")] - public void ReadJsonWorksCorrectly(string json, KspVersion expected) + public void ReadJsonWorksCorrectly(string json, GameVersion expected) { // Act var result = JsonConvert.DeserializeObject(json); // Assert - Assert.That(result.KspVersion, Is.EqualTo(expected)); + Assert.That(result.GameVersion, Is.EqualTo(expected)); } [TestCaseSource("ReadJsonFailureCases")] @@ -67,16 +67,16 @@ public void ReadJsonThrowsOnInvalidValue(string json) Assert.That(act, Throws.Exception); } - [TestCase(typeof(KspVersion), true)] - [TestCase(typeof(KspVersionBound), false)] - [TestCase(typeof(KspVersionRange), false)] + [TestCase(typeof(GameVersion), true)] + [TestCase(typeof(GameVersionBound), false)] + [TestCase(typeof(GameVersionRange), false)] [TestCase(typeof(string), false)] [TestCase(typeof(int), false)] [TestCase(typeof(object), false)] public void CanConvertWorksCorrectly(Type objectType, bool expected) { // Arrange - var sut = new KspVersionJsonConverter(); + var sut = new GameVersionJsonConverter(); // Act var result = sut.CanConvert(objectType); @@ -87,7 +87,7 @@ public void CanConvertWorksCorrectly(Type objectType, bool expected) private sealed class TestPoco { - public KspVersion KspVersion { get; set; } + public GameVersion GameVersion { get; set; } } } } diff --git a/Tests/Core/Versioning/KspVersionRangeTests.cs b/Tests/Core/Versioning/KspVersionRangeTests.cs index ec2c11ecea..0e2541dde0 100644 --- a/Tests/Core/Versioning/KspVersionRangeTests.cs +++ b/Tests/Core/Versioning/KspVersionRangeTests.cs @@ -1,41 +1,42 @@ -using CKAN.Versioning; +using CKAN.Versioning; +using CKAN.Games; using NUnit.Framework; #pragma warning disable 414 namespace Tests.Core.Versioning { - public sealed class KspVersionRangeTests + public sealed class GameVersionRangeTests { private static readonly object[] EqualityCases = { new object[] { - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 2, 3, 4), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 2, 3, 4), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false) ), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(5, 6, 7, 8), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(5, 6, 7, 8), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(5, 6, 7, 8), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(5, 6, 7, 8), true) ), true } @@ -45,28 +46,28 @@ public sealed class KspVersionRangeTests { new object[] { - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), "[,]" }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound()), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound()), "(1.2.3.4,]" }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(5, 6, 7, 8), false)), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(5, 6, 7, 8), false)), "(1.2.3.4,5.6.7.8)" }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), true), - new KspVersionBound(new KspVersion(5, 6, 7, 8), true)), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), true), + new GameVersionBound(new GameVersion(5, 6, 7, 8), true)), "[1.2.3.4,5.6.7.8]" } }; @@ -75,245 +76,245 @@ public sealed class KspVersionRangeTests { new object[] { - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), true), - new KspVersionBound(new KspVersion(1, 2, 3, 4), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), true), + new GameVersionBound(new GameVersion(1, 2, 3, 4), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), true), - new KspVersionBound(new KspVersion(1, 2, 3, 4), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), true), + new GameVersionBound(new GameVersion(1, 2, 3, 4), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), true), - new KspVersionBound(new KspVersion(1, 2, 3, 4), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), true), + new GameVersionBound(new GameVersion(1, 2, 3, 4), true) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 2, 3, 4), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 2, 3, 4), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false) ), null }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), false), - new KspVersionBound(new KspVersion(1, 2, 3, 4), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), false), + new GameVersionBound(new GameVersion(1, 2, 3, 4), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), true), - new KspVersionBound(new KspVersion(1, 2, 3, 4), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), true), + new GameVersionBound(new GameVersion(1, 2, 3, 4), true) ), null }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(1, 1, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(1, 1, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 1, 0, 0), true), - new KspVersionBound(new KspVersion(1, 2, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 1, 0, 0), true), + new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), null }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1235), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1235), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1235), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1235), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), null }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true), - new KspVersionBound(new KspVersion(1, 0, 4, 1234), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true), + new GameVersionBound(new GameVersion(1, 0, 4, 1234), true) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 4, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 4, 0), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 4, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 4, 0), true) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(1, 1, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(1, 1, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(1, 1, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(1, 1, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(1, 1, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(1, 1, 0, 0), false) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 1, 0, 0), true), - new KspVersionBound(new KspVersion(1, 2, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 1, 0, 0), true), + new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 1, 0, 0), true), - new KspVersionBound(new KspVersion(1, 2, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 1, 0, 0), true), + new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 1, 0, 0), true), - new KspVersionBound(new KspVersion(1, 2, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 1, 0, 0), true), + new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 1, 0, 0), true), - new KspVersionBound(new KspVersion(1, 2, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 1, 0, 0), true), + new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(1, 1, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(1, 1, 0, 0), false) ), null }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(1, 1, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(1, 1, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 1, 0, 0), true), - new KspVersionBound(new KspVersion(1, 2, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 1, 0, 0), true), + new GameVersionBound(new GameVersion(1, 2, 0, 0), false) ), null }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound() + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound() ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ) }, new object[] { - new KspVersionRange( - new KspVersionBound(), - new KspVersionBound(new KspVersion(1, 0, 4, 0), true) + new GameVersionRange( + new GameVersionBound(), + new GameVersionBound(new GameVersion(1, 0, 4, 0), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 5, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 5, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 4, 0), true), - new KspVersionBound(new KspVersion(1, 0, 4, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 4, 0), true), + new GameVersionBound(new GameVersion(1, 0, 4, 0), true) ) }, new object[] { - new KspVersionRange( - new KspVersionBound(), - new KspVersionBound(new KspVersion(1, 0, 4, 0), false) + new GameVersionRange( + new GameVersionBound(), + new GameVersionBound(new GameVersion(1, 0, 4, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 3, 0), true), - new KspVersionBound(new KspVersion(1, 0, 4, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 3, 0), true), + new GameVersionBound(new GameVersion(1, 0, 4, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 3, 0), true), - new KspVersionBound(new KspVersion(1, 0, 4, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 3, 0), true), + new GameVersionBound(new GameVersion(1, 0, 4, 0), false) ) } }; @@ -322,103 +323,103 @@ public sealed class KspVersionRangeTests { new object[] { - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), - new KspVersionRange(new KspVersionBound(), new KspVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), + new GameVersionRange(new GameVersionBound(), new GameVersionBound()), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), false), - new KspVersionBound(new KspVersion(2, 0, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), false), + new GameVersionBound(new GameVersion(2, 0, 0, 0), false) ), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), false), - new KspVersionBound(new KspVersion(2, 0, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), false), + new GameVersionBound(new GameVersion(2, 0, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), false), - new KspVersionBound(new KspVersion(2, 0, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), false), + new GameVersionBound(new GameVersion(2, 0, 0, 0), false) ), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), false), - new KspVersionBound(new KspVersion(2, 0, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), false), + new GameVersionBound(new GameVersion(2, 0, 0, 0), false) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), false }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(3, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(3, 0, 0, 0), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(2, 0, 0, 0), false), - new KspVersionBound(new KspVersion(4, 0, 0, 0), false) + new GameVersionRange( + new GameVersionBound(new GameVersion(2, 0, 0, 0), false), + new GameVersionBound(new GameVersion(4, 0, 0, 0), false) ), false }, new object[] { - new KspVersionRange( - new KspVersionBound(), - new KspVersionBound(new KspVersion(3, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(), + new GameVersionBound(new GameVersion(3, 0, 0, 0), true) ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), true }, new object[] { - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound() + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound() ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), true }, new object[] { - new KspVersionRange( - new KspVersionBound(), - new KspVersionBound() + new GameVersionRange( + new GameVersionBound(), + new GameVersionBound() ), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), true) + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), true) ), true }, @@ -428,11 +429,11 @@ public sealed class KspVersionRangeTests public void CtorWorksCorrectly() { // Arrange - var lower = new KspVersionBound(new KspVersion(1, 2, 3, 4), false); - var upper = new KspVersionBound(new KspVersion(5, 6, 7, 8), true); + var lower = new GameVersionBound(new GameVersion(1, 2, 3, 4), false); + var upper = new GameVersionBound(new GameVersion(5, 6, 7, 8), true); // Act - var result = new KspVersionRange(lower, upper); + var result = new GameVersionRange(lower, upper); // Assert Assert.That(result.Lower, Is.EqualTo(lower)); @@ -443,14 +444,14 @@ public void CtorWorksCorrectly() public void RangeFromVersionsEqualsRangeFromBounds() { // Arrange - var lowerBound = new KspVersionBound(new KspVersion(1, 2, 0, 0), true); - var upperBound = new KspVersionBound(new KspVersion(2, 4, 7, 0), false); - var lowerVersion = new KspVersion(1, 2); - var upperVersion = new KspVersion(2, 4, 6); + var lowerBound = new GameVersionBound(new GameVersion(1, 2, 0, 0), true); + var upperBound = new GameVersionBound(new GameVersion(2, 4, 7, 0), false); + var lowerVersion = new GameVersion(1, 2); + var upperVersion = new GameVersion(2, 4, 6); // Act - var resultFromBounds = new KspVersionRange(lowerBound, upperBound); - var resultFromVersions = new KspVersionRange(lowerVersion, upperVersion); + var resultFromBounds = new GameVersionRange(lowerBound, upperBound); + var resultFromVersions = new GameVersionRange(lowerVersion, upperVersion); // Assert Assert.That(resultFromBounds.Lower, Is.EqualTo(resultFromVersions.Lower)); @@ -463,7 +464,7 @@ public void CtorThrowsOnNullLowerParameter() // Act // ReSharper disable once ObjectCreationAsStatement TestDelegate act = - () => new KspVersionRange(null, new KspVersionBound(new KspVersion(1, 2, 3, 4), false)); + () => new GameVersionRange(null, new GameVersionBound(new GameVersion(1, 2, 3, 4), false)); // Assert Assert.That(act, Throws.Exception); @@ -475,14 +476,14 @@ public void CtorThrowsOnNullUpperParameter() // Act // ReSharper disable once ObjectCreationAsStatement TestDelegate act = - () => new KspVersionRange(new KspVersionBound(new KspVersion(1, 2, 3, 4), false), null); + () => new GameVersionRange(new GameVersionBound(new GameVersion(1, 2, 3, 4), false), null); // Assert Assert.That(act, Throws.Exception); } [TestCaseSource("ToStringCases")] - public void ToStringWorksCorrectly(KspVersionRange vr, string expected) + public void ToStringWorksCorrectly(GameVersionRange vr, string expected) { // Act var result = vr.ToString(); @@ -492,7 +493,7 @@ public void ToStringWorksCorrectly(KspVersionRange vr, string expected) } [TestCaseSource("IntersectWithCases")] - public void IntersectWithWorksCorrectly(KspVersionRange left, KspVersionRange right, KspVersionRange expected) + public void IntersectWithWorksCorrectly(GameVersionRange left, GameVersionRange right, GameVersionRange expected) { // Act var result = left.IntersectWith(right); @@ -502,7 +503,7 @@ public void IntersectWithWorksCorrectly(KspVersionRange left, KspVersionRange ri } [TestCaseSource("IsSupersetOfCases")] - public void IsSupersetOfWorksCorrectly(KspVersionRange left, KspVersionRange right, bool expected) + public void IsSupersetOfWorksCorrectly(GameVersionRange left, GameVersionRange right, bool expected) { // Act var result = left.IsSupersetOf(right); @@ -515,7 +516,7 @@ public void IsSupersetOfWorksCorrectly(KspVersionRange left, KspVersionRange rig public void IsSupersetOfThrowsOnNullParameter() { // Arrange - var sut = new KspVersionRange(new KspVersionBound(), new KspVersionBound()); + var sut = new GameVersionRange(new GameVersionBound(), new GameVersionBound()); // Act TestDelegate act = () => sut.IsSupersetOf(null); @@ -525,7 +526,7 @@ public void IsSupersetOfThrowsOnNullParameter() } [TestCaseSource("EqualityCases")] - public void EqualityWorksCorrectly(KspVersionRange vr1, KspVersionRange vr2, bool areEqual) + public void EqualityWorksCorrectly(GameVersionRange vr1, GameVersionRange vr2, bool areEqual) { // Act var genericEquals = vr1.Equals(vr2); @@ -548,7 +549,7 @@ public void EqualityWorksCorrectly(KspVersionRange vr1, KspVersionRange vr2, boo public void NullEqualityWorksCorrectly() { // Arrange - var sut = new KspVersionRange(new KspVersionBound(), new KspVersionBound()); + var sut = new GameVersionRange(new GameVersionBound(), new GameVersionBound()); // Act // ReSharper disable ConditionIsAlwaysTrueOrFalse @@ -573,7 +574,7 @@ public void NullEqualityWorksCorrectly() public void ReferenceEqualityWorksCorrectly() { // Arrange - var sut = new KspVersionRange(new KspVersionBound(), new KspVersionBound()); + var sut = new GameVersionRange(new GameVersionBound(), new GameVersionBound()); // Act var genericEquals = sut.Equals(sut); @@ -599,19 +600,19 @@ public void GetHashCodeDoesNotThrow( ) { // Arrange - var lower = new KspVersionBound( - new KspVersion(lowerMajor, lowerMinor, lowerPatch, lowerBuilder), + var lower = new GameVersionBound( + new GameVersion(lowerMajor, lowerMinor, lowerPatch, lowerBuilder), lowerInclusive ); - var upper = new KspVersionBound( - new KspVersion(upperMajor, upperMinor, upperPatch, upperBuilder), + var upper = new GameVersionBound( + new GameVersion(upperMajor, upperMinor, upperPatch, upperBuilder), upperInclusive ); // Act // ReSharper disable once ReturnValueOfPureMethodIsNotUsed - TestDelegate act = () => new KspVersionRange(lower, upper).GetHashCode(); + TestDelegate act = () => new GameVersionRange(lower, upper).GetHashCode(); // Assert Assert.That(act, Throws.Nothing); @@ -621,10 +622,11 @@ public void GetHashCodeDoesNotThrow( public void VersionSpan_AllVersions_CorrectString() { // Arrange - KspVersion min = KspVersion.Any; - KspVersion max = KspVersion.Any; + IGame game = new KerbalSpaceProgram(); + GameVersion min = GameVersion.Any; + GameVersion max = GameVersion.Any; // Act - string s = KspVersionRange.VersionSpan(min, max); + string s = GameVersionRange.VersionSpan(game, min, max); // Assert Assert.AreEqual("KSP all versions", s); } @@ -633,10 +635,11 @@ public void VersionSpan_AllVersions_CorrectString() public void VersionSpan_MinOnly_CorrectString() { // Arrange - KspVersion min = new KspVersion(1, 0, 0); - KspVersion max = KspVersion.Any; + IGame game = new KerbalSpaceProgram(); + GameVersion min = new GameVersion(1, 0, 0); + GameVersion max = GameVersion.Any; // Act - string s = KspVersionRange.VersionSpan(min, max); + string s = GameVersionRange.VersionSpan(game, min, max); // Assert Assert.AreEqual("KSP 1.0.0 and later", s); } @@ -645,10 +648,11 @@ public void VersionSpan_MinOnly_CorrectString() public void VersionSpan_MaxOnly_CorrectString() { // Arrange - KspVersion min = KspVersion.Any; - KspVersion max = new KspVersion(1, 0, 0); + IGame game = new KerbalSpaceProgram(); + GameVersion min = GameVersion.Any; + GameVersion max = new GameVersion(1, 0, 0); // Act - string s = KspVersionRange.VersionSpan(min, max); + string s = GameVersionRange.VersionSpan(game, min, max); // Assert Assert.AreEqual("KSP 1.0.0 and earlier", s); } @@ -657,10 +661,11 @@ public void VersionSpan_MaxOnly_CorrectString() public void VersionSpan_OneOnly_CorrectString() { // Arrange - KspVersion min = new KspVersion(1, 0, 0); - KspVersion max = new KspVersion(1, 0, 0); + IGame game = new KerbalSpaceProgram(); + GameVersion min = new GameVersion(1, 0, 0); + GameVersion max = new GameVersion(1, 0, 0); // Act - string s = KspVersionRange.VersionSpan(min, max); + string s = GameVersionRange.VersionSpan(game, min, max); // Assert Assert.AreEqual("KSP 1.0.0", s); } @@ -669,10 +674,11 @@ public void VersionSpan_OneOnly_CorrectString() public void VersionSpan_FiniteRange_CorrectString() { // Arrange - KspVersion min = new KspVersion(1, 0, 0); - KspVersion max = new KspVersion(1, 1, 1); + IGame game = new KerbalSpaceProgram(); + GameVersion min = new GameVersion(1, 0, 0); + GameVersion max = new GameVersion(1, 1, 1); // Act - string s = KspVersionRange.VersionSpan(min, max); + string s = GameVersionRange.VersionSpan(game, min, max); // Assert Assert.AreEqual("KSP 1.0.0 - 1.1.1", s); } diff --git a/Tests/Core/Versioning/KspVersionTests.cs b/Tests/Core/Versioning/KspVersionTests.cs index df921ff72b..32fd98f729 100644 --- a/Tests/Core/Versioning/KspVersionTests.cs +++ b/Tests/Core/Versioning/KspVersionTests.cs @@ -7,14 +7,14 @@ namespace Tests.Core.Versioning { [TestFixture] - public class KspVersionTests + public class GameVersionTests { private static readonly object[] ParseCases = { - new object[] { "1", new KspVersion(1) }, - new object[] { "1.2", new KspVersion(1, 2) }, - new object[] { "1.2.3", new KspVersion(1, 2, 3) }, - new object[] { "1.2.3.4", new KspVersion(1, 2, 3, 4) } + new object[] { "1", new GameVersion(1) }, + new object[] { "1.2", new GameVersion(1, 2) }, + new object[] { "1.2.3", new GameVersion(1, 2, 3) }, + new object[] { "1.2.3.4", new GameVersion(1, 2, 3, 4) } }; private static readonly object[] ParseFailureCases = @@ -32,70 +32,70 @@ public class KspVersionTests private static readonly object[] EqualityCases = { - new object[] { new KspVersion(), null, false }, - new object[] { new KspVersion(), new KspVersion(), true }, - new object[] { new KspVersion(1), new KspVersion(1), true }, - new object[] { new KspVersion(1, 2), new KspVersion(1, 2), true}, - new object[] { new KspVersion(1, 2, 3), new KspVersion(1, 2, 3), true}, - new object[] { new KspVersion(1, 2, 3, 4), new KspVersion(1, 2, 3, 4), true}, - new object[] { new KspVersion(), new KspVersion(1), false }, - new object[] { new KspVersion(1), new KspVersion(1, 2), false }, - new object[] { new KspVersion(1, 2), new KspVersion(1, 2, 3), false}, - new object[] { new KspVersion(1, 2, 3), new KspVersion(1, 2, 3, 4), false}, - new object[] { new KspVersion(1, 2, 3, 4), new KspVersion(1, 2, 3, 5), false} + new object[] { new GameVersion(), null, false }, + new object[] { new GameVersion(), new GameVersion(), true }, + new object[] { new GameVersion(1), new GameVersion(1), true }, + new object[] { new GameVersion(1, 2), new GameVersion(1, 2), true}, + new object[] { new GameVersion(1, 2, 3), new GameVersion(1, 2, 3), true}, + new object[] { new GameVersion(1, 2, 3, 4), new GameVersion(1, 2, 3, 4), true}, + new object[] { new GameVersion(), new GameVersion(1), false }, + new object[] { new GameVersion(1), new GameVersion(1, 2), false }, + new object[] { new GameVersion(1, 2), new GameVersion(1, 2, 3), false}, + new object[] { new GameVersion(1, 2, 3), new GameVersion(1, 2, 3, 4), false}, + new object[] { new GameVersion(1, 2, 3, 4), new GameVersion(1, 2, 3, 5), false} }; private static readonly object[] CompareToCases = { - new object[] { new KspVersion(), new KspVersion(), 0 }, - new object[] { new KspVersion(1), new KspVersion(1), 0 }, - new object[] { new KspVersion(1, 2), new KspVersion(1, 2), 0 }, - new object[] { new KspVersion(1, 2, 3), new KspVersion(1, 2, 3), 0 }, - new object[] { new KspVersion(1, 2, 3, 4), new KspVersion(1, 2, 3, 4), 0 }, - new object[] { new KspVersion(), new KspVersion(1), -1 }, - new object[] { new KspVersion(1), new KspVersion(1, 2), -1 }, - new object[] { new KspVersion(1, 2), new KspVersion(1, 2, 3), -1 }, - new object[] { new KspVersion(1, 2, 3), new KspVersion(1, 2, 3, 4), -1 }, - new object[] { new KspVersion(1, 2, 3, 4), new KspVersion(1, 2, 3, 5), -1 }, - new object[] { new KspVersion(1), new KspVersion(), 1 }, - new object[] { new KspVersion(1, 2), new KspVersion(1), 1 }, - new object[] { new KspVersion(1, 2, 3), new KspVersion(1, 2), 1 }, - new object[] { new KspVersion(1, 2, 3, 5), new KspVersion(1, 2, 3, 4), 1} + new object[] { new GameVersion(), new GameVersion(), 0 }, + new object[] { new GameVersion(1), new GameVersion(1), 0 }, + new object[] { new GameVersion(1, 2), new GameVersion(1, 2), 0 }, + new object[] { new GameVersion(1, 2, 3), new GameVersion(1, 2, 3), 0 }, + new object[] { new GameVersion(1, 2, 3, 4), new GameVersion(1, 2, 3, 4), 0 }, + new object[] { new GameVersion(), new GameVersion(1), -1 }, + new object[] { new GameVersion(1), new GameVersion(1, 2), -1 }, + new object[] { new GameVersion(1, 2), new GameVersion(1, 2, 3), -1 }, + new object[] { new GameVersion(1, 2, 3), new GameVersion(1, 2, 3, 4), -1 }, + new object[] { new GameVersion(1, 2, 3, 4), new GameVersion(1, 2, 3, 5), -1 }, + new object[] { new GameVersion(1), new GameVersion(), 1 }, + new object[] { new GameVersion(1, 2), new GameVersion(1), 1 }, + new object[] { new GameVersion(1, 2, 3), new GameVersion(1, 2), 1 }, + new object[] { new GameVersion(1, 2, 3, 5), new GameVersion(1, 2, 3, 4), 1} }; private static readonly object[] ToVersionRangeWorksCorrectlyCases = { - new object[] { new KspVersion(), KspVersionRange.Any }, + new object[] { new GameVersion(), GameVersionRange.Any }, new object[] { - new KspVersion(1), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 0, 0, 0), inclusive: true), - new KspVersionBound(new KspVersion(2, 0, 0, 0), inclusive: false) + new GameVersion(1), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 0, 0, 0), inclusive: true), + new GameVersionBound(new GameVersion(2, 0, 0, 0), inclusive: false) ) }, new object[] { - new KspVersion(1, 2), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 0, 0), inclusive: true), - new KspVersionBound(new KspVersion(1, 3, 0, 0), inclusive: false) + new GameVersion(1, 2), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 0, 0), inclusive: true), + new GameVersionBound(new GameVersion(1, 3, 0, 0), inclusive: false) ) }, new object[] { - new KspVersion(1, 2, 3), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 0), inclusive: true), - new KspVersionBound(new KspVersion(1, 2, 4, 0), inclusive: false) + new GameVersion(1, 2, 3), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 0), inclusive: true), + new GameVersionBound(new GameVersion(1, 2, 4, 0), inclusive: false) ) }, new object[] { - new KspVersion(1, 2, 3, 4), - new KspVersionRange( - new KspVersionBound(new KspVersion(1, 2, 3, 4), inclusive: true), - new KspVersionBound(new KspVersion(1, 2, 3, 4), inclusive: true) + new GameVersion(1, 2, 3, 4), + new GameVersionRange( + new GameVersionBound(new GameVersion(1, 2, 3, 4), inclusive: true), + new GameVersionBound(new GameVersion(1, 2, 3, 4), inclusive: true) ) } }; @@ -104,7 +104,7 @@ public class KspVersionTests public void ParameterlessCtorWorksCorrectly() { // Act - var result = new KspVersion(); + var result = new GameVersion(); // Assert Assert.AreEqual(-1, result.Major); @@ -127,7 +127,7 @@ public void ParameterlessCtorWorksCorrectly() public void SingleParameterCtorWorksCorrectly() { // Act - var result = new KspVersion(1); + var result = new GameVersion(1); // Assert Assert.AreEqual(1, result.Major); @@ -151,7 +151,7 @@ public void SingleParameterCtorThrowsOnInvalidParameters(int major) { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => new KspVersion(major); + TestDelegate act = () => new GameVersion(major); // Assert Assert.That(act, Throws.Exception.InstanceOf()); @@ -161,7 +161,7 @@ public void SingleParameterCtorThrowsOnInvalidParameters(int major) public void DoubleParameterCtorWorksCorrectly() { // Act - var result = new KspVersion(1, 2); + var result = new GameVersion(1, 2); // Assert Assert.AreEqual(1, result.Major); @@ -186,7 +186,7 @@ public void DoubleParameterCtorThrowsOnInvalidParameters(int major, int minor) { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => new KspVersion(major, minor); + TestDelegate act = () => new GameVersion(major, minor); // Assert Assert.That(act, Throws.Exception.InstanceOf()); @@ -196,7 +196,7 @@ public void DoubleParameterCtorThrowsOnInvalidParameters(int major, int minor) public void TripleParameterCtorWorksCorrectly() { // Act - var result = new KspVersion(1, 2, 3); + var result = new GameVersion(1, 2, 3); // Assert Assert.AreEqual(1, result.Major); @@ -222,7 +222,7 @@ public void TripleParameterCtorThrowsOnInvalidParameters(int major, int minor, i { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => new KspVersion(major, minor, patch); + TestDelegate act = () => new GameVersion(major, minor, patch); // Assert Assert.That(act, Throws.Exception.InstanceOf()); @@ -232,7 +232,7 @@ public void TripleParameterCtorThrowsOnInvalidParameters(int major, int minor, i public void QuadrupleParameterCtorWorksCorrectly() { // Act - var result = new KspVersion(1, 2, 3, 4); + var result = new GameVersion(1, 2, 3, 4); // Assert Assert.AreEqual(1, result.Major); @@ -259,17 +259,17 @@ public void QuadrupleParameterCtorThrowsOnInvalidParameters(int major, int minor { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => new KspVersion(major, minor, patch, build); + TestDelegate act = () => new GameVersion(major, minor, patch, build); // Assert Assert.That(act, Throws.Exception.InstanceOf()); } [TestCaseSource("ParseCases")] - public void ParseWorksCorrectly(string s, KspVersion version) + public void ParseWorksCorrectly(string s, GameVersion version) { // Act - var result = KspVersion.Parse(s); + var result = GameVersion.Parse(s); // Assert Assert.AreEqual(version, result); @@ -281,14 +281,14 @@ public void ParseThrowsExceptionOnInvalidParameter(string s) { // Act // ReSharper disable once ObjectCreationAsStatement - TestDelegate act = () => KspVersion.Parse(s); + TestDelegate act = () => GameVersion.Parse(s); // Assert Assert.That(act, Throws.Exception); } [TestCaseSource("ToVersionRangeWorksCorrectlyCases")] - public void ToVersionRangeWorksCorrectly(KspVersion version, KspVersionRange expectedRange) + public void ToVersionRangeWorksCorrectly(GameVersion version, GameVersionRange expectedRange) { // Act var result = version.ToVersionRange(); @@ -298,11 +298,11 @@ public void ToVersionRangeWorksCorrectly(KspVersion version, KspVersionRange exp } [TestCaseSource("ParseCases")] - public void TryParseWorksCorrectly(string s, KspVersion version) + public void TryParseWorksCorrectly(string s, GameVersion version) { // Act - KspVersion result; - var success = KspVersion.TryParse(s, out result); + GameVersion result; + var success = GameVersion.TryParse(s, out result); // Assert Assert.IsTrue(success); @@ -314,15 +314,15 @@ public void TryParseWorksCorrectly(string s, KspVersion version) public void TryParseReturnsFalseOnInvalidParameter(string s) { // Act - KspVersion result; - var success = KspVersion.TryParse(s, out result); + GameVersion result; + var success = GameVersion.TryParse(s, out result); // Assert Assert.IsFalse(success); } [TestCaseSource("EqualityCases")] - public void EqualityWorksCorrectly(KspVersion a, KspVersion b, bool areEqual) + public void EqualityWorksCorrectly(GameVersion a, GameVersion b, bool areEqual) { // Act var genericEquality = a.Equals(b); @@ -342,7 +342,7 @@ public void EqualityWorksCorrectly(KspVersion a, KspVersion b, bool areEqual) } [TestCaseSource("CompareToCases")] - public void CompareToWorksCorrectly(KspVersion v1, KspVersion v2, int comparison) + public void CompareToWorksCorrectly(GameVersion v1, GameVersion v2, int comparison) { // Act var genericCompareTo = v1.CompareTo(v2); @@ -380,16 +380,16 @@ public void CompareToThrowsOnNullParameters() // Act // ReSharper disable ReturnValueOfPureMethodIsNotUsed // ReSharper disable UnusedVariable - TestDelegate actGenericCompareTo = () => new KspVersion().CompareTo(null); - TestDelegate actNonGenericCompareTo = () => new KspVersion().CompareTo((object)null); - TestDelegate lessThanOperatorNullLeft = () => { var _ = null < new KspVersion(); }; - TestDelegate lessThanOperatorNullRight = () => { var _ = new KspVersion() < null; }; - TestDelegate lessThanOrEqualOperatorNullLeft = () => { var _ = null <= new KspVersion(); }; - TestDelegate lessThanOrEqualOperatorNullRight = () => { var _ = new KspVersion() <= null; }; - TestDelegate greaterThanOperatorNullLeft = () => { var _ = null > new KspVersion(); }; - TestDelegate greaterThanOperatorNullRight = () => { var _ = new KspVersion() > null; }; - TestDelegate greaterThanOrEqualOperatorNullLeft = () => { var _ = null >= new KspVersion(); }; - TestDelegate greaterThanOrEqualOperatorNullRight = () => { var _ = new KspVersion() >= null; }; + TestDelegate actGenericCompareTo = () => new GameVersion().CompareTo(null); + TestDelegate actNonGenericCompareTo = () => new GameVersion().CompareTo((object)null); + TestDelegate lessThanOperatorNullLeft = () => { var _ = null < new GameVersion(); }; + TestDelegate lessThanOperatorNullRight = () => { var _ = new GameVersion() < null; }; + TestDelegate lessThanOrEqualOperatorNullLeft = () => { var _ = null <= new GameVersion(); }; + TestDelegate lessThanOrEqualOperatorNullRight = () => { var _ = new GameVersion() <= null; }; + TestDelegate greaterThanOperatorNullLeft = () => { var _ = null > new GameVersion(); }; + TestDelegate greaterThanOperatorNullRight = () => { var _ = new GameVersion() > null; }; + TestDelegate greaterThanOrEqualOperatorNullLeft = () => { var _ = null >= new GameVersion(); }; + TestDelegate greaterThanOrEqualOperatorNullRight = () => { var _ = new GameVersion() >= null; }; // ReSharper restore UnusedVariable // ReSharper restore ReturnValueOfPureMethodIsNotUsed @@ -411,7 +411,7 @@ public void NonGenericCompareToThrowsOnInvalidType() { // Act // ReSharper disable once ReturnValueOfPureMethodIsNotUsed - TestDelegate act = () => new KspVersion().CompareTo(new object()); + TestDelegate act = () => new GameVersion().CompareTo(new object()); // Assert Assert.That(act, Throws.ArgumentException); @@ -427,7 +427,7 @@ public void GetHashCodeDoesNotThrow( { // Act // ReSharper disable once ReturnValueOfPureMethodIsNotUsed - TestDelegate act = () => new KspVersion(major, minor, patch, build).GetHashCode(); + TestDelegate act = () => new GameVersion(major, minor, patch, build).GetHashCode(); // Assert Assert.That(act, Throws.Nothing); diff --git a/Tests/Data/DisposableKSP.cs b/Tests/Data/DisposableKSP.cs index f0f22a6b3c..f0143b0d66 100644 --- a/Tests/Data/DisposableKSP.cs +++ b/Tests/Data/DisposableKSP.cs @@ -1,7 +1,8 @@ using System; using System.IO; -using CKAN; using NUnit.Framework; +using CKAN; +using CKAN.Games; namespace Tests.Data { @@ -15,7 +16,7 @@ public class DisposableKSP : IDisposable private readonly string _goodKsp = TestData.good_ksp_dir(); private readonly string _disposableDir; - public KSP KSP { get; private set; } + public GameInstance KSP { get; private set; } /// /// Creates a copy of the provided argument, or a known-good KSP install if passed null. @@ -38,7 +39,7 @@ public DisposableKSP(string directoryToClone = null, string registryFile = null) File.Copy(registryFile, registryPath, true); } - KSP = new KSP(_disposableDir, "disposable", new NullUser()); + KSP = new GameInstance(new KerbalSpaceProgram(), _disposableDir, "disposable", new NullUser()); Logging.Initialize(); } diff --git a/Tests/Data/TestData.cs b/Tests/Data/TestData.cs index 81307a4062..88447d8339 100644 --- a/Tests/Data/TestData.cs +++ b/Tests/Data/TestData.cs @@ -719,14 +719,16 @@ public static string GoodJsonConfig() { return @" { - ""KspInstances"": [ + ""GameInstances"": [ { ""Name"": ""instance1"", - ""Path"": ""instance1_path"" + ""Path"": ""instance1_path"", + ""Game"": ""KSP"" }, { ""Name"": ""instance2"", - ""Path"": ""instance2_path"" + ""Path"": ""instance2_path"", + ""Game"": ""KSP"" } ], ""AuthTokens"": { @@ -751,14 +753,16 @@ public static string MissingJsonConfig() { return @" { - ""KspInstances"": [ + ""GameInstances"": [ { ""Name"": ""instance1"", - ""Path"": ""instance1_path"" + ""Path"": ""instance1_path"", + ""Game"": ""KSP"" }, { ""Name"": ""instance2"", - ""Path"": ""instance2_path"" + ""Path"": ""instance2_path"", + ""Game"": ""KSP"" } ], ""RefreshRate"": 4, @@ -775,14 +779,16 @@ public static string ExtraJsonConfig() { return @" { - ""KspInstances"": [ + ""GameInstances"": [ { ""Name"": ""instance1"", - ""Path"": ""instance1_path"" + ""Path"": ""instance1_path"", + ""Game"": ""KSP"" }, { ""Name"": ""instance2"", - ""Path"": ""instance2_path"" + ""Path"": ""instance2_path"", + ""Game"": ""KSP"" } ], ""AuthTokens"": { @@ -810,14 +816,16 @@ public static string BadJsonConfig() { return @" { - ""KspInstances"": + ""GameInstances"": { ""Name"": ""instance1"", - ""Path"": ""instance1_path"" + ""Path"": ""instance1_path"", + ""Game"": ""KSP"" }, { ""Name"": ""instance2"", - ""Path"": ""instance2_path"" + ""Path"": ""instance2_path"", + ""Game"": ""KSP"" } ], ""AuthTokens"": { @@ -849,7 +857,7 @@ public RandomModuleGenerator(Random generator) } public CkanModule GeneratorRandomModule( - KspVersion ksp_version = null, + GameVersion ksp_version = null, List conflicts = null, List depends = null, List suggests = null, @@ -863,7 +871,7 @@ public CkanModule GeneratorRandomModule( @abstract = Generator.Next().ToString(CultureInfo.InvariantCulture), identifier = identifier ?? Generator.Next().ToString(CultureInfo.InvariantCulture), spec_version = new ModuleVersion(1.ToString(CultureInfo.InvariantCulture)), - ksp_version = ksp_version ?? KspVersion.Parse("0." + Generator.Next()), + ksp_version = ksp_version ?? GameVersion.Parse("0." + Generator.Next()), version = version ?? new ModuleVersion(Generator.Next().ToString(CultureInfo.InvariantCulture)) }; mod.ksp_version_max = mod.ksp_version_min = null; diff --git a/Tests/GUI/GH1866.cs b/Tests/GUI/GH1866.cs index f028b5756c..8c5178f29f 100644 --- a/Tests/GUI/GH1866.cs +++ b/Tests/GUI/GH1866.cs @@ -19,7 +19,7 @@ public class GH1866 { private CkanModule _anyVersionModule; private DisposableKSP _instance; - private KSPManager _manager; + private GameInstanceManager _manager; private FakeConfiguration _config; private RegistryManager _registryManager; private Registry _registry; @@ -57,7 +57,7 @@ public void Up() _registryManager = RegistryManager.Instance(_instance.KSP); _registry = Registry.Empty(); _config = new FakeConfiguration(_instance.KSP, _instance.KSP.Name); - _manager = new KSPManager( + _manager = new GameInstanceManager( new NullUser(), _config ); diff --git a/Tests/GUI/GUIMod.cs b/Tests/GUI/GUIMod.cs index 9d51f6c160..b46b8e1dd5 100644 --- a/Tests/GUI/GUIMod.cs +++ b/Tests/GUI/GUIMod.cs @@ -21,7 +21,7 @@ public void NewGuiModsAreNotSelectedForUpgrade() { var config = new FakeConfiguration(tidy.KSP, tidy.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { @@ -57,7 +57,7 @@ public void HasUpdateReturnsTrueWhenUpdateAvailible() } [Test] - public void KSPCompatibility_OutOfOrderGameVersions_TrueMaxVersion() + public void GameCompatibility_OutOfOrderGameVersions_TrueMaxVersion() { using (var tidy = new DisposableKSP()) { @@ -83,7 +83,7 @@ public void KSPCompatibility_OutOfOrderGameVersions_TrueMaxVersion() GUIMod m = new GUIMod(mainVersion, registry, tidy.KSP.VersionCriteria(), false); // Assert - Assert.AreEqual("1.4.2", m.KSPCompatibility); + Assert.AreEqual("1.4.2", m.GameCompatibility); } } diff --git a/Tests/GUI/ModList.cs b/Tests/GUI/ModList.cs index 32c7e6fd9b..1cd5bf1002 100644 --- a/Tests/GUI/ModList.cs +++ b/Tests/GUI/ModList.cs @@ -48,7 +48,7 @@ public void IsVisible_WithAllAndNoNameFilter_ReturnsTrueForCompatible() { var config = new FakeConfiguration(tidy.KSP, tidy.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { @@ -88,7 +88,7 @@ public void ConstructModList_NumberOfRows_IsEqualToNumberOfMods() { var config = new FakeConfiguration(tidy.KSP, tidy.KSP.Name); - KSPManager manager = new KSPManager( + GameInstanceManager manager = new GameInstanceManager( new NullUser(), config ) { diff --git a/Tests/GUI/ResourcesTests.cs b/Tests/GUI/ResourcesTests.cs index d4dada84b4..7f514ba3ea 100644 --- a/Tests/GUI/ResourcesTests.cs +++ b/Tests/GUI/ResourcesTests.cs @@ -31,12 +31,12 @@ public class ResourcesTests TestCase(typeof(CKAN.Main)), TestCase(typeof(CKAN.AboutDialog)), TestCase(typeof(CKAN.AskUserForAutoUpdatesDialog)), - TestCase(typeof(CKAN.CloneFakeKspDialog)), - TestCase(typeof(CKAN.CompatibleKspVersionsDialog)), + TestCase(typeof(CKAN.CloneFakeGameDialog)), + TestCase(typeof(CKAN.CompatibleGameVersionsDialog)), TestCase(typeof(CKAN.EditLabelsDialog)), TestCase(typeof(CKAN.ErrorDialog)), - TestCase(typeof(CKAN.KSPCommandLineOptionsDialog)), - TestCase(typeof(CKAN.ManageKspInstancesDialog)), + TestCase(typeof(CKAN.GameCommandLineOptionsDialog)), + TestCase(typeof(CKAN.ManageGameInstancesDialog)), TestCase(typeof(CKAN.NewRepoDialog)), TestCase(typeof(CKAN.NewUpdateDialog)), TestCase(typeof(CKAN.PluginsDialog)), diff --git a/Tests/NetKAN/AVC.cs b/Tests/NetKAN/AVC.cs index c62eac2896..a3efed4bc8 100644 --- a/Tests/NetKAN/AVC.cs +++ b/Tests/NetKAN/AVC.cs @@ -40,61 +40,61 @@ public void JsonOneLineVersion() [Test] public void WildcardMajor_OutputsAnyVersion() { - var converter = new JsonAvcToKspVersion(); + var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":-1, ""MINOR"":-1, ""PATCH"":-1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (KspVersion) converter.ReadJson(reader, null, null, null); + var result = (GameVersion) converter.ReadJson(reader, null, null, null); Assert.That(!result.IsMajorDefined); } [Test] public void WildcardMinor_VersionOnlyHasMajor() { - var converter = new JsonAvcToKspVersion(); + var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1, ""MINOR"":-1, ""PATCH"":-1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (KspVersion) converter.ReadJson(reader, null, null, null); - Assert.That(result, Is.EqualTo(KspVersion.Parse("1"))); + var result = (GameVersion) converter.ReadJson(reader, null, null, null); + Assert.That(result, Is.EqualTo(GameVersion.Parse("1"))); } [Test] public void WildcardPatch_VersionOnlyHasMajorMinor() { - var converter = new JsonAvcToKspVersion(); + var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1, ""MINOR"":5, ""PATCH"":-1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (KspVersion)converter.ReadJson(reader, null, null, null); - Assert.That(result, Is.EqualTo(KspVersion.Parse("1.5"))); + var result = (GameVersion)converter.ReadJson(reader, null, null, null); + Assert.That(result, Is.EqualTo(GameVersion.Parse("1.5"))); } [Test] public void MissingMajor_OutputsAnyVersion() { - var converter = new JsonAvcToKspVersion(); + var converter = new JsonAvcToGameVersion(); string json = @"{}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (KspVersion) converter.ReadJson(reader, null, null, null); + var result = (GameVersion) converter.ReadJson(reader, null, null, null); Assert.That(!result.IsMajorDefined); } [Test] public void MissingMinor_VersionOnlyHasMajor() { - var converter = new JsonAvcToKspVersion(); + var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (KspVersion) converter.ReadJson(reader, null, null, null); - Assert.That(result, Is.EqualTo(KspVersion.Parse("1"))); + var result = (GameVersion) converter.ReadJson(reader, null, null, null); + Assert.That(result, Is.EqualTo(GameVersion.Parse("1"))); } [Test] public void MissingPatch_VersionOnlyHasMajorMinor() { - var converter = new JsonAvcToKspVersion(); + var converter = new JsonAvcToGameVersion(); string json = @"{""MAJOR"":1, ""MINOR"":5}"; var reader = new JsonTextReader(new StringReader(json)); - var result = (KspVersion)converter.ReadJson(reader, null, null, null); - Assert.That(result, Is.EqualTo(KspVersion.Parse("1.5"))); + var result = (GameVersion)converter.ReadJson(reader, null, null, null); + Assert.That(result, Is.EqualTo(GameVersion.Parse("1.5"))); } } diff --git a/Tests/NetKAN/SDMod.cs b/Tests/NetKAN/SDMod.cs index 103259f1f2..7c1262546f 100644 --- a/Tests/NetKAN/SDMod.cs +++ b/Tests/NetKAN/SDMod.cs @@ -43,7 +43,7 @@ public void SD_Expand_KSP_Version_1156(string original, string expected) { Assert.AreEqual( expected, - SDVersion.JsonConvertKSPVersion.ExpandVersionIfNeeded(original) + SDVersion.JsonConvertGameVersion.ExpandVersionIfNeeded(original) ); } } diff --git a/Tests/NetKAN/Services/ModuleServiceTests.cs b/Tests/NetKAN/Services/ModuleServiceTests.cs index 9c3d62c8c5..00318d56e6 100644 --- a/Tests/NetKAN/Services/ModuleServiceTests.cs +++ b/Tests/NetKAN/Services/ModuleServiceTests.cs @@ -87,13 +87,13 @@ public void GetsInternalAvcCorrectly() Assert.That(result.version, Is.EqualTo(new ModuleVersion("1.1.0.0")), "ModuleService should get correct version from the internal AVC file." ); - Assert.That(result.ksp_version, Is.EqualTo(KspVersion.Parse("0.24.2")), + Assert.That(result.ksp_version, Is.EqualTo(GameVersion.Parse("0.24.2")), "ModuleService should get correct ksp_version from the internal AVC file." ); - Assert.That(result.ksp_version_min, Is.EqualTo(KspVersion.Parse("0.24.0")), + Assert.That(result.ksp_version_min, Is.EqualTo(GameVersion.Parse("0.24.0")), "ModuleService should get correct ksp_version_min from the internal AVC file." ); - Assert.That(result.ksp_version_max, Is.EqualTo(KspVersion.Parse("0.24.2")), + Assert.That(result.ksp_version_max, Is.EqualTo(GameVersion.Parse("0.24.2")), "ModuleService should get correct ksp_version_max from the internal AVC file." ); } diff --git a/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs b/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs index 46f50a9055..5d3a1eb249 100644 --- a/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs +++ b/Tests/NetKAN/Transformers/AvcKrefTransformerTests.cs @@ -37,7 +37,7 @@ public sealed class AvcKrefTransformerTests }" ) ] - public void Transform_SimpleVersionFile_PropertiesSet(string remoteUrl, string version, string kspVersion, string download, string remoteAvc) + public void Transform_SimpleVersionFile_PropertiesSet(string remoteUrl, string version, string GameVersion, string download, string remoteAvc) { // Arrange var mHttp = new Mock(); @@ -51,7 +51,7 @@ public void Transform_SimpleVersionFile_PropertiesSet(string remoteUrl, string v // Assert var json = m.Json(); Assert.AreEqual((string)json["version"], version); - Assert.AreEqual((string)json["ksp_version"], kspVersion); + Assert.AreEqual((string)json["ksp_version"], GameVersion); Assert.AreEqual((string)json["download"], download); } diff --git a/Tests/NetKAN/Transformers/AvcTransformerTests.cs b/Tests/NetKAN/Transformers/AvcTransformerTests.cs index fab5a83cda..10dbae3ce2 100644 --- a/Tests/NetKAN/Transformers/AvcTransformerTests.cs +++ b/Tests/NetKAN/Transformers/AvcTransformerTests.cs @@ -23,7 +23,7 @@ public void AddsMissingVersionInfo() var avcVersion = new AvcVersion { version = new ModuleVersion("1.0.0"), - ksp_version = KspVersion.Parse("1.0.4") + ksp_version = GameVersion.Parse("1.0.4") }; var mHttp = new Mock(); @@ -54,14 +54,14 @@ public void AddsMissingVersionInfo() } [Test] - public void PreferentiallyAddsRangedKspVersionInfo() + public void PreferentiallyAddsRangedGameVersionInfo() { // Arrange var avcVersion = new AvcVersion { - ksp_version = KspVersion.Parse("1.0.4"), - ksp_version_min = KspVersion.Parse("0.90"), - ksp_version_max = KspVersion.Parse("1.0.3") + ksp_version = GameVersion.Parse("1.0.4"), + ksp_version_min = GameVersion.Parse("0.90"), + ksp_version_max = GameVersion.Parse("1.0.3") }; var mHttp = new Mock(); @@ -169,7 +169,7 @@ public void PreferentiallyAddsRangedKspVersionInfo() null, null, null, "any", null, null )] - public void CorrectlyCalculatesKspVersionInfo( + public void CorrectlyCalculatesGameVersionInfo( string existingKsp, string existingKspMin, string existingKspMax, string avcKsp, string avcKspMin, string avcKspMax, string expectedKsp, string expectedKspMin, string expectedKspMax @@ -194,13 +194,13 @@ public void CorrectlyCalculatesKspVersionInfo( var avcVersion = new AvcVersion(); if (!string.IsNullOrWhiteSpace(avcKsp)) - avcVersion.ksp_version = KspVersion.Parse(avcKsp); + avcVersion.ksp_version = GameVersion.Parse(avcKsp); if (!string.IsNullOrWhiteSpace(avcKspMin)) - avcVersion.ksp_version_min = KspVersion.Parse(avcKspMin); + avcVersion.ksp_version_min = GameVersion.Parse(avcKspMin); if (!string.IsNullOrWhiteSpace(avcKspMax)) - avcVersion.ksp_version_max = KspVersion.Parse(avcKspMax); + avcVersion.ksp_version_max = GameVersion.Parse(avcKspMax); var mHttp = new Mock(); var mModuleService = new Mock(); diff --git a/Tests/NetKAN/Transformers/CurseTransformerTests.cs b/Tests/NetKAN/Transformers/CurseTransformerTests.cs index 551d620063..5eb425b0f6 100644 --- a/Tests/NetKAN/Transformers/CurseTransformerTests.cs +++ b/Tests/NetKAN/Transformers/CurseTransformerTests.cs @@ -16,7 +16,7 @@ public sealed class CurseTransformerTests // GH #199: Don't pre-fill KSP version fields if we see a ksp_min/max [Test] - public void DoesNotReplaceKspVersionProperties() + public void DoesNotReplaceGameVersionProperties() { // Arrange var mApi = new Mock(); diff --git a/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs b/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs index b7191da8d3..cd8f312748 100644 --- a/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs +++ b/Tests/NetKAN/Transformers/SpacedockTransformerTests.cs @@ -18,7 +18,7 @@ public sealed class SpacedockTransformerTests // GH #199: Don't pre-fill KSP version fields if we see a ksp_min/max [Test] - public void DoesNotReplaceKspVersionProperties() + public void DoesNotReplaceGameVersionProperties() { // Arrange var mApi = new Mock();