Esempio n. 1
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)
            {
                new CompatibleKspVersionsDialog(CurrentInstance, !actuallyVisible)
                .ShowDialog();
            }

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

            Filter((GUIModFilter)configuration.ActiveFilter);
        }
Esempio n. 2
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);
        }
Esempio n. 3
0
        public Main(string[] cmdlineArgs, GUIUser User, bool showConsole)
        {
            log.Info("Starting the GUI");
            m_CommandLineArgs = cmdlineArgs;
            m_User            = User;

            User.displayMessage = AddStatusMessage;
            User.displayError   = ErrorDialog;

            controlFactory = new ControlFactory();
            Instance       = this;
            mainModList    = new MainModList(source => UpdateFilters(this));
            InitializeComponent();

            // We need to initialize error dialog first to display errors
            m_ErrorDialog = controlFactory.CreateControl <ErrorDialog>();

            // We want to check our current instance is null first, as it may
            // have already been set by a command-line option.
            Manager = new KSPManager(User);
            if (CurrentInstance == null && manager.GetPreferredInstance() == null)
            {
                Hide();

                var result = new ChooseKSPInstance().ShowDialog();
                if (result == DialogResult.Cancel || result == DialogResult.Abort)
                {
                    Application.Exit();
                    return;
                }
            }

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

            FilterToolButton.MouseHover           += (sender, args) => FilterToolButton.ShowDropDown();
            launchKSPToolStripMenuItem.MouseHover += (sender, args) => launchKSPToolStripMenuItem.ShowDropDown();
            ApplyToolButton.MouseHover            += (sender, args) => ApplyToolButton.ShowDropDown();

            ModList.CurrentCellDirtyStateChanged += ModList_CurrentCellDirtyStateChanged;
            ModList.CellValueChanged             += ModList_CellValueChanged;

            m_TabController = new TabController(MainTabControl);
            m_TabController.ShowTab("ManageModsTabPage");

            RecreateDialogs();

            if (!showConsole)
            {
                Util.HideConsoleWindow();
            }

            // Disable the modinfo controls until a mod has been choosen.
            ModInfoTabControl.Enabled = false;

            // WinForms on Mac OS X has a nasty bug where the UI thread hogs the CPU,
            // making our download speeds really slow unless you move the mouse while
            // downloading. Yielding periodically addresses that.
            // https://bugzilla.novell.com/show_bug.cgi?id=663433
            if (Platform.IsMac)
            {
                var yield_timer = new Timer {
                    Interval = 2
                };
                yield_timer.Tick += (sender, e) => {
                    Thread.Yield();
                };
                yield_timer.Start();
            }

            Application.Run(this);
        }
Esempio n. 4
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 && 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);
        }
Esempio n. 5
0
        public void LaunchGame()
        {
            var split = configuration.CommandLineArguments.Split(' ');

            if (split.Length == 0)
            {
                return;
            }

            var registry = RegistryManager.Instance(CurrentInstance).registry;

            var suppressedIdentifiers = CurrentInstance.GetSuppressedCompatWarningIdentifiers;
            var incomp = registry.IncompatibleInstalled(CurrentInstance.VersionCriteria())
                         .Where(m => !m.Module.IsDLC && !suppressedIdentifiers.Contains(m.identifier))
                         .ToList();

            if (incomp.Any())
            {
                // Warn that it might not be safe to run Game with incompatible modules installed
                string incompatDescrip = incomp
                                         .Select(m => $"{m.Module} ({registry.CompatibleGameVersions(CurrentInstance.game, m.Module)})")
                                         .Aggregate((a, b) => $"{a}{Environment.NewLine}{b}");
                var ver    = CurrentInstance.Version();
                var result = SuppressableYesNoDialog(
                    string.Format(Properties.Resources.MainLaunchWithIncompatible, incompatDescrip),
                    string.Format(Properties.Resources.MainLaunchDontShow,
                                  CurrentInstance.game.ShortName,
                                  new GameVersion(ver.Major, ver.Minor, ver.Patch)),
                    Properties.Resources.MainLaunch,
                    Properties.Resources.MainGoBack
                    );
                if (result.Item1 != DialogResult.Yes)
                {
                    return;
                }
                else if (result.Item2)
                {
                    CurrentInstance.AddSuppressedCompatWarningIdentifiers(
                        incomp.Select(m => m.identifier).ToHashSet()
                        );
                }
            }

            split = CurrentInstance.game.AdjustCommandLine(split,
                                                           Main.Instance.CurrentInstance.Version());
            var binary = split[0];
            var args   = string.Join(" ", split.Skip(1));

            try
            {
                Directory.SetCurrentDirectory(CurrentInstance.GameDir());

                Process p = new Process()
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        FileName  = binary,
                        Arguments = args
                    },
                    EnableRaisingEvents = true
                };

                GameInstance inst = CurrentInstance;
                p.Exited += (sender, e) => GameExit(inst);

                p.Start();
                CurrentInstance.playTime.Start();
            }
            catch (Exception exception)
            {
                currentUser.RaiseError(Properties.Resources.MainLaunchFailed, exception.Message);
            }
        }
Esempio n. 6
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);
        }
Esempio n. 7
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)}";
                UpdateStatusBar();
            });

            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);
        }
Esempio n. 8
0
File: Main.cs Progetto: javisar/CKAN
        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 (!ONI)
            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();
            }
#else
            configuration.CheckForUpdatesOnLaunch      = false;
            configuration.CheckForUpdatesOnLaunchNoNag = false;
            configuration.Save();
#endif
            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;

#if (!ONI)
            URLHandlers.RegisterURLHandler(configuration, currentUser);
#endif
            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()} - {GameConfig.Constants.GameNameShort} {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);
        }
Esempio n. 9
0
        protected override void OnLoad(EventArgs e)
        {
            Location = m_Configuration.WindowLoc;
            Size     = m_Configuration.WindowSize;

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

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

            if (m_Configuration.CheckForUpdatesOnLaunch)
            {
                try
                {
                    log.Info("Making autoupdate call");
                    var latest_version  = AutoUpdate.FetchLatestCkanVersion();
                    var current_version = new Version(Meta.Version());

                    if (latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher ckan version");
                        var release_notes = AutoUpdate.FetchLatestCkanVersionReleaseNotes();
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            log.Info("Start ckan update");
                            AutoUpdate.StartUpdateProcess(true);
                        }
                    }
                }
                catch (Exception exception)
                {
                    m_User.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;

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

            m_CacheWorker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            m_CacheWorker.RunWorkerCompleted += PostModCaching;
            m_CacheWorker.DoWork             += CacheMod;

            m_User.displayYesNo = YesNoDialog;
            URLHandlers.RegisterURLHandler(m_Configuration, m_User);
            m_User.displayYesNo = null;

            ApplyToolButton.Enabled = false;

            if (m_Configuration.RefreshOnStartup)
            {
                UpdateRepo();
            }

            CurrentInstanceUpdated();

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

            if (m_CommandLineArgs.Length >= 2)
            {
                var identifier = m_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);
                }

                int i = 0;
                log.Debug("Attempting to select mod from startup parameters");
                foreach (DataGridViewRow row in ModList.Rows)
                {
                    var module = ((GUIMod)row.Tag);
                    if (identifier == module.Identifier)
                    {
                        ModList.FirstDisplayedScrollingRowIndex = i;
                        row.Selected = true;
                        break;
                    }

                    i++;
                }
                log.Debug("Failed to select mod from startup parameters");
            }

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

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

            m_PluginController = new PluginController(pluginsPath, true);

            log.Info("GUI started");
            ModList.Select();
            base.OnLoad(e);
        }
Esempio n. 10
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.Version());

                    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;

            m_CacheWorker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            m_CacheWorker.RunWorkerCompleted += PostModCaching;
            m_CacheWorker.DoWork             += CacheMod;

            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.Version(), 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);
        }
Esempio n. 11
0
        public Main(string[] cmdlineArgs, GUIUser user, bool showConsole)
        {
            log.Info("Starting the GUI");
            commandLineArgs = cmdlineArgs;
            currentUser     = user;

            user.displayMessage = AddStatusMessage;
            user.displayError   = ErrorDialog;

            controlFactory = new ControlFactory();
            Instance       = this;
            mainModList    = new MainModList(source => UpdateFilters(this), TooManyModsProvide, user);

            navHistory            = new NavigationHistory <GUIMod>();
            navHistory.IsReadOnly = true; // read-only until the UI is started.
                                          // we switch out of it at the end of OnLoad()
                                          // when we call NavInit()

            InitializeComponent();

            // We need to initialize error dialog first to display errors
            errorDialog = controlFactory.CreateControl <ErrorDialog>();

            // We want to check our current instance is null first, as it may
            // have already been set by a command-line option.
            Manager = new KSPManager(user);
            if (CurrentInstance == null && manager.GetPreferredInstance() == null)
            {
                Hide();

                var result = new ChooseKSPInstance().ShowDialog();
                if (result == DialogResult.Cancel || result == DialogResult.Abort)
                {
                    Application.Exit();
                    return;
                }
            }

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

            // Check if there is any other instances already running.
            // This is not entirely necessary, but we can show a nicer error message this way.
            try
            {
                #pragma warning disable 219
                var lockedReg = RegistryManager.Instance(CurrentInstance).registry;
                #pragma warning restore 219
            }
            catch (RegistryInUseKraken kraken)
            {
                errorDialog.ShowErrorDialog(kraken.ToString());

                return;
            }

            FilterToolButton.MouseHover           += (sender, args) => FilterToolButton.ShowDropDown();
            launchKSPToolStripMenuItem.MouseHover += (sender, args) => launchKSPToolStripMenuItem.ShowDropDown();
            ApplyToolButton.MouseHover            += (sender, args) => ApplyToolButton.ShowDropDown();

            ModList.CurrentCellDirtyStateChanged += ModList_CurrentCellDirtyStateChanged;
            ModList.CellValueChanged             += ModList_CellValueChanged;

            tabController = new TabController(MainTabControl);
            tabController.ShowTab("ManageModsTabPage");

            RecreateDialogs();

            if (!showConsole)
            {
                Util.HideConsoleWindow();
            }

            // Disable the modinfo controls until a mod has been choosen.
            ModInfoTabControl.Enabled = false;

            // WinForms on Mac OS X has a nasty bug where the UI thread hogs the CPU,
            // making our download speeds really slow unless you move the mouse while
            // downloading. Yielding periodically addresses that.
            // https://bugzilla.novell.com/show_bug.cgi?id=663433
            if (Platform.IsMac)
            {
                var timer = new Timer {
                    Interval = 2
                };
                timer.Tick += (sender, e) => {
                    Thread.Yield();
                };
                timer.Start();
            }

            Application.Run(this);

            var registry = RegistryManager.Instance(Manager.CurrentInstance);
            if (registry != null)
            {
                registry.Dispose();
            }
        }