Exemplo n.º 1
0
		public FileInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			//[assembly: InstallFile(RepositoryPath = "/Root/Test/asdf.css", ResourcePath = "/res.asdf.css")]
			var repositoryPath = GetParameterValue<string>("RepositoryPath");
			var contentName = ContentManager.Path.GetFileName(repositoryPath);
			var containerPath = ContentManager.Path.GetParentPath(repositoryPath);

			ContainerPath = containerPath;
			ContentName = contentName;
			RawAttachments = "Binary:" + ResourceName;
		}
Exemplo n.º 2
0
        /// <summary>Get a randomised basic manifest.</summary>
        /// <param name="manifest">The mod manifest.</param>
        /// <param name="allowStatusChange">Whether the code being tested is allowed to change the mod status.</param>
        private Mock <IModMetadata> GetMetadata(IManifest manifest, bool allowStatusChange = false)
        {
            Mock <IModMetadata> mod = new Mock <IModMetadata>(MockBehavior.Strict);

            mod.Setup(p => p.DataRecord).Returns(() => null);
            mod.Setup(p => p.Status).Returns(ModMetadataStatus.Found);
            mod.Setup(p => p.DisplayName).Returns(manifest.UniqueID);
            mod.Setup(p => p.Manifest).Returns(manifest);
            if (allowStatusChange)
            {
                mod
                .Setup(p => p.SetStatus(It.IsAny <ModMetadataStatus>(), It.IsAny <string>()))
                .Callback <ModMetadataStatus, string>((status, message) => Console.WriteLine($"<{manifest.UniqueID} changed status: [{status}] {message}"))
                .Returns(mod.Object);
            }
            return(mod);
        }
Exemplo n.º 3
0
        /*********
        ** Private methods
        *********/
        /// <summary>Add a simple option without clamped values.</summary>
        /// <typeparam name="T">The option value type.</typeparam>
        /// <param name="mod">The mod's manifest.</param>
        /// <param name="name">The label text to show in the form.</param>
        /// <param name="tooltip">The tooltip text shown when the cursor hovers on the field, or <c>null</c> to disable the tooltip.</param>
        /// <param name="getValue">Get the current value from the mod config.</param>
        /// <param name="setValue">Set a new value in the mod config.</param>
        /// <param name="fieldId">The unique field ID used when raising field-changed events, or <c>null</c> to generate a random one.</param>
        private void AddSimpleOption <T>(IManifest mod, Func <string> name, Func <string> tooltip, Func <T> getValue, Action <T> setValue, string fieldId)
        {
            this.AssertNotNull(mod, nameof(mod));
            this.AssertNotNull(name, nameof(name));
            this.AssertNotNull(getValue, nameof(getValue));
            this.AssertNotNull(setValue, nameof(setValue));

            ModConfig modConfig = this.ConfigManager.Get(mod, assert: true);

            Type[] valid = new[] { typeof(bool), typeof(int), typeof(float), typeof(string), typeof(SButton), typeof(KeybindList) };
            if (!valid.Contains(typeof(T)))
            {
                throw new ArgumentException("Invalid config option type.");
            }

            modConfig.AddOption(new SimpleModOption <T>(fieldId, name, tooltip, modConfig, getValue, setValue));
        }
Exemplo n.º 4
0
        public static void Initialize(IMonitor m, IManifest mf)
        {
            monitor  = m;
            manifest = mf;
            rand     = new Random();

            NoData = new ConfigDialog
            {
                Call       = "Hi, @!",
                Response   = "O hey, @!",
                Callers    = "",
                Responders = "",
                When       = new Dictionary <string, string>()
            };

            Data = new List <ConfigDialog>();
        }
Exemplo n.º 5
0
        internal FishingApi(
            IModHelper helper,
            IMonitor monitor,
            IManifest manifest,
            FishConfig fishConfig,
            TreasureConfig treasureConfig,
            Func <IEnumerable <IFishingContentSource> > contentSourcesFactory,
            EntryManagerFactory <FishEntry, FishAvailabilityInfo> fishEntryManagerFactory,
            EntryManagerFactory <TrashEntry, AvailabilityInfo> trashEntryManagerFactory,
            EntryManagerFactory <TreasureEntry, AvailabilityInfo> treasureEntryManagerFactory,
            FishingEffectManagerFactory fishingEffectManagerFactory,
            Lazy <IOptional <IEmpApi> > empApi
            )
        {
            this.helper         = helper ?? throw new ArgumentNullException(nameof(helper));
            this.monitor        = monitor ?? throw new ArgumentNullException(nameof(monitor));
            this.manifest       = manifest ?? throw new ArgumentNullException(nameof(manifest));
            this.fishConfig     = fishConfig ?? throw new ArgumentNullException(nameof(fishConfig));
            this.treasureConfig =
                treasureConfig ?? throw new ArgumentNullException(nameof(treasureConfig));
            this.contentSourcesFactory = contentSourcesFactory
                                         ?? throw new ArgumentNullException(nameof(contentSourcesFactory));
            this.fishEntryManagerFactory = fishEntryManagerFactory
                                           ?? throw new ArgumentNullException(nameof(fishEntryManagerFactory));
            this.trashEntryManagerFactory = trashEntryManagerFactory
                                            ?? throw new ArgumentNullException(nameof(trashEntryManagerFactory));
            this.treasureEntryManagerFactory = treasureEntryManagerFactory
                                               ?? throw new ArgumentNullException(nameof(treasureEntryManagerFactory));
            this.fishingEffectManagerFactory = fishingEffectManagerFactory
                                               ?? throw new ArgumentNullException(nameof(fishingEffectManagerFactory));
            this.empApi = empApi ?? throw new ArgumentNullException(nameof(empApi));

            this.fishTraits            = new();
            this.fishManagers          = new();
            this.trashManagers         = new();
            this.treasureManagers      = new();
            this.fishingEffectManagers = new();
            this.stateKey = $"{manifest.UniqueID}/fishing-state";

            this.CreatedDefaultFishingInfo += this.ApplyMapOverrides;
            this.CreatedDefaultFishingInfo += this.ApplyEmpOverrides;
            this.CreatedDefaultFishingInfo += FishingApi.ApplyMagicBait;
            this.PreparedFishChances       += FishingApi.ApplyCuriosityLure;

            this.reloadRequested = true;
        }
        public ProgressionManager(IMonitor monitor, IModHelper helper, IManifest modManifest)
        {
            Instance ??= this;

            if (Instance != this)
            {
                monitor.Log($"Another instance of {nameof(ProgressionManager)} is created", LogLevel.Warn);
                return;
            }

            _monitor     = monitor;
            _helper      = helper;
            _modManifest = modManifest;

            _helper.Events.GameLoop.DayEnding             += OnSave;
            _helper.Events.GameLoop.DayStarted            += OnLoad;
            _helper.Events.Multiplayer.ModMessageReceived += OnMessageReceived;
        }
Exemplo n.º 7
0
        /// <summary>Add a numeric option with optional clamping.</summary>
        /// <typeparam name="T">The option value type.</typeparam>
        /// <param name="mod">The mod's manifest.</param>
        /// <param name="name">The label text to show in the form.</param>
        /// <param name="tooltip">The tooltip text shown when the cursor hovers on the field, or <c>null</c> to disable the tooltip.</param>
        /// <param name="getValue">Get the current value from the mod config.</param>
        /// <param name="setValue">Set a new value in the mod config.</param>
        /// <param name="min">The minimum allowed value, or <c>null</c> to allow any.</param>
        /// <param name="max">The maximum allowed value, or <c>null</c> to allow any.</param>
        /// <param name="interval">The interval of values that can be selected.</param>
        /// <param name="formatValue">Get the display text to show for a value, or <c>null</c> to show the number as-is.</param>
        /// <param name="fieldId">The unique field ID used when raising field-changed events, or <c>null</c> to generate a random one.</param>
        private void AddNumericOption <T>(IManifest mod, Func <string> name, Func <string> tooltip, Func <T> getValue, Action <T> setValue, T?min, T?max, T?interval, Func <T, string> formatValue, string fieldId)
            where T : struct
        {
            this.AssertNotNull(mod, nameof(mod));
            this.AssertNotNull(name, nameof(name));
            this.AssertNotNull(getValue, nameof(getValue));
            this.AssertNotNull(setValue, nameof(setValue));

            ModConfig modConfig = this.ConfigManager.Get(mod, assert: true);

            Type[] valid = { typeof(int), typeof(float) };
            if (!valid.Contains(typeof(T)))
            {
                throw new ArgumentException("Invalid config option type.");
            }

            modConfig.AddOption(new NumericModOption <T>(fieldId: fieldId, name: name, tooltip: tooltip, mod: modConfig, getValue: getValue, setValue: setValue, min: min, max: max, interval: interval, formatValue: formatValue));
        }
Exemplo n.º 8
0
 internal void AddToGMCM(IGenericModConfigMenuApi api, IManifest mod)
 {
     api.AddComplexOption(
         mod: mod,
         name: Name,
         tooltip: Tooltip,
         draw: (b, position) => Draw(b, position),
         height: () => GetHeight(),
         beforeMenuOpened: () =>
     {
         LastMouseLeftPressed = null;
         LastHoverPosition    = null;
     },
         beforeMenuClosed: () => { },
         afterReset: () => { },
         beforeSave: () => { }
         );
 }
Exemplo n.º 9
0
        /// <summary>The mod entry point, called after the mod is first loaded.</summary>
        /// <param name="helper">Provides simplified APIs for writing mods.</param>
        public override void Entry(IModHelper helper)
        {
            Manifest    = this.ModManifest;
            this.Config = helper.ReadConfig <Config>();

            if (Constants.TargetPlatform == GamePlatform.Android)
            {
                this.Monitor.Log("Android support is an experimental feature, may cause some problems. Before you report a bug please content me on my discord https://discord.gg/wnEDqKF Thank you.", LogLevel.Alert);
            }

            this.RegisterAssetEditors(helper);
            this.ContentPackManager = new ContentPackManager(this.Monitor, this.Config.EnableDebug);
            this.ContentLoader      = new ContentLoader(helper, this.ContentPackManager, this.Monitor);
            this.Patcher            = new GamePatcher(this.ModManifest.UniqueID, this.Monitor, this.Config.EnableDebug);
            this.RegisterEvents(helper.Events);
            this.ContentPackManager.LoadContentPacks(helper.ContentPacks.GetOwned());
            Commander.Register(this);
        }
Exemplo n.º 10
0
        public void StartNewPage(IManifest mod, string pageName)
        {
            if (!Mod.instance.configs.ContainsKey(mod))
            {
                throw new ArgumentException("Mod not registered");
            }

            var modConfig = Mod.instance.configs[mod];

            if (modConfig.Options.ContainsKey(pageName))
            {
                modConfig.ActiveRegisteringPage = modConfig.Options[pageName];
            }
            else
            {
                modConfig.Options.Add(pageName, modConfig.ActiveRegisteringPage = new ModConfig.ModPage(pageName));
            }
        }
        public static void AddMultiSelectTextOption <T>(
            this IGenericModConfigMenuApi api,
            IManifest mod,
            Func <T, bool> getValue,
            Action <T> addValue,
            Action <T> removeValue,
            Func <string> name,
            Func <float, int> columns,
            T[] allowedValues,
            Func <string>?tooltip = null,
            Func <T, string>?formatAllowedValue = null,
            Action?afterValuesUpdated           = null
            )
        {
            var option = new MultiSelectTextOption <T>(getValue, addValue, removeValue, name, columns, allowedValues, tooltip, formatAllowedValue, afterValuesUpdated);

            option.AddToGMCM(api, mod);
        }
Exemplo n.º 12
0
 public ModOverrideEntry(
     IManifest mod,
     Action <string, string, string?, Action <string?> >?title,
     Action <string, string, string, Action <string> >?text,
     Action <string, string, IReadOnlyList <Item>, Action <IEnumerable <Item> > >?items,
     Action <string, string, string?, Action <string?> >?recipe,
     Action <string, string, int, Action <int> >?background,
     Action <string, string, int?, Action <int?> >?textColor
     )
 {
     this.Mod        = mod;
     this.Title      = title;
     this.Text       = text;
     this.Items      = items;
     this.Recipe     = recipe;
     this.Background = background;
     this.TextColor  = textColor;
 }
Exemplo n.º 13
0
        /*********
        ** Private methods
        *********/
        /// <summary>Get whether a manifest field has a meaningful value for the purposes of enforcing <see cref="IsDefault"/>.</summary>
        /// <param name="manifest">The mod manifest.</param>
        /// <param name="key">The field key matching <see cref="ModDataFieldKey"/>.</param>
        private bool HasFieldValue(IManifest manifest, ModDataFieldKey key)
        {
            switch (key)
            {
            // update key
            case ModDataFieldKey.UpdateKey:
                return(manifest.UpdateKeys.Any(p => !string.IsNullOrWhiteSpace(p)));

            // non-manifest fields
            case ModDataFieldKey.StatusReasonPhrase:
            case ModDataFieldKey.StatusReasonDetails:
            case ModDataFieldKey.Status:
                return(false);

            default:
                return(false);
            }
        }
Exemplo n.º 14
0
        public void AddCrop(
            IManifest manifest,

            string id,

            Item item,
            string name,

            int regrow,
            bool isGiantCrop,
            bool isPaddyCrop,
            bool isTrellisCrop,

            Item[] seeds,

            WorldDate start,
            WorldDate end,

            Tuple <Texture2D, Rectangle?, Color?, Texture2D, Rectangle?, Color?> sprite,
            Tuple <Texture2D, Rectangle?, Color?, Texture2D, Rectangle?, Color?> giantSprite,

            IReadOnlyCollection <int> phases,
            IReadOnlyCollection <Tuple <Texture2D, Rectangle?, Color?, Texture2D, Rectangle?, Color?> > phaseSprites
            )
        {
            var provider = Mod.Crops.GetModProvider(manifest);

            provider !.AddCrop(
                id: id,
                item: item,
                name: name,
                sprite: sprite == null ? (item == null ? null : SpriteHelper.GetSprite(item)) : HydrateSprite(sprite),
                isTrellisCrop: isTrellisCrop,
                isGiantCrop: isGiantCrop,
                giantSprite: HydrateSprite(giantSprite),
                seeds: seeds,
                isPaddyCrop: isPaddyCrop,
                phases: phases,
                phaseSprites: HydrateSprites(phaseSprites),
                regrow: regrow,
                start: start,
                end: end
                );
        }
        public IManifestEntry ProcessManifestEntry(
            IManifest manifest,
            ObjectType entryType,
            string path,
            dynamic jsonObject,
            IReferenceFinderService referenceFinderService)
        {
            var manifestEntry = new ManifestEntry(manifest, entryType, path, jsonObject, referenceFinderService);

            var di = new DirectoryInfo(Path.Combine(manifest.Mod.SourceDirectoryPath, manifestEntry.Path));

            try
            {
                var files = di.EnumerateFiles();

                if (entryType == ObjectType.CCDefaults && files.Count() > 1)
                {
                    throw new InvalidProgramException(
                              $"Encountered more than ONE CC settings files for a CC Manifest Entry at [{di.FullName}]");
                }

                files.ToList().ForEach(
                    file =>
                {
                    dynamic ccSettingsData = JsonConvert.DeserializeObject(File.ReadAllText(file.FullName));
                    foreach (var ccSetting in ccSettingsData.Settings)
                    {
                        var objectDefinition = ObjectDefinitionFactory.ObjectDefinitionFactorySingleton.Get(
                            entryType,
                            null,
                            ccSetting,
                            file.FullName,
                            referenceFinderService);
                        manifestEntry.Objects.Add(objectDefinition);
                    }
                });
            }
            catch (Exception ex)
            {
                this.logger.Error($"An exception occurred trying to process manifestEntry.", ex);
            }

            return(manifestEntry);
        }
Exemplo n.º 16
0
 void SetManifestInfoInternal(IManifest manifest)
 {
     lblProductId.Text       = "Product ID: " + manifest.ProductId;
     lblTitle.Text           = "Title: " + manifest.Title;
     lblVersion.Text         = "Version: " + manifest.Version;
     lblPlatformVersion.Text = "Platform version: " + Util.GetEnumDescription(manifest.PlatformVersion);
     lblAuthor.Text          = "Author: " + manifest.Author;
     tbxCapabilities.Clear();
     tbxRequirements.Clear();
     tbxScreenResolutions.Clear();
     tbxFileTypes.Clear();
     tbxURIs.Clear();
     foreach (var capability in manifest.Capabilities)
     {
         tbxCapabilities.AppendText(capability.Id + ": " + capability.Description + "\r\n");
     }
     foreach (var requirement in manifest.Requirements)
     {
         tbxRequirements.AppendText(string.Format("{0}: {1}\r\n", requirement.Id, requirement.Description));
     }
     foreach (var screenResolution in manifest.ScreenResolutions)
     {
         tbxScreenResolutions.AppendText(string.Format("{0}: {1}\r\n", screenResolution.ToString(), Util.GetEnumDescription(screenResolution)));
     }
     if (manifest.PlatformVersion != PlatformVersion.Version71)
     {
         ShowExcessTabs();
         foreach (var fileType in manifest.SupportedFileTypes)
         {
             tbxFileTypes.AppendText(fileType + "\r\n");
         }
         foreach (var uri in manifest.AssociatedURIs)
         {
             tbxURIs.AppendText(uri + "\r\n");
         }
     }
     else
     {
         var requirement = Requirement.GetRequirement("ID_REQ_MEMORY_90");
         tbxRequirements.AppendText(string.Format("{0}: {1}\r\n", requirement.Id, requirement.Description));
         HideExcessTabs();
     }
 }
Exemplo n.º 17
0
        /// <summary>Get the dependencies declared in a manifest.</summary>
        /// <param name="manifest">The mod manifest.</param>
        /// <param name="loadedMods">The loaded mods.</param>
        private IEnumerable <ModDependency> GetDependenciesFrom(IManifest manifest, IModMetadata[] loadedMods)
        {
            IModMetadata FindMod(string id) => loadedMods.FirstOrDefault(m => m.HasID(id));

            // yield dependencies
            if (manifest.Dependencies != null)
            {
                foreach (var entry in manifest.Dependencies)
                {
                    yield return(new ModDependency(entry.UniqueID, entry.MinimumVersion, FindMod(entry.UniqueID), entry.IsRequired));
                }
            }

            // yield content pack parent
            if (manifest.ContentPackFor != null)
            {
                yield return(new ModDependency(manifest.ContentPackFor.UniqueID, manifest.ContentPackFor.MinimumVersion, FindMod(manifest.ContentPackFor.UniqueID), isRequired: true));
            }
        }
        public IManifestEntry ProcessManifestEntry(
            IManifest manifest,
            ObjectType entryType,
            string path,
            dynamic jsonObject,
            IReferenceFinderService referenceFinderService)
        {
            var manifestEntry = new ManifestEntry(manifest, entryType, path, jsonObject, referenceFinderService);

            var objectDefinition = ObjectDefinitionFactory.ObjectDefinitionFactorySingleton.Get(
                entryType,
                new ObjectDefinitionDescription(null, null, null, null, (JObject)jsonObject),
                (JObject)jsonObject,
                path,
                referenceFinderService);

            manifestEntry.Objects.Add(objectDefinition);
            return(manifestEntry);
        }
Exemplo n.º 19
0
        /// <summary>The mod entry point, called after the mod is first loaded.</summary>
        /// <param name="helper">Provides simplified APIs for writing mods.</param>
        public override void Entry(IModHelper helper)
        {
            ModHelper  = this.Helper;
            ModMonitor = this.Monitor;
            Manifest   = this.ModManifest;

            helper.Events.GameLoop.SaveLoaded   += this.OnSaveLoaded;
            helper.Events.GameLoop.Saving       += this.OnSaving;
            helper.Events.GameLoop.Saved        += this.OnSaved;
            helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked;
            npcTracker = new NpcTracker();
            assetPool  = new AssetPool();
            var assetManager = new AssetManager();

            assetPool.addAssetManager(new KeyValuePair <string, AssetManager>("testNPC", assetManager));
            this.initializeExamples();
            this.initializeAssetPool();
            assetPool.loadAllAssets();
        }
        /// <summary>Register a token which defines methods by duck-typing convention.</summary>
        /// <param name="mod">The manifest of the mod defining the token.</param>
        /// <param name="name">The token name.</param>
        /// <param name="provider">The token value provider.</param>
        private void RegisterValueProviderByConvention(IManifest mod, string name, object provider)
        {
            // validate token
            if (provider == null)
            {
                this.Monitor.Log($"Rejected token '{name}' added by {mod.Name} because the token is null.", LogLevel.Error);
                return;
            }

            // get a strongly-typed wrapper
            if (!ConventionWrapper.TryCreate(provider, this.Reflection, out ConventionWrapper wrapper, out string error))
            {
                this.Monitor.Log($"Rejected token '{name}' added by {mod.Name} because it could not be mapped: {error}", LogLevel.Error);
                return;
            }

            // register
            this.RegisterValueProvider(mod, new ConventionValueProvider(name, wrapper));
        }
Exemplo n.º 21
0
        private void CreateConfigMenu(IManifest manifest)
        {
            GenericModConfigMenuApi api = Helper.ModRegistry.GetApi <GenericModConfigMenuApi>("spacechase0.GenericModConfigMenu");

            if (api != null)
            {
                api.RegisterModConfig(manifest, () => DataLoader.ModConfig = new ModConfig(), () => Helper.WriteConfig(DataLoader.ModConfig));

                api.RegisterSimpleOption(manifest, "Disable Letter", "You won't receive the letter about how the Crystalarium can clone Prismatic Shards and can be tuned to clone more stuff. Needs to restart.", () => DataLoader.ModConfig.DisableLetter, (bool val) => DataLoader.ModConfig.DisableLetter = val);

                api.RegisterLabel(manifest, "Get Object Back Properties:", "Properties that affect what happen to the object you place into cloners.");

                api.RegisterSimpleOption(manifest, "On Change", "Get the object back when changing the object being cloned or removing the cloner from the ground.", () => DataLoader.ModConfig.GetObjectBackOnChange, (bool val) => DataLoader.ModConfig.GetObjectBackOnChange = val);

                api.RegisterSimpleOption(manifest, "Immediately", "Get the object back immediately after placing it into the cloner. If set, the mod will ignore the 'On Change' property.", () => DataLoader.ModConfig.GetObjectBackImmediately, (bool val) => DataLoader.ModConfig.GetObjectBackImmediately = val);

                api.RegisterSimpleOption(manifest, "Override Cloner Config", "If checked the mod will use these 'get object back properties' instead of the ones defined for each cloner.", () => DataLoader.ModConfig.OverrideContentPackGetObjectProperties, (bool val) => DataLoader.ModConfig.OverrideContentPackGetObjectProperties = val);
            }
        }
Exemplo n.º 22
0
        public void AddCrop(
            IManifest manifest,

            string id,

            Item item,
            string name,

            int regrow,
            bool isGiantCrop,
            bool isPaddyCrop,
            bool isTrellisCrop,

            WorldDate start,
            WorldDate end,

            SpriteInfo sprite,
            SpriteInfo giantSprite,

            IReadOnlyCollection <int> phases,
            IReadOnlyCollection <SpriteInfo> phaseSprites
            )
        {
            var provider = Mod.Crops.GetModProvider(manifest);

            provider !.AddCrop(
                id: id,
                item: item,
                name: name,
                sprite: sprite,
                isTrellisCrop: isTrellisCrop,
                isGiantCrop: isGiantCrop,
                giantSprite: giantSprite,
                seeds: null,
                isPaddyCrop: isPaddyCrop,
                phases: phases,
                phaseSprites: phaseSprites,
                regrow: regrow,
                start: start,
                end: end
                );
        }
Exemplo n.º 23
0
        /// <summary>Get a parsed representation of the <see cref="ModDataRecord.Fields"/> which match a given manifest.</summary>
        /// <param name="manifest">The manifest to match.</param>
        public ParsedModDataRecord GetParsed(IManifest manifest)
        {
            // get raw record
            if (!this.TryGetRaw(manifest, out string displayName, out ModDataRecord record))
            {
                return(null);
            }

            // parse fields
            ParsedModDataRecord parsed = new ParsedModDataRecord {
                DisplayName = displayName, DataRecord = record
            };

            foreach (ModDataField field in record.GetFields().Where(field => field.IsMatch(manifest)))
            {
                switch (field.Key)
                {
                // update key
                case ModDataFieldKey.UpdateKey:
                    parsed.UpdateKey = field.Value;
                    break;

                // alternative URL
                case ModDataFieldKey.AlternativeUrl:
                    parsed.AlternativeUrl = field.Value;
                    break;

                // status
                case ModDataFieldKey.Status:
                    parsed.Status             = (ModStatus)Enum.Parse(typeof(ModStatus), field.Value, ignoreCase: true);
                    parsed.StatusUpperVersion = field.UpperVersion;
                    break;

                // status reason phrase
                case ModDataFieldKey.StatusReasonPhrase:
                    parsed.StatusReasonPhrase = field.Value;
                    break;
                }
            }

            return(parsed);
        }
Exemplo n.º 24
0
        /// <summary>Get whether the manifest lists a given mod ID as a dependency.</summary>
        /// <param name="manifest">The manifest.</param>
        /// <param name="modID">The mod ID.</param>
        /// <param name="canBeOptional">Whether the dependency can be optional.</param>
        public static bool HasDependency(this IManifest manifest, string modID, bool canBeOptional = true)
        {
            if (manifest == null)
            {
                return(false);
            }

            // check content pack for
            if (manifest.ContentPackFor?.UniqueID?.EqualsIgnoreCase(modID) == true)
            {
                return(true);
            }

            // check dependencies
            IManifestDependency dependency = manifest.Dependencies?.FirstOrDefault(p => p.UniqueID.EqualsIgnoreCase(modID));

            return
                (dependency != null &&
                 (canBeOptional || dependency.IsRequired));
        }
Exemplo n.º 25
0
        /*********
        ** Public methods
        *********/
        /// <inheritdoc />
        public void ResetProgress(IManifest manifest)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException(nameof(manifest));
            }

            Mod.Instance.Monitor.Log($"{manifest.Name} reset the current player's magic progress.", LogLevel.Info);

            SpellBook book = Game1.player.GetSpellBook();

            foreach (var spell in book.KnownSpells.Values.ToArray())
            {
                if (spell.Level > 0)
                {
                    book.ForgetSpell(spell.SpellId, 1);
                }
            }
            book.UseSpellPoints(book.FreePoints);
        }
Exemplo n.º 26
0
        public async void Check(IManifest manifest)
        {
            try
            {
                var latestVersion = await GetCurrentVersion(manifest.UniqueID).ConfigureAwait(false);

                if (latestVersion.IsNewerThan(manifest.Version))
                {
                    NotifyNewVersion(manifest.Name);
                }
                else
                {
                    NotifyUpToDate(manifest.Name);
                }
            }
            catch (Exception e)
            {
                NotifyFailure(manifest.Name, e.Message);
            }
        }
Exemplo n.º 27
0
        public SiloSize(Mod mod)
        {
            Helper   = mod.Helper;
            Monitor  = mod.Monitor;
            Manifest = mod.ModManifest;
            Config   = Helper.ReadConfig <ModConfig>();

            AutoHayBuildings.UnionWith(Config.AutoHayBuildings);
            Capacity = Math.Max(1, Config.SiloSize);
            try {
                SiloSizePatcher.Initialize(mod, Capacity);
                SiloSizePatcher.Execute();
                SiloSizePatcher.Cleanup();
                string comparo = Capacity > ORIG_SILO_SIZE ? "bigger" : Capacity < ORIG_SILO_SIZE ? "smaller" : "same-sized";
                Monitor.Log($"All patching successful. Enjoy your {comparo} silos!", LogLevel.Info);
            }
            catch (Exception ex) {
                Monitor.Log($"Patching failed. Technical details:\n{ex}", LogLevel.Error);
            }
        }
Exemplo n.º 28
0
        public void RegisterToken(IManifest mod, string name, Func <bool> updateContext, Func <bool> isReady, Func <string, IEnumerable <string> > getValue, bool allowsInput, bool requiresInput)
        {
            // log deprecation warning
            string warning = $"{mod.Name} used an experimental token API that will break in the next Content Patcher update.";

            if (this.LoggedDeprecationWarnings.Add(warning))
            {
                this.Monitor.Log(warning, LogLevel.Warn);
            }

            // hack to wrap legacy token
            ConventionWrapper wrapper = new ConventionWrapper();

            this.Reflection.GetField <ConventionDelegates.UpdateContext>(wrapper, $"{nameof(wrapper.UpdateContext)}Impl").SetValue(() => updateContext());
            this.Reflection.GetField <ConventionDelegates.IsReady>(wrapper, $"{nameof(wrapper.IsReady)}Impl").SetValue(() => isReady());
            this.Reflection.GetField <ConventionDelegates.GetValues>(wrapper, $"{nameof(wrapper.GetValues)}Impl").SetValue(input => getValue(input));
            this.Reflection.GetField <ConventionDelegates.AllowsInput>(wrapper, $"{nameof(wrapper.AllowsInput)}Impl").SetValue(() => allowsInput);
            this.Reflection.GetField <ConventionDelegates.RequiresInput>(wrapper, $"{nameof(wrapper.RequiresInput)}Impl").SetValue(() => requiresInput);
            this.RegisterValueProvider(mod, new ConventionValueProvider(name, wrapper));
        }
Exemplo n.º 29
0
        /// <summary>Gets the update status of all mods.</summary>
        /// <param name="statuses">All mod statuses.</param>
        /// <returns>Whether any non skipped statuses were added.</returns>
        public bool GetUpdateStatuses(out IList <ModStatus> statuses)
        {
            statuses = new List <ModStatus>();

            bool addedNonSkippedStatus = false;

            foreach (object modMetaData in GetInstanceField <IEnumerable <object> >(GetInstanceField <object>(this.helper.ModRegistry, "Registry"), "Mods"))
            {
                ModEntryModel result   = GetInstanceProperty <ModEntryModel>(modMetaData, "UpdateCheckData");
                IManifest     manifest = GetInstanceProperty <IManifest>(modMetaData, "Manifest");

                string fallbackURL = manifest.UpdateKeys?.Select(this.toolkit.GetUpdateUrl).FirstOrDefault(p => p != null) ?? "";

                if (result == null)
                {
                    statuses.Add(new ModStatus(UpdateStatus.Skipped, manifest, fallbackURL, null, "SMAPI didn't check for an update"));
                    continue;
                }

                if (result.SuggestedUpdate == null)
                {
                    if (result.Errors.Length != 0)
                    {
                        // Return the first error. That's not perfect, but generally users don't care why each different update failed, they just want to know there was an error.
                        statuses.Add(new ModStatus(UpdateStatus.Error, manifest, fallbackURL, null, result.Errors[0]));
                    }
                    else
                    {
                        statuses.Add(new ModStatus(UpdateStatus.UpToDate, manifest, fallbackURL));
                    }
                }
                else
                {
                    statuses.Add(new ModStatus(UpdateStatus.OutOfDate, manifest, result.SuggestedUpdate.Url, result.SuggestedUpdate.Version.ToString()));
                }

                addedNonSkippedStatus = true;
            }

            return(addedNonSkippedStatus);
        }
Exemplo n.º 30
0
        public DataLoader(IModHelper helper, IManifest manifest)
        {
            Helper    = helper;
            I18N      = helper.Translation;
            ModConfig = helper.ReadConfig <ModConfig>();

            Dictionary <object, int> CrystalariumData = DataLoader.Helper.Data.ReadJsonFile <Dictionary <object, int> >(CrystalariumDataJson) ?? DefaultCystalariumData;

            DataLoader.Helper.Data.WriteJsonFile(CrystalariumDataJson, CrystalariumData);

            Dictionary <int, string> objects = DataLoader.Helper.Content.Load <Dictionary <int, string> >("Data\\ObjectInformation", ContentSource.GameContent);

            CrystalariumData.ToList().ForEach(d =>
            {
                int?id = GetId(d.Key, objects);
                if (id.HasValue && !CrystalariumDataId.ContainsKey(id.Value))
                {
                    CrystalariumDataId[id.Value] = d.Value;
                }
            });

            DataLoader.LoadContentPacksCommand();

            if (!ModConfig.DisableLetter)
            {
                MailDao.SaveLetter
                (
                    new Letter
                    (
                        "CustomCrystalarium"
                        , I18N.Get("CustomCrystalarium.Letter")
                        , (l) => !Game1.player.mailReceived.Contains(l.Id)
                        , (l) => Game1.player.mailReceived.Add(l.Id)
                    )
                {
                    Title = I18N.Get("CustomCrystalarium.Letter.Title")
                }
                );
            }
            CreateConfigMenu(manifest);
        }
Exemplo n.º 31
0
        /// <summary>Log info about loaded mods.</summary>
        /// <param name="loaded">The full list of loaded content packs and mods.</param>
        /// <param name="loadedContentPacks">The loaded content packs.</param>
        /// <param name="loadedMods">The loaded mods.</param>
        /// <param name="skippedMods">The mods which could not be loaded.</param>
        /// <param name="logParanoidWarnings">Whether to log issues for mods which directly use potentially sensitive .NET APIs like file or shell access.</param>
        public void LogModInfo(IModMetadata[] loaded, IModMetadata[] loadedContentPacks, IModMetadata[] loadedMods, IModMetadata[] skippedMods, bool logParanoidWarnings)
        {
            // log loaded mods
            this.Monitor.Log($"Loaded {loadedMods.Length} mods" + (loadedMods.Length > 0 ? ":" : "."), LogLevel.Info);
            foreach (IModMetadata metadata in loadedMods.OrderBy(p => p.DisplayName))
            {
                IManifest manifest = metadata.Manifest;
                this.Monitor.Log(
                    $"   {metadata.DisplayName} {manifest.Version}"
                    + (!string.IsNullOrWhiteSpace(manifest.Author) ? $" by {manifest.Author}" : "")
                    + (!string.IsNullOrWhiteSpace(manifest.Description) ? $" | {manifest.Description}" : ""),
                    LogLevel.Info
                    );
            }

            this.Monitor.Newline();

            // log loaded content packs
            if (loadedContentPacks.Any())
            {
                string GetModDisplayName(string id) => loadedMods.FirstOrDefault(p => p.HasID(id))?.DisplayName;

                this.Monitor.Log($"Loaded {loadedContentPacks.Length} content packs:", LogLevel.Info);
                foreach (IModMetadata metadata in loadedContentPacks.OrderBy(p => p.DisplayName))
                {
                    IManifest manifest = metadata.Manifest;
                    this.Monitor.Log(
                        $"   {metadata.DisplayName} {manifest.Version}"
                        + (!string.IsNullOrWhiteSpace(manifest.Author) ? $" by {manifest.Author}" : "")
                        + $" | for {GetModDisplayName(metadata.Manifest.ContentPackFor.UniqueID)}"
                        + (!string.IsNullOrWhiteSpace(manifest.Description) ? $" | {manifest.Description}" : ""),
                        LogLevel.Info
                        );
                }

                this.Monitor.Newline();
            }

            // log mod warnings
            this.LogModWarnings(loaded, skippedMods, logParanoidWarnings);
        }
Exemplo n.º 32
0
        public static bool TryParse(Stream json, out IManifest manifest, out Exception exception)
        {
            manifest = null;
            exception = null;

            try
            {
                using (var streamReader = new StreamReader(json))
                using (var jsonReader = new JsonTextReader(streamReader))
                {
                    var obj = JToken.ReadFrom(jsonReader) as JObject;

                    if (obj == null)
                        return false;

                    JToken manifestVersionToken;

                    if (!obj.TryGetValue("manifest_version", out manifestVersionToken))
                        return false;

                    if (manifestVersionToken.Type != JTokenType.Integer)
                        return false;

                    var manifestVersion = manifestVersionToken.Value<int>();

                    if (!ManifestReaders.ContainsKey(manifestVersion))
                        return false;

                    var manifestReader = ManifestReaders[manifestVersion]();
                    manifest = manifestReader.Read(obj);

                    return true;
                }
            }
            catch (Exception e)
            {
                exception = e;
                return false;
            }
        }
Exemplo n.º 33
0
 public static bool TryParse(Stream json, out IManifest manifest)
 {
     Exception exception;
     return TryParse(json, out manifest, out exception);
 }
Exemplo n.º 34
0
		public PackageInfo(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			Name = GetParameterValue<string>("Name");
			ResourceRoot = GetParameterValue<string>("ResourceRoot");
			Version = GetParameterValue<string>("Version");
		}
Exemplo n.º 35
0
		public PageTemplateInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			ContentName = GetParameterValue<string>("ContentName");
		}
Exemplo n.º 36
0
		public PrerequisitStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData) { }
Exemplo n.º 37
0
		public ItemInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			ResourceName = GetParameterValue<string>("ResourcePath");
		}
Exemplo n.º 38
0
		public FileInstallStep(IManifest manifest, string filePath, string repositoryContainerPath) : base(manifest, null)
		{
			ResourceName = filePath;
			ContainerPath = repositoryContainerPath;
		}
Exemplo n.º 39
0
		public InstallerAssemblyInfo(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData) { }
Exemplo n.º 40
0
 public void SetManifestInformation(IManifest manifest)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new Action<IManifest>(SetManifestInfoInternal), manifest);
     }
     else
     {
         SetManifestInfoInternal(manifest);
     }
 }
Exemplo n.º 41
0
		public InstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
		}
Exemplo n.º 42
0
 public DbScriptInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
 {
     Running = GetParameterValue<PositionInSequence>("Running");
 }
Exemplo n.º 43
0
		public RequiredSenseNetVersionStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			RequiredVersion = GetParameterValue<string>("Version");
		}
Exemplo n.º 44
0
		public ContentViewInstallStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			ContentName = GetParameterValue<string>("ContentName");
			ParentFolderName = GetParameterValue<string>("ContentTypeName");
			ViewMode = GetParameterValue<ContentViewMode>("ViewMode");
		}
Exemplo n.º 45
0
		public RequiredPackageStep(IManifest manifest, CustomAttributeData rawData) : base(manifest, rawData)
		{
			RequiredPackageName = GetParameterValue<string>("Name");
			RequiredVersion = GetParameterValue<string>("Version");
		}
Exemplo n.º 46
0
 void SetManifestInfoInternal(IManifest manifest)
 {
     lblProductId.Text = "Product ID: " + manifest.ProductId;
     lblTitle.Text = "Title: " + manifest.Title;
     lblVersion.Text = "Version: " + manifest.Version;
     lblPlatformVersion.Text = "Platform version: " + Util.GetEnumDescription(manifest.PlatformVersion);
     lblAuthor.Text = "Author: " + manifest.Author;
     tbxCapabilities.Clear();
     tbxRequirements.Clear();
     tbxScreenResolutions.Clear();
     tbxFileTypes.Clear();
     tbxURIs.Clear();
     foreach (var capability in manifest.Capabilities)
     {
         tbxCapabilities.AppendText(capability.Id + ": " + capability.Description + "\r\n");
     }
     foreach (var requirement in manifest.Requirements)
     {
         tbxRequirements.AppendText(string.Format("{0}: {1}\r\n", requirement.Id, requirement.Description));
     }
     foreach (var screenResolution in manifest.ScreenResolutions)
     {
         tbxScreenResolutions.AppendText(string.Format("{0}: {1}\r\n", screenResolution.ToString(), Util.GetEnumDescription(screenResolution)));
     }
     if (manifest.PlatformVersion != PlatformVersion.Version71)
     {
         ShowExcessTabs();
         foreach (var fileType in manifest.SupportedFileTypes)
         {
             tbxFileTypes.AppendText(fileType + "\r\n");
         }
         foreach (var uri in manifest.AssociatedURIs)
         {
             tbxURIs.AppendText(uri + "\r\n");
         }
     }
     else
     {
         var requirement = Requirement.GetRequirement("ID_REQ_MEMORY_90");
         tbxRequirements.AppendText(string.Format("{0}: {1}\r\n", requirement.Id, requirement.Description));
         HideExcessTabs();
     }
 }