Exemple #1
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 #2
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"),
                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>
        /// Exports installed mods to a .ckan file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportModListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var exportOptions = new List <ExportOption>
            {
                new ExportOption(ExportFileType.CkanFavourite, "CKAN favourites list (*.ckan)", "ckan"),
                new ExportOption(ExportFileType.Ckan, "CKAN modpack (enforces exact mod versions) (*.ckan)", "ckan"),
                new ExportOption(ExportFileType.PlainText, "Plain text (*.txt)", "txt"),
                new ExportOption(ExportFileType.Markdown, "Markdown (*.md)", "md"),
                new ExportOption(ExportFileType.BbCode, "BBCode (*.txt)", "txt"),
                new ExportOption(ExportFileType.Csv, "Comma-separated values (*.csv)", "csv"),
                new ExportOption(ExportFileType.Tsv, "Tab-separated values (*.tsv)", "tsv")
            };

            var filter = string.Join("|", exportOptions.Select(i => i.ToString()).ToArray());

            var dlg = new SaveFileDialog
            {
                Filter = filter,
                Title  = Resources.ExportInstalledModsDialogTitle
            };

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var exportOption = exportOptions[dlg.FilterIndex - 1]; // FilterIndex is 1-indexed

                if (exportOption.ExportFileType == ExportFileType.Ckan || exportOption.ExportFileType == ExportFileType.CkanFavourite)
                {
                    bool recommends = false;
                    bool versions   = true;

                    if (exportOption.ExportFileType == ExportFileType.CkanFavourite)
                    {
                        recommends = true;
                        versions   = false;
                    }

                    // Save, just to be certain that the installed-*.ckan metapackage is generated
                    RegistryManager.Instance(CurrentInstance).Save(true, recommends, versions);

                    // TODO: The core might eventually save as something other than 'installed-default.ckan'
                    File.Copy(Path.Combine(CurrentInstance.CkanDir(), "installed-default.ckan"), dlg.FileName, true);
                }
                else
                {
                    var fileMode = File.Exists(dlg.FileName) ? FileMode.Truncate : FileMode.CreateNew;

                    using (var stream = new FileStream(dlg.FileName, fileMode))
                    {
                        var registry = RegistryManager.Instance(CurrentInstance).registry;

                        new Exporter(exportOption.ExportFileType).Export(registry, stream);
                    }
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Exports installed mods to a .ckan file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportModListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dlg = new SaveFileDialog();

            dlg.Filter = Resources.CKANFileFilter;
            dlg.Title  = Resources.ExportInstalledModsDialogTitle;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                // Save, just to be certain that the installed-*.ckan metapackage is generated
                RegistryManager.Instance(CurrentInstance).Save();

                // TODO: The core might eventually save as something other than 'installed-default.ckan'
                File.Copy(Path.Combine(CurrentInstance.CkanDir(), "installed-default.ckan"), dlg.FileName);
            }
        }
Exemple #5
0
        public void CurrentInstanceUpdated()
        {
            Util.Invoke(this, () =>
            {
                Text = String.Format("CFAN {0} - Factorio {1}    --    {2}", Meta.Version(), CurrentInstance.Version(),
                                     CurrentInstance.GameDir());
                KSPVersionLabel.Text = String.Format("Factorio {0}", CurrentInstance.Version());
            });

            m_Configuration = Configuration.LoadOrCreateConfiguration
                              (
                CurrentInstance.findFactorioBinaryPath(),
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml"),
                Repo.default_ckan_repo.ToString()
                              );
            UpdateModsList();
            ChangeSet = null;
            Conflicts = null;

            Filter((GUIModFilter)m_Configuration.ActiveFilter);
        }
Exemple #6
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 #7
0
        public Main(string[] cmdlineArgs, KSPManager mgr, GUIUser user, bool showConsole)
        {
            log.Info("Starting the GUI");
            commandLineArgs = cmdlineArgs;

            manager     = mgr ?? new KSPManager(user);
            currentUser = user;

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

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

            InitializeComponent();

            // Replace mono's broken, ugly toolstrip renderer
            if (Platform.IsMono)
            {
                menuStrip1.Renderer = new FlatToolStripRenderer();
                menuStrip2.Renderer = new FlatToolStripRenderer();
                fileToolStripMenuItem.DropDown.Renderer     = new FlatToolStripRenderer();
                settingsToolStripMenuItem.DropDown.Renderer = new FlatToolStripRenderer();
                helpToolStripMenuItem.DropDown.Renderer     = new FlatToolStripRenderer();
                FilterToolButton.DropDown.Renderer          = new FlatToolStripRenderer();
                minimizedContextMenuStrip.Renderer          = new FlatToolStripRenderer();
                ModListContextMenuStrip.Renderer            = new FlatToolStripRenderer();
                ModListHeaderContextMenuStrip.Renderer      = new FlatToolStripRenderer();
            }

            // Initialize all user interaction dialogs.
            RecreateDialogs();

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

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

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

            // 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");

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

            // Disable the modinfo controls until a mod has been choosen. This has an effect if the modlist is empty.
            ActiveModInfo = null;

            // 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();
            }

            // Set the window name and class for X11
            if (Platform.IsX11)
            {
                HandleCreated += (sender, e) => X11.SetWMClass("CKAN", "CKAN", Handle);
            }

            Application.Run(this);

            var registry = RegistryManager.Instance(Manager.CurrentInstance);
            registry?.Dispose();
        }
Exemple #8
0
        public Main(string[] cmdlineArgs, GameInstanceManager mgr, bool showConsole)
        {
            log.Info("Starting the GUI");
            commandLineArgs = cmdlineArgs;

            Configuration.IConfiguration mainConfig = ServiceLocator.Container.Resolve <Configuration.IConfiguration>();

            // If the language is not set yet in the config, try to save the current language.
            // If it isn't supported, it'll still be null afterwards. Doesn't matter, .NET handles the resource selection.
            // Once the user chooses a language in the settings, the string will be no longer null, and we can change
            // CKAN's language here before any GUI components are initialized.
            if (string.IsNullOrEmpty(mainConfig.Language))
            {
                string runtimeLanguage = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                mainConfig.Language = runtimeLanguage;
            }
            else
            {
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(mainConfig.Language);
            }

            InitializeComponent();

            Instance = this;

            currentUser = new GUIUser(this, this.Wait);
            manager     = mgr ?? new GameInstanceManager(currentUser);

            controlFactory = new ControlFactory();

            // React when the user clicks a tag or filter link in mod info
            ModInfo.OnChangeFilter += ManageMods.Filter;

            // Replace mono's broken, ugly toolstrip renderer
            if (Platform.IsMono)
            {
                menuStrip1.Renderer = new FlatToolStripRenderer();
                fileToolStripMenuItem.DropDown.Renderer     = new FlatToolStripRenderer();
                settingsToolStripMenuItem.DropDown.Renderer = new FlatToolStripRenderer();
                helpToolStripMenuItem.DropDown.Renderer     = new FlatToolStripRenderer();
                minimizedContextMenuStrip.Renderer          = new FlatToolStripRenderer();
            }

            // Initialize all user interaction dialogs.
            RecreateDialogs();

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

                var result = new ManageGameInstancesDialog(!actuallyVisible, currentUser).ShowDialog();
                if (result == DialogResult.Cancel || result == DialogResult.Abort)
                {
                    Application.Exit();
                    return;
                }
            }

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

            // 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;
            }

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

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

            // Disable the modinfo controls until a mod has been choosen. This has an effect if the modlist is empty.
            ActiveModInfo = null;

            // 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();
            }

            // Set the window name and class for X11
            if (Platform.IsX11)
            {
                HandleCreated += (sender, e) => X11.SetWMClass("CKAN", "CKAN", Handle);
            }

            Application.Run(this);

            var registry = RegistryManager.Instance(Manager.CurrentInstance);
            registry?.Dispose();
        }
Exemple #9
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 #10
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 #11
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 #12
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 #13
0
        private void Main_Load(object sender, EventArgs e)
        {
            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;

            UpdateModsList();

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

            ApplyToolButton.Enabled = false;

            ModList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

            Text = String.Format("CKAN {0} - KSP {1}", Meta.Version(), CurrentInstance.Version());
            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;
                foreach (DataGridViewRow row in ModList.Rows)
                {
                    var module = ((GUIMod)row.Tag).ToCkanModule();
                    if (identifier == module.identifier)
                    {
                        ModList.FirstDisplayedScrollingRowIndex = i;
                        row.Selected = true;
                        break;
                    }

                    i++;
                }
            }

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

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

            m_PluginController = new PluginController(pluginsPath, true);
        }
Exemple #14
0
        protected override void OnLoad(EventArgs e)
        {
            enableTls2IfPossible();
            Location = m_Configuration.WindowLoc;
            Size     = m_Configuration.WindowSize;

            if (CurrentInstance.lacksFactorioAuthData())
            {
                m_User.RaiseError(
                    "Your config file located in {0} does not contain Factorio authorization data. Mods from official factorio.com mod portal will not be shown.\n\rYou can fix it by launching Factorio, entering in-game mod manager (mods -> install mods), quitting the game and restarting CFAN.",
                    new object[] { CurrentInstance.getFactorioAuthDataPath() }
                    );
            }

            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");
                    AutoUpdate.Instance.FetchLatestReleaseInfo();
                    var latest_version  = AutoUpdate.Instance.LatestVersion;
                    var current_version = new CFANVersion(Meta.Version(), "");

                    if (AutoUpdate.Instance.IsFetched() && latest_version.IsGreaterThan(current_version))
                    {
                        log.Debug("Found higher cfan version");
                        var release_notes = AutoUpdate.Instance.ReleaseNotes;
                        var dialog        = new NewUpdateDialog(latest_version.ToString(), release_notes);
                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            log.Info("Start cfan update");
                            BackgroundWorker bw = new BackgroundWorker();
                            bw.DoWork += (sender, args) => AutoUpdate.Instance.StartUpdateProcess(true, PleaseWait.User);
                            bw.RunWorkerAsync();
                            new PleaseWait().ShowDialog(this);
                        }
                    }
                }
                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;

            var old_YesNoDialog = m_User.displayYesNo;

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

            ApplyToolButton.Enabled = false;

            CurrentInstanceUpdated();
            CheckForConsistency();

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

            Text = String.Format("CFAN {0} - Factorio {1}  --  {2}", Meta.Version(), CurrentInstance.Version(),
                                 CurrentInstance.GameDir());
            KSPVersionLabel.Text = String.Format("Factorio {0}", CurrentInstance.Version());

            if (m_CommandLineArgs.Length >= 2)
            {
                var identifier = m_CommandLineArgs[1];
                if (identifier.StartsWith("//"))
                {
                    identifier = identifier.Substring(2);
                }
                else if (identifier.StartsWith("cfan://"))
                {
                    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);
            }

            m_PluginController = new PluginController(pluginsPath, true);

            CurrentInstance.RebuildKSPSubDir();

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #15
0
        public Main(string[] cmdlineArgs, GUIUser User, GuiOptions guiOptions)
        {
            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), TooManyModsProvide, User);
            InitializeComponent();

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

            Manager = new KSPManager(User);

            if (guiOptions?.FactorioInstallName != null)
            {
                // Set a KSP directory by its alias.
                try
                {
                    manager.SetCurrentInstance(guiOptions.FactorioInstallName);
                }
                catch (InvalidKSPInstanceKraken)
                {
                    User.RaiseError("Invalid Factorio installation specified \"{0}\", use '--factorio-dir' to specify by path, or 'list-installs' to see known Factorio installations", guiOptions.FactorioInstallName);
                }
            }
            else if (guiOptions?.FactorioDirectory != null)
            {
                // Set a KSP directory by its path
                manager.SetCurrentInstanceByPath(guiOptions.FactorioDirectory);
            }

            // We want to check our current instance is null first, as it may
            // have already been set by a command-line option.
            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
                              (
                CurrentInstance.findFactorioBinaryPath(),
                Path.Combine(CurrentInstance.CkanDir(), "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 (guiOptions?.ShowConsole != true)
            {
                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);
        }
Exemple #16
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);

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

            InitializeComponent();

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

            // We want to check if 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.CkanDir(), "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.SelectedModule = null;

            // 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);
            registry?.Dispose();
        }
Exemple #17
0
        public Main(string[] cmdlineArgs, GameInstanceManager mgr, bool showConsole)
        {
            log.Info("Starting the GUI");
            commandLineArgs = cmdlineArgs;

            Configuration.IConfiguration mainConfig = ServiceLocator.Container.Resolve <Configuration.IConfiguration>();

            // If the language is not set yet in the config, try to save the current language.
            // If it isn't supported, it'll still be null afterwards. Doesn't matter, .NET handles the resource selection.
            // Once the user chooses a language in the settings, the string will be no longer null, and we can change
            // CKAN's language here before any GUI components are initialized.
            if (string.IsNullOrEmpty(mainConfig.Language))
            {
                string runtimeLanguage = Thread.CurrentThread.CurrentUICulture.IetfLanguageTag;
                mainConfig.Language = runtimeLanguage;
            }
            else
            {
                CultureInfo.DefaultThreadCurrentUICulture = Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(mainConfig.Language);
            }

            InitializeComponent();

            Instance = this;

            currentUser = new GUIUser(this, this.Wait);
            if (mgr != null)
            {
                // With a working GUI, assign a GUIUser to the GameInstanceManager to replace the ConsoleUser
                mgr.User = currentUser;
                manager  = mgr;
            }
            else
            {
                manager = new GameInstanceManager(currentUser);
            }

            controlFactory = new ControlFactory();

            // React when the user clicks a tag or filter link in mod info
            ModInfo.OnChangeFilter += ManageMods.Filter;

            // Replace mono's broken, ugly toolstrip renderer
            if (Platform.IsMono)
            {
                menuStrip1.Renderer = new FlatToolStripRenderer();
                fileToolStripMenuItem.DropDown.Renderer     = new FlatToolStripRenderer();
                settingsToolStripMenuItem.DropDown.Renderer = new FlatToolStripRenderer();
                helpToolStripMenuItem.DropDown.Renderer     = new FlatToolStripRenderer();
                minimizedContextMenuStrip.Renderer          = new FlatToolStripRenderer();
            }

            // Initialize all user interaction dialogs.
            RecreateDialogs();

            // Make sure we have an instance
            if (CurrentInstance == null)
            {
                // Maybe we can find an instance automatically (e.g., portable, only, default)
                manager.GetPreferredInstance();
            }
            // A loop that ends when we have a valid instance or the user gives up
            do
            {
                if (CurrentInstance == null && !InstancePromptAtStart())
                {
                    // User cancelled, give up
                    return;
                }
                // We now have a tentative instance. Check if it's locked.
                try
                {
                    // This will throw RegistryInUseKraken if locked by another process
                    var regMgr = RegistryManager.Instance(CurrentInstance);
                    // Tell the user their registry was reset if it was corrupted
                    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;
                        // But the instance is actually fine because a new registry was just created
                    }
                }
                catch (RegistryInUseKraken kraken)
                {
                    errorDialog.ShowErrorDialog(kraken.ToString());
                    // Couldn't get the lock, there is no current instance
                    manager.CurrentInstance = null;
                    if (manager.Instances.All(inst => !inst.Value.Valid || inst.Value.IsMaybeLocked))
                    {
                        // Everything's invalid or locked, give up
                        Application.Exit();
                        return;
                    }
                }
            } while (CurrentInstance == null);
            // We can only reach this point if CurrentInstance is not null
            // AND we acquired the lock for it successfully

            // Get the instance's GUI onfig
            configuration = GUIConfiguration.LoadOrCreateConfiguration(
                Path.Combine(CurrentInstance.CkanDir(), "GUIConfig.xml"));

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

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

            // Disable the modinfo controls until a mod has been choosen. This has an effect if the modlist is empty.
            ActiveModInfo = null;

            // 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();
            }

            // Set the window name and class for X11
            if (Platform.IsX11)
            {
                HandleCreated += (sender, e) => X11.SetWMClass("CKAN", "CKAN", Handle);
            }

            Application.Run(this);

            if (CurrentInstance != null)
            {
                var registry = RegistryManager.Instance(Manager.CurrentInstance);
                registry?.Dispose();
            }
        }
Exemple #18
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");
                    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)
                        {
                            log.Info("Start ckan update");
                            AutoUpdate.Instance.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;

            var old_YesNoDialog = m_User.displayYesNo;

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

            ApplyToolButton.Enabled = false;

            CurrentInstanceUpdated();

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

            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);
                }

                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);
            }

            m_PluginController = new PluginController(pluginsPath, true);

            CurrentInstance.RebuildKSPSubDir();

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #19
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 = CheckForCKANUpdate();

            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.game.RebuildSubdirectories(CurrentInstance);

            log.Info("GUI started");
            base.OnLoad(e);
        }
Exemple #20
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 #21
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;

            UpdateModsList();

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

            ApplyToolButton.Enabled = false;

            CurrentInstanceUpdated();

            ModList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

            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).ToCkanModule();
                    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");
            base.OnLoad(e);
        }