Example #1
0
        public void VersionConstructorInvalid(string ver)
        {
            var result = GameVersion.TryParse(ver, out var v);

            Assert.False(result);
            Assert.Null(v);
        }
Example #2
0
        /// <summary>
        /// Initialize the popup
        /// </summary>
        public CompatibleVersionDialog(IGame game) : base()
        {
            int l = GetLeft(),
                r = GetRight();
            int t = GetTop(),
                b = GetBottom();

            loadOptions(game);
            choices = new ConsoleListBox <GameVersion>(
                l + 2, t + 2, r - 2, b - 4,
                options,
                new List <ConsoleListBoxColumn <GameVersion> >()
            {
                new ConsoleListBoxColumn <GameVersion>()
                {
                    Header   = "Predefined Version",
                    Width    = r - l - 5,
                    Renderer = v => v.ToString(),
                    Comparer = (v1, v2) => v1.CompareTo(v2)
                }
            },
                0, 0, ListSortDirection.Descending
                );
            AddObject(choices);
            choices.AddTip("Enter", "Select version");
            choices.AddBinding(Keys.Enter, (object sender, ConsoleTheme theme) => {
                choice = choices.Selection;
                return(false);
            });

            manualEntry = new ConsoleField(
                l + 2, b - 2, r - 2
                )
            {
                GhostText = () => "<Enter a version>"
            };
            AddObject(manualEntry);
            manualEntry.AddTip("Enter", "Accept value", () => GameVersion.TryParse(manualEntry.Value, out choice));
            manualEntry.AddBinding(Keys.Enter, (object sender, ConsoleTheme theme) => {
                if (GameVersion.TryParse(manualEntry.Value, out choice))
                {
                    // Good value, done running
                    return(false);
                }
                else
                {
                    // Not valid, so they can't even see the key binding
                    return(true);
                }
            });

            AddTip("Esc", "Cancel");
            AddBinding(Keys.Escape, (object sender, ConsoleTheme theme) => {
                choice = null;
                return(false);
            });

            CenterHeader = () => "Select Compatible Version";
        }
Example #3
0
        public void TryParseReturnsFalseOnInvalidParameter(string s)
        {
            // Act
            GameVersion result;
            var         success = GameVersion.TryParse(s, out result);

            // Assert
            Assert.IsFalse(success);
        }
Example #4
0
        public void TryParseWorksCorrectly(string s, GameVersion version)
        {
            // Act
            GameVersion result;
            var         success = GameVersion.TryParse(s, out result);

            // Assert
            Assert.IsTrue(success);
            Assert.AreEqual(version, result);
            Assert.AreEqual(s, result.ToString());
        }
Example #5
0
        private void LoadCompatibleVersions()
        {
            String path = CompatibleGameVersionsFile();

            if (File.Exists(path))
            {
                CompatibleGameVersions compatibleGameVersions = JsonConvert.DeserializeObject <CompatibleGameVersions>(File.ReadAllText(path));

                _compatibleVersions = compatibleGameVersions.Versions
                                      .Select(v => GameVersion.Parse(v)).ToList();

                // Get version without throwing exceptions for null
                GameVersion mainVer = null;
                GameVersion.TryParse(compatibleGameVersions.GameVersionWhenWritten, out mainVer);
                GameVersionWhenCompatibleVersionsWereStored = mainVer;
            }
        }
Example #6
0
 public void Test_That_Parsing_Negatives_Is_Not_Allowed(string version)
 {
     Assert.False(GameVersion.TryParse(version, out _));
     Assert.Throws <FormatException>(() => GameVersion.Parse(version));
 }
Example #7
0
        /// <summary>
        /// User is done. Start cloning or faking, depending on the clicked radio button.
        /// Close the window if everything went right.
        /// </summary>
        private async void buttonOK_Click(object sender, EventArgs e)
        {
            string newName = textBoxNewName.Text;
            string newPath = textBoxNewPath.Text;

            // Do some basic checks.
            if (String.IsNullOrWhiteSpace(newName))
            {
                user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterName);
                return;
            }
            if (String.IsNullOrWhiteSpace(newPath))
            {
                user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterPath);
                return;
            }

            // Show progress bar and deactivate controls.
            progressBar.Style = ProgressBarStyle.Marquee;
            progressBar.Show();
            foreach (Control ctrl in this.Controls)
            {
                ctrl.Enabled = false;
            }

            // Clone the specified instance.
            // Done in a new task to not block the GUI thread.
            if (radioButtonClone.Checked)
            {
                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogCloningInstance);

                try
                {
                    await Task.Run(() =>
                    {
                        GameInstance sourceInstance = manager.Instances.Values
                                                      .FirstOrDefault(i => i.GameDir() == textBoxClonePath.Text);
                        GameInstance instanceToClone = new GameInstance(
                            sourceInstance.game,
                            textBoxClonePath.Text,
                            "irrelevant",
                            user
                            );

                        if (instanceToClone.Valid)
                        {
                            manager.CloneInstance(instanceToClone, newName, newPath);
                        }
                        else
                        {
                            throw new NotKSPDirKraken(instanceToClone.GameDir());
                        }
                    });
                }
                catch (InstanceNameTakenKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogNameAlreadyUsed);
                    reactivateDialog();
                    return;
                }
                catch (NotKSPDirKraken kraken)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogInstanceNotValid, kraken.path));
                    reactivateDialog();
                    return;
                }
                catch (PathErrorKraken kraken)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogDestinationNotEmpty, kraken.path));
                    reactivateDialog();
                    return;
                }
                catch (IOException ex)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogCloneFailed, ex.Message));
                    reactivateDialog();
                    return;
                }
                catch (Exception ex)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogCloneFailed, ex.Message));
                    reactivateDialog();
                    return;
                }

                if (checkBoxSetAsDefault.Checked)
                {
                    manager.SetAutoStart(newName);
                }

                if (checkBoxSwitchInstance.Checked)
                {
                    manager.SetCurrentInstance(newName);
                }

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogSuccessfulClone);

                DialogResult = DialogResult.OK;
                this.Close();
            }

            // Create a new dummy instance.
            // Also in a separate task.
            else if (radioButtonFake.Checked)
            {
                GameVersion GameVersion = GameVersion.Parse(comboBoxGameVersion.Text);

                Dictionary <DLC.IDlcDetector, GameVersion> dlcs = new Dictionary <DLC.IDlcDetector, GameVersion>();
                if (!String.IsNullOrWhiteSpace(textBoxMHDlcVersion.Text) && textBoxMHDlcVersion.Text.ToLower() != "none")
                {
                    if (GameVersion.TryParse(textBoxMHDlcVersion.Text, out GameVersion ver))
                    {
                        dlcs.Add(new DLC.MakingHistoryDlcDetector(), ver);
                    }
                    else
                    {
                        user.RaiseError(Properties.Resources.CloneFakeKspDialogDlcVersionMalformatted, "Making History");
                        reactivateDialog();
                        return;
                    }
                }
                if (!String.IsNullOrWhiteSpace(textBoxBGDlcVersion.Text) && textBoxBGDlcVersion.Text.ToLower() != "none")
                {
                    if (GameVersion.TryParse(textBoxBGDlcVersion.Text, out GameVersion ver))
                    {
                        dlcs.Add(new DLC.BreakingGroundDlcDetector(), ver);
                    }
                    else
                    {
                        user.RaiseError(Properties.Resources.CloneFakeKspDialogDlcVersionMalformatted, "Breaking Ground");
                        reactivateDialog();
                        return;
                    }
                }

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogCreatingInstance);

                try
                {
                    await Task.Run(() =>
                    {
                        manager.FakeInstance(new KerbalSpaceProgram(), newName, newPath, GameVersion, dlcs);
                    });
                }
                catch (InstanceNameTakenKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogNameAlreadyUsed);
                    reactivateDialog();
                    return;
                }
                catch (BadInstallLocationKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogDestinationNotEmpty, newPath);
                    reactivateDialog();
                    return;
                }
                catch (Exception ex)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogFakeFailed, ex.Message));
                    reactivateDialog();
                    return;
                }

                if (checkBoxSetAsDefault.Checked)
                {
                    manager.SetAutoStart(newName);
                }

                if (checkBoxSwitchInstance.Checked)
                {
                    manager.SetCurrentInstance(newName);
                }

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogSuccessfulCreate);

                DialogResult = DialogResult.OK;
                this.Close();
            }
        }
Example #8
0
        public int RunSubCommand(GameInstanceManager manager, CommonOptions opts, SubCommandOptions options)
        {
            var exitCode = Exit.OK;

            Parser.Default.ParseArgumentsStrict(options.options.ToArray(), new CompatOptions(), (string option, object suboptions) =>
            {
                // ParseArgumentsStrict calls us unconditionally, even with bad arguments
                if (!string.IsNullOrEmpty(option) && suboptions != null)
                {
                    CommonOptions comOpts = (CommonOptions)suboptions;
                    comOpts.Merge(opts);
                    _user       = new ConsoleUser(comOpts.Headless);
                    _kspManager = manager ?? new GameInstanceManager(_user);
                    exitCode    = comOpts.Handle(_kspManager, _user);
                    if (exitCode != Exit.OK)
                    {
                        return;
                    }

                    switch (option)
                    {
                    case "list":
                        {
                            var ksp = MainClass.GetGameInstance(_kspManager);

                            const string versionHeader = "Version";
                            const string actualHeader  = "Actual";

                            var output = ksp
                                         .GetCompatibleVersions()
                                         .Select(i => new
                            {
                                Version = i,
                                Actual  = false
                            })
                                         .ToList();

                            output.Add(new
                            {
                                Version = ksp.Version(),
                                Actual  = true
                            });

                            output = output
                                     .OrderByDescending(i => i.Actual)
                                     .ThenByDescending(i => i.Version)
                                     .ToList();

                            var versionWidth = Enumerable
                                               .Repeat(versionHeader, 1)
                                               .Concat(output.Select(i => i.Version.ToString()))
                                               .Max(i => i.Length);

                            var actualWidth = Enumerable
                                              .Repeat(actualHeader, 1)
                                              .Concat(output.Select(i => i.Actual.ToString()))
                                              .Max(i => i.Length);

                            const string columnFormat = "{0}  {1}";

                            _user.RaiseMessage(string.Format(columnFormat,
                                                             versionHeader.PadRight(versionWidth),
                                                             actualHeader.PadRight(actualWidth)
                                                             ));

                            _user.RaiseMessage(string.Format(columnFormat,
                                                             new string('-', versionWidth),
                                                             new string('-', actualWidth)
                                                             ));

                            foreach (var line in output)
                            {
                                _user.RaiseMessage(string.Format(columnFormat,
                                                                 line.Version.ToString().PadRight(versionWidth),
                                                                 line.Actual.ToString().PadRight(actualWidth)
                                                                 ));
                            }
                        }
                        break;

                    case "add":
                        {
                            var ksp        = MainClass.GetGameInstance(_kspManager);
                            var addOptions = (CompatAddOptions)suboptions;

                            GameVersion GameVersion;
                            if (GameVersion.TryParse(addOptions.Version, out GameVersion))
                            {
                                var newCompatibleVersion = ksp.GetCompatibleVersions();
                                newCompatibleVersion.Add(GameVersion);
                                ksp.SetCompatibleVersions(newCompatibleVersion);
                            }
                            else
                            {
                                _user.RaiseError("ERROR: Invalid KSP version.");
                                exitCode = Exit.ERROR;
                            }
                        }
                        break;

                    case "forget":
                        {
                            var ksp        = MainClass.GetGameInstance(_kspManager);
                            var addOptions = (CompatForgetOptions)suboptions;

                            GameVersion GameVersion;
                            if (GameVersion.TryParse(addOptions.Version, out GameVersion))
                            {
                                if (GameVersion != ksp.Version())
                                {
                                    var newCompatibleVersion = ksp.GetCompatibleVersions();
                                    newCompatibleVersion.RemoveAll(i => i == GameVersion);
                                    ksp.SetCompatibleVersions(newCompatibleVersion);
                                }
                                else
                                {
                                    _user.RaiseError("ERROR: Cannot forget actual KSP version.");
                                    exitCode = Exit.ERROR;
                                }
                            }
                            else
                            {
                                _user.RaiseError("ERROR: Invalid KSP version.");
                                exitCode = Exit.ERROR;
                            }
                        }
                        break;

                    default:
                        exitCode = Exit.BADOPT;
                        break;
                    }
                }
            }, () => { exitCode = MainClass.AfterHelp(); });
            return(exitCode);
        }