Exemple #1
0
        // TODO: We should have a command (probably this one) that shows
        // info about uninstalled modules.
        private static int Show(ShowOptions options)
        {
            if (options.Modname == null)
            {
                // empty argument
                User.WriteLine("show <module> - module name argument missing, perhaps you forgot it?");
                return(Exit.BADOPT);
            }

            RegistryManager registry_manager = RegistryManager.Instance(KSPManager.CurrentInstance);
            InstalledModule module           = registry_manager.registry.InstalledModule(options.Modname);

            if (module == null)
            {
                User.WriteLine("{0} not installed.", options.Modname);
                User.WriteLine("Try `ckan list` to show installed modules");
                return(Exit.BADOPT);
            }

            // TODO: Print *lots* of information out; I should never have to dig through JSON

            User.WriteLine("{0} version {1}", module.Module.name, module.Module.version);

            User.WriteLine("\n== Files ==\n");

            IEnumerable <string> files = module.Files;

            foreach (string file in files)
            {
                User.WriteLine(file);
            }

            return(Exit.OK);
        }
Exemple #2
0
        /// <summary>
        /// 安装所有模块
        /// </summary>
        public void InstallModule(ModuleInfo moduleInfo)
        {
            InstallModuleMigrate(moduleInfo);
            var installedModule = _unitOfWork.Module.Query().FirstOrDefault(x => x.ModuleAssemblyName == moduleInfo.Name);

            if (installedModule == null)
            {
                installedModule = new InstalledModule
                {
                    Active             = false,
                    DateInstalled      = DateTime.UtcNow,
                    Installed          = true,
                    ModuleAssemblyName = moduleInfo.Name,
                    ModuleName         = moduleInfo.Name,
                    ModuleVersion      = moduleInfo.Config.Version,
                };
                _unitOfWork.ExecuteAndCommit(uow =>
                {
                    uow.Module.Add(installedModule);
                });
            }
            else
            {
                installedModule.Active        = true;
                installedModule.DateActivated = DateTime.UtcNow;
                _unitOfWork.ExecuteAndCommit(uow =>
                {
                    return(uow.Module.Update(installedModule));
                });
            }
            RegisterAssemblyInPartManager(moduleInfo);
        }
Exemple #3
0
        /// <summary>
        /// Creates and returns a new <see cref="UploadStorageConfig"/> (or
        /// subclass) for use with the current request.
        /// </summary>
        /// <returns>a new <see cref="UploadStorageConfig"/> or subclass.</returns>
        /// <remarks>If the installed module does not explicitly support
        /// creating <see cref="UploadStorageConfig"/> objects, this method returns
        /// the <see cref="UploadStorageConfig"/> created by the currently selected
        /// <see cref="UploadStorageProvider"/>.</remarks>
        public static UploadStorageConfig CreateUploadStorageConfig()
        {
            UploadStorageConfig storageConfig = InstalledModule.CreateUploadStorageConfig();

            if (storageConfig == null)
            {
                storageConfig = UploadStorage.CreateUploadStorageConfig();
            }
            return(storageConfig);
        }
Exemple #4
0
        private int MarkAuto(MarkAutoOptions opts, bool value, string verb, string descrip)
        {
            if (opts.modules.Count < 1)
            {
                user.RaiseMessage("Usage: ckan mark {0} Mod [Mod2 ...]", verb);
                return(Exit.BADOPT);
            }

            int exitCode = opts.Handle(manager, user);

            if (exitCode != Exit.OK)
            {
                return(exitCode);
            }

            var  ksp      = MainClass.GetGameInstance(manager);
            var  regMgr   = RegistryManager.Instance(ksp);
            bool needSave = false;

            Search.AdjustModulesCase(ksp, opts.modules);
            foreach (string id in opts.modules)
            {
                InstalledModule im = regMgr.registry.InstalledModule(id);
                if (im == null)
                {
                    user.RaiseError("{0} is not installed.", id);
                }
                else if (im.AutoInstalled == value)
                {
                    user.RaiseError("{0} is already marked as {1}.", id, descrip);
                }
                else
                {
                    user.RaiseMessage("Marking {0} as {1}...", id, descrip);
                    try
                    {
                        im.AutoInstalled = value;
                        needSave         = true;
                    }
                    catch (ModuleIsDLCKraken kraken)
                    {
                        user.RaiseMessage($"Can't mark expansion '{kraken.module.name}' as auto-installed.");
                        return(Exit.BADOPT);
                    }
                }
            }
            if (needSave)
            {
                regMgr.Save(false);
                user.RaiseMessage("Changes made!");
            }
            return(Exit.OK);
        }
Exemple #5
0
 /// <summary>
 /// Cancels the upload specified by the given post-back ID.
 /// </summary>
 /// <param name="postBackID">
 /// The post-back ID of the upload to cancel.
 /// </param>
 /// <remarks>The module should attempt to stop the upload if possible.  Calling
 /// <see cref="BindProgressState"/> after calling this method must cause
 /// <see cref="IUploadProgressState.Status"/> to be <see cref="UploadStatus.Cancelled"/>.
 /// </remarks>
 public static void CancelPostBack(string postBackID)
 {
     if (HttpContext.Current != null &&
         HttpContext.Current.Items["NeatUpload_Cancelled_" + postBackID] != null)
     {
         return;
     }
     InstalledModule.CancelPostBack(postBackID);
     if (HttpContext.Current != null)
     {
         HttpContext.Current.Items["NeatUpload_Cancelled_" + postBackID] = true;
     }
 }
Exemple #6
0
        /// <summary>
        /// Converts an <see cref="HttpPostedFile"/> to an <see cref="UploadedFile"/>
        /// that is associated with a particular control.
        /// </summary>
        /// <param name="controlUniqueID">
        /// The UniqueID of the control with which the returned <see cref="UploadedFile"/>
        /// should be associated.  If the <see cref="UploadedFile"/> is added to an
        /// <see cref="UploadedFileCollection"/>, the UniqueID can be used to retrieve
        /// it.
        /// </param>
        /// <param name="file">
        /// The <see cref="HttpPostedFile"/> to convert to an <see cref="UploadedFile"/>.
        /// </param>
        /// <returns>
        /// The <see cref="UploadedFile"/> that corresponds to the <see cref="HttpPostedFile"/>.
        /// </returns>
        /// <remarks>If an <see cref="IUploadModule"/> is not installed or it does not support
        /// conversion, this method will delegate to <see cref="UploadStorage.ConvertToUploadedFile"/>
        /// which will use the currently configured <see cref="UploadStorageProvider"/>
        /// </remarks>
        public static UploadedFile ConvertToUploadedFile(string controlUniqueID, HttpPostedFile file)
        {
            UploadedFile uploadedFile = null;

            if (InstalledModule != null)
            {
                uploadedFile = InstalledModule.ConvertToUploadedFile(controlUniqueID, file);
            }
            if (uploadedFile == null)
            {
                uploadedFile = UploadStorage.ConvertToUploadedFile(controlUniqueID, file);
            }
            return(uploadedFile);
        }
Exemple #7
0
        /// <summary>
        /// Shows information about the mod.
        /// </summary>
        /// <returns>Success status.</returns>
        /// <param name="module">The module to show.</param>
        public int ShowMod(InstalledModule module)
        {
            // Display the basic info.
            int return_value = ShowMod(module.Module);

            // Display InstalledModule specific information.
            ICollection <string> files = module.Files as ICollection <string>;

            if (files == null)
            {
                throw new InvalidCastException();
            }

            user.RaiseMessage("\nShowing {0} installed files:", files.Count);
            foreach (string file in files)
            {
                user.RaiseMessage("- {0}", file);
            }

            return(return_value);
        }
Exemple #8
0
        /// <summary>
        /// Fills in an <see cref="IUploadProgressState"/> object with the progress state for
        /// a given post-back ID and control UniqueID.
        /// </summary>
        /// <param name="postBackID">
        /// The post-back ID for which the progress state should be retrieved.
        /// </param>
        /// <param name="controlUniqueID">
        /// The UniqueID of the control for which the processing state should be retrieved,
        /// or null to retrieve progress state without processing state.
        /// </param>
        /// <param name="progressState">
        /// A <see cref="IUploadProgressState"/> to be filled in with the progress state
        /// for the given post-back ID and control UniqueID.
        /// </param>
        /// <remarks>The progress state is cached for the length of the current request to
        /// ensure consistency across multiple calls during a single request and to reduce
        /// the number of calls made
        /// to the underlying <see cref="IUploadModule"/> implementation since some
        /// implementations might need to access the network to determine the
        /// progress state.</remarks>
        public static void BindProgressState(string postBackID, string controlUniqueID, IUploadProgressState progressState)
        {
            HttpContext ctx = HttpContext.Current;

            if (ctx == null)
            {
                InstalledModule.BindProgressState(postBackID, controlUniqueID, progressState);
                return;
            }

            string cacheKey = String.Format("NeatUpload_cachedProgressState_{0}-{1}", postBackID, controlUniqueID);
            UploadProgressState cachedProgressState = ctx.Items[cacheKey] as Internal.UI.UploadProgressState;

            if (cachedProgressState == null)
            {
                cachedProgressState = new UploadProgressState();
                InstalledModule.BindProgressState(postBackID, controlUniqueID, cachedProgressState);
                ctx.Items[cacheKey] = cachedProgressState;
            }
            UploadProgressState.Copy(cachedProgressState, progressState);
        }
Exemple #9
0
        /// <summary>
        /// Gets a protected string to use as the value of the <see cref="ArmoredCookiesQueryParam"/>
        /// when making the requests in a multi-request upload.
        /// </summary>
        /// <returns>the protected string representing the cookies.</returns>
        /// <remarks>If the installed module does not explicitly support armored
        /// cookies, NeatUpoad will create a <see cref="Hashtable"/>
        /// containing the cookie names/values that ASP.NET uses for session ID and forms
        /// auth, and will pass it to <see cref="ObjectProtector.Protect"/>.
        /// </remarks>
        public static string GetArmoredCookies()
        {
            string armoredCookies = InstalledModule.GetArmoredCookies();

            if (armoredCookies == null)
            {
                HttpCookieCollection cookies     = HttpContext.Current.Request.Cookies;
                Hashtable            authCookies = new Hashtable();
                string[]             cookieNames
                    = new string[] { "ASP.NET_SESSIONID", "ASPSESSION", System.Web.Security.FormsAuthentication.FormsCookieName };
                foreach (string cookieName in cookieNames)
                {
                    HttpCookie cookie = cookies[cookieName];
                    if (cookie != null)
                    {
                        authCookies.Add(cookieName, cookie.Value);
                    }
                }

                armoredCookies = ObjectProtector.Protect(authCookies);
            }
            return(armoredCookies);
        }
Exemple #10
0
        /// <summary>
        /// Shows information about the mod.
        /// </summary>
        /// <returns>Success status.</returns>
        /// <param name="module">The module to show.</param>
        private int ShowMod(InstalledModule module, ShowOptions opts)
        {
            // Display the basic info.
            int return_value = ShowMod(module.Module, opts);

            if (!opts.without_files && !module.Module.IsDLC)
            {
                // Display InstalledModule specific information.
                ICollection <string> files = module.Files as ICollection <string>;
                if (files == null)
                {
                    throw new InvalidCastException();
                }

                user.RaiseMessage("");
                user.RaiseMessage("Showing {0} installed files:", files.Count);
                foreach (string file in files)
                {
                    user.RaiseMessage("  - {0}", file);
                }
            }

            return(return_value);
        }
Exemple #11
0
Fichier : Main.cs Projet : pjf/CKAN
        // TODO: We should have a command (probably this one) that shows
        // info about uninstalled modules.
        private static int Show(ShowOptions options, CKAN.KSP current_instance, IUser user)
        {
            if (options.Modname == null)
            {
                // empty argument
                user.RaiseMessage("show <module> - module name argument missing, perhaps you forgot it?");
                return Exit.BADOPT;
            }

            RegistryManager registry_manager = RegistryManager.Instance(current_instance);
            InstalledModule module = registry_manager.registry.InstalledModule(options.Modname);

            if (module == null)
            {
                user.RaiseMessage("{0} not installed.", options.Modname);
                user.RaiseMessage("Try `ckan list` to show installed modules");
                return Exit.BADOPT;
            }

            // TODO: Print *lots* of information out; I should never have to dig through JSON

            #region Abstract and description
            if (!string.IsNullOrEmpty(module.Module.@abstract))
                user.RaiseMessage("{0}: {1}", module.Module.name, module.Module.@abstract);
            else
                user.RaiseMessage("{0}", module.Module.name);

            if (!string.IsNullOrEmpty(module.Module.description))
                user.RaiseMessage("\n{0}\n", module.Module.description);
            #endregion

            #region General info (author, version...)
            user.RaiseMessage("\nModule info:");
            user.RaiseMessage("- version:\t{0}", module.Module.version);
            user.RaiseMessage("- authors:\t{0}", string.Join(", ", module.Module.author));
            user.RaiseMessage("- status:\t{0}", module.Module.release_status);
            user.RaiseMessage("- license:\t{0}", module.Module.license); 
            #endregion

            #region Relationships
            if (module.Module.depends != null && module.Module.depends.Count > 0)
            {
                user.RaiseMessage("\nDepends:");
                foreach (RelationshipDescriptor dep in module.Module.depends)
                    user.RaiseMessage("- {0}", RelationshipToPrintableString(dep));
            }

            if (module.Module.recommends != null && module.Module.recommends.Count > 0)
            {
                user.RaiseMessage("\nRecommends:");
                foreach (RelationshipDescriptor dep in module.Module.recommends)
                    user.RaiseMessage("- {0}", RelationshipToPrintableString(dep));
            }

            if (module.Module.suggests != null && module.Module.suggests.Count > 0)
            {
                user.RaiseMessage("\nSuggests:");
                foreach (RelationshipDescriptor dep in module.Module.suggests)
                    user.RaiseMessage("- {0}", RelationshipToPrintableString(dep));
            }

            if (module.Module.ProvidesList != null && module.Module.ProvidesList.Count > 0)
            {
                user.RaiseMessage("\nProvides:");
                foreach (string prov in module.Module.ProvidesList)
                    user.RaiseMessage("- {0}", prov);
            } 
            #endregion

            user.RaiseMessage("\nResources:");
            if (module.Module.resources.bugtracker != null) user.RaiseMessage("- bugtracker: {0}", module.Module.resources.bugtracker.ToString());
            if (module.Module.resources.homepage != null) user.RaiseMessage("- homepage: {0}", module.Module.resources.homepage.ToString());
            if (module.Module.resources.kerbalstuff != null) user.RaiseMessage("- kerbalstuff: {0}", module.Module.resources.kerbalstuff.ToString());
            if (module.Module.resources.repository != null) user.RaiseMessage("- repository: {0}", module.Module.resources.repository.ToString());
            

            ICollection<string> files = module.Files as ICollection<string>;
            if (files == null) throw new InvalidCastException();

            user.RaiseMessage("\nShowing {0} installed files:", files.Count);
            foreach (string file in files)
            {
                user.RaiseMessage("- {0}", file);
            }

            return Exit.OK;
        }
Exemple #12
0
        /// <summary>
        /// Shows information about the mod.
        /// </summary>
        /// <returns>Success status.</returns>
        /// <param name="module">The module to show.</param>
        public int ShowMod(InstalledModule module)
        {
            // Display the basic info.
            int return_value = ShowMod(module.Module);

            // Display InstalledModule specific information.
            ICollection<string> files = module.Files as ICollection<string>;
            if (files == null) throw new InvalidCastException();

            user.RaiseMessage("\nShowing {0} installed files:", files.Count);
            foreach (string file in files)
            {
                user.RaiseMessage("- {0}", file);
            }

            return return_value;
        }
Exemple #13
0
        public int RunCommand(CKAN.GameInstance ksp, object raw_options)
        {
            ListOptions options = (ListOptions)raw_options;

            IRegistryQuerier registry = RegistryManager.Instance(ksp).registry;

            ExportFileType?exportFileType = null;

            if (!string.IsNullOrWhiteSpace(options.export))
            {
                exportFileType = GetExportFileType(options.export);

                if (exportFileType == null)
                {
                    user.RaiseError("Unknown export format: {0}", options.export);
                }
            }

            if (!(options.porcelain) && exportFileType == null)
            {
                user.RaiseMessage("\r\nKSP found at {0}\r\n", ksp.GameDir());
                user.RaiseMessage("KSP Version: {0}\r\n", ksp.Version());

                user.RaiseMessage("Installed Modules:\r\n");
            }

            if (exportFileType == null)
            {
                var installed = new SortedDictionary <string, ModuleVersion>(registry.Installed());

                foreach (KeyValuePair <string, ModuleVersion> mod in installed)
                {
                    ModuleVersion current_version = mod.Value;
                    string        modInfo         = string.Format("{0} {1}", mod.Key, mod.Value);
                    string        bullet          = "*";

                    if (current_version is ProvidesModuleVersion)
                    {
                        // Skip virtuals for now.
                        continue;
                    }
                    else if (current_version is UnmanagedModuleVersion)
                    {
                        // Autodetected dll
                        bullet = "A";
                    }
                    else
                    {
                        try
                        {
                            // Check if upgrades are available, and show appropriately.
                            log.DebugFormat("Check if upgrades are available for {0}", mod.Key);
                            CkanModule      latest  = registry.LatestAvailable(mod.Key, ksp.VersionCriteria());
                            CkanModule      current = registry.GetInstalledVersion(mod.Key);
                            InstalledModule inst    = registry.InstalledModule(mod.Key);

                            if (latest == null)
                            {
                                // Not compatible!
                                log.InfoFormat("Latest {0} is not compatible", mod.Key);
                                bullet = "X";
                                if (current == null)
                                {
                                    log.DebugFormat(" {0} installed version not found in registry", mod.Key);
                                }

                                // Check if mod is replaceable
                                if (current.replaced_by != null)
                                {
                                    ModuleReplacement replacement = registry.GetReplacement(mod.Key, ksp.VersionCriteria());
                                    if (replacement != null)
                                    {
                                        // Replaceable!
                                        bullet  = ">";
                                        modInfo = string.Format("{0} > {1} {2}", modInfo, replacement.ReplaceWith.name, replacement.ReplaceWith.version);
                                    }
                                }
                            }
                            else if (latest.version.IsEqualTo(current_version))
                            {
                                // Up to date
                                log.InfoFormat("Latest {0} is {1}", mod.Key, latest.version);
                                bullet = (inst?.AutoInstalled ?? false) ? "+" : "-";
                                // Check if mod is replaceable
                                if (current.replaced_by != null)
                                {
                                    ModuleReplacement replacement = registry.GetReplacement(latest.identifier, ksp.VersionCriteria());
                                    if (replacement != null)
                                    {
                                        // Replaceable!
                                        bullet  = ">";
                                        modInfo = string.Format("{0} > {1} {2}", modInfo, replacement.ReplaceWith.name, replacement.ReplaceWith.version);
                                    }
                                }
                            }
                            else if (latest.version.IsGreaterThan(mod.Value))
                            {
                                // Upgradable
                                bullet = "^";
                            }
                        }
                        catch (ModuleNotFoundKraken)
                        {
                            log.InfoFormat("{0} is installed, but no longer in the registry", mod.Key);
                            bullet = "?";
                        }
                    }

                    user.RaiseMessage("{0} {1}", bullet, modInfo);
                }
            }
            else
            {
                var stream = Console.OpenStandardOutput();
                new Exporter(exportFileType.Value).Export(registry, stream);
                stream.Flush();
            }

            if (!(options.porcelain) && exportFileType == null)
            {
                user.RaiseMessage("\r\nLegend: -: Up to date. +:Auto-installed. X: Incompatible. ^: Upgradable. >: Replaceable\r\n        A: Autodetected. ?: Unknown. *: Broken. ");
                // Broken mods are in a state that CKAN doesn't understand, and therefore can't handle automatically
            }

            return(Exit.OK);
        }
Exemple #14
0
 /// <summary>
 /// Sets the processing state object associated with the current upload and
 /// given control UniqueID.  The processing state object can be retrieved by passing an
 /// <see cref="IUploadProgressState"/> object to <see cref="BindProgressState"/> and
 /// then accessing <see cref="IUploadProgressState.ProcessingState"/>.
 /// </summary>
 /// <param name="controlUniqueID">
 /// The UniqueID of the control that the processing state is associated with.
 /// </param>
 /// <param name="state">
 /// A <see cref="System.Object"/> that represents the processing state.  This must be
 /// serializable.
 /// </param>
 /// <returns>true if the module supports setting processing state, otherwise false.</returns>
 public static bool SetProcessingState(string controlUniqueID, object state)
 {
     return(InstalledModule.SetProcessingState(controlUniqueID, state));
 }
Exemple #15
0
 /// <summary>
 /// Adds a message to the IIS log file.
 /// </summary>
 /// <param name="param">The message to add.</param>
 /// <remarks>If the implementation does not suppport this method, it does nothing.</remarks>
 public static void AppendToLog(string param)
 {
     InstalledModule.AppendToLog(param);
 }
Exemple #16
0
        public int RunCommand(CKAN.KSP ksp, object raw_options)
        {
            ShowOptions options = (ShowOptions)raw_options;

            if (options.Modname == null)
            {
                // empty argument
                user.RaiseMessage("show <module> - module name argument missing, perhaps you forgot it?");
                return(Exit.BADOPT);
            }

            // Check installed modules for an exact match.
            InstalledModule installedModuleToShow = ksp.Registry.InstalledModule(options.Modname);

            if (installedModuleToShow != null)
            {
                // Show the installed module.
                return(ShowMod(installedModuleToShow));
            }

            // Module was not installed, look for an exact match in the available modules,
            // either by "name" (the user-friendly display name) or by identifier
            CfanModule moduleToShow = ksp.Registry
                                      .Available(ksp.Version())
                                      .SingleOrDefault(
                mod => mod.title == options.Modname ||
                mod.identifier == options.Modname
                );

            if (moduleToShow == null)
            {
                // No exact match found. Try to look for a close match for this KSP version.
                user.RaiseMessage("{0} not found or installed.", options.Modname);
                user.RaiseMessage("Looking for close matches in available mods for KSP {0}.", ksp.Version());

                Search            search  = new Search(user);
                List <CfanModule> matches = search.PerformSearch(ksp, options.Modname);

                // Display the results of the search.
                if (matches.Count == 0)
                {
                    // No matches found.
                    user.RaiseMessage("No close matches found.");
                    return(Exit.BADOPT);
                }
                else if (matches.Count == 1)
                {
                    // If there is only 1 match, display it.
                    user.RaiseMessage("Found 1 close match: {0}", matches[0].title);
                    user.RaiseMessage("");

                    moduleToShow = matches[0];
                }
                else
                {
                    // Display the found close matches.
                    string[] strings_matches = new string[matches.Count];

                    for (int i = 0; i < matches.Count; i++)
                    {
                        strings_matches[i] = matches[i].title;
                    }

                    int selection = user.RaiseSelectionDialog("Close matches", strings_matches);

                    if (selection < 0)
                    {
                        return(Exit.BADOPT);
                    }

                    // Mark the selection as the one to show.
                    moduleToShow = matches[selection];
                }
            }

            return(ShowMod(moduleToShow));
        }
Exemple #17
0
        /// <summary>
        /// Initialize the screen
        /// </summary>
        /// <param name="mgr">Game instance manager object containing the current instance</param>
        /// <param name="dbg">True if debug options should be available, false otherwise</param>
        public ModListScreen(GameInstanceManager mgr, bool dbg)
        {
            debug    = dbg;
            manager  = mgr;
            registry = RegistryManager.Instance(manager.CurrentInstance).registry;

            moduleList = new ConsoleListBox <CkanModule>(
                1, 4, -1, -2,
                GetAllMods(),
                new List <ConsoleListBoxColumn <CkanModule> >()
            {
                new ConsoleListBoxColumn <CkanModule>()
                {
                    Header   = "",
                    Width    = 1,
                    Renderer = StatusSymbol
                }, new ConsoleListBoxColumn <CkanModule>()
                {
                    Header   = "Name",
                    Width    = 44,
                    Renderer = m => m.name ?? ""
                }, new ConsoleListBoxColumn <CkanModule>()
                {
                    Header   = "Version",
                    Width    = 10,
                    Renderer = m => ModuleInstaller.StripEpoch(m.version?.ToString() ?? ""),
                    Comparer = (a, b) => a.version.CompareTo(b.version)
                }, new ConsoleListBoxColumn <CkanModule>()
                {
                    Header   = "Max game version",
                    Width    = 17,
                    Renderer = m => registry.LatestCompatibleKSP(m.identifier)?.ToString() ?? "",
                    Comparer = (a, b) => registry.LatestCompatibleKSP(a.identifier).CompareTo(registry.LatestCompatibleKSP(b.identifier))
                }
            },
                1, 0, ListSortDirection.Descending,
                (CkanModule m, string filter) => {
                // Search for author
                if (filter.StartsWith("@"))
                {
                    string authorFilt = filter.Substring(1);
                    if (string.IsNullOrEmpty(authorFilt))
                    {
                        return(true);
                    }
                    else
                    {
                        // Remove special characters from search term
                        authorFilt = CkanModule.nonAlphaNums.Replace(authorFilt, "");
                        return(m.SearchableAuthors.Any((author) => author.IndexOf(authorFilt, StringComparison.CurrentCultureIgnoreCase) == 0));
                    }
                    // Other special search params: installed, updatable, new, conflicting and dependends
                }
                else if (filter.StartsWith("~"))
                {
                    if (filter.Length <= 1)
                    {
                        // Don't blank the list for just "~" by itself
                        return(true);
                    }
                    else
                    {
                        switch (filter.Substring(1, 1))
                        {
                        case "i":
                            return(registry.IsInstalled(m.identifier, false));

                        case "u":
                            return(registry.HasUpdate(m.identifier, manager.CurrentInstance.VersionCriteria()));

                        case "n":
                            // Filter new
                            return(recent.Contains(m.identifier));

                        case "c":
                            if (m.conflicts != null)
                            {
                                string conflictsWith = filter.Substring(2);
                                // Search for mods depending on a given mod
                                foreach (var rel in m.conflicts)
                                {
                                    if (rel.StartsWith(conflictsWith))
                                    {
                                        return(true);
                                    }
                                }
                            }
                            return(false);

                        case "d":
                            if (m.depends != null)
                            {
                                string dependsOn = filter.Substring(2);
                                // Search for mods depending on a given mod
                                foreach (var rel in m.depends)
                                {
                                    if (rel.StartsWith(dependsOn))
                                    {
                                        return(true);
                                    }
                                }
                            }
                            return(false);
                        }
                    }
                    return(false);
                }
                else
                {
                    filter = CkanModule.nonAlphaNums.Replace(filter, "");

                    return(m.SearchableIdentifier.IndexOf(filter, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                           m.SearchableName.IndexOf(filter, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                           m.SearchableAbstract.IndexOf(filter, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                           m.SearchableDescription.IndexOf(filter, StringComparison.CurrentCultureIgnoreCase) >= 0);
                }
            }
                );

            searchBox = new ConsoleField(-searchWidth, 2, -1)
            {
                GhostText = () => Focused() == searchBox
                    ? "<Type to search>"
                    : "<Ctrl+F to search>"
            };
            searchBox.OnChange += (ConsoleField sender, string newValue) => {
                moduleList.FilterString = newValue;
            };

            AddObject(new ConsoleLabel(
                          1, 2, -searchWidth - 2,
                          () => $"{moduleList.VisibleRowCount()} mods"
                          ));
            AddObject(searchBox);
            AddObject(moduleList);

            AddBinding(Keys.CtrlQ, (object sender, ConsoleTheme theme) => false);
            AddBinding(Keys.AltX, (object sender, ConsoleTheme theme) => false);
            AddBinding(Keys.F1, (object sender, ConsoleTheme theme) => Help(theme));
            AddBinding(Keys.AltH, (object sender, ConsoleTheme theme) => Help(theme));
            AddBinding(Keys.F5, (object sender, ConsoleTheme theme) => UpdateRegistry(theme));
            AddBinding(Keys.CtrlR, (object sender, ConsoleTheme theme) => UpdateRegistry(theme));
            AddBinding(Keys.CtrlU, (object sender, ConsoleTheme theme) => UpgradeAll(theme));

            // Now a bunch of convenience shortcuts so you don't get stuck in the search box
            searchBox.AddBinding(Keys.PageUp, (object sender, ConsoleTheme theme) => {
                SetFocus(moduleList);
                return(true);
            });
            searchBox.AddBinding(Keys.PageDown, (object sender, ConsoleTheme theme) => {
                SetFocus(moduleList);
                return(true);
            });
            searchBox.AddBinding(Keys.Enter, (object sender, ConsoleTheme theme) => {
                SetFocus(moduleList);
                return(true);
            });

            moduleList.AddBinding(Keys.CtrlF, (object sender, ConsoleTheme theme) => {
                SetFocus(searchBox);
                return(true);
            });
            moduleList.AddBinding(Keys.Escape, (object sender, ConsoleTheme theme) => {
                searchBox.Clear();
                return(true);
            });

            moduleList.AddTip("Enter", "Details",
                              () => moduleList.Selection != null
                              );
            moduleList.AddBinding(Keys.Enter, (object sender, ConsoleTheme theme) => {
                if (moduleList.Selection != null)
                {
                    LaunchSubScreen(theme, new ModInfoScreen(manager, plan, moduleList.Selection, debug));
                }
                return(true);
            });

            // Conditionally show only one of these based on selected mod status

            moduleList.AddTip("+", "Install",
                              () => moduleList.Selection != null && !moduleList.Selection.IsDLC &&
                              !registry.IsInstalled(moduleList.Selection.identifier, false)
                              );
            moduleList.AddTip("+", "Upgrade",
                              () => moduleList.Selection != null && !moduleList.Selection.IsDLC &&
                              registry.HasUpdate(moduleList.Selection.identifier, manager.CurrentInstance.VersionCriteria())
                              );
            moduleList.AddTip("+", "Replace",
                              () => moduleList.Selection != null &&
                              registry.GetReplacement(moduleList.Selection.identifier, manager.CurrentInstance.VersionCriteria()) != null
                              );
            moduleList.AddBinding(Keys.Plus, (object sender, ConsoleTheme theme) => {
                if (moduleList.Selection != null && !moduleList.Selection.IsDLC)
                {
                    if (!registry.IsInstalled(moduleList.Selection.identifier, false))
                    {
                        plan.ToggleInstall(moduleList.Selection);
                    }
                    else if (registry.IsInstalled(moduleList.Selection.identifier, false) &&
                             registry.HasUpdate(moduleList.Selection.identifier, manager.CurrentInstance.VersionCriteria()))
                    {
                        plan.ToggleUpgrade(moduleList.Selection);
                    }
                    else if (registry.GetReplacement(moduleList.Selection.identifier, manager.CurrentInstance.VersionCriteria()) != null)
                    {
                        plan.ToggleReplace(moduleList.Selection.identifier);
                    }
                }
                return(true);
            });

            moduleList.AddTip("-", "Remove",
                              () => moduleList.Selection != null && !moduleList.Selection.IsDLC &&
                              registry.IsInstalled(moduleList.Selection.identifier, false) &&
                              !registry.IsAutodetected(moduleList.Selection.identifier)
                              );
            moduleList.AddBinding(Keys.Minus, (object sender, ConsoleTheme theme) => {
                if (moduleList.Selection != null && !moduleList.Selection.IsDLC &&
                    registry.IsInstalled(moduleList.Selection.identifier, false) &&
                    !registry.IsAutodetected(moduleList.Selection.identifier))
                {
                    plan.ToggleRemove(moduleList.Selection);
                }
                return(true);
            });

            moduleList.AddTip("F8", "Mark auto-installed",
                              () => moduleList.Selection != null && !moduleList.Selection.IsDLC &&
                              (!registry.InstalledModule(moduleList.Selection.identifier)?.AutoInstalled ?? false)
                              );
            moduleList.AddTip("F8", "Mark user-selected",
                              () => moduleList.Selection != null && !moduleList.Selection.IsDLC &&
                              (registry.InstalledModule(moduleList.Selection.identifier)?.AutoInstalled ?? false)
                              );
            moduleList.AddBinding(Keys.F8, (object sender, ConsoleTheme theme) => {
                InstalledModule im = registry.InstalledModule(moduleList.Selection.identifier);
                if (im != null && !moduleList.Selection.IsDLC)
                {
                    im.AutoInstalled = !im.AutoInstalled;
                    RegistryManager.Instance(manager.CurrentInstance).Save(false);
                }
                return(true);
            });

            AddTip("F9", "Apply changes", plan.NonEmpty);
            AddBinding(Keys.F9, (object sender, ConsoleTheme theme) => {
                ApplyChanges(theme);
                return(true);
            });

            // Show total download size of all installed mods
            AddObject(new ConsoleLabel(
                          1, -1, searchWidth,
                          () => $"{CkanModule.FmtSize(totalInstalledDownloadSize())} installed",
                          null,
                          th => th.DimLabelFg
                          ));

            AddObject(new ConsoleLabel(
                          -searchWidth, -1, -2,
                          () => {
                int days = daysSinceUpdated(registryFilePath());
                return(days < 1 ? ""
                        :  days == 1 ? $"Updated at least {days} day ago"
                        :              $"Updated at least {days} days ago");
            },
                          null,
                          (ConsoleTheme th) => {
                int daysSince = daysSinceUpdated(registryFilePath());
                if (daysSince < daysTillStale)
                {
                    return(th.RegistryUpToDate);
                }
                else if (daysSince < daystillVeryStale)
                {
                    return(th.RegistryStale);
                }
                else
                {
                    return(th.RegistryVeryStale);
                }
            }
                          ));

            List <ConsoleMenuOption> opts = new List <ConsoleMenuOption>()
            {
                new ConsoleMenuOption("Sort...", "",
                                      "Change the sorting of the list of mods",
                                      true, null, null, moduleList.SortMenu()),
                null,
                new ConsoleMenuOption("Refresh mod list", "F5, Ctrl+R",
                                      "Refresh the list of mods",
                                      true, UpdateRegistry),
                new ConsoleMenuOption("Upgrade all", "Ctrl+U",
                                      "Mark all available updates for installation",
                                      true, UpgradeAll, null, null, HasAnyUpgradeable()),
                new ConsoleMenuOption("Audit recommendations", "",
                                      "List mods suggested and recommended by installed mods",
                                      true, ViewSuggestions),
                new ConsoleMenuOption("Import downloads...", "",
                                      "Select manually downloaded mods to import into CKAN",
                                      true, ImportDownloads),
                new ConsoleMenuOption("Export installed...", "",
                                      "Save your mod list",
                                      true, ExportInstalled),
                null,
                new ConsoleMenuOption("Select game instance...", "",
                                      "Switch to a different game instance",
                                      true, SelectInstall),
                new ConsoleMenuOption("Authentication tokens...", "",
                                      "Edit authentication tokens sent to download servers",
                                      true, EditAuthTokens),
                null,
                new ConsoleMenuOption("Help", helpKey,
                                      "Tips & tricks",
                                      true, Help),
                null,
                new ConsoleMenuOption("Quit", "Ctrl+Q",
                                      "Exit to DOS",
                                      true, (ConsoleTheme th) => false)
            };

            if (debug)
            {
                opts.Add(null);
                opts.Add(new ConsoleMenuOption("DEBUG: Capture key...", "",
                                               "Print details of how your system reports a keystroke for debugging",
                                               true, CaptureKey));
            }
            mainMenu = new ConsolePopupMenu(opts);
        }
Exemple #18
0
        public int RunCommand(CKAN.KSP ksp, object raw_options)
        {
            ShowOptions options = (ShowOptions)raw_options;

            if (options.Modname == null)
            {
                // empty argument
                user.RaiseMessage("show <module> - module name argument missing, perhaps you forgot it?");
                return(Exit.BADOPT);
            }

            // Look for the module in the registry.
            List <CkanModule> modules = ksp.Registry.Available(ksp.Version());
            CkanModule        module  = null;

            foreach (CkanModule mod in modules)
            {
                if (mod.name == options.Modname)
                {
                    module = mod;
                }
            }

            if (module == null)
            {
                // No exact match found. Try to look for a close match.
                user.RaiseMessage("{0} not found.", options.Modname);
                user.RaiseMessage("Looking for close matches.");

                Search            search  = new Search(user);
                List <CkanModule> matches = search.PerformSearch(ksp, options.Modname);

                if (matches.Count == 0)
                {
                    user.RaiseMessage("No close matches found.");
                    return(Exit.BADOPT);
                }
                else if (matches.Count == 1)
                {
                    // If there is only 1 match, display it.
                    user.RaiseMessage("Found 1 close match: {0}", matches[0].name);
                    user.RaiseMessage("");

                    module = matches[0];
                }
                else
                {
                    // Display the found close matches.
                    string[] strings_matches = new string[matches.Count];

                    for (int i = 0; i < matches.Count; i++)
                    {
                        strings_matches[i] = matches[i].name;
                    }

                    string message = "Close matches";

                    int selection = user.RaiseSelectionDialog(message, strings_matches);

                    if (selection < 0)
                    {
                        return(Exit.BADOPT);
                    }

                    // Mark the selection as the one to show.
                    module = matches[selection];
                }
            }

            // Is the selected module already installed?
            InstalledModule installed_module = ksp.Registry.InstalledModule(module.identifier);

            if (installed_module != null)
            {
                ShowMod(installed_module);
            }
            else
            {
                ShowMod(module);
            }

            return(Exit.OK);
        }