Exemple #1
0
        /// <summary>
        /// Fetches all the latest release info, populating our attributes in
        /// the process.
        /// </summary>
        public void FetchLatestReleaseInfo()
        {
            var response = MakeRequest(latestCKANReleaseApiUrl);

            try
            {
                fetchedCkanUrl = RetrieveUrl(response, 0);
                // Check whether the release includes the auto updater
                foreach (var asset in response.assets)
                {
                    string url = asset.browser_download_url.ToString();
                    if (url.EndsWith("AutoUpdater.exe"))
                    {
                        fetchedUpdaterUrl = new Tuple <Uri, long>(new Uri(url), (long)asset.size);
                        break;
                    }
                }
                if (fetchedUpdaterUrl == null)
                {
                    // Older releases don't include the auto updater
                    fetchedUpdaterUrl = RetrieveUrl(MakeRequest(oldLatestUpdaterReleaseApiUrl), 0);
                }
            }
            catch (Kraken)
            {
                LatestVersion = new Version(Meta.GetVersion());
                return;
            }

            ReleaseNotes  = ExtractReleaseNotes(response.body.ToString());
            LatestVersion = new CKANVersion(response.tag_name.ToString(), response.name.ToString());
        }
Exemple #2
0
        public void CurrentInstanceUpdated()
        {
            Util.Invoke(this, () =>
            {
                Text = String.Format("CKAN {0} - KSP {1}    --    {2}", Meta.GetVersion(), CurrentInstance.Version(),
                                     CurrentInstance.GameDir());
            });

            configuration = Configuration.LoadOrCreateConfiguration
                            (
                Path.Combine(CurrentInstance.GameDir(), "CKAN/GUIConfig.xml"),
                Repo.default_ckan_repo.ToString()
                            );

            if (CurrentInstance.CompatibleVersionsAreFromDifferentKsp)
            {
                CompatibleKspVersionsDialog dialog = new CompatibleKspVersionsDialog(CurrentInstance);
                dialog.ShowDialog();
            }

            UpdateModsList();
            ChangeSet = null;
            Conflicts = null;

            Filter((GUIModFilter)configuration.ActiveFilter);
        }
Exemple #3
0
        /// <summary>
        /// Look for a CKAN update and start installing it if found.
        /// Note that this will happen on a background thread!
        /// </summary>
        /// <returns>
        /// true if update found, false otherwise.
        /// </returns>
        private bool CheckForCKANUpdate()
        {
            if (configuration.CheckForUpdatesOnLaunch && AutoUpdate.CanUpdate)
            {
                try
                {
                    log.Info("Making auto-update call");
                    AutoUpdate.Instance.FetchLatestReleaseInfo();
                    var latest_version  = AutoUpdate.Instance.latestUpdate.Version;
                    var current_version = new ModuleVersion(Meta.GetVersion());

                    if (AutoUpdate.Instance.IsFetched() && latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher ckan version");
                        var release_notes = AutoUpdate.Instance.latestUpdate.ReleaseNotes;
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            UpdateCKAN();
                            return(true);
                        }
                    }
                }
                catch (Exception exception)
                {
                    currentUser.RaiseError(Properties.Resources.MainAutoUpdateFailed, exception.Message);
                    log.Error("Error in auto-update", exception);
                }
            }
            return(false);
        }
Exemple #4
0
        private void CurrentInstanceUpdated()
        {
            Util.Invoke(this, () =>
            {
                Text = $"CKAN {Meta.GetVersion()} - KSP {CurrentInstance.Version()}    --    {CurrentInstance.GameDir()}";
            });

            configuration = Configuration.LoadOrCreateConfiguration
                            (
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml"),
                CKAN.Repository.default_ckan_repo_uri.ToString()
                            );

            if (CurrentInstance.CompatibleVersionsAreFromDifferentKsp)
            {
                CompatibleKspVersionsDialog dialog = new CompatibleKspVersionsDialog(CurrentInstance);
                dialog.ShowDialog();
            }

            UpdateModsList();
            ChangeSet = null;
            Conflicts = null;

            Filter((GUIModFilter)configuration.ActiveFilter);
        }
Exemple #5
0
        /// <summary>
        /// React to switching to a new game instance
        /// </summary>
        /// <param name="onStartup">true if this is the initial load and should trigger auto repo updates, false otherwise</param>
        private void CurrentInstanceUpdated(bool onStartup)
        {
            Util.Invoke(this, () =>
            {
                Text = $"CKAN {Meta.GetVersion()} - KSP {CurrentInstance.Version()}    --    {CurrentInstance.GameDir()}";
            });

            configuration = Configuration.LoadOrCreateConfiguration(
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml")
                );

            if (CurrentInstance.CompatibleVersionsAreFromDifferentKsp)
            {
                new CompatibleKspVersionsDialog(CurrentInstance, !actuallyVisible)
                .ShowDialog();
            }

            bool repoUpdateNeeded = configuration.RefreshOnStartup ||
                                    !RegistryManager.Instance(CurrentInstance).registry.HasAnyAvailable();

            if (onStartup && repoUpdateNeeded)
            {
                UpdateRepo();
            }
            else
            {
                UpdateModsList();
            }
            ChangeSet = null;
            Conflicts = null;

            Filter((GUIModFilter)configuration.ActiveFilter);
        }
Exemple #6
0
        public void UpdateDialog()
        {
            RefreshReposListBox();
            RefreshAuthTokensListBox();

            LocalVersionLabel.Text = Meta.GetVersion();

            CheckUpdateOnLaunchCheckbox.Checked = Main.Instance.configuration.CheckForUpdatesOnLaunch;
            RefreshOnStartupCheckbox.Checked    = Main.Instance.configuration.RefreshOnStartup;
            HideEpochsCheckbox.Checked          = Main.Instance.configuration.HideEpochs;
            HideVCheckbox.Checked          = Main.Instance.configuration.HideV;
            AutoSortUpdateCheckBox.Checked = Main.Instance.configuration.AutoSortByUpdate;
            EnableTrayIconCheckBox.Checked = MinimizeToTrayCheckBox.Enabled = Main.Instance.configuration.EnableTrayIcon;
            MinimizeToTrayCheckBox.Checked = Main.Instance.configuration.MinimizeToTray;
            PauseRefreshCheckBox.Checked   = Main.Instance.configuration.RefreshPaused;

            UpdateRefreshRate();

            UpdateCacheInfo(config.DownloadCacheDir);
            if (config.CacheSizeLimit.HasValue)
            {
                // Show setting in MB
                CacheLimit.Text = (config.CacheSizeLimit.Value / 1024 / 1024).ToString();
            }
        }
Exemple #7
0
        /// <summary>
        /// Returns true if we support at least spec_version of the CKAN spec.
        /// </summary>
        internal static bool IsSpecSupported(ModuleVersion spec_vesion)
        {
            // This could be a read-only state variable; do we have those in C#?
            ModuleVersion release = new ModuleVersion(Meta.GetVersion(VersionFormat.Short));

            return(release == null || release.IsGreaterThan(spec_vesion));
        }
Exemple #8
0
        public void UpdateDialog()
        {
            RefreshReposListBox();

            LocalVersionLabel.Text = Meta.GetVersion();

            CheckUpdateOnLaunchCheckbox.Checked = Main.Instance.configuration.CheckForUpdatesOnLaunch;
            RefreshOnStartupCheckbox.Checked    = Main.Instance.configuration.RefreshOnStartup;
            HideEpochsCheckbox.Checked          = Main.Instance.configuration.HideEpochs;

            UpdateCacheInfo();
        }
Exemple #9
0
        public void UpdateDialog()
        {
            RefreshReposListBox();
            RefreshAuthTokensListBox();

            LocalVersionLabel.Text = Meta.GetVersion();

            CheckUpdateOnLaunchCheckbox.Checked = Main.Instance.configuration.CheckForUpdatesOnLaunch;
            RefreshOnStartupCheckbox.Checked    = Main.Instance.configuration.RefreshOnStartup;
            HideEpochsCheckbox.Checked          = Main.Instance.configuration.HideEpochs;
            HideVCheckbox.Checked          = Main.Instance.configuration.HideV;
            AutoSortUpdateCheckBox.Checked = Main.Instance.configuration.AutoSortByUpdate;

            UpdateCacheInfo(winReg.DownloadCacheDir);
        }
Exemple #10
0
        /// <summary>
        /// Fetches all the latest release info, populating our attributes in
        /// the process.
        /// </summary>
        public void FetchLatestReleaseInfo()
        {
            var response = MakeRequest(latestCKANReleaseApiUrl);

            try
            {
                fetchedUpdaterUrl = RetrieveUrl(MakeRequest(latestUpdaterReleaseApiUrl));
                fetchedCkanUrl    = RetrieveUrl(response);
            }
            catch (Kraken)
            {
                LatestVersion = new Version(Meta.GetVersion());
                return;
            }

            string body = response.body.ToString();

            ReleaseNotes  = ExtractReleaseNotes(body);
            LatestVersion = new CKANVersion(response.tag_name.ToString(), response.name.ToString());
        }
Exemple #11
0
        public void UpdateDialog()
        {
            RefreshReposListBox(false);
            RefreshAuthTokensListBox();
            UpdateLanguageSelectionComboBox();

            LocalVersionLabel.Text = Meta.GetVersion();

            CheckUpdateOnLaunchCheckbox.Checked = Main.Instance.configuration.CheckForUpdatesOnLaunch;
            RefreshOnStartupCheckbox.Checked    = Main.Instance.configuration.RefreshOnStartup;
            HideEpochsCheckbox.Checked          = Main.Instance.configuration.HideEpochs;
            HideVCheckbox.Checked          = Main.Instance.configuration.HideV;
            AutoSortUpdateCheckBox.Checked = Main.Instance.configuration.AutoSortByUpdate;
            EnableTrayIconCheckBox.Checked = MinimizeToTrayCheckBox.Enabled = Main.Instance.configuration.EnableTrayIcon;
            MinimizeToTrayCheckBox.Checked = Main.Instance.configuration.MinimizeToTray;
            PauseRefreshCheckBox.Checked   = Main.Instance.configuration.RefreshPaused;

            UpdateRefreshRate();

            UpdateCacheInfo(config.DownloadCacheDir);
        }
Exemple #12
0
        private void CheckForUpdatesButton_Click(object sender, EventArgs e)
        {
            try
            {
                AutoUpdate.Instance.FetchLatestReleaseInfo();
                var latestVersion = AutoUpdate.Instance.latestUpdate.Version;
                if (latestVersion.IsGreaterThan(new ModuleVersion(Meta.GetVersion(VersionFormat.Short))) && AutoUpdate.Instance.IsFetched())
                {
                    InstallUpdateButton.Enabled = true;
                }
                else
                {
                    InstallUpdateButton.Enabled = false;
                }

                LatestVersionLabel.Text = latestVersion.ToString();
            }
            catch (Exception ex)
            {
                log.Warn("Exception caught in CheckForUpdates:\r\n" + ex);
            }
        }
Exemple #13
0
        private void CurrentInstanceUpdated()
        {
            Util.Invoke(this, () =>
            {
                Text = $"CKAN {Meta.GetVersion()} - KSP {CurrentInstance.Version()}    --    {CurrentInstance.GameDir()}";
            });

            configuration = Configuration.LoadOrCreateConfiguration(
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml")
                );

            if (CurrentInstance.CompatibleVersionsAreFromDifferentKsp)
            {
                new CompatibleKspVersionsDialog(CurrentInstance, !actuallyVisible)
                .ShowDialog();
            }

            UpdateModsList();
            ChangeSet = null;
            Conflicts = null;

            Filter((GUIModFilter)configuration.ActiveFilter);
        }
Exemple #14
0
        // this probably needs to be refactored
        private void InstallMods(object sender, DoWorkEventArgs e)
        {
            installCanceled = false;
            ClearLog();

            var opts = (KeyValuePair <ModChanges, RelationshipResolverOptions>)e.Argument;

            IRegistryQuerier registry  = RegistryManager.Instance(manager.CurrentInstance).registry;
            ModuleInstaller  installer = ModuleInstaller.GetInstance(CurrentInstance, Manager.Cache, GUI.user);

            // Avoid accumulating multiple event handlers
            installer.onReportModInstalled -= OnModInstalled;
            installer.onReportModInstalled += OnModInstalled;
            // setup progress callback

            // this will be the final list of mods we want to install
            HashSet <CkanModule> toInstall = new HashSet <CkanModule>();
            var toUninstall = new HashSet <string>();
            var toUpgrade   = new HashSet <string>();

            // First compose sets of what the user wants installed, upgraded, and removed.
            foreach (ModChange change in opts.Key)
            {
                switch (change.ChangeType)
                {
                case GUIModChangeType.Remove:
                    toUninstall.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Update:
                    toUpgrade.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Install:
                    toInstall.Add(change.Mod.ToModule());
                    break;

                case GUIModChangeType.Replace:
                    ModuleReplacement repl = registry.GetReplacement(change.Mod.ToModule(), CurrentInstance.VersionCriteria());
                    if (repl != null)
                    {
                        toUninstall.Add(repl.ToReplace.identifier);
                        toInstall.Add(repl.ReplaceWith);
                    }
                    break;
                }
            }

            // Prompt for recommendations and suggestions, if any
            var recRows = getRecSugRows(
                opts.Key.Where(ch => ch.ChangeType == GUIModChangeType.Install)
                .Select(ch => ch.Mod.ToModule()),
                registry, toInstall
                );

            if (recRows.Any())
            {
                ShowRecSugDialog(recRows, toInstall);
            }

            tabController.HideTab("ChooseRecommendedModsTabPage");

            if (installCanceled)
            {
                tabController.ShowTab("ManageModsTabPage");
                e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                return;
            }

            // Now let's make all our changes.
            tabController.RenameTab("WaitTabPage", "Status log");
            ShowWaitDialog();
            tabController.SetTabLock(true);

            IDownloader downloader = new NetAsyncModulesDownloader(GUI.user);

            cancelCallback = () =>
            {
                downloader.CancelDownload();
                installCanceled = true;
            };

            // checks if all actions were successfull
            bool processSuccessful       = false;
            bool resolvedAllProvidedMods = false;

            // uninstall/installs/upgrades until every list is empty
            // if the queue is NOT empty, resolvedAllProvidedMods is set to false until the action is done
            while (!resolvedAllProvidedMods)
            {
                try
                {
                    e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                    if (toUninstall.Count > 0)
                    {
                        processSuccessful = false;
                        if (!installCanceled)
                        {
                            installer.UninstallList(toUninstall, false, toInstall.Select(m => m.identifier));
                            processSuccessful = true;
                        }
                    }
                    if (toUpgrade.Count > 0)
                    {
                        processSuccessful = false;
                        if (!installCanceled)
                        {
                            installer.Upgrade(toUpgrade, downloader);
                            processSuccessful = true;
                        }
                    }
                    if (toInstall.Count > 0)
                    {
                        processSuccessful = false;
                        if (!installCanceled)
                        {
                            installer.InstallList(toInstall, opts.Value, downloader, false);
                            processSuccessful = true;
                        }
                    }
                    e.Result = new KeyValuePair <bool, ModChanges>(processSuccessful, opts.Key);
                    if (installCanceled)
                    {
                        return;
                    }
                    resolvedAllProvidedMods = true;
                }
                catch (TooManyModsProvideKraken k)
                {
                    // Prompt user to choose which mod to use
                    CkanModule chosen = TooManyModsProvideCore(k).Result;
                    // Close the selection prompt
                    Util.Invoke(this, () =>
                    {
                        tabController.ShowTab("WaitTabPage");
                        tabController.HideTab("ChooseProvidedModsTabPage");
                    });
                    if (chosen != null)
                    {
                        // User picked a mod, queue it up for installation
                        toInstall.Add(chosen);
                        // DON'T return so we can loop around and try the above InstallList call again
                    }
                    else
                    {
                        // User cancelled, get out
                        tabController.ShowTab("ManageModsTabPage");
                        e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                        return;
                    }
                }
                catch (DependencyNotSatisfiedKraken ex)
                {
                    GUI.user.RaiseMessage(
                        "{0} requires {1} but it is not listed in the index, or not available for your version of KSP.",
                        ex.parent, ex.module);
                    return;
                }
                catch (ModuleNotFoundKraken ex)
                {
                    GUI.user.RaiseMessage(
                        "Module {0} required but it is not listed in the index, or not available for your version of KSP.",
                        ex.module);
                    return;
                }
                catch (BadMetadataKraken ex)
                {
                    GUI.user.RaiseMessage("Bad metadata detected for module {0}: {1}", ex.module, ex.Message);
                    return;
                }
                catch (FileExistsKraken ex)
                {
                    if (ex.owningModule != null)
                    {
                        GUI.user.RaiseMessage(
                            "\r\nOh no! We tried to overwrite a file owned by another mod!\r\n" +
                            "Please try a `ckan update` and try again.\r\n\r\n" +
                            "If this problem re-occurs, then it maybe a packaging bug.\r\n" +
                            "Please report it at:\r\n\r\n" +
                            "https://github.com/KSP-CKAN/NetKAN/issues/new\r\n\r\n" +
                            "Please including the following information in your report:\r\n\r\n" +
                            "File           : {0}\r\n" +
                            "Installing Mod : {1}\r\n" +
                            "Owning Mod     : {2}\r\n" +
                            "CKAN Version   : {3}\r\n",
                            ex.filename, ex.installingModule, ex.owningModule,
                            Meta.GetVersion()
                            );
                    }
                    else
                    {
                        GUI.user.RaiseMessage(
                            "\r\n\r\nOh no!\r\n\r\n" +
                            "It looks like you're trying to install a mod which is already installed,\r\n" +
                            "or which conflicts with another mod which is already installed.\r\n\r\n" +
                            "As a safety feature, the CKAN will *never* overwrite or alter a file\r\n" +
                            "that it did not install itself.\r\n\r\n" +
                            "If you wish to install {0} via the CKAN,\r\n" +
                            "then please manually uninstall the mod which owns:\r\n\r\n" +
                            "{1}\r\n\r\n" + "and try again.\r\n",
                            ex.installingModule, ex.filename
                            );
                    }

                    GUI.user.RaiseMessage("Your GameData has been returned to its original state.\r\n");
                    return;
                }
                catch (InconsistentKraken ex)
                {
                    // The prettiest Kraken formats itself for us.
                    GUI.user.RaiseMessage(ex.InconsistenciesPretty);
                    return;
                }
                catch (CancelledActionKraken)
                {
                    return;
                }
                catch (MissingCertificateKraken kraken)
                {
                    // Another very pretty kraken.
                    GUI.user.RaiseMessage(kraken.ToString());
                    return;
                }
                catch (DownloadThrottledKraken kraken)
                {
                    string msg = kraken.ToString();
                    GUI.user.RaiseMessage(msg);
                    if (YesNoDialog($"{msg}\r\n\r\nOpen settings now?", "Open Settings", "No"))
                    {
                        // Launch the URL describing this host's throttling practices, if any
                        if (kraken.infoUrl != null)
                        {
                            Process.Start(new ProcessStartInfo()
                            {
                                UseShellExecute = true,
                                FileName        = kraken.infoUrl.ToString()
                            });
                        }
                        // Now pretend they clicked the menu option for the settings
                        Enabled = false;
                        settingsDialog.ShowDialog();
                        Enabled = true;
                    }
                    return;
                }
                catch (ModuleDownloadErrorsKraken kraken)
                {
                    GUI.user.RaiseMessage(kraken.ToString());
                    GUI.user.RaiseError(kraken.ToString());
                    return;
                }
                catch (DirectoryNotFoundKraken kraken)
                {
                    GUI.user.RaiseMessage("\r\n{0}", kraken.Message);
                    return;
                }
                catch (DllNotFoundException)
                {
                    if (GUI.user.RaiseYesNoDialog("libcurl installation not found. Open wiki page for help?"))
                    {
                        Process.Start(new ProcessStartInfo()
                        {
                            UseShellExecute = true,
                            FileName        = "https://github.com/KSP-CKAN/CKAN/wiki/libcurl"
                        });
                    }
                    throw;
                }
            }
        }
Exemple #15
0
        protected override void OnLoad(EventArgs e)
        {
            Location    = configuration.WindowLoc;
            Size        = configuration.WindowSize;
            WindowState = configuration.IsWindowMaximised ? FormWindowState.Maximized : FormWindowState.Normal;
            splitContainer1.SplitterDistance       = configuration.PanelPosition;
            ModInfoTabControl.ModMetaSplitPosition = configuration.ModInfoPosition;

            if (!configuration.CheckForUpdatesOnLaunchNoNag && AutoUpdate.CanUpdate)
            {
                log.Debug("Asking user if they wish for auto-updates");
                if (new AskUserForAutoUpdatesDialog().ShowDialog() == DialogResult.OK)
                {
                    configuration.CheckForUpdatesOnLaunch = true;
                }

                configuration.CheckForUpdatesOnLaunchNoNag = true;
                configuration.Save();
            }

            bool autoUpdating = false;

            if (configuration.CheckForUpdatesOnLaunch && AutoUpdate.CanUpdate)
            {
                try
                {
                    log.Info("Making auto-update call");
                    AutoUpdate.Instance.FetchLatestReleaseInfo();
                    var latest_version  = AutoUpdate.Instance.LatestVersion;
                    var current_version = new Version(Meta.GetVersion());

                    if (AutoUpdate.Instance.IsFetched() && latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher ckan version");
                        var release_notes = AutoUpdate.Instance.ReleaseNotes;
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            UpdateCKAN();
                            autoUpdating = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    currentUser.RaiseError($"Error in auto-update:\n\t{exception.Message}");
                    log.Error("Error in auto-update", exception);
                }
            }

            m_UpdateRepoWorker = new BackgroundWorker {
                WorkerReportsProgress = false, WorkerSupportsCancellation = true
            };

            m_UpdateRepoWorker.RunWorkerCompleted += PostUpdateRepo;
            m_UpdateRepoWorker.DoWork             += UpdateRepo;

            installWorker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            installWorker.RunWorkerCompleted += PostInstallMods;
            installWorker.DoWork             += InstallMods;

            var old_YesNoDialog = currentUser.displayYesNo;

            currentUser.displayYesNo = YesNoDialog;
            URLHandlers.RegisterURLHandler(configuration, currentUser);
            currentUser.displayYesNo = old_YesNoDialog;

            ApplyToolButton.Enabled = false;

            CurrentInstanceUpdated();

            // We would like to refresh if we're configured to refresh on startup,
            // or if we have no currently available modules.
            bool repoUpdateNeeded = configuration.RefreshOnStartup ||
                                    !RegistryManager.Instance(CurrentInstance).registry.HasAnyAvailable();

            // If we're auto-updating the client then we shouldn't interfere with the progress tab
            if (!autoUpdating && repoUpdateNeeded)
            {
                UpdateRepo();
            }

            Text = $"CKAN {Meta.GetVersion()} - KSP {CurrentInstance.Version()}  --  {CurrentInstance.GameDir()}";

            if (commandLineArgs.Length >= 2)
            {
                var identifier = commandLineArgs[1];
                if (identifier.StartsWith("//"))
                {
                    identifier = identifier.Substring(2);
                }
                else if (identifier.StartsWith("ckan://"))
                {
                    identifier = identifier.Substring(7);
                }

                if (identifier.EndsWith("/"))
                {
                    identifier = identifier.Substring(0, identifier.Length - 1);
                }

                log.Debug("Attempting to select mod from startup parameters");
                FocusMod(identifier, true, true);
                ModList.Refresh();
                log.Debug("Failed to select mod from startup parameters");
            }

            var pluginsPath = Path.Combine(CurrentInstance.CkanDir(), "Plugins");

            if (!Directory.Exists(pluginsPath))
            {
                Directory.CreateDirectory(pluginsPath);
            }

            pluginController = new PluginController(pluginsPath);

            CurrentInstance.RebuildKSPSubDir();

            // Initialize navigation. This should be called as late as
            // possible, once the UI is "settled" from its initial load.
            NavInit();

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #16
0
        private void PostInstallMods(object sender, RunWorkerCompletedEventArgs e)
        {
            tabController.SetTabLock(false);

            if (e.Error != null)
            {
                switch (e.Error)
                {
                case DependencyNotSatisfiedKraken exc:
                    currentUser.RaiseMessage(Properties.Resources.MainInstallDepNotSatisfied, exc.parent, exc.module);
                    break;

                case ModuleNotFoundKraken exc:
                    currentUser.RaiseMessage(Properties.Resources.MainInstallNotFound, exc.module);
                    break;

                case BadMetadataKraken exc:
                    currentUser.RaiseMessage(Properties.Resources.MainInstallBadMetadata, exc.module, exc.Message);
                    break;

                case FileExistsKraken exc:
                    if (exc.owningModule != null)
                    {
                        currentUser.RaiseMessage(
                            Properties.Resources.MainInstallFileExists,
                            exc.filename, exc.installingModule, exc.owningModule,
                            Meta.GetVersion()
                            );
                    }
                    else
                    {
                        currentUser.RaiseMessage(
                            Properties.Resources.MainInstallUnownedFileExists,
                            exc.installingModule, exc.filename
                            );
                    }
                    currentUser.RaiseMessage(Properties.Resources.MainInstallGameDataReverted);
                    break;

                case InconsistentKraken exc:
                    currentUser.RaiseMessage(exc.InconsistenciesPretty);
                    break;

                case CancelledActionKraken exc:
                    currentUser.RaiseMessage(exc.Message);
                    installCanceled = true;
                    break;

                case MissingCertificateKraken exc:
                    currentUser.RaiseMessage(exc.ToString());
                    break;

                case DownloadThrottledKraken exc:
                    string msg = exc.ToString();
                    currentUser.RaiseMessage(msg);
                    if (YesNoDialog(string.Format(Properties.Resources.MainInstallOpenSettingsPrompt, msg),
                                    Properties.Resources.MainInstallOpenSettings,
                                    Properties.Resources.MainInstallNo))
                    {
                        // Launch the URL describing this host's throttling practices, if any
                        if (exc.infoUrl != null)
                        {
                            Utilities.ProcessStartURL(exc.infoUrl.ToString());
                        }
                        // Now pretend they clicked the menu option for the settings
                        Enabled = false;
                        new SettingsDialog(currentUser).ShowDialog();
                        Enabled = true;
                    }
                    break;

                case ModuleDownloadErrorsKraken exc:
                    currentUser.RaiseMessage(exc.ToString());
                    currentUser.RaiseError(exc.ToString());
                    break;

                case DirectoryNotFoundKraken exc:
                    currentUser.RaiseMessage("\r\n{0}", exc.Message);
                    break;

                case ModuleIsDLCKraken exc:
                    string dlcMsg = string.Format(Properties.Resources.MainInstallCantInstallDLC, exc.module.name);
                    currentUser.RaiseMessage(dlcMsg);
                    currentUser.RaiseError(dlcMsg);
                    break;
                }

                FailWaitDialog(
                    Properties.Resources.MainInstallErrorInstalling,
                    Properties.Resources.MainInstallKnownError,
                    Properties.Resources.MainInstallFailed,
                    false
                    );
            }
            else
            {
                // The Result property throws if InstallMods threw (!!!)
                KeyValuePair <bool, ModChanges> result = (KeyValuePair <bool, ModChanges>)e.Result;
                if (!installCanceled)
                {
                    // Rebuilds the list of GUIMods
                    ManageMods.UpdateModsList(null);

                    if (modChangedCallback != null)
                    {
                        foreach (var mod in result.Value)
                        {
                            modChangedCallback(mod.Mod, mod.ChangeType);
                        }
                    }

                    // install successful
                    AddStatusMessage(Properties.Resources.MainInstallSuccess);
                    HideWaitDialog(true);
                }
                else
                {
                    // User cancelled the installation
                    if (result.Key)
                    {
                        FailWaitDialog(
                            Properties.Resources.MainInstallCancelTooLate,
                            Properties.Resources.MainInstallCancelAfterInstall,
                            Properties.Resources.MainInstallProcessComplete,
                            true
                            );
                    }
                    else
                    {
                        FailWaitDialog(
                            Properties.Resources.MainInstallProcessCanceled,
                            Properties.Resources.MainInstallCanceledManually,
                            Properties.Resources.MainInstallInstallCanceled,
                            false
                            );
                    }
                }
            }

            Util.Invoke(this, () => Enabled = true);
            Util.Invoke(menuStrip1, () => menuStrip1.Enabled = true);
        }
Exemple #17
0
        protected override void OnLoad(EventArgs e)
        {
            SetStartPosition();
            Size        = configuration.WindowSize;
            WindowState = configuration.IsWindowMaximised ? FormWindowState.Maximized : FormWindowState.Normal;

            if (!configuration.CheckForUpdatesOnLaunchNoNag && AutoUpdate.CanUpdate)
            {
                log.Debug("Asking user if they wish for auto-updates");
                if (new AskUserForAutoUpdatesDialog().ShowDialog() == DialogResult.OK)
                {
                    configuration.CheckForUpdatesOnLaunch = true;
                }

                configuration.CheckForUpdatesOnLaunchNoNag = true;
                configuration.Save();
            }

            bool autoUpdating = false;

            if (configuration.CheckForUpdatesOnLaunch && AutoUpdate.CanUpdate)
            {
                try
                {
                    log.Info("Making auto-update call");
                    AutoUpdate.Instance.FetchLatestReleaseInfo();
                    var latest_version  = AutoUpdate.Instance.latestUpdate.Version;
                    var current_version = new ModuleVersion(Meta.GetVersion());

                    if (AutoUpdate.Instance.IsFetched() && latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher ckan version");
                        var release_notes = AutoUpdate.Instance.latestUpdate.ReleaseNotes;
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            UpdateCKAN();
                            autoUpdating = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    currentUser.RaiseError(Properties.Resources.MainAutoUpdateFailed, exception.Message);
                    log.Error("Error in auto-update", exception);
                }
            }

            CheckTrayState();
            InitRefreshTimer();

            m_UpdateRepoWorker = new BackgroundWorker {
                WorkerReportsProgress = false, WorkerSupportsCancellation = true
            };

            m_UpdateRepoWorker.RunWorkerCompleted += PostUpdateRepo;
            m_UpdateRepoWorker.DoWork             += UpdateRepo;

            installWorker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            installWorker.RunWorkerCompleted += PostInstallMods;
            installWorker.DoWork             += InstallMods;

            URLHandlers.RegisterURLHandler(configuration, currentUser);

            CurrentInstanceUpdated(!autoUpdating);

            if (commandLineArgs.Length >= 2)
            {
                var identifier = commandLineArgs[1];
                if (identifier.StartsWith("//"))
                {
                    identifier = identifier.Substring(2);
                }
                else if (identifier.StartsWith("ckan://"))
                {
                    identifier = identifier.Substring(7);
                }

                if (identifier.EndsWith("/"))
                {
                    identifier = identifier.Substring(0, identifier.Length - 1);
                }

                log.Debug("Attempting to select mod from startup parameters");
                ManageMods.FocusMod(identifier, true, true);
                ManageMods.ModGrid.Refresh();
                log.Debug("Failed to select mod from startup parameters");
            }

            var pluginsPath = Path.Combine(CurrentInstance.CkanDir(), "Plugins");

            if (!Directory.Exists(pluginsPath))
            {
                Directory.CreateDirectory(pluginsPath);
            }

            pluginController = new PluginController(pluginsPath);

            CurrentInstance.RebuildKSPSubDir();

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #18
0
        protected override void OnLoad(EventArgs e)
        {
            if (configuration.WindowLoc.X == -1 && configuration.WindowLoc.Y == -1)
            {
                // Center on screen for first launch
                StartPosition = FormStartPosition.CenterScreen;
            }
            else if (Platform.IsMac)
            {
                // Make sure there's room at the top for the MacOSX menu bar
                Location = Util.ClampedLocationWithMargins(
                    configuration.WindowLoc, configuration.WindowSize,
                    new Size(0, 30), new Size(0, 0)
                    );
            }
            else
            {
                // Just make sure it's fully on screen
                Location = Util.ClampedLocation(configuration.WindowLoc, configuration.WindowSize);
            }
            Size        = configuration.WindowSize;
            WindowState = configuration.IsWindowMaximised ? FormWindowState.Maximized : FormWindowState.Normal;

            if (!configuration.CheckForUpdatesOnLaunchNoNag && AutoUpdate.CanUpdate)
            {
                log.Debug("Asking user if they wish for auto-updates");
                if (new AskUserForAutoUpdatesDialog().ShowDialog() == DialogResult.OK)
                {
                    configuration.CheckForUpdatesOnLaunch = true;
                }

                configuration.CheckForUpdatesOnLaunchNoNag = true;
                configuration.Save();
            }

            bool autoUpdating = false;

            if (configuration.CheckForUpdatesOnLaunch && AutoUpdate.CanUpdate)
            {
                try
                {
                    log.Info("Making auto-update call");
                    AutoUpdate.Instance.FetchLatestReleaseInfo();
                    var latest_version  = AutoUpdate.Instance.latestUpdate.Version;
                    var current_version = new ModuleVersion(Meta.GetVersion());

                    if (AutoUpdate.Instance.IsFetched() && latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher ckan version");
                        var release_notes = AutoUpdate.Instance.latestUpdate.ReleaseNotes;
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            UpdateCKAN();
                            autoUpdating = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    currentUser.RaiseError($"Error in auto-update:\n\t{exception.Message}");
                    log.Error("Error in auto-update", exception);
                }
            }

            CheckTrayState();
            InitRefreshTimer();

            m_UpdateRepoWorker = new BackgroundWorker {
                WorkerReportsProgress = false, WorkerSupportsCancellation = true
            };

            m_UpdateRepoWorker.RunWorkerCompleted += PostUpdateRepo;
            m_UpdateRepoWorker.DoWork             += UpdateRepo;

            installWorker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            installWorker.RunWorkerCompleted += PostInstallMods;
            installWorker.DoWork             += InstallMods;

            URLHandlers.RegisterURLHandler(configuration, currentUser);

            ApplyToolButton.Enabled = false;

            CurrentInstanceUpdated(!autoUpdating);

            if (commandLineArgs.Length >= 2)
            {
                var identifier = commandLineArgs[1];
                if (identifier.StartsWith("//"))
                {
                    identifier = identifier.Substring(2);
                }
                else if (identifier.StartsWith("ckan://"))
                {
                    identifier = identifier.Substring(7);
                }

                if (identifier.EndsWith("/"))
                {
                    identifier = identifier.Substring(0, identifier.Length - 1);
                }

                log.Debug("Attempting to select mod from startup parameters");
                FocusMod(identifier, true, true);
                ModList.Refresh();
                log.Debug("Failed to select mod from startup parameters");
            }

            var pluginsPath = Path.Combine(CurrentInstance.CkanDir(), "Plugins");

            if (!Directory.Exists(pluginsPath))
            {
                Directory.CreateDirectory(pluginsPath);
            }

            pluginController = new PluginController(pluginsPath);

            CurrentInstance.RebuildKSPSubDir();

            // Initialize navigation. This should be called as late as
            // possible, once the UI is "settled" from its initial load.
            NavInit();

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #19
0
        protected override void OnLoad(EventArgs e)
        {
            Location = configuration.WindowLoc;
            Size     = configuration.WindowSize;

            if (!configuration.CheckForUpdatesOnLaunchNoNag)
            {
                log.Debug("Asking user if they wish for autoupdates");
                if (new AskUserForAutoUpdatesDialog().ShowDialog() == DialogResult.OK)
                {
                    configuration.CheckForUpdatesOnLaunch = true;
                }

                configuration.CheckForUpdatesOnLaunchNoNag = true;
                configuration.Save();
            }

            bool autoUpdating = false;

            if (configuration.CheckForUpdatesOnLaunch)
            {
                try
                {
                    log.Info("Making autoupdate call");
                    AutoUpdate.Instance.FetchLatestReleaseInfo();
                    var latest_version  = AutoUpdate.Instance.LatestVersion;
                    var current_version = new Version(Meta.GetVersion());

                    if (AutoUpdate.Instance.IsFetched() && latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher ckan version");
                        var release_notes = AutoUpdate.Instance.ReleaseNotes;
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            UpdateCKAN();
                            autoUpdating = true;
                        }
                    }
                }
                catch (Exception exception)
                {
                    currentUser.RaiseError("Error in autoupdate: \n\t" + exception.Message + "");
                    log.Error("Error in autoupdate", exception);
                }
            }

            m_UpdateRepoWorker = new BackgroundWorker {
                WorkerReportsProgress = false, WorkerSupportsCancellation = true
            };

            m_UpdateRepoWorker.RunWorkerCompleted += PostUpdateRepo;
            m_UpdateRepoWorker.DoWork             += UpdateRepo;

            installWorker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            installWorker.RunWorkerCompleted += PostInstallMods;
            installWorker.DoWork             += InstallMods;

            var old_YesNoDialog = currentUser.displayYesNo;

            currentUser.displayYesNo = YesNoDialog;
            URLHandlers.RegisterURLHandler(configuration, currentUser);
            currentUser.displayYesNo = old_YesNoDialog;

            ApplyToolButton.Enabled = false;

            CurrentInstanceUpdated();

            // if we're autoUpdating then we shouldn't interfere progress tab
            if (configuration.RefreshOnStartup && !autoUpdating)
            {
                UpdateRepo();
            }

            Text = String.Format("CKAN {0} - KSP {1}  --  {2}", Meta.GetVersion(), CurrentInstance.Version(),
                                 CurrentInstance.GameDir());

            if (commandLineArgs.Length >= 2)
            {
                var identifier = commandLineArgs[1];
                if (identifier.StartsWith("//"))
                {
                    identifier = identifier.Substring(2);
                }
                else if (identifier.StartsWith("ckan://"))
                {
                    identifier = identifier.Substring(7);
                }

                if (identifier.EndsWith("/"))
                {
                    identifier = identifier.Substring(0, identifier.Length - 1);
                }

                log.Debug("Attempting to select mod from startup parameters");
                FocusMod(identifier, true, true);
                ModList.Refresh();
                log.Debug("Failed to select mod from startup parameters");
            }

            var pluginsPath = Path.Combine(CurrentInstance.CkanDir(), "Plugins");

            if (!Directory.Exists(pluginsPath))
            {
                Directory.CreateDirectory(pluginsPath);
            }

            pluginController = new PluginController(pluginsPath, true);

            CurrentInstance.RebuildKSPSubDir();

            NavInit();  // initialize navigation. this should be called as late
                        // as possible, once the UI is "settled" from its initial
                        // load.

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #20
0
        // this probably needs to be refactored
        private void InstallMods(object sender, DoWorkEventArgs e)
        {
            installCanceled = false;
            ClearLog();

            var opts = (KeyValuePair <ModChanges, RelationshipResolverOptions>)e.Argument;

            IRegistryQuerier registry  = RegistryManager.Instance(manager.CurrentInstance).registry;
            ModuleInstaller  installer = ModuleInstaller.GetInstance(CurrentInstance, Manager.Cache, GUI.user);

            // Avoid accumulating multiple event handlers
            installer.onReportModInstalled -= OnModInstalled;
            installer.onReportModInstalled += OnModInstalled;
            // setup progress callback

            // this will be the final list of mods we want to install
            HashSet <CkanModule> toInstall = new HashSet <CkanModule>();
            var toUninstall = new HashSet <string>();
            var toUpgrade   = new HashSet <string>();

            // First compose sets of what the user wants installed, upgraded, and removed.
            foreach (ModChange change in opts.Key)
            {
                switch (change.ChangeType)
                {
                case GUIModChangeType.Remove:
                    toUninstall.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Update:
                    toUpgrade.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Install:
                    toInstall.Add(change.Mod.ToModule());
                    break;

                case GUIModChangeType.Replace:
                    ModuleReplacement repl = registry.GetReplacement(change.Mod.ToModule(), CurrentInstance.VersionCriteria());
                    if (repl != null)
                    {
                        toUninstall.Add(repl.ToReplace.identifier);
                        toInstall.Add(repl.ReplaceWith);
                    }
                    break;
                }
            }

            // Prompt for recommendations and suggestions, if any
            var recRows = getRecSugRows(
                opts.Key.Where(ch => ch.ChangeType == GUIModChangeType.Install)
                .Select(ch => ch.Mod.ToModule()),
                registry, toInstall
                );

            if (recRows.Any())
            {
                ShowRecSugDialog(recRows, toInstall);
            }

            tabController.HideTab("ChooseRecommendedModsTabPage");

            if (installCanceled)
            {
                tabController.ShowTab("ManageModsTabPage");
                e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                return;
            }

            // Now let's make all our changes.
            tabController.RenameTab("WaitTabPage", Properties.Resources.MainInstallWaitTitle);
            ShowWaitDialog();
            tabController.SetTabLock(true);

            IDownloader downloader = new NetAsyncModulesDownloader(GUI.user, Manager.Cache);

            cancelCallback = () =>
            {
                downloader.CancelDownload();
                installCanceled = true;
            };

            // checks if all actions were successfull
            bool processSuccessful       = false;
            bool resolvedAllProvidedMods = false;

            // uninstall/installs/upgrades until every list is empty
            // if the queue is NOT empty, resolvedAllProvidedMods is set to false until the action is done
            while (!resolvedAllProvidedMods)
            {
                try
                {
                    e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                    if (toUninstall.Count > 0)
                    {
                        processSuccessful = false;
                        if (!installCanceled)
                        {
                            installer.UninstallList(toUninstall, false, toInstall.Select(m => m.identifier));
                            processSuccessful = true;
                        }
                    }
                    if (toUpgrade.Count > 0)
                    {
                        processSuccessful = false;
                        if (!installCanceled)
                        {
                            installer.Upgrade(toUpgrade, downloader);
                            processSuccessful = true;
                        }
                    }
                    if (toInstall.Count > 0)
                    {
                        processSuccessful = false;
                        if (!installCanceled)
                        {
                            installer.InstallList(toInstall, opts.Value, downloader, false);
                            processSuccessful = true;
                        }
                    }
                    e.Result = new KeyValuePair <bool, ModChanges>(processSuccessful, opts.Key);
                    if (installCanceled)
                    {
                        return;
                    }
                    resolvedAllProvidedMods = true;
                }
                catch (TooManyModsProvideKraken k)
                {
                    // Prompt user to choose which mod to use
                    CkanModule chosen = TooManyModsProvideCore(k).Result;
                    // Close the selection prompt
                    Util.Invoke(this, () =>
                    {
                        tabController.ShowTab("WaitTabPage");
                        tabController.HideTab("ChooseProvidedModsTabPage");
                    });
                    if (chosen != null)
                    {
                        // User picked a mod, queue it up for installation
                        toInstall.Add(chosen);
                        // DON'T return so we can loop around and try the above InstallList call again
                    }
                    else
                    {
                        // User cancelled, get out
                        tabController.ShowTab("ManageModsTabPage");
                        e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                        return;
                    }
                }
                catch (DependencyNotSatisfiedKraken ex)
                {
                    GUI.user.RaiseMessage(Properties.Resources.MainInstallDepNotSatisfied, ex.parent, ex.module);
                    return;
                }
                catch (ModuleNotFoundKraken ex)
                {
                    GUI.user.RaiseMessage(Properties.Resources.MainInstallNotFound, ex.module);
                    return;
                }
                catch (BadMetadataKraken ex)
                {
                    GUI.user.RaiseMessage(Properties.Resources.MainInstallBadMetadata, ex.module, ex.Message);
                    return;
                }
                catch (FileExistsKraken ex)
                {
                    if (ex.owningModule != null)
                    {
                        GUI.user.RaiseMessage(
                            Properties.Resources.MainInstallFileExists,
                            ex.filename, ex.installingModule, ex.owningModule,
                            Meta.GetVersion()
                            );
                    }
                    else
                    {
                        GUI.user.RaiseMessage(
                            Properties.Resources.MainInstallUnownedFileExists,
                            ex.installingModule, ex.filename
                            );
                    }
                    GUI.user.RaiseMessage(Properties.Resources.MainInstallGameDataReverted);
                    return;
                }
                catch (InconsistentKraken ex)
                {
                    // The prettiest Kraken formats itself for us.
                    GUI.user.RaiseMessage(ex.InconsistenciesPretty);
                    return;
                }
                catch (CancelledActionKraken)
                {
                    return;
                }
                catch (MissingCertificateKraken kraken)
                {
                    // Another very pretty kraken.
                    GUI.user.RaiseMessage(kraken.ToString());
                    return;
                }
                catch (DownloadThrottledKraken kraken)
                {
                    string msg = kraken.ToString();
                    GUI.user.RaiseMessage(msg);
                    if (YesNoDialog(string.Format(Properties.Resources.MainInstallOpenSettingsPrompt, msg),
                                    Properties.Resources.MainInstallOpenSettings,
                                    Properties.Resources.MainInstallNo))
                    {
                        // Launch the URL describing this host's throttling practices, if any
                        if (kraken.infoUrl != null)
                        {
                            Process.Start(new ProcessStartInfo()
                            {
                                UseShellExecute = true,
                                FileName        = kraken.infoUrl.ToString()
                            });
                        }
                        // Now pretend they clicked the menu option for the settings
                        Enabled = false;
                        settingsDialog.ShowDialog();
                        Enabled = true;
                    }
                    return;
                }
                catch (ModuleDownloadErrorsKraken kraken)
                {
                    GUI.user.RaiseMessage(kraken.ToString());
                    GUI.user.RaiseError(kraken.ToString());
                    return;
                }
                catch (DirectoryNotFoundKraken kraken)
                {
                    GUI.user.RaiseMessage("\r\n{0}", kraken.Message);
                    return;
                }
                catch (DllNotFoundException)
                {
                    if (GUI.user.RaiseYesNoDialog(Properties.Resources.MainInstallLibCurlMissing))
                    {
                        Process.Start(new ProcessStartInfo()
                        {
                            UseShellExecute = true,
                            FileName        = "https://github.com/KSP-CKAN/CKAN/wiki/libcurl"
                        });
                    }
                    throw;
                }
            }
        }
Exemple #21
0
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutDialog));
     this.label1     = new System.Windows.Forms.Label();
     this.linkLabel1 = new System.Windows.Forms.LinkLabel();
     this.linkLabel2 = new System.Windows.Forms.LinkLabel();
     this.linkLabel3 = new System.Windows.Forms.LinkLabel();
     this.linkLabel4 = new System.Windows.Forms.LinkLabel();
     this.label2     = new System.Windows.Forms.Label();
     this.linkLabel5 = new System.Windows.Forms.LinkLabel();
     this.SuspendLayout();
     //
     // label1
     //
     this.label1.Anchor    = System.Windows.Forms.AnchorStyles.Top;
     this.label1.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.label1.Location  = new System.Drawing.Point(12, 9);
     this.label1.Name      = "label1";
     this.label1.Size      = new System.Drawing.Size(317, 20);
     this.label1.TabIndex  = 0;
     this.label1.Text      = "CKAN - The Comprehensive Kerbal Archive Network";
     this.label1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
     //
     // linkLabel1
     //
     this.linkLabel1.AutoSize  = true;
     this.linkLabel1.LinkArea  = new System.Windows.Forms.LinkArea(0, 8);
     this.linkLabel1.Location  = new System.Drawing.Point(140, 29);
     this.linkLabel1.Name      = "linkLabel1";
     this.linkLabel1.Size      = new System.Drawing.Size(43, 17);
     this.linkLabel1.TabIndex  = 1;
     this.linkLabel1.TabStop   = true;
     this.linkLabel1.Text      = "License";
     this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     this.linkLabel1.UseCompatibleTextRendering = true;
     this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
     //
     // linkLabel2
     //
     this.linkLabel2.AutoSize     = true;
     this.linkLabel2.LinkArea     = new System.Windows.Forms.LinkArea(0, 7);
     this.linkLabel2.Location     = new System.Drawing.Point(141, 56);
     this.linkLabel2.Name         = "linkLabel2";
     this.linkLabel2.Size         = new System.Drawing.Size(43, 13);
     this.linkLabel2.TabIndex     = 2;
     this.linkLabel2.TabStop      = true;
     this.linkLabel2.Text         = "Authors";
     this.linkLabel2.TextAlign    = System.Drawing.ContentAlignment.MiddleCenter;
     this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
     //
     // linkLabel3
     //
     this.linkLabel3.AutoSize     = true;
     this.linkLabel3.LinkArea     = new System.Windows.Forms.LinkArea(0, 6);
     this.linkLabel3.Location     = new System.Drawing.Point(52, 84);
     this.linkLabel3.Name         = "linkLabel3";
     this.linkLabel3.Size         = new System.Drawing.Size(41, 13);
     this.linkLabel3.TabIndex     = 3;
     this.linkLabel3.TabStop      = true;
     this.linkLabel3.Text         = "Source";
     this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked);
     //
     // linkLabel4
     //
     this.linkLabel4.AutoSize     = true;
     this.linkLabel4.LinkArea     = new System.Windows.Forms.LinkArea(0, 12);
     this.linkLabel4.Location     = new System.Drawing.Point(213, 84);
     this.linkLabel4.Name         = "linkLabel4";
     this.linkLabel4.Size         = new System.Drawing.Size(73, 13);
     this.linkLabel4.TabIndex     = 4;
     this.linkLabel4.TabStop      = true;
     this.linkLabel4.Text         = "Forum Thread";
     this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked);
     //
     // label2
     //
     this.label2.Location  = new System.Drawing.Point(79, 106);
     this.label2.Name      = "label2";
     this.label2.Size      = new System.Drawing.Size(184, 18);
     this.label2.TabIndex  = 5;
     this.label2.Text      = "Version " + Meta.GetVersion();
     this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     //
     // linkLabel5
     //
     this.linkLabel5.LinkArea  = new System.Windows.Forms.LinkArea(0, 15);
     this.linkLabel5.Location  = new System.Drawing.Point(125, 84);
     this.linkLabel5.Name      = "linkLabel5";
     this.linkLabel5.Size      = new System.Drawing.Size(71, 13);
     this.linkLabel5.TabIndex  = 6;
     this.linkLabel5.TabStop   = true;
     this.linkLabel5.Text      = "Homepage";
     this.linkLabel5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
     this.linkLabel5.UseCompatibleTextRendering = true;
     this.linkLabel5.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel5_LinkClicked);
     //
     // AboutDialog
     //
     this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
     this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
     this.ClientSize          = new System.Drawing.Size(341, 133);
     this.Controls.Add(this.linkLabel5);
     this.Controls.Add(this.label2);
     this.Controls.Add(this.linkLabel4);
     this.Controls.Add(this.linkLabel3);
     this.Controls.Add(this.linkLabel2);
     this.Controls.Add(this.linkLabel1);
     this.Controls.Add(this.label1);
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
     this.Icon            = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
     this.MaximizeBox     = false;
     this.MinimizeBox     = false;
     this.Name            = "AboutDialog";
     this.Text            = "About";
     this.ResumeLayout(false);
     this.PerformLayout();
 }
Exemple #22
0
        private void InstallMods(object sender, DoWorkEventArgs e) // this probably needs to be refactored
        {
            ShowWaitDialog();
            installCanceled = false;

            ClearLog();

            var opts = (KeyValuePair <ModChanges, RelationshipResolverOptions>)e.Argument;

            IRegistryQuerier registry  = RegistryManager.Instance(manager.CurrentInstance).registry;
            ModuleInstaller  installer = ModuleInstaller.GetInstance(CurrentInstance, GUI.user);

            // Avoid accumulating multiple event handlers
            installer.onReportModInstalled -= OnModInstalled;
            installer.onReportModInstalled += OnModInstalled;
            // setup progress callback

            toInstall = new HashSet <CkanModule>();
            var toUninstall = new HashSet <string>();
            var toUpgrade   = new HashSet <string>();

            // First compose sets of what the user wants installed, upgraded, and removed.
            foreach (ModChange change in opts.Key)
            {
                switch (change.ChangeType)
                {
                case GUIModChangeType.Remove:
                    toUninstall.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Update:
                    toUpgrade.Add(change.Mod.Identifier);
                    break;

                case GUIModChangeType.Install:
                    toInstall.Add(change.Mod.ToModule());
                    break;
                }
            }

            // Now work on satisifying dependencies.

            var recommended = new Dictionary <CkanModule, List <string> >();
            var suggested   = new Dictionary <CkanModule, List <string> >();

            foreach (var change in opts.Key)
            {
                if (change.ChangeType == GUIModChangeType.Install)
                {
                    AddMod(change.Mod.ToModule().recommends, recommended, change.Mod.Identifier, registry);
                    AddMod(change.Mod.ToModule().suggests, suggested, change.Mod.Identifier, registry);
                }
            }

            ShowSelection(recommended);
            ShowSelection(suggested, true);

            tabController.HideTab("ChooseRecommendedModsTabPage");

            if (installCanceled)
            {
                tabController.HideTab("WaitTabPage");
                tabController.ShowTab("ManageModsTabPage");
                e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                return;
            }

            // Now let's make all our changes.

            tabController.RenameTab("WaitTabPage", "Status log");
            tabController.ShowTab("WaitTabPage");
            tabController.SetTabLock(true);

            IDownloader downloader = new NetAsyncModulesDownloader(GUI.user);

            cancelCallback = () =>
            {
                downloader.CancelDownload();
                installCanceled = true;
            };

            bool resolvedAllProvidedMods = false;

            while (!resolvedAllProvidedMods)
            {
                try
                {
                    e.Result = new KeyValuePair <bool, ModChanges>(false, opts.Key);
                    if (!installCanceled && toUninstall.Count > 0)
                    {
                        installer.UninstallList(toUninstall);
                    }
                    if (!installCanceled && toUpgrade.Count > 0)
                    {
                        installer.Upgrade(toUpgrade, downloader);
                    }
                    if (!installCanceled && toInstall.Count > 0)
                    {
                        installer.InstallList(toInstall, opts.Value, downloader);
                    }
                    e.Result = new KeyValuePair <bool, ModChanges>(!installCanceled, opts.Key);
                    if (installCanceled)
                    {
                        return;
                    }
                    resolvedAllProvidedMods = true;
                }
                catch (DependencyNotSatisfiedKraken ex)
                {
                    GUI.user.RaiseMessage(
                        "{0} requires {1} but it is not listed in the index, or not available for your version of KSP.",
                        ex.parent, ex.module);
                    return;
                }
                catch (ModuleNotFoundKraken ex)
                {
                    GUI.user.RaiseMessage(
                        "Module {0} required but it is not listed in the index, or not available for your version of KSP.",
                        ex.module);
                    return;
                }
                catch (BadMetadataKraken ex)
                {
                    GUI.user.RaiseMessage("Bad metadata detected for module {0}: {1}", ex.module, ex.Message);
                    return;
                }
                catch (FileExistsKraken ex)
                {
                    if (ex.owningModule != null)
                    {
                        GUI.user.RaiseMessage(
                            "\r\nOh no! We tried to overwrite a file owned by another mod!\r\n" +
                            "Please try a `ckan update` and try again.\r\n\r\n" +
                            "If this problem re-occurs, then it maybe a packaging bug.\r\n" +
                            "Please report it at:\r\n\r\n" +
                            "https://github.com/KSP-CKAN/NetKAN/issues/new\r\n\r\n" +
                            "Please including the following information in your report:\r\n\r\n" +
                            "File           : {0}\r\n" +
                            "Installing Mod : {1}\r\n" +
                            "Owning Mod     : {2}\r\n" +
                            "CKAN Version   : {3}\r\n",
                            ex.filename, ex.installingModule, ex.owningModule,
                            Meta.GetVersion()
                            );
                    }
                    else
                    {
                        GUI.user.RaiseMessage(
                            "\r\n\r\nOh no!\r\n\r\n" +
                            "It looks like you're trying to install a mod which is already installed,\r\n" +
                            "or which conflicts with another mod which is already installed.\r\n\r\n" +
                            "As a safety feature, the CKAN will *never* overwrite or alter a file\r\n" +
                            "that it did not install itself.\r\n\r\n" +
                            "If you wish to install {0} via the CKAN,\r\n" +
                            "then please manually uninstall the mod which owns:\r\n\r\n" +
                            "{1}\r\n\r\n" + "and try again.\r\n",
                            ex.installingModule, ex.filename
                            );
                    }

                    GUI.user.RaiseMessage("Your GameData has been returned to its original state.\r\n");
                    return;
                }
                catch (InconsistentKraken ex)
                {
                    // The prettiest Kraken formats itself for us.
                    GUI.user.RaiseMessage(ex.InconsistenciesPretty);
                    return;
                }
                catch (CancelledActionKraken)
                {
                    return;
                }
                catch (MissingCertificateKraken kraken)
                {
                    // Another very pretty kraken.
                    GUI.user.RaiseMessage(kraken.ToString());
                    return;
                }
                catch (DownloadThrottledKraken kraken)
                {
                    string msg = kraken.ToString();
                    GUI.user.RaiseMessage(msg);
                    if (YesNoDialog($"{msg}\r\n\r\nOpen settings now?"))
                    {
                        // Launch the URL describing this host's throttling practices, if any
                        if (kraken.infoUrl != null)
                        {
                            Process.Start(new ProcessStartInfo()
                            {
                                UseShellExecute = true,
                                FileName        = kraken.infoUrl.ToString()
                            });
                        }
                        // Now pretend they clicked the menu option for the settings
                        Enabled = false;
                        settingsDialog.ShowDialog();
                        Enabled = true;
                    }
                    return;
                }
                catch (ModuleDownloadErrorsKraken kraken)
                {
                    GUI.user.RaiseMessage(kraken.ToString());
                    GUI.user.RaiseError(kraken.ToString());
                    return;
                }
                catch (DirectoryNotFoundKraken kraken)
                {
                    GUI.user.RaiseMessage("\r\n{0}", kraken.Message);
                    return;
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// React to switching to a new game instance
        /// </summary>
        /// <param name="allowRepoUpdate">true if a repo update is allowed if needed (e.g. on initial load), false otherwise</param>
        private void CurrentInstanceUpdated(bool allowRepoUpdate)
        {
            log.Debug("Current instance updated, scanning");
            CurrentInstance.Scan();
            Util.Invoke(this, () =>
            {
                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()
                    );
            });

            if (CurrentInstance.CompatibleVersionsAreFromDifferentGameVersion)
            {
                new CompatibleGameVersionsDialog(CurrentInstance, !actuallyVisible)
                .ShowDialog();
            }

            // This will throw RegistryInUseKraken if locked by another process
            var regMgr   = RegistryManager.Instance(CurrentInstance);
            var registry = regMgr.registry;

            if (!string.IsNullOrEmpty(regMgr.previousCorruptedMessage) &&
                !string.IsNullOrEmpty(regMgr.previousCorruptedPath))
            {
                errorDialog.ShowErrorDialog(Properties.Resources.MainCorruptedRegistry,
                                            regMgr.previousCorruptedPath, regMgr.previousCorruptedMessage,
                                            Path.Combine(Path.GetDirectoryName(regMgr.previousCorruptedPath) ?? "", regMgr.LatestInstalledExportFilename()));
                regMgr.previousCorruptedMessage = null;
                regMgr.previousCorruptedPath    = null;
            }
            registry.BuildTagIndex(ManageMods.mainModList.ModuleTags);

            configuration = GUIConfiguration.LoadOrCreateConfiguration(
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml"));

            bool repoUpdateNeeded = configuration.RefreshOnStartup ||
                                    !RegistryManager.Instance(CurrentInstance).registry.HasAnyAvailable();

            if (allowRepoUpdate)
            {
                // If not allowing, don't do anything
                if (repoUpdateNeeded)
                {
                    // Update the filters after UpdateRepo() completed.
                    // Since this happens with a backgroundworker, Filter() is added as callback for RunWorkerCompleted.
                    // Remove it again after it ran, else it stays there and is added again and again.
                    void filterUpdate(object sender, RunWorkerCompletedEventArgs e)
                    {
                        SetupDefaultSearch();
                        m_UpdateRepoWorker.RunWorkerCompleted -= filterUpdate;
                    }

                    m_UpdateRepoWorker.RunWorkerCompleted += filterUpdate;

                    ManageMods.ModGrid.Rows.Clear();
                    UpdateRepo();
                }
                else
                {
                    SetupDefaultSearch();
                    ManageMods.UpdateModsList();
                }
            }
            ManageMods.InstanceUpdated(CurrentInstance);
        }
Exemple #24
0
        /// <summary>
        /// Helper function to wrap around calls to ModuleInstaller.
        /// Handles some of the possible krakens and displays user friendly messages for them.
        /// </summary>
        private static bool WasSuccessful(Action action)
        {
            try
            {
                action();
            }
            catch (ModuleNotFoundKraken ex)
            {
                GUI.user.RaiseMessage(
                    "Module {0} required but it is not listed in the index, or not available for your version of KSP.",
                    ex.module);
                return(false);
            }
            catch (BadMetadataKraken ex)
            {
                GUI.user.RaiseMessage("Bad metadata detected for module {0}: {1}", ex.module, ex.Message);
                return(false);
            }
            catch (FileExistsKraken ex)
            {
                if (ex.owningModule != null)
                {
                    GUI.user.RaiseMessage(
                        "\r\nOh no! We tried to overwrite a file owned by another mod!\r\n" +
                        "Please try a `ckan update` and try again.\r\n\r\n" +
                        "If this problem re-occurs, then it maybe a packaging bug.\r\n" +
                        "Please report it at:\r\n\r\n" +
                        "https://github.com/KSP-CKAN/NetKAN/issues/new\r\n\r\n" +
                        "Please including the following information in your report:\r\n\r\n" +
                        "File           : {0}\r\n" +
                        "Installing Mod : {1}\r\n" +
                        "Owning Mod     : {2}\r\n" +
                        "CKAN Version   : {3}\r\n",
                        ex.filename, ex.installingModule, ex.owningModule,
                        Meta.GetVersion()
                        );
                }
                else
                {
                    GUI.user.RaiseMessage(
                        "\r\n\r\nOh no!\r\n\r\n" +
                        "It looks like you're trying to install a mod which is already installed,\r\n" +
                        "or which conflicts with another mod which is already installed.\r\n\r\n" +
                        "As a safety feature, the CKAN will *never* overwrite or alter a file\r\n" +
                        "that it did not install itself.\r\n\r\n" +
                        "If you wish to install {0} via the CKAN,\r\n" +
                        "then please manually uninstall the mod which owns:\r\n\r\n" +
                        "{1}\r\n\r\n" + "and try again.\r\n",
                        ex.installingModule, ex.filename
                        );
                }

                GUI.user.RaiseMessage("Your GameData has been returned to its original state.\r\n");
                return(false);
            }
            catch (InconsistentKraken ex)
            {
                // The prettiest Kraken formats itself for us.
                GUI.user.RaiseMessage(ex.InconsistenciesPretty);
                return(false);
            }
            catch (CancelledActionKraken)
            {
                return(false);
            }
            catch (MissingCertificateKraken kraken)
            {
                // Another very pretty kraken.
                GUI.user.RaiseMessage(kraken.ToString());
                return(false);
            }
            catch (DownloadErrorsKraken)
            {
                // User notified in InstallList
                return(false);
            }
            catch (DirectoryNotFoundKraken kraken)
            {
                GUI.user.RaiseMessage("\r\n{0}", kraken.Message);
                return(false);
            }
            return(true);
        }
Exemple #25
0
        /// <summary>
        /// React to switching to a new game instance
        /// </summary>
        /// <param name="allowRepoUpdate">true if a repo update is allowed if needed (e.g. on initial load), false otherwise</param>
        private void CurrentInstanceUpdated(bool allowRepoUpdate)
        {
            CurrentInstance.Scan();
            Util.Invoke(this, () =>
            {
                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()
                    );
            });

            configuration = GUIConfiguration.LoadOrCreateConfiguration(
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml")
                );

            if (CurrentInstance.CompatibleVersionsAreFromDifferentGameVersion)
            {
                new CompatibleGameVersionsDialog(CurrentInstance, !actuallyVisible)
                .ShowDialog();
            }

            (RegistryManager.Instance(CurrentInstance).registry as Registry)
            ?.BuildTagIndex(ManageMods.mainModList.ModuleTags);

            bool repoUpdateNeeded = configuration.RefreshOnStartup ||
                                    !RegistryManager.Instance(CurrentInstance).registry.HasAnyAvailable();

            if (allowRepoUpdate)
            {
                // If not allowing, don't do anything
                if (repoUpdateNeeded)
                {
                    // Update the filters after UpdateRepo() completed.
                    // Since this happens with a backgroundworker, Filter() is added as callback for RunWorkerCompleted.
                    // Remove it again after it ran, else it stays there and is added again and again.
                    void filterUpdate(object sender, RunWorkerCompletedEventArgs e)
                    {
                        ManageMods.Filter(
                            (GUIModFilter)configuration.ActiveFilter,
                            ManageMods.mainModList.ModuleTags.Tags.GetOrDefault(configuration.TagFilter),
                            ManageMods.mainModList.ModuleLabels.LabelsFor(CurrentInstance.Name)
                            .FirstOrDefault(l => l.Name == configuration.CustomLabelFilter)
                            );
                        m_UpdateRepoWorker.RunWorkerCompleted -= filterUpdate;
                    }

                    m_UpdateRepoWorker.RunWorkerCompleted += filterUpdate;

                    ManageMods.ModGrid.Rows.Clear();
                    UpdateRepo();
                }
                else
                {
                    ManageMods.UpdateModsList();
                    ManageMods.Filter(
                        (GUIModFilter)configuration.ActiveFilter,
                        ManageMods.mainModList.ModuleTags.Tags.GetOrDefault(configuration.TagFilter),
                        ManageMods.mainModList.ModuleLabels.LabelsFor(CurrentInstance.Name)
                        .FirstOrDefault(l => l.Name == configuration.CustomLabelFilter)
                        );
                }
            }
            ManageMods.InstanceUpdated(CurrentInstance);
        }
Exemple #26
0
 public AboutDialog()
 {
     InitializeComponent();
     ApplyFormCompatibilityFixes();
     StartPosition     = FormStartPosition.CenterScreen;
     versionLabel.Text = string.Format(Properties.Resources.AboutDialogLabel2Text, Meta.GetVersion());
 }