Beispiel #1
0
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="enabled">Whether to enable this data layer.</param>
 /// <param name="updatesPerSecond">The number of updates needed per second.</param>
 /// <param name="updateWhenViewChange">Whether to update the layer when the player's tile view changes.</param>
 /// <param name="shortcutKey">The key binding which switches to this layer when the overlay is open.</param>
 public LayerConfig(bool?enabled = null, decimal?updatesPerSecond = null, bool?updateWhenViewChange = null, KeybindList?shortcutKey = null)
 {
     this.Enabled              = enabled ?? true;
     this.UpdatesPerSecond     = updatesPerSecond ?? 60;
     this.UpdateWhenViewChange = updateWhenViewChange ?? true;
     this.ShortcutKey          = shortcutKey ?? new();
 }
Beispiel #2
0
        /// <summary>Register the config menu if available.</summary>
        public void Register()
        {
            // get config menu
            var menu = this.ConfigMenu;

            if (!menu.IsLoaded)
            {
                return;
            }

            // register
            menu
            .RegisterConfig()
            .AddCheckbox(
                label: "Require Horse Flute",
                description: "Whether you need the horse flute item in your inventory to summon a horse. Default false.",
                get: config => config.RequireHorseFlute,
                set: (config, value) => config.RequireHorseFlute = value
                )
            .AddKeyBinding(
                label: "Summon Horse Button",
                description: "The button to press which plays the flute and summons a horse. Default H.",
                get: config => this.GetSingleButton(config.SummonHorseKey),
                set: (config, value) => config.SummonHorseKey = KeybindList.ForSingle(value)
                );
        }
 public ItemHighlighter(string uniqueId, KeybindList hotkey, bool highlightOthersWhenHeld, ItemHighlightFunction highlighter, Action onStart = null, Action onFinish = null)
     : base(uniqueId, hotkey, highlighter)
 {
     this.highlightOthersWhenHeld = highlightOthersWhenHeld;
     this.onStart  = onStart;
     this.onFinish = onFinish;
 }
Beispiel #4
0
        private void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
        {
            fluteBlockApi = Helper.ModRegistry.GetApi <IAdvancedFluteBlocksApi>("aedenthorn.AdvancedFluteBlocks");
            trainTrackApi = Helper.ModRegistry.GetApi <ITrainTracksApi>("aedenthorn.TrainTracks");

            // get Generic Mod Config Menu's API (if it's installed)
            var configMenu = Helper.ModRegistry.GetApi <IGenericModConfigMenuApi>("spacechase0.GenericModConfigMenu");

            if (configMenu is null)
            {
                return;
            }

            // register mod
            configMenu.Register(
                mod: ModManifest,
                reset: () => Config = new ModConfig(),
                save: () => Helper.WriteConfig(Config)
                );

            configMenu.AddBoolOption(
                mod: ModManifest,
                name: () => "Mod Enabled?",
                getValue: () => Config.EnableMod,
                setValue: value => Config.EnableMod = value
                );
            configMenu.AddTextOption(
                mod : ModManifest,
                name : () => "Import Key",
                getValue : () => Config.ImportKey.ToString(),
                setValue : delegate(string value) { try { Config.ImportKey = KeybindList.Parse(value); } catch { } }
                );
        }
Beispiel #5
0
        /// <summary>Reads the JSON representation of the object.</summary>
        /// <param name="reader">The JSON reader.</param>
        /// <param name="objectType">The object type.</param>
        /// <param name="existingValue">The object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string path = reader.Path;

            switch (reader.TokenType)
            {
            case JsonToken.Null:
                return(objectType == typeof(Keybind)
                        ? (object)new Keybind()
                        : new KeybindList());

            case JsonToken.String:
            {
                string str = JToken.Load(reader).Value <string>();

                if (objectType == typeof(Keybind))
                {
                    return(Keybind.TryParse(str, out Keybind parsed, out string[] errors)
                                ? parsed
                                : throw new SParseException($"Can't parse {nameof(Keybind)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}"));
                }
                else
                {
                    return(KeybindList.TryParse(str, out KeybindList parsed, out string[] errors)
                                ? parsed
                                : throw new SParseException($"Can't parse {nameof(KeybindList)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}"));
                }
            }

            default:
                throw new SParseException($"Can't parse {objectType} from unexpected {reader.TokenType} node (path: {reader.Path}).");
            }
        }
Beispiel #6
0
        private void CheckForKeybindConflict()
        {
            try
            {
                if (Helper.ModRegistry.IsLoaded("CJBok.CheatsMenu"))
                {
                    // whether the pet menu is set to the default
                    if (Config.PetMenuKey.IsBound && Config.PetMenuKey.Keybinds.Length == 1 && Config.PetMenuKey.Keybinds[0].Buttons.Length == 1 && Config.PetMenuKey.Keybinds[0].Buttons[0] == SButton.P)
                    {
                        var data = Helper.ModRegistry.Get("CJBok.CheatsMenu");

                        var path = data.GetType().GetProperty("DirectoryPath");

                        if (path != null && path.GetValue(data) != null)
                        {
                            var list = ReadConfigFile("config.json", path.GetValue(data) as string, new[] { "OpenMenuKey" }, data.Manifest.Name);

                            if (list["OpenMenuKey"] == "P")
                            {
                                Config.PetMenuKey = KeybindList.Parse("");
                                DebugLog("Unassigned pet menu key because cjb cheats menu is bound to the same key.");
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Beispiel #7
0
        public void TryParse_InvalidValues(string input, string expectedError)
        {
            // act
            bool success = KeybindList.TryParse(input, out KeybindList parsed, out string[] errors);

            // assert
            Assert.IsFalse(success, "Parsing unexpectedly succeeded.");
            Assert.IsNull(parsed, "The parsed result should be null.");
            Assert.IsNotNull(errors, message: "The errors should never be null.");
            Assert.AreEqual(expectedError, string.Join("; ", errors), "The errors don't match the expected ones.");
        }
Beispiel #8
0
        public string TryParse_MultiValues(string input)
        {
            // act
            bool success = KeybindList.TryParse(input, out KeybindList parsed, out string[] errors);

            // assert
            Assert.IsTrue(success, "Parsing unexpectedly failed.");
            Assert.IsNotNull(parsed, "The parsed result should not be null.");
            Assert.IsNotNull(errors, message: "The errors should never be null.");
            Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors.");
            return(parsed.ToString());
        }
Beispiel #9
0
        /// <summary>Get the first button in a key binding, if any.</summary>
        /// <param name="keybindList">The key binding list.</param>
        private SButton GetSingleButton(KeybindList keybindList)
        {
            foreach (Keybind keybind in keybindList.Keybinds)
            {
                if (keybind.IsBound)
                {
                    return(keybind.Buttons.First());
                }
            }

            return(SButton.None);
        }
Beispiel #10
0
        public void TryParse_SimpleValue(SButton button)
        {
            // act
            bool success = KeybindList.TryParse($"{button}", out KeybindList parsed, out string[] errors);

            // assert
            Assert.IsTrue(success, "Parsing unexpectedly failed.");
            Assert.IsNotNull(parsed, "The parsed result should not be null.");
            Assert.AreEqual(parsed.ToString(), $"{button}");
            Assert.IsNotNull(errors, message: "The errors should never be null.");
            Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors.");
        }
Beispiel #11
0
 private void Input_ButtonsChanged(object sender, StardewModdingAPI.Events.ButtonsChangedEventArgs e)
 {
     if (!Config.EnableMod || animationDict == null)
     {
         return;
     }
     foreach (var kvp in animationDict)
     {
         if (kvp.Value.keyTrigger != null && KeybindList.TryParse(kvp.Value.keyTrigger, out KeybindList keybind, out string[] errors) && keybind.JustPressed())
         {
             PlayAnimation(kvp.Key, kvp.Value);
         }
     }
 }
Beispiel #12
0
        /// <inheritdoc />
        public void SuppressActiveKeybinds(KeybindList keybindList)
        {
            foreach (Keybind keybind in keybindList.Keybinds)
            {
                if (!keybind.GetState().IsDown())
                {
                    continue;
                }

                foreach (SButton button in keybind.Buttons)
                {
                    this.Suppress(button);
                }
            }
        }
Beispiel #13
0
 private void SuppressKeys(object sender, ButtonsChangedEventArgs e)
 {
     if (Config != null)
     {
         foreach (var keyValue in Config.SuppressedKeys)
         {
             switch (keyValue.Value)
             {
             case ModConfig.SuppressMode.SuppressOnlyInMenu when Context.IsWorldReady && Game1.activeClickableMenu != null:
             case ModConfig.SuppressMode.SuppressOnlyWhenPlayerFree when Context.IsPlayerFree:
             case ModConfig.SuppressMode.SuppressOnlyWhenPlayerCanMove when Context.CanPlayerMove:
             case ModConfig.SuppressMode.Suppress:
                 this.Helper.Input.SuppressActiveKeybinds(KeybindList.ForSingle(keyValue.Key));
                 break;
             }
         }
     }
 }
Beispiel #14
0
        public KeyBindGui() : base("Key Bind UI")
        {
            var mods = Environment.CurrentDirectory + "/" + "Mods";

            foreach (var info in new DirectoryInfo(mods).GetDirectories())
            {
                var keyBindListInfo = new KeyBindListInfo();
                var config          = new FileInfo(info.FullName + "/config.json");
                keyBindListInfo.ConfigFileInfo = config;
                if (!config.Exists)
                {
                    continue;
                }

                keyBindListInfo.Name = info.Name;
                var read     = new JsonTextReader(config.OpenText());
                var readFrom = (JObject)JToken.ReadFrom(read);
                read.Close();
                foreach (var keyValuePair in readFrom)
                {
                    if (keyValuePair.Value == null || keyValuePair.Value.Type != JTokenType.String)
                    {
                        continue;
                    }
                    try
                    {
                        keyBindListInfo.KeyBindList[keyValuePair.Key] =
                            KeybindList.Parse(keyValuePair.Value.ToString()).ToString();
                    }
                    catch (Exception e)
                    {
                        // ignored
                    }
                }

                AddElement(new Button(info.Name,
                                      ModEntry.GetInstance().Helper.Translation.Get("KeyBindUI.Framework.Screen.ModsGui.KeySetting"))
                {
                    OnLeftClicked = () => { OpenScreenGui(new KeyBindListGui(keyBindListInfo)); }
                });
            }
        }
Beispiel #15
0
        /*********
        ** Private methods
        *********/

        /// <summary>Raised when button is pressed</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>

        private void CheckHotkey(object sender, ButtonsChangedEventArgs e)
        {
            if (myKeybinds.Value == null)
            {
                return;
            }
            KeybindList keybinds = myKeybinds.Value;
            Farmer      player   = Game1.player;

            if (!keybinds.JustPressed())
            {
                return;
            }

            if (bestItem.Value != null && keybinds.GetByType(KeybindType.CancelKeybind).IsPressed())
            {
                keybinds.SuppressType(Helper, KeybindType.CancelKeybind);
                RestoreLastItem(player);
                return;
            }

            if (bestItem.Value != null && keybinds.PressedByType(KeybindType.ForceEatFoodKeybind))
            {
                keybinds.SuppressType(Helper, KeybindType.ForceEatFoodKeybind);
                EatBestItem(player);
                return;
            }

            if (keybinds.PressedByType(KeybindType.CycleFoodKeybind))
            {
                keybinds.SuppressType(Helper, KeybindType.CycleFoodKeybind);
                CheckBestItems(player);
            }

            if (bestItem != null && (keybinds.PressedByType(KeybindType.ForceEatFoodKeybind) || keybinds.PressedByType(KeybindType.EatCurrentFoodKeybind)))
            {
                keybinds.SuppressType(Helper, KeybindType.ForceEatFoodKeybind);
                keybinds.SuppressType(Helper, KeybindType.EatCurrentFoodKeybind);
                EatBestItem(player);
            }
        }
Beispiel #16
0
        public SButtonState GetState(string input, string stateMap)
        {
            // act
            bool success = KeybindList.TryParse(input, out KeybindList parsed, out string[] errors);

            if (success && parsed?.Keybinds != null)
            {
                foreach (var keybind in parsed.Keybinds)
#pragma warning disable 618 // method is marked obsolete because it should only be used in unit tests
                {
                    keybind.GetButtonState = key => this.GetStateFromMap(key, stateMap);
                }
#pragma warning restore 618
            }

            // assert
            Assert.IsTrue(success, "Parsing unexpected failed");
            Assert.IsNotNull(parsed, "The parsed result should not be null.");
            Assert.IsNotNull(errors, message: "The errors should never be null.");
            Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors.");
            return(parsed.GetState());
        }
        /// <summary>Show a confirmation message for the given noclip mode, if enabled.</summary>
        /// <param name="noclipEnabled">Whether noclip was enabled; else noclip was disabled.</param>
        /// <param name="keybind">The keybind that was pressed.</param>
        private void ShowConfirmationMessage(bool noclipEnabled, KeybindList keybind)
        {
            // skip if message not enabled
            if (noclipEnabled && !this.Config.ShowEnabledMessage)
            {
                return;
            }
            if (!noclipEnabled && !this.Config.ShowDisabledMessage)
            {
                return;
            }

            // show message
            Game1.hudMessages.RemoveAll(p => p.number == ModEntry.MessageID);
            string keybindStr = keybind.GetKeybindCurrentlyDown().ToString();
            string text       = noclipEnabled ? I18n.EnabledMessage(keybindStr) : I18n.DisabledMessage(keybindStr);

            Game1.addHUDMessage(new HUDMessage(text, HUDMessage.error_type)
            {
                noIcon = true, number = ModEntry.MessageID
            });
        }
        /// <summary>Check for and fix invalid tool settings.</summary>
        private void VerifyModConfig()
        {
            if (Config.AxeConfig.RadiusAtEachPowerLevel.Count() < 4)
            {
                Monitor.Log("Missing values in configs.json AxeConfig.RadiusAtEachPowerLevel. The default values will be restored.", LogLevel.Warn);
                Config.AxeConfig.RadiusAtEachPowerLevel = new List <int>()
                {
                    1, 2, 3, 4
                };
            }
            else if (Config.AxeConfig.RadiusAtEachPowerLevel.Any(i => i < 0))
            {
                Monitor.Log("Illegal negative value for shockwave radius in configs.json AxeConfig.RadiusAtEachPowerLevel. Those values will be replaced with zero.", LogLevel.Warn);
                Config.AxeConfig.RadiusAtEachPowerLevel = Config.AxeConfig.RadiusAtEachPowerLevel.Select(x => x < 0 ? 0 : x).ToList();
            }

            if (Config.PickaxeConfig.RadiusAtEachPowerLevel.Count() < 4)
            {
                Monitor.Log("Missing values in configs.json PickaxeConfig.RadiusAtEachPowerLevel. The default values will be restored.", LogLevel.Warn);
                Config.PickaxeConfig.RadiusAtEachPowerLevel = new List <int>()
                {
                    1, 2, 3, 4
                };
            }
            else if (Config.PickaxeConfig.RadiusAtEachPowerLevel.Any(i => i < 0))
            {
                Monitor.Log("Illegal negative value for shockwave radius in configs.json PickaxeConfig.RadiusAtEachPowerLevel. Those values will be replaced with zero.", LogLevel.Warn);
                Config.PickaxeConfig.RadiusAtEachPowerLevel = Config.PickaxeConfig.RadiusAtEachPowerLevel.Select(x => x < 0 ? 0 : x).ToList();
            }

            if (Config.RequireModkey && !Config.Modkey.IsBound)
            {
                Monitor.Log("'RequireModkey' setting is set to true, but no Modkey is bound. Default keybind will be restored. To disable the Modkey, set this value to false.", LogLevel.Warn);
                Config.Modkey = KeybindList.ForSingle(SButton.LeftShift);
            }

            if (Config.StaminaCostMultiplier < 0)
            {
                Monitor.Log("'StaminaCostMultiplier' is set to a negative value in configs.json. This may cause game-breaking bugs.", LogLevel.Warn);
            }

            if (Config.ShockwaveDelay < 0)
            {
                Monitor.Log("Illegal negative value for 'ShockwaveDelay' in configs.json. The default value will be restored.", LogLevel.Warn);
                Config.ShockwaveDelay = 200;
            }

            if (Utility.HasHigherLevelToolMod(ModRegistry))
            {
                Monitor.Log("Prismatic or Radioactive Tools detected.", LogLevel.Info);

                if (Config.AxeConfig.RadiusAtEachPowerLevel.Count() < 5)
                {
                    Monitor.Log("Adding default fifth radius value to Axe configurations.", LogLevel.Info);
                    Config.AxeConfig.RadiusAtEachPowerLevel.Add(5);
                }
                else if (Config.AxeConfig.RadiusAtEachPowerLevel.Count() > 5)
                {
                    Monitor.Log("Too many values in configs.json AxeConfig.RadiusAtEachPowerLevel. Additional values will be removed.", LogLevel.Warn);
                    Config.AxeConfig.RadiusAtEachPowerLevel = Config.AxeConfig.RadiusAtEachPowerLevel.Take(5).ToList();
                }

                if (Config.PickaxeConfig.RadiusAtEachPowerLevel.Count() < 5)
                {
                    Monitor.Log("Adding default fifth radius value to Pickaxe configurations.", LogLevel.Info);
                    Config.PickaxeConfig.RadiusAtEachPowerLevel.Add(5);
                }
                else if (Config.PickaxeConfig.RadiusAtEachPowerLevel.Count() > 5)
                {
                    Monitor.Log("Too many values in configs.json PickaxeConfig.RadiusAtEachPowerLevel. Additional values will be removed.", LogLevel.Warn);
                    Config.PickaxeConfig.RadiusAtEachPowerLevel = Config.PickaxeConfig.RadiusAtEachPowerLevel.Take(5).ToList();
                }
            }
            else
            {
                if (Config.AxeConfig.RadiusAtEachPowerLevel.Count() > 4)
                {
                    Monitor.Log("Too many values in configs.json AxeConfig.RadiusAtEachPowerLevel. Additional values will be removed.", LogLevel.Warn);
                    Config.AxeConfig.RadiusAtEachPowerLevel = Config.AxeConfig.RadiusAtEachPowerLevel.Take(4).ToList();
                }

                if (Config.PickaxeConfig.RadiusAtEachPowerLevel.Count() > 4)
                {
                    Monitor.Log("Too many values in configs.json PickaxeConfig.RadiusAtEachPowerLevel. Additional values will be removed.", LogLevel.Warn);
                    Config.PickaxeConfig.RadiusAtEachPowerLevel = Config.PickaxeConfig.RadiusAtEachPowerLevel.Take(4).ToList();
                }
            }

            Helper.WriteConfig(Config);
        }
Beispiel #19
0
 public AxisList(KeybindList list)
 {
     controlList = list;
 }
 void IRangeHighlightAPI.AddItemRangeHighlighter(string uniqueId, SButton?hotkey, bool highlightOthersWhenHeld, Action onRangeCalculationStart, Func <Item, int, string, Tuple <Color, bool[, ]> > highlighter, Action onRangeCalculationFinish)
 {
     rangeHighlighter.AddItemHighlighter(uniqueId, KeybindList.ForSingle(hotkey ?? SButton.None), highlightOthersWhenHeld, highlighter, onRangeCalculationStart, onRangeCalculationFinish);
 }
 void IRangeHighlightAPI.AddItemRangeHighlighter(string uniqueId, SButton?hotkey, bool highlightOthersWhenHeld, Func <Item, int, string, Tuple <Color, bool[, ]> > highlighter)
 {
     rangeHighlighter.AddItemHighlighter(uniqueId, KeybindList.ForSingle(hotkey ?? SButton.None), highlightOthersWhenHeld, highlighter);
 }
 void IRangeHighlightAPI.AddItemRangeHighlighter(string uniqueId, KeybindList hotkey, bool highlightOthersWhenHeld, Func <Item, int, string, Tuple <Color, bool[, ]> > highlighter)
 {
     rangeHighlighter.AddItemHighlighter(uniqueId, hotkey, highlightOthersWhenHeld, highlighter);
 }
 void IRangeHighlightAPI.AddItemRangeHighlighter(string uniqueId, SButton?hotkey, Func <string, Tuple <Color, bool[, ]> > highlighter)
 {
     rangeHighlighter.AddItemHighlighter(uniqueId, KeybindList.ForSingle(hotkey ?? SButton.None), true, (Item item, int itemID, string lowerName) => { return(highlighter(lowerName)); });
 }
 void IRangeHighlightAPI.AddBuildingRangeHighlighter(string uniqueId, SButton?hotkey,
                                                     Func <BluePrint, Tuple <Color, bool[, ], int, int> > blueprintHighlighter,
                                                     Func <Building, Tuple <Color, bool[, ], int, int> > buildingHighlighter)
 {
     rangeHighlighter.AddBuildingHighlighter(uniqueId, KeybindList.ForSingle(hotkey ?? SButton.None), blueprintHighlighter, buildingHighlighter);
 }
 void IRangeHighlightAPI.AddBuildingRangeHighlighter(string uniqueId, KeybindList hotkey,
                                                     Func <BluePrint, Tuple <Color, bool[, ], int, int> > blueprintHighlighter,
                                                     Func <Building, Tuple <Color, bool[, ], int, int> > buildingHighlighter)
 {
     rangeHighlighter.AddBuildingHighlighter(uniqueId, hotkey, blueprintHighlighter, buildingHighlighter);
 }
        // ----- Hooks for applying highlights ----

        void IRangeHighlightAPI.AddBuildingRangeHighlighter(string uniqueId, KeybindList hotkey, Func <Building, Tuple <Color, bool[, ], int, int> > highlighter)
        {
            rangeHighlighter.AddBuildingHighlighter(uniqueId, hotkey, null, highlighter);
        }
 public void AddBuildingHighlighter(string uniqueId, KeybindList hotkey,
                                    BlueprintHighlightFunction blueprintHighlighter, BuildingHighlightFunction buildingHighlighter)
 {
     blueprintHighlighters.Insert(0, new Highlighter <BlueprintHighlightFunction>(uniqueId, hotkey, blueprintHighlighter));
     buildingHighlighters.Insert(0, new Highlighter <BuildingHighlightFunction>(uniqueId, hotkey, buildingHighlighter));
 }
 public void AddItemHighlighter(string uniqueId, KeybindList hotkey, bool highlightOthersWhenHeld, ItemHighlightFunction highlighter, Action onStart = null, Action onFinish = null)
 {
     itemHighlighters.Insert(0, new ItemHighlighter(uniqueId, hotkey, highlightOthersWhenHeld, highlighter, onStart, onFinish));
 }
 public Highlighter(string uniqueId, KeybindList hotkey, T highlighter)
 {
     this.uniqueId    = uniqueId;
     this.hotkey      = hotkey;
     this.highlighter = highlighter;
 }
 public ModConfigKeys(KeybindList?toggleDebug, KeybindList?debugPrevTexture, KeybindList?debugNextTexture)
 {
     this.ToggleDebug      = toggleDebug ?? new(SButton.F3);
     this.DebugPrevTexture = debugPrevTexture ?? new(SButton.LeftControl);
     this.DebugNextTexture = debugNextTexture ?? new(SButton.RightControl);
 }