Large Cleanup to Code Imports and Formatting

This commit is contained in:
Kam committed 2026-01-22 23:07:38 -05:00
1 parent 31aac0d6b3
commit a9b602713c
155 files changed
+4089 -2194

No files matched your search

+8 -2
View File
@@ -4,7 +4,13 @@ import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.*;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppedEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.relauncher.Side;
@@ -18,6 +24,7 @@ import kamkeel.npcs.command.profile.CommandProfile;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.profile.CNPCData;
import kamkeel.npcs.developer.Developer;
import kamkeel.npcs.network.PacketHandler;
@@ -68,7 +75,6 @@ import noppes.npcs.controllers.SpawnController;
import noppes.npcs.controllers.TagController;
import noppes.npcs.controllers.TransportController;
import noppes.npcs.enchants.EnchantInterface;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import noppes.npcs.entity.EntityChairMount;
import noppes.npcs.entity.EntityCustomNpc;
import noppes.npcs.entity.EntityMagicProjectile;
+32 -15
View File
@@ -1,8 +1,8 @@
package noppes.npcs;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.ability.TelegraphRemovePacket;
import kamkeel.npcs.network.packets.data.ability.TelegraphSpawnPacket;
@@ -35,32 +35,48 @@ public class DataAbilities {
// CONFIGURATION (saved to NBT)
// ═══════════════════════════════════════════════════════════════════
/** List of abilities this NPC can use */
/**
* List of abilities this NPC can use
*/
private List<Ability> abilities = new ArrayList<>();
/** Whether the ability system is enabled for this NPC */
/**
* Whether the ability system is enabled for this NPC
*/
public boolean enabled = false;
/** Minimum ticks between ability selections (global cooldown) */
/**
* Minimum ticks between ability selections (global cooldown)
*/
public int globalCooldown = 20;
// ═══════════════════════════════════════════════════════════════════
// RUNTIME STATE (not saved)
// ═══════════════════════════════════════════════════════════════════
/** Currently executing ability (null if none) */
/**
* Currently executing ability (null if none)
*/
private transient Ability currentAbility;
/** Per-ability cooldown timers (ability ID -> world time when cooldown ends) */
/**
* Per-ability cooldown timers (ability ID -> world time when cooldown ends)
*/
private transient Map<String, Long> cooldowns = new HashMap<>();
/** Ticks until next ability can be selected (global cooldown timer) */
/**
* Ticks until next ability can be selected (global cooldown timer)
*/
private transient int globalCooldownTimer = 0;
/** Last target used for ability execution */
/**
* Last target used for ability execution
*/
private transient EntityLivingBase lastTarget;
/** Recent hit timestamps for hit count condition */
/**
* Recent hit timestamps for hit count condition
*/
private transient List<Long> recentHitTimes = new ArrayList<>();
// ═══════════════════════════════════════════════════════════════════
@@ -532,11 +548,11 @@ public class DataAbilities {
* Fire an ability hit event. Called by abilities when they hit an entity.
* Returns null if the event was cancelled, otherwise returns the (possibly modified) event.
*
* @param ability The ability doing the hit
* @param target The original target of the ability
* @param hitEntity The entity being hit
* @param damage The damage amount
* @param knockback The horizontal knockback
* @param ability The ability doing the hit
* @param target The original target of the ability
* @param hitEntity The entity being hit
* @param damage The damage amount
* @param knockback The horizontal knockback
* @param knockbackUp The vertical knockback (deprecated, ignored)
* @return The event (with possibly modified values), or null if cancelled
*/
@@ -636,7 +652,7 @@ public class DataAbilities {
/**
* Check if ability is controlling NPC movement (AI pathfinding should be blocked).
* Called by AI tasks to determine if they should try to path.
*
* <p>
* Rules:
* - WINDUP phase: Block AI if lockMovement is true
* - ACTIVE phase: Block AI if lockMovement OR hasAbilityMovement is true
@@ -672,6 +688,7 @@ public class DataAbilities {
/**
* Check if NPC movement should be blocked due to ability execution.
*
* @deprecated Use isAbilityControllingMovement() instead
*/
@Deprecated
+16 -17
View File
@@ -38,7 +38,6 @@ import noppes.npcs.controllers.CustomGuiController;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.EffectScript;
import noppes.npcs.controllers.data.ForgeDataScript;
import noppes.npcs.controllers.data.IScriptBlockHandler;
import noppes.npcs.controllers.data.IScriptHandler;
@@ -265,7 +264,7 @@ public class EventHooks {
noppes.npcs.scripted.event.NpcEvent.InitEvent event = new noppes.npcs.scripted.event.NpcEvent.InitEvent(npc.wrappedNPC);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.INIT, event);
npc.script.callScript(EnumScriptType.INIT, event);
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
npc.advanced.soulStoneInit = false;
}
@@ -276,7 +275,7 @@ public class EventHooks {
noppes.npcs.scripted.event.NpcEvent.UpdateEvent event = new noppes.npcs.scripted.event.NpcEvent.UpdateEvent(npc.wrappedNPC);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.TICK, event);
npc.script.callScript(EnumScriptType.TICK, event);
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCDialog(EntityNPCInterface npc, EntityPlayer player, int dialogId, int optionId, Dialog dialog) {
@@ -297,7 +296,7 @@ public class EventHooks {
NpcEvent.DialogClosedEvent event = new NpcEvent.DialogClosedEvent(npc.wrappedNPC, player, dialogId, optionId, dialog);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.DIALOG_CLOSE, event);
npc.script.callScript(EnumScriptType.DIALOG_CLOSE, event, "player", event.getPlayer(), "dialog", event.getDialogId(), "option", event.getOptionId(), "dialogObj", event.getDialog());
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCInteract(EntityNPCInterface npc, EntityPlayer player) {
@@ -307,7 +306,7 @@ public class EventHooks {
NpcEvent.InteractEvent event = new NpcEvent.InteractEvent(npc.wrappedNPC, player);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.INTERACT, event);
boolean result = npc.script.callScript(EnumScriptType.INTERACT, event, "player", player);
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
return result;
}
@@ -318,7 +317,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ATTACK_MELEE, event);
npc.script.callScript(EnumScriptType.ATTACK_MELEE, event, "target", event.target);
npc.script.callScript(EnumScriptType.ATTACK, event, "target", event.target);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCMeleeSwing(EntityNPCInterface npc, NpcEvent.SwingEvent event) {
@@ -327,7 +326,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ATTACK_SWING, event);
npc.script.callScript(EnumScriptType.ATTACK_SWING, event);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCRangedAttack(EntityNPCInterface npc, NpcEvent.RangedLaunchedEvent event) {
@@ -337,7 +336,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.RANGED_LAUNCHED, event);
npc.script.callScript(EnumScriptType.RANGED_LAUNCHED, event, "target", event.target);
npc.script.callScript(EnumScriptType.ATTACK, event, "target", event.target);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static void onNPCKilledEntity(EntityNPCInterface npc, EntityLivingBase entity) {
@@ -347,7 +346,7 @@ public class EventHooks {
NpcEvent.KilledEntityEvent event = new NpcEvent.KilledEntityEvent(npc.wrappedNPC, entity);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.KILLS, event);
npc.script.callScript(EnumScriptType.KILLS, event, "target", entity);
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCTarget(EntityNPCInterface npc, NpcEvent.TargetEvent event) {
@@ -356,7 +355,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.TARGET, event);
npc.script.callScript(EnumScriptType.TARGET, event);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCTargetLost(EntityNPCInterface npc, EntityLivingBase prevtarget, EntityLivingBase newTarget) {
@@ -366,7 +365,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.TARGET_LOST, event);
npc.script.callScript(EnumScriptType.TARGET_LOST, event);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static void onNPCCollide(EntityNPCInterface npc, Entity entity) {
@@ -376,7 +375,7 @@ public class EventHooks {
NpcEvent.CollideEvent event = new NpcEvent.CollideEvent(npc.wrappedNPC, entity);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.COLLIDE, event);
npc.script.callScript(EnumScriptType.COLLIDE, event, "entity", entity);
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCDamaged(EntityNPCInterface npc, NpcEvent.DamagedEvent event) {
@@ -385,7 +384,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.DAMAGED, event);
npc.script.callScript(EnumScriptType.DAMAGED, event);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static boolean onNPCKilled(EntityNPCInterface npc, NpcEvent.DiedEvent event) {
@@ -394,7 +393,7 @@ public class EventHooks {
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.KILLED, event);
npc.script.callScript(EnumScriptType.KILLED, event);
return NpcAPI.EVENT_BUS.post(event);
return NpcAPI.EVENT_BUS.post(event);
}
public static void onNPCTimer(EntityNPCInterface npc, int id) {
@@ -404,7 +403,7 @@ public class EventHooks {
NpcEvent.TimerEvent event = new NpcEvent.TimerEvent(npc.wrappedNPC, id);
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.TIMER, event);
npc.script.callScript(EnumScriptType.TIMER, event);
NpcAPI.EVENT_BUS.post(event);
NpcAPI.EVENT_BUS.post(event);
}
public static void onProjectileTick(EntityProjectile projectile) {
@@ -422,7 +421,7 @@ public class EventHooks {
EntityNPCInterface npc = (EntityNPCInterface) thrower;
npc.script.callScript(EnumScriptType.PROJECTILE_TICK, event);
}
}
}
NpcAPI.EVENT_BUS.post(event);
@@ -442,7 +441,7 @@ public class EventHooks {
EntityNPCInterface npc = (EntityNPCInterface) thrower;
npc.script.callScript(EnumScriptType.PROJECTILE_IMPACT, event);
}
}
}
NpcAPI.EVENT_BUS.post(event);
-1
View File
@@ -6,7 +6,6 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptUnit;
@@ -4,7 +4,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.StatCollector;
import noppes.npcs.entity.EntityNPCInterface;
import java.awt.*;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
@@ -36,7 +36,7 @@ public class ScriptForgeEventHandler {
@SubscribeEvent
public void forgeEntity(Event event) {
if (CustomNpcs.getServer() != null && ScriptController.Instance.forgeScripts.isEnabled()) {
if(FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT){
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) {
return;
}
@@ -62,7 +62,6 @@ import noppes.npcs.items.ItemNpcTool;
import noppes.npcs.quests.QuestItem;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.item.ScriptCustomizableItem;
import noppes.npcs.scripted.item.ScriptItemStack;
import static noppes.npcs.config.ConfigMain.TrackedQuestUpdateFrequency;
@@ -549,7 +548,7 @@ public class ScriptPlayerEventHandler {
if (event.source.getEntity() instanceof EntityPlayerMP) {
EntityPlayerMP playerMP = (EntityPlayerMP) event.source.getEntity();
if(playerMP.getHeldItem() != null) {
if (playerMP.getHeldItem() != null) {
IItemStack itemStack = NpcAPI.Instance().getIItemStack(playerMP.getHeldItem());
if (itemStack instanceof ScriptCustomizableItem) {
ScriptCustomizableItem sci = (ScriptCustomizableItem) itemStack;
@@ -51,7 +51,6 @@ import noppes.npcs.controllers.ServerCloneController;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.Line;
import noppes.npcs.controllers.data.LinkedItem;
import noppes.npcs.controllers.data.MarkData;
import noppes.npcs.controllers.data.Party;
import noppes.npcs.controllers.data.PlayerData;
@@ -60,7 +59,6 @@ import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestData;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.items.ItemExcalibur;
import noppes.npcs.items.ItemLinked;
import noppes.npcs.items.ItemShield;
import noppes.npcs.items.ItemSoulstoneEmpty;
import noppes.npcs.quests.QuestKill;
@@ -10,8 +10,8 @@ import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.WorldServer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.entity.EntityNPCInterface;
import noppes.npcs.controllers.data.action.ActionManager;
import noppes.npcs.entity.EntityNPCInterface;
public class ServerTickHandler {
@@ -28,8 +28,8 @@ import noppes.npcs.client.renderer.blocks.BlockScriptedRenderer;
import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.IScriptBlockHandler;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.entity.data.DataTimers;
import noppes.npcs.scripted.BlockScriptedWrapper;
@@ -39,8 +39,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class TileScripted extends TileEntity implements IScriptBlockHandler, IScriptHandlerPacket {
public List<IScriptUnit> scripts = new ArrayList<>();
@@ -449,7 +447,7 @@ public class TileScripted extends TileEntity implements IScriptBlockHandler, ISc
public List<IScriptUnit> getScripts() {
return scripts;
}
@SideOnly(Side.CLIENT)
@Override
@@ -1,5 +1,6 @@
package noppes.npcs.client;
import kamkeel.npcs.network.enums.EnumSyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.controllers.MusicController;
@@ -15,7 +16,6 @@ import noppes.npcs.controllers.data.AnimationData;
import noppes.npcs.controllers.data.Party;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.SkinOverlay;
import kamkeel.npcs.network.enums.EnumSyncType;
import noppes.npcs.util.CacheHashMap;
import java.util.EnumMap;
@@ -6,6 +6,8 @@ import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import kamkeel.npcs.addon.client.DBCClient;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.model.ModelBiped;
@@ -138,9 +140,6 @@ import noppes.npcs.client.renderer.RenderNpcCrystal;
import noppes.npcs.client.renderer.RenderNpcDragon;
import noppes.npcs.client.renderer.RenderNpcSlime;
import noppes.npcs.client.renderer.RenderProjectile;
import kamkeel.npcs.client.renderer.TelegraphRenderer;
import noppes.npcs.scripted.item.ScriptCustomItem;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphManager;
import noppes.npcs.client.renderer.blocks.BlockBannerRenderer;
import noppes.npcs.client.renderer.blocks.BlockBarrelRenderer;
import noppes.npcs.client.renderer.blocks.BlockBeamRenderer;
@@ -214,6 +213,7 @@ import noppes.npcs.entity.data.ModelPartData;
import noppes.npcs.items.ItemLinked;
import noppes.npcs.items.ItemNpcTool;
import noppes.npcs.items.ItemScripted;
import noppes.npcs.scripted.item.ScriptCustomItem;
import org.lwjgl.input.Keyboard;
import tconstruct.client.tabs.InventoryTabCustomNpc;
import tconstruct.client.tabs.InventoryTabVanilla;
@@ -635,7 +635,7 @@ public class ClientProxy extends CommonProxy {
return GuiScriptInterface.create(null, (TileScripted) tile);
}
@Override
public void spawnParticle(EntityLivingBase player, String string, Object... ob) {
@@ -5,11 +5,12 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphManager;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.packets.player.CheckPlayerValue;
import kamkeel.npcs.network.packets.player.InputDevicePacket;
import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket;
import kamkeel.npcs.network.packets.player.ScreenSizePacket;
import kamkeel.npcs.network.packets.player.SpecialKeyStatePacket;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
@@ -18,7 +19,6 @@ import net.minecraft.world.World;
import noppes.npcs.CustomNpcs;
import noppes.npcs.client.controllers.MusicController;
import noppes.npcs.client.controllers.ScriptSoundController;
import kamkeel.npcs.controllers.data.ability.telegraph.TelegraphManager;
import noppes.npcs.client.gui.hud.ClientHudManager;
import noppes.npcs.client.gui.hud.CompassHudComponent;
import noppes.npcs.client.gui.hud.EnumHudComponent;
@@ -11,7 +11,7 @@ import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
@@ -199,6 +199,7 @@ public class MusicController {
/**
* Stops a specific sound by its resource key.
* This is used to stop dialog sounds without affecting Bard music.
*
* @param soundKey The sound resource key to stop
*/
public void stopSound(String soundKey) {
@@ -5,34 +5,41 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.DataScript;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* NPC Script GUI - extends GuiScriptInterface but with unique behavior:
* - Uses scroll-based tab selection instead of top buttons
* - Shows settings/script toggle
* - Shows settings/script toggle
* - Uses DataScript with getNPCScript(index) access pattern
* - Has console filtering by hook type
*/
public class GuiScript extends GuiScriptInterface {
public boolean showScript = false;
public DataScript script;
private static int activeConsole = 0;
public GuiScript(EntityNPCInterface npc) {
super();
this.npc = npc;
@@ -40,7 +47,7 @@ public class GuiScript extends GuiScriptInterface {
this.handler = script;
this.useScrollTabs = true;
this.useSettingsToggle = true;
// Initialize hook list for NPC scripts
hookList.add("script.init");
hookList.add("script.update");
@@ -57,20 +64,20 @@ public class GuiScript extends GuiScriptInterface {
hookList.add("script.targetLost");
hookList.add("script.projectileTick");
hookList.add("script.projectileImpact");
NPCScriptPacket.Get();
}
@Override
protected ScriptContext getScriptContext() {
return ScriptContext.NPC;
}
@Override
protected int getActiveScriptIndex() {
return this.activeTab;
}
@Override
protected ScriptContainer getCurrentContainer() {
return script.getNPCScript(activeTab);
@@ -99,13 +106,13 @@ public class GuiScript extends GuiScriptInterface {
initSettingsView();
}
}
private void initScriptView() {
ScriptContainer container = getCurrentContainer();
// ==================== CALCULATE VIEWPORT BOUNDS ====================
int editorX, editorY, editorWidth, editorHeight;
if (isFullscreen) {
// Fullscreen: viewport fills screen with configured padding
FullscreenConfig.paddingTop = 30;
@@ -123,11 +130,11 @@ public class GuiScript extends GuiScriptInterface {
editorWidth = 239;
editorHeight = 208;
}
// ==================== HOOKS SCROLL (hidden in fullscreen) ====================
if (!isFullscreen) {
addLabel(new GuiNpcLabel(0, "script.hooks", guiLeft + 4, guiTop + 5));
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
hooks.setSize(68, 198);
hooks.guiLeft = guiLeft + 4;
@@ -142,28 +149,28 @@ public class GuiScript extends GuiScriptInterface {
GuiScriptTextArea activeArea = getActiveScriptArea();
if (activeArea == null) {
activeArea = new GuiScriptTextArea(this, 2, editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.script);
container == null ? "" : container.script);
activeArea.setListener(this);
this.closeOnEsc(activeArea::closeOnEsc);
textAreas.put(idx, activeArea);
} else {
activeArea.init(editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.script);
activeArea.init(editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.script);
}
activeArea.setLanguage(script.getLanguage());
activeArea.setScriptContext(getScriptContext());
// Setup fullscreen key binding
GuiScriptTextArea.KEYS.FULLSCREEN.setTask(e -> {
if (e.isPress()) {
toggleFullscreen();
}
});
activeArea.enableCodeHighlighting();
addTextField(activeArea);
// Initialize fullscreen button
int scrollbarOffset = activeArea.hasVerticalScrollbar() ? -8 : -2;
fullscreenButton.initGui(editorX + editorWidth, editorY, scrollbarOffset);
@@ -184,35 +191,35 @@ public class GuiScript extends GuiScriptInterface {
addScroll(scroll);
}
}
private void initSettingsView() {
addLabel(new GuiNpcLabel(0, "script.console", guiLeft + 4, guiTop + 16));
if (getTopButton(14) != null)
getTopButton(14).active = true;
GuiNpcTextArea consoleArea = new GuiNpcTextArea(2, this, guiLeft + 4, guiTop + 26, 226, 186, getConsoleText());
consoleArea.canEdit = false;
addTextField(consoleArea);
addButton(new GuiNpcButton(100, guiLeft + 232, guiTop + 170, 56, 20, "gui.copy"));
addButton(new GuiNpcButton(102, guiLeft + 232, guiTop + 192, 56, 20, "gui.clear"));
List<String> consoleOptions = new ArrayList<>();
consoleOptions.add("All");
consoleOptions.addAll(hookList);
addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20,
consoleOptions.toArray(new String[0]), activeConsole));
addButton(new GuiNpcButton(105, guiLeft + 60, guiTop + 4, 80, 20,
consoleOptions.toArray(new String[0]), activeConsole));
addLabel(new GuiNpcLabel(1, "script.language", guiLeft + 232, guiTop + 30));
List<String> languageOptions = getLanguageOptions();
addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20,
languageOptions.toArray(new String[0]), getLanguageIndex(languageOptions)));
addButton(new GuiNpcButton(103, guiLeft + 294, guiTop + 25, 80, 20,
languageOptions.toArray(new String[0]), getLanguageIndex(languageOptions)));
getButton(103).enabled = languageOptions.size() > 0;
addLabel(new GuiNpcLabel(2, "gui.enabled", guiLeft + 232, guiTop + 53));
addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20,
new String[]{"gui.no", "gui.yes"}, script.enabled ? 1 : 0));
addButton(new GuiNpcButton(104, guiLeft + 294, guiTop + 48, 50, 20,
new String[]{"gui.no", "gui.yes"}, script.enabled ? 1 : 0));
if (MinecraftServer.getServer() != null)
addButton(new GuiNpcButton(106, guiLeft + 232, guiTop + 71, 150, 20, "script.openfolder"));
@@ -280,12 +287,12 @@ public class GuiScript extends GuiScriptInterface {
NoppesStringUtils.setClipboardContents(getTextField(2).getText());
}
if (guibutton.id == 101) {
displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"),
StatCollector.translateToLocal("gui.sure"), 101));
displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"),
StatCollector.translateToLocal("gui.sure"), 101));
}
if (guibutton.id == 102) {
displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"),
StatCollector.translateToLocal("gui.sure"), 102));
displayGuiScreen(new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"),
StatCollector.translateToLocal("gui.sure"), 102));
}
if (guibutton.id == 103) {
script.scriptLanguage = ((GuiNpcButton) guibutton).displayString;
@@ -20,7 +20,7 @@ public class GuiScriptList extends SubGuiInterface {
public GuiScriptList(List<String> scripts, ScriptContainer container) {
this(scripts, (IScriptUnit) container);
}
public GuiScriptList(List<String> scripts, IScriptUnit scriptUnit) {
this.scriptUnit = scriptUnit;
setBackground("menubg.png");
@@ -8,7 +8,6 @@ import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.client.gui.global.GuiNPCManageEffects;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.EffectScript;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButtonYesNo;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -18,6 +17,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.EffectScript;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
@@ -36,7 +36,7 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Fields
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
// Current tab (10=Quest, 11=Dialog, 12=Transport, 13=Bank, 14=Faction, 15=Magic)
private int currentTab = 10;
@@ -99,7 +99,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
public SubGuiPlayerData(String playerName) {
this.playerName = playerName;
xSize = 420;
@@ -112,7 +113,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Layout Helpers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
private int getPaddedLeft() {
return guiLeft + leftPadding;
}
@@ -135,7 +137,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Component Setup Helpers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
private void setupTopButtons() {
// Show General Display Information
GuiMenuTopButton playerTab = new GuiMenuTopButton(-10, guiLeft + 4, guiTop - 10, playerName);
@@ -192,7 +195,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// initGui() & Tab Initialization
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void initGui() {
super.initGui();
@@ -489,7 +493,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Drawing Helpers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
@@ -525,7 +530,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Mouse & Resizing Handlers
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void mouseClicked(int mouseX, int mouseY, int mouseButton) {
int hitMargin = 3;
@@ -672,7 +678,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Key & Search Field Handling
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void keyTyped(char c, int i) {
super.keyTyped(c, i);
@@ -894,7 +901,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Action Handling
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void actionPerformed(GuiButton button) {
if (button.id == -5) {
@@ -1043,7 +1051,8 @@ public class SubGuiPlayerData extends SubGuiInterface implements IPlayerDataInfo
////////////////////////////////////////////////////////////////////////////////
// Data Setting Methods (IPlayerDataInfo)
////////////////////////////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////////////////////////////
@Override
public void setQuestData(Map<String, Integer> questCategories, Map<String, Integer> questActive, Map<String, Integer> questFinished) {
this.questCatData = new HashMap<>(questCategories);
@@ -10,7 +10,18 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNPCInterface2;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IScrollData;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.entity.EntityNPCInterface;
@@ -10,7 +10,14 @@ import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.select.GuiAnimationSelection;
import noppes.npcs.client.gui.select.GuiSoundSelection;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
@@ -18,13 +25,13 @@ import java.util.List;
/**
* Base SubGui for editing ability configuration with tabbed interface.
* Uses GuiMenuTopButton for navigation tabs.
*
* <p>
* Tabs:
* - General: Name, Weight, Lock Movement, Interruptible, Timing
* - Type: Type-specific settings per Ability (override in subclasses)
* - Target: Min/Max Range, Targeting Mode, Conditions (up to 3)
* - Effects: Sounds, Animations, Telegraph settings, Colors
*
* <p>
* Subclasses should override initTypeTab() and handleTypeButton()/handleTypeTextField()
* to provide type-specific settings UI.
*/
@@ -376,13 +383,13 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
String typeId = cond.getTypeId();
switch (typeId) {
case "hp_above":
return StatCollector.translateToLocal("condition.hp_above") + " " + (int)(getConditionThreshold(cond) * 100) + "%";
return StatCollector.translateToLocal("condition.hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "hp_below":
return StatCollector.translateToLocal("condition.hp_below") + " " + (int)(getConditionThreshold(cond) * 100) + "%";
return StatCollector.translateToLocal("condition.hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "target_hp_above":
return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int)(getConditionThreshold(cond) * 100) + "%";
return StatCollector.translateToLocal("condition.target_hp_above") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "target_hp_below":
return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int)(getConditionThreshold(cond) * 100) + "%";
return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%";
case "hit_count":
Condition.ConditionHitCount hitCount = (Condition.ConditionHitCount) cond;
return StatCollector.translateToLocal("condition.hit_count") + ": " + hitCount.getRequiredHits() + "/" + hitCount.getWithinTicks() + "t";
@@ -566,8 +573,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
// General tab buttons
else if (id == 14) {
interruptible = ((GuiNpcButton) guibutton).getValue() == 1;
}
else if (id == 16) {
} else if (id == 16) {
lockMovement = ((GuiNpcButton) guibutton).getValue() == 1;
}
@@ -619,12 +625,10 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
else if (id == 20) {
showTelegraph = ((GuiNpcButton) guibutton).getValue() == 1;
initGui();
}
else if (id == 22) {
} else if (id == 22) {
editingColorId = 22;
setSubGui(new SubGuiColorSelector(windUpColor));
}
else if (id == 24) {
} else if (id == 24) {
editingColorId = 24;
setSubGui(new SubGuiColorSelector(activeColor));
}
@@ -633,8 +637,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
else if (id == 30) {
editingSoundId = 30;
setSubGui(new GuiSoundSelection(windUpSound));
}
else if (id == 31) {
} else if (id == 31) {
editingSoundId = 31;
setSubGui(new GuiSoundSelection(activeSound));
}
@@ -642,8 +645,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
else if (id == 35) {
windUpSound = "";
initGui();
}
else if (id == 36) {
} else if (id == 36) {
activeSound = "";
initGui();
}
@@ -651,8 +653,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
else if (id == 32) {
editingAnimationId = 32;
setSubGui(new GuiAnimationSelection(windUpAnimationId));
}
else if (id == 33) {
} else if (id == 33) {
editingAnimationId = 33;
setSubGui(new GuiAnimationSelection(activeAnimationId));
}
@@ -661,8 +662,7 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi
windUpAnimationId = -1;
windUpAnimationName = null;
initGui();
}
else if (id == 38) {
} else if (id == 38) {
activeAnimationId = -1;
activeAnimationName = null;
initGui();
@@ -3,7 +3,11 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import java.util.ArrayList;
import java.util.List;
@@ -2,7 +2,11 @@ package noppes.npcs.client.gui.advanced;
import kamkeel.npcs.controllers.data.ability.Condition;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
/**
* SubGui for editing a single ability condition.
@@ -106,7 +110,7 @@ public class SubGuiConditionEdit extends SubGuiInterface implements ITextfieldLi
} else {
// HP threshold field (as percentage)
addLabel(new GuiNpcLabel(2, "condition.percent", labelX, y + 5));
int percent = (int)(threshold * 100);
int percent = (int) (threshold * 100);
GuiNpcTextField thresholdField = new GuiNpcTextField(4, this, fontRendererObj, fieldX, y, 40, 20, String.valueOf(percent));
thresholdField.setIntegersOnly();
thresholdField.setMinMaxDefault(1, 99, 50);
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityBeam;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Beam ability type-specific settings.
@@ -72,21 +72,39 @@ public class SubGuiAbilityBeam extends SubGuiAbilityConfig {
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 106: beam.setPiercing(value == 1); break;
case 107: beam.setLockOnTarget(value == 1); break;
case 108: beam.setSweepBackAndForth(value == 1); break;
case 106:
beam.setPiercing(value == 1);
break;
case 107:
beam.setLockOnTarget(value == 1);
break;
case 108:
beam.setSweepBackAndForth(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: beam.setDamage(parseFloat(field, beam.getDamage())); break;
case 101: beam.setDamageInterval(field.getInteger()); break;
case 102: beam.setBeamLength(parseFloat(field, beam.getBeamLength())); break;
case 103: beam.setBeamWidth(parseFloat(field, beam.getBeamWidth())); break;
case 104: beam.setSweepAngle(parseFloat(field, beam.getSweepAngle())); break;
case 105: beam.setSweepSpeed(parseFloat(field, beam.getSweepSpeed())); break;
case 100:
beam.setDamage(parseFloat(field, beam.getDamage()));
break;
case 101:
beam.setDamageInterval(field.getInteger());
break;
case 102:
beam.setBeamLength(parseFloat(field, beam.getBeamLength()));
break;
case 103:
beam.setBeamWidth(parseFloat(field, beam.getBeamWidth()));
break;
case 104:
beam.setSweepAngle(parseFloat(field, beam.getSweepAngle()));
break;
case 105:
beam.setSweepSpeed(parseFloat(field, beam.getSweepSpeed()));
break;
}
}
}
@@ -1,10 +1,10 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCharge;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Charge ability type-specific settings.
@@ -50,10 +50,18 @@ public class SubGuiAbilityCharge extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: charge.setDamage(parseFloat(field, charge.getDamage())); break;
case 101: charge.setChargeSpeed(parseFloat(field, charge.getChargeSpeed())); break;
case 102: charge.setKnockback(parseFloat(field, charge.getKnockback())); break;
case 104: charge.setHitWidth(parseFloat(field, charge.getHitWidth())); break;
case 100:
charge.setDamage(parseFloat(field, charge.getDamage()));
break;
case 101:
charge.setChargeSpeed(parseFloat(field, charge.getChargeSpeed()));
break;
case 102:
charge.setKnockback(parseFloat(field, charge.getKnockback()));
break;
case 104:
charge.setHitWidth(parseFloat(field, charge.getHitWidth()));
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCutter;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Cutter ability type-specific settings.
@@ -82,23 +82,45 @@ public class SubGuiAbilityCutter extends SubGuiAbilityConfig {
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 106: cutter.setSweepMode(AbilityCutter.SweepMode.values()[value]); break;
case 107: cutter.setPiercing(value == 1); break;
case 106:
cutter.setSweepMode(AbilityCutter.SweepMode.values()[value]);
break;
case 107:
cutter.setPiercing(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: cutter.setDamage(parseFloat(field, cutter.getDamage())); break;
case 101: cutter.setRange(parseFloat(field, cutter.getRange())); break;
case 102: cutter.setArcAngle(parseFloat(field, cutter.getArcAngle())); break;
case 103: cutter.setInnerRadius(parseFloat(field, cutter.getInnerRadius())); break;
case 104: cutter.setKnockback(parseFloat(field, cutter.getKnockback())); break;
case 105: cutter.setSweepSpeed(parseFloat(field, cutter.getSweepSpeed())); break;
case 108: cutter.setStunDuration(field.getInteger()); break;
case 109: cutter.setPoisonDurationSeconds(field.getInteger()); break;
case 110: cutter.setPoisonLevel(field.getInteger()); break;
case 100:
cutter.setDamage(parseFloat(field, cutter.getDamage()));
break;
case 101:
cutter.setRange(parseFloat(field, cutter.getRange()));
break;
case 102:
cutter.setArcAngle(parseFloat(field, cutter.getArcAngle()));
break;
case 103:
cutter.setInnerRadius(parseFloat(field, cutter.getInnerRadius()));
break;
case 104:
cutter.setKnockback(parseFloat(field, cutter.getKnockback()));
break;
case 105:
cutter.setSweepSpeed(parseFloat(field, cutter.getSweepSpeed()));
break;
case 108:
cutter.setStunDuration(field.getInteger());
break;
case 109:
cutter.setPoisonDurationSeconds(field.getInteger());
break;
case 110:
cutter.setPoisonLevel(field.getInteger());
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityDash;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Dash ability type-specific settings.
@@ -52,8 +52,12 @@ public class SubGuiAbilityDash extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101: dash.setDashDistance(parseFloat(field, dash.getDashDistance())); break;
case 102: dash.setDashSpeed(parseFloat(field, dash.getDashSpeed())); break;
case 101:
dash.setDashDistance(parseFloat(field, dash.getDashDistance()));
break;
case 102:
dash.setDashSpeed(parseFloat(field, dash.getDashSpeed()));
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Guard ability type-specific settings.
@@ -86,11 +86,21 @@ public class SubGuiAbilityGuard extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: guard.setDamageReduction(parseFloat(field, guard.getDamageReduction())); break;
case 103: guard.setCounterValue(parseFloat(field, guard.getCounterValue())); break;
case 104: guard.setCounterChance(parseFloat(field, guard.getCounterChance())); break;
case 105: guard.setCounterSound(field.getText()); break;
case 106: guard.setCounterAnimationId(field.getInteger()); break;
case 100:
guard.setDamageReduction(parseFloat(field, guard.getDamageReduction()));
break;
case 103:
guard.setCounterValue(parseFloat(field, guard.getCounterValue()));
break;
case 104:
guard.setCounterChance(parseFloat(field, guard.getCounterChance()));
break;
case 105:
guard.setCounterSound(field.getText());
break;
case 106:
guard.setCounterAnimationId(field.getInteger());
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHazard;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Hazard ability type-specific settings.
@@ -77,22 +77,42 @@ public class SubGuiAbilityHazard extends SubGuiAbilityConfig {
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 100: hazard.setShape(AbilityHazard.HazardShape.values()[value]); break;
case 101: hazard.setPlacement(AbilityHazard.PlacementMode.values()[value]); break;
case 109: hazard.setAffectsCaster(value == 1); break;
case 100:
hazard.setShape(AbilityHazard.HazardShape.values()[value]);
break;
case 101:
hazard.setPlacement(AbilityHazard.PlacementMode.values()[value]);
break;
case 109:
hazard.setAffectsCaster(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 102: hazard.setRadius(parseFloat(field, hazard.getRadius())); break;
case 103: hazard.setInnerRadius(parseFloat(field, hazard.getInnerRadius())); break;
case 104: hazard.setDamagePerTick(parseFloat(field, hazard.getDamagePerTick())); break;
case 105: hazard.setDamageInterval(field.getInteger()); break;
case 106: hazard.setSlownessLevel(field.getInteger()); break;
case 107: hazard.setDebuffDuration(field.getInteger()); break;
case 108: hazard.setPoisonLevel(field.getInteger()); break;
case 102:
hazard.setRadius(parseFloat(field, hazard.getRadius()));
break;
case 103:
hazard.setInnerRadius(parseFloat(field, hazard.getInnerRadius()));
break;
case 104:
hazard.setDamagePerTick(parseFloat(field, hazard.getDamagePerTick()));
break;
case 105:
hazard.setDamageInterval(field.getInteger());
break;
case 106:
hazard.setSlownessLevel(field.getInteger());
break;
case 107:
hazard.setDebuffDuration(field.getInteger());
break;
case 108:
hazard.setPoisonLevel(field.getInteger());
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeal;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Heal ability type-specific settings.
@@ -57,18 +57,30 @@ public class SubGuiAbilityHeal extends SubGuiAbilityConfig {
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 103: heal.setInstantHeal(value == 1); break;
case 104: heal.setHealSelf(value == 1); break;
case 105: heal.setHealAllies(value == 1); break;
case 103:
heal.setInstantHeal(value == 1);
break;
case 104:
heal.setHealSelf(value == 1);
break;
case 105:
heal.setHealAllies(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: heal.setHealAmount(parseFloat(field, heal.getHealAmount())); break;
case 101: heal.setHealPercent(parseFloat(field, heal.getHealPercent())); break;
case 102: heal.setHealRadius(parseFloat(field, heal.getHealRadius())); break;
case 100:
heal.setHealAmount(parseFloat(field, heal.getHealAmount()));
break;
case 101:
heal.setHealPercent(parseFloat(field, heal.getHealPercent()));
break;
case 102:
heal.setHealRadius(parseFloat(field, heal.getHealRadius()));
break;
}
}
}
@@ -1,10 +1,10 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Heavy Hit ability type-specific settings.
@@ -52,11 +52,21 @@ public class SubGuiAbilityHeavyHit extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: heavyHit.setDamage(parseFloat(field, heavyHit.getDamage())); break;
case 101: heavyHit.setPotionDurationSeconds(field.getInteger()); break;
case 102: heavyHit.setKnockback(parseFloat(field, heavyHit.getKnockback())); break;
case 103: heavyHit.setSlownessLevel(field.getInteger()); break;
case 104: heavyHit.setWeaknessLevel(field.getInteger()); break;
case 100:
heavyHit.setDamage(parseFloat(field, heavyHit.getDamage()));
break;
case 101:
heavyHit.setPotionDurationSeconds(field.getInteger());
break;
case 102:
heavyHit.setKnockback(parseFloat(field, heavyHit.getKnockback()));
break;
case 103:
heavyHit.setSlownessLevel(field.getInteger());
break;
case 104:
heavyHit.setWeaknessLevel(field.getInteger());
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityOrb;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Orb ability type-specific settings.
@@ -75,22 +75,42 @@ public class SubGuiAbilityOrb extends SubGuiAbilityConfig {
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104: orb.setHoming(value == 1); break;
case 106: orb.setExplosive(value == 1); break;
case 104:
orb.setHoming(value == 1);
break;
case 106:
orb.setExplosive(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: orb.setDamage(parseFloat(field, orb.getDamage())); break;
case 101: orb.setOrbSpeed(parseFloat(field, orb.getOrbSpeed())); break;
case 102: orb.setOrbSize(parseFloat(field, orb.getOrbSize())); break;
case 103: orb.setMaxDistance(parseFloat(field, orb.getMaxDistance())); break;
case 105: orb.setHomingStrength(parseFloat(field, orb.getHomingStrength())); break;
case 107: orb.setExplosionRadius(parseFloat(field, orb.getExplosionRadius())); break;
case 108: orb.setKnockback(parseFloat(field, orb.getKnockback())); break;
case 109: orb.setMaxLifetime(field.getInteger()); break;
case 100:
orb.setDamage(parseFloat(field, orb.getDamage()));
break;
case 101:
orb.setOrbSpeed(parseFloat(field, orb.getOrbSpeed()));
break;
case 102:
orb.setOrbSize(parseFloat(field, orb.getOrbSize()));
break;
case 103:
orb.setMaxDistance(parseFloat(field, orb.getMaxDistance()));
break;
case 105:
orb.setHomingStrength(parseFloat(field, orb.getHomingStrength()));
break;
case 107:
orb.setExplosionRadius(parseFloat(field, orb.getExplosionRadius()));
break;
case 108:
orb.setKnockback(parseFloat(field, orb.getKnockback()));
break;
case 109:
orb.setMaxLifetime(field.getInteger());
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Projectile ability type-specific settings.
@@ -79,19 +79,33 @@ public class SubGuiAbilityProjectile extends SubGuiAbilityConfig {
String[] projTypes = {"fireball", "arrow", "magic"};
projectile.setProjectileType(projTypes[value]);
break;
case 104: projectile.setExplosive(value == 1); break;
case 106: projectile.setHoming(value == 1); break;
case 104:
projectile.setExplosive(value == 1);
break;
case 106:
projectile.setHoming(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: projectile.setDamage(parseFloat(field, projectile.getDamage())); break;
case 101: projectile.setSpeed(parseFloat(field, projectile.getSpeed())); break;
case 102: projectile.setKnockback(parseFloat(field, projectile.getKnockback())); break;
case 105: projectile.setExplosionRadius(parseFloat(field, projectile.getExplosionRadius())); break;
case 107: projectile.setHomingStrength(parseFloat(field, projectile.getHomingStrength())); break;
case 100:
projectile.setDamage(parseFloat(field, projectile.getDamage()));
break;
case 101:
projectile.setSpeed(parseFloat(field, projectile.getSpeed()));
break;
case 102:
projectile.setKnockback(parseFloat(field, projectile.getKnockback()));
break;
case 105:
projectile.setExplosionRadius(parseFloat(field, projectile.getExplosionRadius()));
break;
case 107:
projectile.setHomingStrength(parseFloat(field, projectile.getHomingStrength()));
break;
}
}
}
@@ -1,10 +1,10 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Shockwave ability type-specific settings.
@@ -55,11 +55,21 @@ public class SubGuiAbilityShockwave extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: shockwave.setDamage(parseFloat(field, shockwave.getDamage())); break;
case 101: shockwave.setPushRadius(parseFloat(field, shockwave.getPushRadius())); break;
case 102: shockwave.setPushStrength(parseFloat(field, shockwave.getPushStrength())); break;
case 103: shockwave.setStunDuration(field.getInteger()); break;
case 104: shockwave.setMaxTargets(field.getInteger()); break;
case 100:
shockwave.setDamage(parseFloat(field, shockwave.getDamage()));
break;
case 101:
shockwave.setPushRadius(parseFloat(field, shockwave.getPushRadius()));
break;
case 102:
shockwave.setPushStrength(parseFloat(field, shockwave.getPushStrength()));
break;
case 103:
shockwave.setStunDuration(field.getInteger());
break;
case 104:
shockwave.setMaxTargets(field.getInteger());
break;
}
}
}
@@ -1,10 +1,10 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Slam ability type-specific settings.
@@ -52,11 +52,21 @@ public class SubGuiAbilitySlam extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: slam.setDamage(parseFloat(field, slam.getDamage())); break;
case 101: slam.setRadius(parseFloat(field, slam.getRadius())); break;
case 102: slam.setKnockbackStrength(parseFloat(field, slam.getKnockbackStrength())); break;
case 103: slam.setLeapSpeed(parseFloat(field, slam.getLeapSpeed())); break;
case 104: slam.setLeapHeight(parseFloat(field, slam.getLeapHeight())); break;
case 100:
slam.setDamage(parseFloat(field, slam.getDamage()));
break;
case 101:
slam.setRadius(parseFloat(field, slam.getRadius()));
break;
case 102:
slam.setKnockbackStrength(parseFloat(field, slam.getKnockbackStrength()));
break;
case 103:
slam.setLeapSpeed(parseFloat(field, slam.getLeapSpeed()));
break;
case 104:
slam.setLeapHeight(parseFloat(field, slam.getLeapHeight()));
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Teleport ability type-specific settings.
@@ -95,21 +95,39 @@ public class SubGuiAbilityTeleport extends SubGuiAbilityConfig {
teleport.setMode(AbilityTeleport.TeleportMode.values()[value]);
initGui();
break;
case 105: teleport.setRequireLineOfSight(value == 1); break;
case 108: teleport.setDamageAtStart(value == 1); break;
case 109: teleport.setDamageAtEnd(value == 1); break;
case 105:
teleport.setRequireLineOfSight(value == 1);
break;
case 108:
teleport.setDamageAtStart(value == 1);
break;
case 109:
teleport.setDamageAtEnd(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101: teleport.setBlinkRadius(parseFloat(field, teleport.getBlinkRadius())); break;
case 102: teleport.setBlinkCount(field.getInteger()); break;
case 103: teleport.setBlinkDelayTicks(field.getInteger()); break;
case 104: teleport.setBehindDistance(parseFloat(field, teleport.getBehindDistance())); break;
case 106: teleport.setDamage(parseFloat(field, teleport.getDamage())); break;
case 107: teleport.setDamageRadius(parseFloat(field, teleport.getDamageRadius())); break;
case 101:
teleport.setBlinkRadius(parseFloat(field, teleport.getBlinkRadius()));
break;
case 102:
teleport.setBlinkCount(field.getInteger());
break;
case 103:
teleport.setBlinkDelayTicks(field.getInteger());
break;
case 104:
teleport.setBehindDistance(parseFloat(field, teleport.getBehindDistance()));
break;
case 106:
teleport.setDamage(parseFloat(field, teleport.getDamage()));
break;
case 107:
teleport.setDamageRadius(parseFloat(field, teleport.getDamageRadius()));
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Trap ability type-specific settings.
@@ -79,14 +79,30 @@ public class SubGuiAbilityTrap extends SubGuiAbilityConfig {
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 101: trap.setTriggerRadius(parseFloat(field, trap.getTriggerRadius())); break;
case 102: trap.setDamage(parseFloat(field, trap.getDamage())); break;
case 103: trap.setDamageRadius(parseFloat(field, trap.getDamageRadius())); break;
case 104: trap.setArmTime(field.getInteger()); break;
case 105: trap.setMaxTriggers(field.getInteger()); break;
case 106: trap.setRootDuration(field.getInteger()); break;
case 107: trap.setStunDuration(field.getInteger()); break;
case 108: trap.setKnockback(parseFloat(field, trap.getKnockback())); break;
case 101:
trap.setTriggerRadius(parseFloat(field, trap.getTriggerRadius()));
break;
case 102:
trap.setDamage(parseFloat(field, trap.getDamage()));
break;
case 103:
trap.setDamageRadius(parseFloat(field, trap.getDamageRadius()));
break;
case 104:
trap.setArmTime(field.getInteger());
break;
case 105:
trap.setMaxTriggers(field.getInteger());
break;
case 106:
trap.setRootDuration(field.getInteger());
break;
case 107:
trap.setStunDuration(field.getInteger());
break;
case 108:
trap.setKnockback(parseFloat(field, trap.getKnockback()));
break;
}
}
}
@@ -1,11 +1,11 @@
package noppes.npcs.client.gui.advanced.ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
/**
* GUI for configuring Vortex ability type-specific settings.
@@ -75,22 +75,42 @@ public class SubGuiAbilityVortex extends SubGuiAbilityConfig {
protected void handleTypeButton(int id, GuiNpcButton button) {
int value = button.getValue();
switch (id) {
case 104: vortex.setAoe(value == 1); break;
case 108: vortex.setDamageOnPull(value == 1); break;
case 104:
vortex.setAoe(value == 1);
break;
case 108:
vortex.setDamageOnPull(value == 1);
break;
}
}
@Override
protected void handleTypeTextField(int id, GuiNpcTextField field) {
switch (id) {
case 100: vortex.setPullRadius(parseFloat(field, vortex.getPullRadius())); break;
case 101: vortex.setPullStrength(parseFloat(field, vortex.getPullStrength())); break;
case 102: vortex.setDamage(parseFloat(field, vortex.getDamage())); break;
case 103: vortex.setKnockback(parseFloat(field, vortex.getKnockback())); break;
case 105: vortex.setMaxTargets(field.getInteger()); break;
case 106: vortex.setStunDuration(field.getInteger()); break;
case 107: vortex.setRootDuration(field.getInteger()); break;
case 109: vortex.setPullDamage(parseFloat(field, vortex.getPullDamage())); break;
case 100:
vortex.setPullRadius(parseFloat(field, vortex.getPullRadius()));
break;
case 101:
vortex.setPullStrength(parseFloat(field, vortex.getPullStrength()));
break;
case 102:
vortex.setDamage(parseFloat(field, vortex.getDamage()));
break;
case 103:
vortex.setKnockback(parseFloat(field, vortex.getKnockback()));
break;
case 105:
vortex.setMaxTargets(field.getInteger());
break;
case 106:
vortex.setStunDuration(field.getInteger());
break;
case 107:
vortex.setRootDuration(field.getInteger());
break;
case 109:
vortex.setPullDamage(parseFloat(field, vortex.getPullDamage()));
break;
}
}
}
@@ -3,13 +3,21 @@ package noppes.npcs.client.gui.global;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import net.minecraft.client.gui.GuiButton;
import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig;
import noppes.npcs.client.gui.advanced.SubGuiAbilityDeleteConfirm;
import noppes.npcs.client.gui.advanced.SubGuiAbilityLoad;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNPCInterface2;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.IAbilityConfigCallback;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Global GUI for managing saved ability presets.
@@ -13,7 +13,6 @@ import noppes.npcs.client.CustomNpcResourceListener;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.SubGuiNpcAvailability;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.RecipeScript;
import noppes.npcs.client.gui.util.GuiButtonBiDirectional;
import noppes.npcs.client.gui.util.GuiContainerNPCInterface2;
import noppes.npcs.client.gui.util.GuiCustomScroll;
@@ -32,6 +31,7 @@ import noppes.npcs.constants.EnumScrollData;
import noppes.npcs.containers.ContainerManageRecipes;
import noppes.npcs.controllers.data.RecipeAnvil;
import noppes.npcs.controllers.data.RecipeCarpentry;
import noppes.npcs.controllers.data.RecipeScript;
import noppes.npcs.entity.EntityNPCInterface;
import org.lwjgl.opengl.GL11;
@@ -13,7 +13,6 @@ import noppes.npcs.client.CustomNpcResourceListener;
import noppes.npcs.client.gui.SubGuiColorSelector;
import noppes.npcs.client.gui.global.GuiNPCManageLinked;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.controllers.data.LinkedItemScript;
import noppes.npcs.client.gui.util.GuiButtonBiDirectional;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
@@ -26,6 +25,7 @@ import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.client.renderer.ImageData;
import noppes.npcs.controllers.data.LinkedItem;
import noppes.npcs.controllers.data.LinkedItemScript;
import org.lwjgl.opengl.GL11;
public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListener, GuiYesNoCallback, ISubGuiListener {
@@ -120,8 +120,8 @@ public class SubGuiLinkedItem extends SubGuiInterface implements ITextfieldListe
GuiNpcTextField digSpeedField = new GuiNpcTextField(12, this, x + 110, y, 50, 20, "" + linkedItem.digSpeed);
digSpeedField.setIntegersOnly().setMinMaxDefault(0, 20, 1);
addTextField(digSpeedField);
GuiNpcTextField attackSpeedField = new GuiNpcTextField(14, this, x +165, y, 50, 20, "" +linkedItem.attackSpeed);
attackSpeedField.setIntegersOnly().setMinMaxDefault(0,999999999,20);
GuiNpcTextField attackSpeedField = new GuiNpcTextField(14, this, x + 165, y, 50, 20, "" + linkedItem.attackSpeed);
attackSpeedField.setIntegersOnly().setMinMaxDefault(0, 999999999, 20);
addTextField(attackSpeedField);
y += spacing;
@@ -9,11 +9,11 @@ import net.minecraft.client.gui.GuiButton;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.NoppesUtil;
import noppes.npcs.client.gui.advanced.GuiNPCAbilities;
import noppes.npcs.client.gui.advanced.GuiNPCAdvancedLinkedNpc;
import noppes.npcs.client.gui.advanced.GuiNPCDialogNpcOptions;
import noppes.npcs.client.gui.advanced.GuiNPCFactionSetup;
import noppes.npcs.client.gui.advanced.GuiNPCLinesMenu;
import noppes.npcs.client.gui.advanced.GuiNPCAbilities;
import noppes.npcs.client.gui.advanced.GuiNPCMagic;
import noppes.npcs.client.gui.advanced.GuiNPCMarks;
import noppes.npcs.client.gui.advanced.GuiNPCNightSetup;
@@ -25,8 +25,8 @@ import noppes.npcs.client.gui.roles.GuiNpcConversation;
import noppes.npcs.client.gui.roles.GuiNpcFollowerJob;
import noppes.npcs.client.gui.roles.GuiNpcGuard;
import noppes.npcs.client.gui.roles.GuiNpcHealer;
import noppes.npcs.client.gui.roles.GuiNpcSpawner;
import noppes.npcs.client.gui.roles.GuiNpcMount;
import noppes.npcs.client.gui.roles.GuiNpcSpawner;
import noppes.npcs.client.gui.roles.GuiNpcTransporter;
import noppes.npcs.client.gui.util.GuiNPCInterface2;
import noppes.npcs.client.gui.util.GuiNpcButton;
@@ -105,7 +105,7 @@ public class EventGuiScriptList extends SubGuiInterface {
public List<String> getScripts() {
return this.container.getExternalScripts();
}
public void save() {
}
}
@@ -1,17 +1,38 @@
package noppes.npcs.client.gui.script;
import noppes.npcs.janino.JaninoScript;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.*;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.util.StatCollector;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.gui.util.*;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuTopButton;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
import noppes.npcs.client.gui.util.GuiNpcTextArea;
import noppes.npcs.client.gui.util.GuiScriptTextArea;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.ISubGuiListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.janino.JaninoScript;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback, ITextChangeListener, ICustomScrollListener, ISubGuiListener {
@@ -21,7 +42,7 @@ public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback
public List<String> allExternalScripts = new ArrayList<>();
private final int scriptLimit = 1;
public String previousHookClicked = "";
// GUI display list
List<String> hooklist = new ArrayList<>();
@@ -83,6 +104,7 @@ public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback
}
}
}
public void initGui() {
this.ySize = (int) ((double) this.xSize * 0.56);
if ((double) this.ySize > (double) this.height * 0.95) {
@@ -95,7 +117,7 @@ public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback
this.guiTop += 10;
int yoffset = (int) ((double) this.ySize * 0.02);
GuiMenuTopButton top;
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize-2 , guiTop - 17, "X"));
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 2, guiTop - 17, "X"));
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
int topXoffset = 0;
int topYoffset = 0;
@@ -135,7 +157,7 @@ public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback
textArea.setListener(this);
this.closeOnEsc(textArea::closeOnEsc);
this.addTextField(textArea);
int left1 = this.guiLeft + this.xSize - 104;
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
@@ -1,7 +1,7 @@
package noppes.npcs.client.gui.script;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.DataScript;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.entity.EntityNPCInterface;
public class GuiNPCEventScripts extends GuiScriptInterface {
@@ -1,7 +1,11 @@
package noppes.npcs.client.gui.script;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.*;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiConfirmOpenLink;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiYesNo;
import net.minecraft.client.gui.GuiYesNoCallback;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.StatCollector;
@@ -21,13 +25,13 @@ import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.IJTextAreaListener;
import noppes.npcs.client.gui.util.ITextChangeListener;
import noppes.npcs.client.gui.util.ITextfieldListener;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.data.ForgeDataScript;
import noppes.npcs.controllers.data.IScriptHandler;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.controllers.data.IScriptHandlerPacket;
import noppes.npcs.controllers.data.IScriptUnit;
import noppes.npcs.scripted.item.ScriptCustomItem;
import org.lwjgl.opengl.Display;
@@ -50,15 +54,21 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
protected Map<Integer, GuiScriptTextArea> textAreas = new HashMap<>();
protected GuiScreen parent;
/** If true, uses scroll-based tab selection instead of top buttons */
/**
* If true, uses scroll-based tab selection instead of top buttons
*/
protected boolean useScrollTabs = false;
/** If true, shows settings/script toggle instead of numbered tabs */
protected boolean useSettingsToggle = false;
/**
* If true, shows settings/script toggle instead of numbered tabs
*/
protected boolean useSettingsToggle = false;
// ==================== FULLSCREEN MODE ====================
/** Whether the editor viewport is currently in fullscreen mode */
/**
* Whether the editor viewport is currently in fullscreen mode
*/
public static boolean isFullscreen = false;
/**
@@ -67,19 +77,29 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
* All padding values are in scaled GUI pixels.
*/
public static class FullscreenConfig {
/** Padding from the top edge of the screen */
/**
* Padding from the top edge of the screen
*/
public static int paddingTop = 20;
/** Padding from the bottom edge of the screen */
/**
* Padding from the bottom edge of the screen
*/
public static int paddingBottom = 20;
/** Padding from the left edge of the screen */
/**
* Padding from the left edge of the screen
*/
public static int paddingLeft = 20;
/** Padding from the right edge of the screen */
/**
* Padding from the right edge of the screen
*/
public static int paddingRight = 20;
}
/** Fullscreen toggle button drawn at top-right of viewport */
/**
* Fullscreen toggle button drawn at top-right of viewport
*/
public final FullscreenButton fullscreenButton = new FullscreenButton();
public GuiScriptInterface() {
this.drawDefaultBackground = true;
this.closeOnEsc = true;
@@ -150,7 +170,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
topXoffset -= top.width + 20 * 22;
}
this.addTopButton(top = new GuiMenuTopButton(ta + 1, top.xPosition + top.width + topXoffset,
top.yPosition + topYoffset, ta + 1 + ""));
top.yPosition + topYoffset, ta + 1 + ""));
topXoffset = 0;
topYoffset = 0;
scriptLimit = ta + 2;
@@ -159,8 +179,8 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
if (isSingle && handler.getSingleScript() != null)
this.addTopButton(
top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset,
"Script"));
top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset,
"Script"));
else if (this.handler.getScripts().size() < 100)
this.addTopButton(new GuiMenuTopButton(scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
@@ -241,15 +261,15 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
GuiScriptTextArea activeArea = getActiveScriptArea();
if (activeArea == null) {
activeArea = new GuiScriptTextArea(this, 2, editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.getScript());
container == null ? "" : container.getScript());
activeArea.setListener(this);
this.closeOnEsc(activeArea::closeOnEsc);
textAreas.put(idx, activeArea);
} else {
activeArea.init(editorX, editorY, editorWidth, editorHeight,
container == null ? "" : container.getScript());
container == null ? "" : container.getScript());
}
// Set the scripting language for proper syntax highlighting
// Use the container's language if available, otherwise fall back to handler's language
String language = (container != null) ? container.getLanguage() : this.handler.getLanguage();
@@ -279,12 +299,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy"));
this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove"));
// Language toggle button (only if handler supports Janino and there is more than one option)
if (handler.supportsJanino() && getLanguageOptions().size() > 1 && container != null) {
this.addButton(new GuiNpcButton(113, left1, this.guiTop + 42 + yoffset, 121, 20, container.getLanguage()));
}
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
@@ -303,7 +323,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
*/
private void initSettingsTab(int yoffset) {
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset,
this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
var8.canEdit = false;
var8.setFocused(true);
this.addTextField(var8);
@@ -319,7 +339,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
this.getButton(103).enabled = languageOptions.size() > 0;
this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36));
this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20,
new String[]{"gui.no", "gui.yes"}, this.handler.getEnabled() ? 1 : 0));
new String[]{"gui.no", "gui.yes"}, this.handler.getEnabled() ? 1 : 0));
if (this.player.worldObj.isRemote) {
this.addButton(new GuiNpcButton(106, var9, this.guiTop + 55, 150, 20, "script.openfolder"));
@@ -382,11 +402,11 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
IScriptUnit container = getCurrentContainer();
if (container == null)
return;
String addString = "";
if (!this.getTextField(2).getText().isEmpty())
addString += "\n";
// Generate the appropriate stub based on language
// hook is already the proper method name from EnumScriptType.function
addString += container.generateHookStub(hook, null);
@@ -525,7 +545,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return textAreas.get(idx);
return null;
}
/**
* Get the current script index for text area storage.
* Override in subclasses with different tab logic.
@@ -533,7 +553,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
protected int getActiveScriptIndex() {
return this.activeTab - 1;
}
/**
* Get the current script container.
* Override in subclasses with different container access patterns.
@@ -642,14 +662,14 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
String language = container != null ? container.getLanguage() : this.handler.getLanguage();
this.setSubGui(new EventGuiScriptList((List) this.languages.get(language), container));
}
// Language toggle button - switch between ECMAScript and Java
if (guibutton.id == 113) {
int idx = getActiveScriptIndex();
if (idx >= 0 && idx < handler.getScripts().size()) {
IScriptUnit currentUnit = handler.getScripts().get(idx);
IScriptUnit newUnit;
if (currentUnit.isJanino()) {
// Switch from Java to ECMAScript
newUnit = new ScriptContainer(handler);
@@ -669,7 +689,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
handler.replaceScriptUnit(idx, newUnit);
// Clear the cached text area so it recreates with new language
textAreas.remove(idx);
// Reinitialize the GUI
initGui();
}
@@ -712,7 +732,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
}
return;
}
loadLanguagesData(compound);
}
@@ -759,7 +779,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
return;
this.setScript();
if (handler instanceof IScriptHandlerPacket)
((IScriptHandlerPacket) handler).sync();
@@ -790,7 +810,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
IScriptUnit current = getCurrentContainer();
if (current != null)
current.ensureCompiled();
if (parent != null) {
this.save();
parent.setWorldAndResolution(mc, width, height);
@@ -838,14 +858,18 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
public int size = 12;
public boolean hovered = false;
/** Initialize button position relative to viewport bounds */
/**
* Initialize button position relative to viewport bounds
*/
public void initGui(int viewportEndX, int viewportY, int scrollbarOffset) {
// Position at top-right, accounting for scrollbar
this.x = viewportEndX + scrollbarOffset - size - 4;
this.y = viewportY + 4;
}
/** Draw the fullscreen toggle button */
/**
* Draw the fullscreen toggle button
*/
public void draw(int mouseX, int mouseY) {
hovered = isMouseOver(mouseX, mouseY);
int y = this.y + getYOffset();
@@ -877,7 +901,7 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
drawRect(right, bottom, right + cornerLen, bottom + 1, iconColor);
drawRect(right, bottom, right + 1, bottom + cornerLen, iconColor);
} else {
// Draw expand icon (corners pointing outward) ⌐¬⌙⌞
// Top-left corner pointing outward
@@ -891,23 +915,27 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
drawRect(x + inset, y + size - inset - 1, x + inset + cornerLen, y + size - inset, iconColor);
// Bottom-right corner pointing outward
drawRect(x + size - inset - 1, y + size - inset - cornerLen, x + size - inset, y + size - inset,
iconColor);
iconColor);
drawRect(x + size - inset - cornerLen, y + size - inset - 1, x + size - inset, y + size - inset,
iconColor);
iconColor);
}
}
public void drawRect(int x1, int y1, int x2, int y2, int color) {
GuiUtil.drawRectD(x1, y1, x2, y2, color);
}
/** Check if mouse is over the button */
/**
* Check if mouse is over the button
*/
public boolean isMouseOver(int mouseX, int mouseY) {
int y = this.y + getYOffset();
return mouseX >= x && mouseX < x + size && mouseY >= y && mouseY < y + size;
}
/** Handle click - returns true if click was consumed */
/**
* Handle click - returns true if click was consumed
*/
public boolean mouseClicked(int mouseX, int mouseY, int button) {
if (button == 0 && isMouseOver(mouseX, mouseY)) {
toggleFullscreen();
@@ -42,7 +42,7 @@ public class SubGuiSelectList extends SubGuiInterface {
scroll1.setSize(140, 180);
}
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize-22 , guiTop - 17, "X"));
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 22, guiTop - 17, "X"));
scroll1.guiLeft = guiLeft + 4;
scroll1.guiTop = guiTop + 14;
@@ -371,6 +371,7 @@ public class GuiTextureSelection extends SubGuiInterface implements ICustomScrol
selectedDomain = domain;
this.location = location;
}
static class TextureData {
String domain;
String absoluteName;
@@ -9,7 +9,7 @@ import noppes.npcs.constants.EnumDiagramLayout;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -109,7 +109,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
//Important for GuiScriptTextArea
for (GuiNpcTextField tf : textfields.values())
tf.initGui();
tf.initGui();
}
@Override
@@ -208,6 +208,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
}
}
}
@Override
public void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) {
if (subgui != null) {
@@ -286,7 +287,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
}
public void close() {
if(GuiNpcTextField.activeTextfield != null)
if (GuiNpcTextField.activeTextfield != null)
GuiNpcTextField.unfocus();
Keyboard.enableRepeatEvents(false);
@@ -537,6 +538,7 @@ public abstract class GuiNPCInterface extends GuiScreen {
public void drawNpcWithExtras(EntityLivingBase entity, int mouseX, int mouseY, float partialTicks) {
drawNpc(entity, mouseX, mouseY, partialTicks);
}
public void drawNpc(EntityLivingBase entity, int mouseX, int mouseY, float partialTicks) {
if (hasSubGui() && !drawNPConSub)
return;
@@ -126,6 +126,7 @@ public class GuiNpcButton extends GuiButton {
}
public AtomicBoolean rightClicked = new AtomicBoolean();
@Override
public boolean mousePressed(Minecraft minecraft, int i, int j) {
boolean bo = super.mousePressed(minecraft, i, j);
@@ -38,10 +38,10 @@ public class GuiNpcTextField extends GuiTextField {
public GuiNpcTextField(int id, GuiScreen parent, int i, int j, int k, int l, String s) {
this(id, parent, Minecraft.getMinecraft().fontRenderer, i, j, k, l, s);
}
public void initGui() {
}
protected boolean charAllowed(char c, int i) {
if (!integersOnly || Character.isDigit(c))
return true;
@@ -8,8 +8,17 @@ import noppes.npcs.NoppesStringUtils;
import noppes.npcs.client.ClientProxy;
import noppes.npcs.client.gui.script.GuiScriptInterface;
import noppes.npcs.client.gui.util.key.OverlayKeyPresetViewer;
import noppes.npcs.client.gui.util.script.*;
import noppes.npcs.client.gui.util.script.BracketMatcher;
import noppes.npcs.client.gui.util.script.CommentHandler;
import noppes.npcs.client.gui.util.script.CursorNavigation;
import noppes.npcs.client.gui.util.script.GoToLineDialog;
import noppes.npcs.client.gui.util.script.IndentHelper;
import noppes.npcs.client.gui.util.script.JavaTextContainer;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import noppes.npcs.client.gui.util.script.RenameRefactorHandler;
import noppes.npcs.client.gui.util.script.ScrollState;
import noppes.npcs.client.gui.util.script.SearchReplaceBar;
import noppes.npcs.client.gui.util.script.SelectionState;
import noppes.npcs.client.key.impl.ScriptEditorKeys;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.util.ValueUtil;
@@ -27,7 +36,7 @@ import static net.minecraft.client.gui.GuiScreen.isCtrlKeyDown;
/**
* Script text editor component with syntax highlighting, bracket matching,
* smooth scrolling, and IDE-like features.
*
* <p>
* Helper classes used:
* - ScrollState: smooth scroll animation and state management
* - SelectionState: cursor position and text selection management
@@ -37,11 +46,11 @@ import static net.minecraft.client.gui.GuiScreen.isCtrlKeyDown;
* - CursorNavigation: cursor movement logic
*/
public class GuiScriptTextArea extends GuiNpcTextField {
// ==================== DIMENSIONS & POSITION ====================
public int x;
public int y;
// ==================== STATE FLAGS ====================
public boolean active = false;
public boolean enabled = true;
@@ -51,7 +60,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
public boolean tripleClicked = false;
private int clickCount = 0;
private long lastClicked = 0L;
// ==================== TEXT & CONTAINER ====================
public String text = null;
public String highlightedWord;
@@ -80,12 +89,12 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// ==================== HELPER CLASS INSTANCES ====================
private final ScrollState scroll = new ScrollState();
private final SelectionState selection = new SelectionState();
// ==================== UI COMPONENTS ====================
private int cursorCounter;
private ITextChangeListener listener;
private static int LINE_NUMBER_GUTTER_WIDTH = 25;
// ==================== UNDO/REDO ====================
public List<UndoData> undoList = new ArrayList<>();
public List<UndoData> redoList = new ArrayList<>();
@@ -97,7 +106,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// ==================== SEARCH/REPLACE ====================
public static final SearchReplaceBar searchBar = new SearchReplaceBar();
// ==================== GO TO LINE ====================
private final GoToLineDialog goToLineDialog = new GoToLineDialog();
@@ -125,11 +134,12 @@ public class GuiScriptTextArea extends GuiNpcTextField {
this.searchBaseHeight = 0;
this.searchAppliedOffset = 0;
this.searchBaseInitialized = false;
KEYS_OVERLAY.openOnClick = true;
initGui();
initializeKeyBindings();
}
public void initGui() {
int endX = x + width, endY = y + height;
int xOffset = hasVerticalScrollbar() ? -8 : -2;
@@ -137,11 +147,11 @@ public class GuiScriptTextArea extends GuiNpcTextField {
KEYS_OVERLAY.borderCol1 = KEYS_OVERLAY.borderCol2 = 0xFF3c3c3c;
int overlayWidth = 160;
KEYS_OVERLAY.initGui(x + (width - overlayWidth) / 2 + 5, y + height / 10, overlayWidth,
height - height / 5 - 10);
height - height / 5 - 10);
KEYS_OVERLAY.viewButton.scale = 0.45f;
KEYS_OVERLAY.viewButton.initGui(endX + xOffset, endY - 26);
// Initialize search bar (preserves state across initGui calls)
searchBar.initGui(x, y, width);
if (searchBar.isVisible()) { // If open
@@ -150,7 +160,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
if (!active) // Focus search if opening another script tab & bar is open
searchBar.focus(false);
}
// Initialize Go To Line dialog
goToLineDialog.initGui(x, y, width);
}
@@ -193,7 +203,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
int visibleLines = effectiveHeight / container.lineHeight;
// Calculate how many lines the search bar covers
int linesHiddenBySRB = searchBarOffset > 0 ? (int) Math.ceil(
(double) searchBarOffset / container.lineHeight) : 0;
(double) searchBarOffset / container.lineHeight) : 0;
for (int i = 0; i < container.lines.size(); i++) {
LineData ld = container.lines.get(i);
@@ -457,12 +467,13 @@ public class GuiScriptTextArea extends GuiNpcTextField {
}
}
}
// ==================== RENDERING ====================
public void drawTextBox(int xMouse, int yMouse) {
if (!visible)
return;
clampSelectionBounds();
// Dynamically calculate gutter width based on line count digits
if (container != null && container.linesCount > 0) {
int maxLineNum = container.linesCount;
@@ -473,7 +484,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// Draw outer border around entire area
int offset = fullscreen() ? 2 : 1;
drawRect(x - offset, y - offset - searchBar.getTotalHeight(), x + width + offset, y + height + offset,
0xffa0a0a0);
0xffa0a0a0);
int searchHeight = searchBar.getTotalHeight();
@@ -483,7 +494,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// Draw text viewport background (starts after gutter)
drawRect(x + LINE_NUMBER_GUTTER_WIDTH, y, x + width, y + height, 0xff000000);
// Draw separator line between gutter and text area
drawRect(x + LINE_NUMBER_GUTTER_WIDTH-1, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, 0xff3c3f41);
drawRect(x + LINE_NUMBER_GUTTER_WIDTH - 1, y, x + LINE_NUMBER_GUTTER_WIDTH, y + height, 0xff3c3f41);
// Enable scissor test to clip drawing to the TEXT viewport rectangle (excludes gutter)
GL11.glEnable(GL11.GL_SCISSOR_TEST);
@@ -509,7 +520,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// Handle scrollbar dragging (delegated to ScrollState)
if (scroll.isClickScrolling())
scroll.handleClickScrolling(yMouse, x, y, height, container.visibleLines, getPaddedLineCount(), maxScroll);
// Update scroll animation
scroll.initializeIfNeeded(scroll.getScrolledLine());
scroll.update(maxScroll);
@@ -535,8 +546,8 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// Calculate braces next to cursor to highlight
int startBracket = 0, endBracket = 0;
if (selection.getStartSelection() >= 0 && text != null && text.length() > 0 &&
(selection.getEndSelection() - selection.getStartSelection() == 1 || !selection.hasSelection())) {
int[] span = BracketMatcher.findBracketSpanAt(text,selection.getStartSelection());
(selection.getEndSelection() - selection.getStartSelection() == 1 || !selection.hasSelection())) {
int[] span = BracketMatcher.findBracketSpanAt(text, selection.getStartSelection());
if (span != null) {
startBracket = span[0];
endBracket = span[1];
@@ -544,12 +555,12 @@ public class GuiScriptTextArea extends GuiNpcTextField {
}
List<JavaTextContainer.LineData> list = new ArrayList<>(container.lines);
// Build brace spans: {origDepth, open line, close line, adjustedDepth}
List<int[]> braceSpans = BracketMatcher.computeBraceSpans(text, list);
// Always highlight unmatched braces (positions in text)
List<Integer> unmatchedBraces = BracketMatcher.findUnmatchedBracePositions(text);
// Determine which exact brace span (openLine/closeLine) to highlight indent guides for
int highlightedOpenLine = -1;
int highlightedCloseLine = -1;
@@ -618,19 +629,19 @@ public class GuiScriptTextArea extends GuiNpcTextField {
float fracPixels = (float) (fracOffset * container.lineHeight);
GL11.glPushMatrix();
GL11.glTranslatef(0.0f, -fracPixels, 0.0f);
// Expand render range by one line above/below so partially-visible lines are drawn
int renderStart = Math.max(0, scroll.getScrolledLine() - 1);
// Compute the last line index to render, including the last partially-visible line if any.
// Adds the fractional scroll offset (fracOffset * lineHeight) to ensure the bottom line is drawn
// when only part of it is visible in the viewport.
int renderEnd = (int) Math.min(list.size() - 1,
scroll.getScrolledLine() + container.visibleLines + fracPixels + 1);
scroll.getScrolledLine() + container.visibleLines + fracPixels + 1);
// Strings start drawing vertically this much into the line.
int stringYOffset = 2;
// Render LINE GUTTER numbers
for (int i = renderStart; i <= renderEnd; i++) {
int posY = y + (i - scroll.getScrolledLine()) * container.lineHeight + stringYOffset;
@@ -698,7 +709,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
}
}
}
// Highlight search matches
if (searchBar.isVisible()) {
List<int[]> searchMatches = searchBar.getMatches();
@@ -747,8 +758,8 @@ public class GuiScriptTextArea extends GuiNpcTextField {
if (occStart <= occEnd) { // Changed from < to <= to handle empty case
int s = ClientProxy.Font.width(line.substring(0, occStart));
int e = isEmpty ? s + 2 : ClientProxy.Font.width(
line.substring(0, occEnd)) + 1; // 2px wide for empty
int occX = x + LINE_NUMBER_GUTTER_WIDTH + s;
line.substring(0, occEnd)) + 1; // 2px wide for empty
int occX = x + LINE_NUMBER_GUTTER_WIDTH + s;
int occEndX = x + LINE_NUMBER_GUTTER_WIDTH + 2 + e;
boolean isPrimary = renameHandler.isPrimaryOccurrence(occ[0]);
@@ -761,12 +772,12 @@ public class GuiScriptTextArea extends GuiNpcTextField {
int borderColor = 0xDDFFFFFF;
//RED BG
drawRect(occX, posY, occEndX, posY + container.lineHeight, 0x33ff0000);
// Top border
drawRect(occX, posY, occEndX, posY + 1, borderColor);
// Bottom border
// Bottom border
drawRect(occX, posY + container.lineHeight - 1, occEndX,
posY + container.lineHeight, borderColor);
posY + container.lineHeight, borderColor);
// Left border
drawRect(occX, posY, occX + 1, posY + container.lineHeight, borderColor);
// Right border
@@ -778,7 +789,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
String currentWord = renameHandler.getCurrentWord();
if (currentWord != null && cursorInWord >= 0 && cursorInWord <= currentWord.length()) {
String beforeCursor = currentWord.substring(0,
Math.min(cursorInWord, currentWord.length()));
Math.min(cursorInWord, currentWord.length()));
int cursorX = occX + ClientProxy.Font.width(beforeCursor);
// drawRect(cursorX, posY + 1, cursorX + 1, posY + container.lineHeight - 1,
// 0xFFFFFFFF);
@@ -789,18 +800,18 @@ public class GuiScriptTextArea extends GuiNpcTextField {
}
}
}
// Highlight the current line (light gray) under any selection
if (active && isEnabled() && (selection.getCursorPosition() >= data.start && selection.getCursorPosition() < data.end || (i == list.size() - 1 && selection.getCursorPosition() == text.length()))) {
drawRect(x , posY, x + width - 1, posY + container.lineHeight, 0x22e0e0e0);
drawRect(x, posY, x + width - 1, posY + container.lineHeight, 0x22e0e0e0);
}
// Highlight selection
if (selection.hasSelection() && selection.getEndSelection() > data.start && selection.getStartSelection() <= data.end) {
if (selection.getStartSelection() < data.end) {
int s = ClientProxy.Font.width(
line.substring(0, Math.max(selection.getStartSelection() - data.start, 0)));
line.substring(0, Math.max(selection.getStartSelection() - data.start, 0)));
int e = ClientProxy.Font.width(
line.substring(0, Math.min(selection.getEndSelection() - data.start, w))) + 1;
line.substring(0, Math.min(selection.getEndSelection() - data.start, w))) + 1;
drawRect(x + LINE_NUMBER_GUTTER_WIDTH + 1 + s, posY, x + LINE_NUMBER_GUTTER_WIDTH + 1 + e, posY + container.lineHeight, 0x992172ff);
}
}
@@ -837,11 +848,11 @@ public class GuiScriptTextArea extends GuiNpcTextField {
boolean highlighted = (openLine == highlightedOpenLine && closeLine == highlightedCloseLine);
int guideColor = highlighted ? 0x9933cc00 : 0x33FFFFFF;
int topY = y + (drawStart - scroll.getScrolledLine()) * container.lineHeight;
int bottomY = y + (endLine - scroll.getScrolledLine() + 1) * container.lineHeight;
if(highlighted)
bottomY-=2;
if (highlighted)
bottomY -= 2;
drawRect(gx, topY, gx + 1, bottomY, guideColor);
}
}
@@ -852,15 +863,15 @@ public class GuiScriptTextArea extends GuiNpcTextField {
boolean recentInput = selection.hadRecentInput();
if (active && isEnabled() && (recentInput || (cursorCounter / 10) % 2 == 0) && (selection.getCursorPosition() >= data.start && selection.getCursorPosition() < data.end || (i == list.size() - 1 && selection.getCursorPosition() == text.length()))) {
int posX = x + LINE_NUMBER_GUTTER_WIDTH + ClientProxy.Font.width(
line.substring(0, Math.min(selection.getCursorPosition() - data.start, line.length())));
drawRect(posX + 1, posY, posX + 2, posY + container.lineHeight, 0xffffffff);
line.substring(0, Math.min(selection.getCursorPosition() - data.start, line.length())));
drawRect(posX + 1, posY, posX + 2, posY + container.lineHeight, 0xffffffff);
}
}
}
GL11.glPopMatrix();
GL11.glDisable(GL11.GL_SCISSOR_TEST);
if (hasVerticalScrollbar()) {
Minecraft.getMinecraft().renderEngine.bindTexture(GuiCustomScroll.resource);
int effLines = Math.max(1, getPaddedLineCount());
@@ -875,7 +886,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// Draw search/replace bar (overlays viewport)
searchBar.draw(xMouse, yMouse);
// Draw go to line dialog (overlays everything)
goToLineDialog.draw(xMouse, yMouse);
KEYS_OVERLAY.draw(xMouse, yMouse, wheelDelta);
@@ -902,13 +913,13 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// visible lines (fractional positions) correctly hit that line.
double fracPixels = scroll.getFractionalOffset() * container.lineHeight;
double yMouseD = yMouse + fracPixels;
ArrayList list = new ArrayList(this.container.lines);
for (int i = 0; i < list.size(); ++i) {
LineData data = (LineData) list.get(i);
//+1 to account for the fractional line
if (i >= scroll.getScrolledLine() && i <= scroll.getScrolledLine() + this.container.visibleLines +1) {
if (i >= scroll.getScrolledLine() && i <= scroll.getScrolledLine() + this.container.visibleLines + 1) {
double yPos = (i - scroll.getScrolledLine()) * this.container.lineHeight;
if (yMouseD >= yPos && yMouseD < yPos + this.container.lineHeight) {
int lineWidth = 0;
@@ -941,13 +952,13 @@ public class GuiScriptTextArea extends GuiNpcTextField {
private int getCursorLineIndex() {
return selection.getCursorLineIndex(container.lines, text != null ? text.length() : 0);
}
// Scroll viewport to keep cursor visible (minimal adjustment, like IntelliJ)
// Only scrolls if cursor is outside the visible area
private void scrollToCursor() {
if (container == null || container.lines == null || container.lines.isEmpty()) return;
int lineIdx = getCursorLineIndex();
int visible = Math.max(1, container.visibleLines);
int effectiveVisible = Math.max(1, visible - bottomPaddingLines);
@@ -1162,27 +1173,27 @@ public class GuiScriptTextArea extends GuiNpcTextField {
KEYS.SEARCH.setTask(e -> {
if (!e.isPress() || !openBoxes.get())
return;
unfocusAll();
searchBar.openSearch();
});
// SEARCH_REPLACE: Open search+replace bar (Ctrl+Shift+R)
// Works in search bar.
KEYS.SEARCH_REPLACE.setTask(e -> {
if (!e.isPress() || !openBoxes.get())
return;
unfocusAll();
searchBar.openSearchReplace();
});
// GO_TO_LINE: Open go to line dialog (Ctrl+G)
// Works in search bar.
KEYS.GO_TO_LINE.setTask(e -> {
if (!e.isPress() || !openBoxes.get())
return;
unfocusAll();
goToLineDialog.toggle();
});
@@ -1221,13 +1232,13 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// Handle rename refactor input first if active
if (renameHandler.isActive() && renameHandler.keyTyped(c, i))
return true;
// Handle Go To Line dialog input first if it has focus
if (goToLineDialog.isVisible() &&goToLineDialog.keyTyped(c, i))
return true;
if (goToLineDialog.isVisible() && goToLineDialog.keyTyped(c, i))
return true;
// Handle search bar input first if it has focus
if (searchBar.isVisible() && searchBar.keyTyped(c, i))
if (searchBar.isVisible() && searchBar.keyTyped(c, i))
return true;
if (!active)
@@ -1339,7 +1350,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
int cursorPos = selection.getCursorPosition();
int prevNonWs = cursorPos - 1;
while (prevNonWs >= 0 && prevNonWs < (text != null ? text.length() : 0) && Character.isWhitespace(
text.charAt(prevNonWs))) {
text.charAt(prevNonWs))) {
prevNonWs--;
}
@@ -1473,7 +1484,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
s = s.substring(0, nearestCondition);
// Adjust selection start to match removed characters
selection.setStartSelection(
selection.getStartSelection() - (selection.getCursorPosition() - nearestCondition));
selection.getStartSelection() - (selection.getCursorPosition() - nearestCondition));
}
setText(s + getSelectionAfterText());
selection.reset(selection.getStartSelection());
@@ -1561,9 +1572,9 @@ public class GuiScriptTextArea extends GuiNpcTextField {
char lastChar = before.charAt(before.length() - 1);
char firstChar = content.charAt(0);
// Avoid adding space when punctuation/brackets are adjacent
if (!Character.isWhitespace(lastChar) &&
if (!Character.isWhitespace(lastChar) &&
lastChar != '{' && lastChar != '(' && lastChar != '[' &&
firstChar != '}' && firstChar != ')' && firstChar != ']' &&
firstChar != '}' && firstChar != ')' && firstChar != ']' &&
firstChar != ';' && firstChar != ',' && firstChar != '.' &&
firstChar != '\n') {
spacer = " ";
@@ -1584,14 +1595,14 @@ public class GuiScriptTextArea extends GuiNpcTextField {
if (selection.getStartSelection() > 0 && selection.getStartSelection() < text.length()) {
char prev = text.charAt(selection.getStartSelection() - 1);
char nextc = text.charAt(selection.getStartSelection());
if ((prev == '(' && nextc == ')') ||
(prev == '[' && nextc == ']') ||
(prev == '{' && nextc == '}') ||
(prev == '\'' && nextc == '\'') ||
if ((prev == '(' && nextc == ')') ||
(prev == '[' && nextc == ']') ||
(prev == '{' && nextc == '}') ||
(prev == '\'' && nextc == '\'') ||
(prev == '"' && nextc == '"')) {
String before = text.substring(0, selection.getStartSelection() - 1);
String after = selection.getStartSelection() + 1 < text.length() ? text.substring(
selection.getStartSelection() + 1) : "";
selection.getStartSelection() + 1) : "";
setText(before + after);
selection.setStartSelection(selection.getStartSelection() - 1);
selection.reset(selection.getStartSelection());
@@ -1757,7 +1768,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// already immediately after the caret, move caret past it instead
// of inserting another closer. This prevents duplicate closers
// when the editor auto-inserts pairs.
if ((c == ')' || c == ']' || c == '"' || c == '\'' ) && after.length() > 0 && after.charAt(0) == c) {
if ((c == ')' || c == ']' || c == '"' || c == '\'') && after.length() > 0 && after.charAt(0) == c) {
// Move caret forward by one (skip over existing closer)
selection.reset(before.length() + 1);
scrollToCursor();
@@ -1805,10 +1816,10 @@ public class GuiScriptTextArea extends GuiNpcTextField {
// ==================== COMMENT TOGGLING ====================
// Uses CommentHandler helper for comment operations
private void toggleCommentSelection() {
CommentHandler.SelectionToggleResult result = CommentHandler.toggleCommentSelection(
text, container.lines, selection.getStartSelection(), selection.getEndSelection());
text, container.lines, selection.getStartSelection(), selection.getEndSelection());
setText(result.newText);
selection.setStartSelection(result.newStartSelection);
selection.setEndSelection(result.newEndSelection);
@@ -1816,15 +1827,15 @@ public class GuiScriptTextArea extends GuiNpcTextField {
private void toggleCommentLineAtCursor() {
CommentHandler.SingleLineToggleResult result = CommentHandler.toggleCommentAtCursor(
text, container.lines, selection.getCursorPosition());
text, container.lines, selection.getCursorPosition());
setText(result.newText);
setCursor(result.newCursorPosition, false);
}
public boolean closeOnEsc(){
return !KEYS_OVERLAY.isVisible() && !searchBar.isVisible() && !goToLineDialog.isVisible() && !renameHandler.isActive();
public boolean closeOnEsc() {
return !KEYS_OVERLAY.isVisible() && !searchBar.isVisible() && !goToLineDialog.isVisible() && !renameHandler.isActive();
}
// ==================== KEYBOARD MODIFIERS ====================
private boolean isAltKeyDown() {
@@ -1872,7 +1883,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
return IndentHelper.getAutoIndentForEnter(currentLine.text, selection.getCursorPosition() - currentLine.start);
}
// ==================== TEXT FORMATTING ====================
private int getTabSize() {
return IndentHelper.TAB_SIZE;
}
@@ -1888,7 +1899,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
setText(result.text);
selection.reset(Math.max(0, Math.min(result.cursorPosition, this.text.length())));
}
// ==================== TAB HANDLING ====================
private void handleTab() {
@@ -1986,7 +1997,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
}
}
}
// ==================== CURSOR MANAGEMENT ====================
private void setCursor(int i, boolean select) {
@@ -2014,7 +2025,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
public String getSelectionAfterText() {
return selection.getTextAfter(text);
}
// ==================== MOUSE HANDLING ====================
public void mouseClicked(int xMouse, int yMouse, int mouseButton) {
@@ -2022,21 +2033,21 @@ public class GuiScriptTextArea extends GuiNpcTextField {
if (goToLineDialog.isVisible() && goToLineDialog.mouseClicked(xMouse, yMouse, mouseButton)) {
return;
}
// Check search bar clicks first
if (searchBar.isVisible() && searchBar.mouseClicked(xMouse, yMouse, mouseButton)) {
return;
}
// If search bar is visible but click was outside it, unfocus the search bar
if (searchBar.isVisible()) {
searchBar.unfocus();
}
// Let the overlay consume clicks (it returns true when it handled the event)
if (KEYS_OVERLAY.mouseClicked(xMouse, yMouse, mouseButton))
return;
// Determine whether click occurred inside the text area bounds
this.active = xMouse >= this.x && xMouse < this.x + this.width && yMouse >= this.y && yMouse < this.y + this.height;
if (this.active) {
@@ -2067,7 +2078,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
if (this.clicked && getPaddedLineCount() * this.container.lineHeight > this.height && xMouse > this.x + this.width - 8) {
// We consumed the mouse-down as a scrollbar drag start
this.clicked = false;
scroll.startScrollbarDrag(yMouse,this.y,this.height, getPaddedLineCount());
scroll.startScrollbarDrag(yMouse, this.y, this.height, getPaddedLineCount());
} else {
// Handle double/triple click selection counting
if (time - this.lastClicked < 300L) {
@@ -2111,7 +2122,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
renameHandler.updateCursor();
++this.cursorCounter;
}
// ==================== TEXT MANAGEMENT ====================
public void setText(String text) {
@@ -2140,7 +2151,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
this.container.init(text, this.width, this.height);
if (this.enableCodeHighlighting)
if (this.enableCodeHighlighting)
this.container.formatCodeText();
// Ensure scroll state stays in bounds after text change
@@ -2202,7 +2213,7 @@ public class GuiScriptTextArea extends GuiNpcTextField {
private void clampSelectionBounds() {
selection.clamp(text != null ? text.length() : 0);
}
// ==================== INNER CLASSES ====================
public static class UndoData {
@@ -143,6 +143,7 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
}
}
}
public void mouseEvent(int i, int j, int k) {
}
@@ -208,6 +209,7 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC
}
public int backgroundColor = 0x66000000;
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
scrollY = (float) lerp(scrollY, nextScrollY, partialTicks);
@@ -112,7 +112,7 @@ public class GuiUtil {
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
public static void drawGradientRectHorizontal(int left, int top, int right, int bottom, int startColor, int endColor) {
double zLevel = 0;
@@ -9,6 +9,7 @@ import kamkeel.npcs.controllers.data.ability.Ability;
public interface IAbilityConfigCallback {
/**
* Called when an ability has been edited and saved.
*
* @param ability The edited ability
*/
void onAbilitySaved(Ability ability);
@@ -79,7 +79,7 @@ public class OverlayKeyPresetViewer {
public void drawOverlay(int wheel) {
scroll.update(wheel);
if (hasBorder) {
// int borderCol2 = 0xffff00ff,borderCol2 = 0xff00ffff; NEON
@@ -133,7 +133,7 @@ public class OverlayKeyPresetViewer {
showOverlay = false;
return true;
}
// If overlay is visible but no element consumed the key, consider it handled
return true;
}
@@ -155,7 +155,7 @@ public class OverlayKeyPresetViewer {
// If overlay is not visible, no other clicks matter
if (!showOverlay)
return false;
boolean isAboveOverlay = isMouseAbove(mouseX, mouseY);
// In click-to-open mode, clicking outside the overlay (and not the button) should close it
if (openOnClick && !isAboveOverlay && !isAboveButton) {
@@ -259,7 +259,7 @@ public class OverlayKeyPresetViewer {
public void drawBar() {
GL11.glPushMatrix();
GL11.glTranslatef(endX - barWidth - 2, startY + yStartSpacing + scrollY * scrollFactor, 1);
GuiUtil.drawRectD(0, 1, barWidth, scrollbarHeight-1, (isMouseAboveBar(mouseX, mouseY) || isMouseDragging) ? 0xffbababa : 0xff767676);
GuiUtil.drawRectD(0, 1, barWidth, scrollbarHeight - 1, (isMouseAboveBar(mouseX, mouseY) || isMouseDragging) ? 0xffbababa : 0xff767676);
GL11.glPopMatrix();
}
@@ -480,7 +480,7 @@ public class OverlayKeyPresetViewer {
int oldMinFilter = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glDisable(GL11.GL_BLEND);
GL11.glPushMatrix();
float color = aboveButton ? 1f : 0.4f;
GL11.glColor4f(color, color, color, 1);
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.util.script;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import java.util.ArrayList;
import java.util.List;
@@ -8,14 +9,15 @@ import java.util.List;
* Handles bracket matching, brace span computation, and indent guide generation.
*/
public class BracketMatcher {
/**
* Find matching bracket at cursor position.
*
* @return int[2] with {startPos, endPos} or null if no bracket found
*/
public static int[] findBracketSpanAt(String text, int pos) {
if (text == null || text.isEmpty()) return null;
// Try at current position
if (pos >= 0 && pos < text.length()) {
char c = text.charAt(pos);
@@ -34,7 +36,10 @@ public class BracketMatcher {
int scan = pos - 1;
while (scan >= 0) {
char sc = text.charAt(scan);
if (sc == ' ' || sc == '\t') { scan--; continue; }
if (sc == ' ' || sc == '\t') {
scan--;
continue;
}
if (sc == '\n') break; // Don't cross line boundary
int found2 = 0;
@@ -73,25 +78,43 @@ public class BracketMatcher {
char next = pos + 1 < text.length() ? text.charAt(pos + 1) : 0;
if (inString) {
if (escape) { escape = false; }
else if (c == '\\') { escape = true; }
else if (c == stringDelimiter) { inString = false; }
else if (c == '\n') { inString = false; }
if (escape) {
escape = false;
} else if (c == '\\') {
escape = true;
} else if (c == stringDelimiter) {
inString = false;
} else if (c == '\n') {
inString = false;
}
continue;
}
if (inBlockComment) {
if (c == '*' && next == '/') { inBlockComment = false; pos++; }
if (c == '*' && next == '/') {
inBlockComment = false;
pos++;
}
continue;
}
if (inLineComment) {
if (c == '\n') { inLineComment = false; }
if (c == '\n') {
inLineComment = false;
}
continue;
}
if (c == '/' && next == '/') { inLineComment = true; pos++; continue; }
if (c == '/' && next == '*') { inBlockComment = true; pos++; continue; }
if (c == '/' && next == '/') {
inLineComment = true;
pos++;
continue;
}
if (c == '/' && next == '*') {
inBlockComment = true;
pos++;
continue;
}
if (c == '"' || c == '\'') {
inString = true;
@@ -193,29 +216,47 @@ public class BracketMatcher {
// String handling
if (inString) {
if (escape) { escape = false; }
else if (c == '\\') { escape = true; }
else if (c == stringDelimiter) { inString = false; }
else if (c == '\n') { inString = false; } // Unterminated string
if (escape) {
escape = false;
} else if (c == '\\') {
escape = true;
} else if (c == stringDelimiter) {
inString = false;
} else if (c == '\n') {
inString = false;
} // Unterminated string
continue;
}
// Block comment handling
if (inBlockComment) {
if (c == '*' && next == '/') { inBlockComment = false; pos++; }
if (c == '*' && next == '/') {
inBlockComment = false;
pos++;
}
continue;
}
// Line comment handling
if (inLineComment) {
if (c == '\n') { inLineComment = false; }
if (c == '\n') {
inLineComment = false;
}
continue;
}
// Start of comments
if (c == '/' && next == '/') { inLineComment = true; pos++; continue; }
if (c == '/' && next == '*') { inBlockComment = true; pos++; continue; }
if (c == '/' && next == '/') {
inLineComment = true;
pos++;
continue;
}
if (c == '/' && next == '*') {
inBlockComment = true;
pos++;
continue;
}
// Start of string
if (c == '"' || c == '\'') {
inString = true;
@@ -256,11 +297,12 @@ public class BracketMatcher {
/**
* Find which brace span should be highlighted based on bracket at position
*
* @return int[2] {openLine, closeLine} or null
*/
public static int[] findHighlightedSpan(int bracketPos, List<LineData> lines, List<int[]> spans) {
if (bracketPos < 0 || lines == null || spans == null) return null;
// Find line containing bracket
int bracketLineIdx = -1;
for (int i = 0; i < lines.size(); i++) {
@@ -270,7 +312,7 @@ public class BracketMatcher {
break;
}
}
if (bracketLineIdx >= 0) {
for (int[] span : spans) {
int openLine = span[1];
@@ -282,13 +324,13 @@ public class BracketMatcher {
}
return null;
}
/**
* Check if a brace at given position has a matching close with same indent
*/
public static boolean hasMatchingCloseWithSameIndent(String text, int bracePos, List<LineData> lines, int currentIndent) {
if (text == null || lines == null || bracePos < 0) return false;
// Find line containing the brace
int openLineIdx = -1;
for (int i = 0; i < lines.size(); i++) {
@@ -298,9 +340,9 @@ public class BracketMatcher {
break;
}
}
if (openLineIdx < 0) return false;
List<int[]> spans = computeBraceSpans(text, lines);
for (int[] span : spans) {
if (span[1] == openLineIdx) {
@@ -314,7 +356,7 @@ public class BracketMatcher {
}
return false;
}
/**
* Get leading whitespace count of a line
*/
@@ -327,4 +369,4 @@ public class BracketMatcher {
}
return indent;
}
}
}
@@ -1,6 +1,13 @@
package noppes.npcs.client.gui.util.script;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Helper class for resolving Java classpath imports and determining class types.
@@ -21,14 +28,14 @@ public class ClassPathFinder {
// Common java.lang classes (auto-imported in Java)
public static final Set<String> JAVA_LANG_CLASSES = new HashSet<>(Arrays.asList(
"Object", "String", "Class", "System", "Math", "Integer", "Double", "Float", "Long", "Short", "Byte",
"Character", "Boolean", "Number", "Void", "Thread", "Runnable", "Exception", "RuntimeException",
"Error", "Throwable", "StringBuilder", "StringBuffer", "Enum", "Comparable", "Iterable",
"CharSequence", "Cloneable", "Process", "ProcessBuilder", "Runtime", "SecurityManager",
"ClassLoader", "Package", "ArithmeticException", "ArrayIndexOutOfBoundsException",
"ClassCastException", "IllegalArgumentException", "IllegalStateException",
"IndexOutOfBoundsException", "NullPointerException", "NumberFormatException",
"UnsupportedOperationException", "AssertionError", "OutOfMemoryError", "StackOverflowError"
"Object", "String", "Class", "System", "Math", "Integer", "Double", "Float", "Long", "Short", "Byte",
"Character", "Boolean", "Number", "Void", "Thread", "Runnable", "Exception", "RuntimeException",
"Error", "Throwable", "StringBuilder", "StringBuffer", "Enum", "Comparable", "Iterable",
"CharSequence", "Cloneable", "Process", "ProcessBuilder", "Runtime", "SecurityManager",
"ClassLoader", "Package", "ArithmeticException", "ArrayIndexOutOfBoundsException",
"ClassCastException", "IllegalArgumentException", "IllegalStateException",
"IndexOutOfBoundsException", "NullPointerException", "NumberFormatException",
"UnsupportedOperationException", "AssertionError", "OutOfMemoryError", "StackOverflowError"
));
/**
@@ -193,10 +200,10 @@ public class ClassPathFinder {
// Full resolution successful
List<ClassSegment> classSegments = buildClassSegments(segments, classStartIdx, n);
return ResolveResult.found(
new ClassInfo(info.resolvedName, info.type, packagePortion.length()),
packagePortion, validClassPortion, classSegments, classStartIdx
);
return ResolveResult.found(
new ClassInfo(info.resolvedName, info.type, packagePortion.length()),
packagePortion, validClassPortion, classSegments, classStartIdx
);
}
}
}
@@ -243,7 +250,7 @@ public class ClassPathFinder {
// Build the typed package path segment by segment and compare with cache
StringBuilder sb = new StringBuilder();
int lastValidIndex = -1;
for (int i = 0; i < classStartIdx; i++) {
if (i > 0) sb.append(".");
sb.append(segments[i]);
@@ -272,7 +279,7 @@ public class ClassPathFinder {
}
}
}
// If we found some valid prefix but not all, return where it stopped being valid
if (lastValidIndex > 0 && lastValidIndex < classStartIdx) {
// Check if segment at lastValidIndex diverges from any known path
@@ -282,15 +289,15 @@ public class ClassPathFinder {
// There's a known continuation - check if typed segment matches
String nextTyped = segments[lastValidIndex];
String cachedRemainder = cached.substring(validPrefix.length() + 1);
String nextCached = cachedRemainder.contains(".") ?
cachedRemainder.substring(0, cachedRemainder.indexOf('.')) : cachedRemainder;
String nextCached = cachedRemainder.contains(".") ?
cachedRemainder.substring(0, cachedRemainder.indexOf('.')) : cachedRemainder;
if (!nextTyped.equals(nextCached)) {
return lastValidIndex; // Divergence point
}
}
}
}
return -1; // No typo detected
}
@@ -312,7 +319,7 @@ public class ClassPathFinder {
registerValidPackage(packagePath);
return true;
}
// Fallback: try to find any class under this package to validate it
String[] testClasses = getTestClassesForPackage(packagePath);
for (String testClass : testClasses) {
@@ -580,7 +587,7 @@ public class ClassPathFinder {
default:
// For unknown packages, try common class suffixes
return new String[]{
packagePath + ".package-info", // Won't work but harmless
packagePath + ".package-info", // Won't work but harmless
};
}
}
@@ -591,7 +598,7 @@ public class ClassPathFinder {
* Parse generic type content and return type names with their positions.
* Handles arbitrary nesting depth like "Map<String, List<Map<String, String>>>"
*
* @param genericContent The content inside <...> (without the outer angle brackets)
* @param genericContent The content inside <...> (without the outer angle brackets)
* @param importedClasses Map of simple name -> full class name for resolution
* @return List of TypeOccurrence with position and type info
*/
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.util.script;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import java.util.List;
/**
@@ -15,18 +16,18 @@ public class CommentHandler {
public final String text;
public final int delta; // Change in length (negative if comment removed)
public final int nonWsIndex; // Index of first non-whitespace character
public ToggleResult(String text, int delta, int nonWsIndex) {
this.text = text;
this.delta = delta;
this.nonWsIndex = nonWsIndex;
}
public boolean wasCommented() {
return delta < 0;
}
}
/**
* Toggle line comment on a single line
*/
@@ -36,11 +37,11 @@ public class CommentHandler {
while (nonWs < lineText.length() && Character.isWhitespace(lineText.charAt(nonWs))) {
nonWs++;
}
boolean hasContent = nonWs < lineText.length();
boolean hasComment = hasContent && lineText.startsWith("//", nonWs);
String newText;
if (hasComment) {
// Remove comment
int cut = Math.min(nonWs + 2, lineText.length());
@@ -52,10 +53,10 @@ public class CommentHandler {
// Empty/whitespace line - no change
newText = lineText;
}
return new ToggleResult(newText, newText.length() - lineText.length(), nonWs);
}
/**
* Result of toggling comments on a selection
*/
@@ -63,33 +64,33 @@ public class CommentHandler {
public final String newText;
public final int newStartSelection;
public final int newEndSelection;
public SelectionToggleResult(String text, int start, int end) {
this.newText = text;
this.newStartSelection = start;
this.newEndSelection = end;
}
}
/**
* Toggle comments on all lines in a selection
*/
public static SelectionToggleResult toggleCommentSelection(
String text,
List<LineData> lines,
int startSelection,
int endSelection) {
String text,
List<LineData> lines,
int startSelection,
int endSelection) {
StringBuilder newText = new StringBuilder(text.length() + 100);
int prevEnd = 0;
int newStart = -1;
int newEnd = -1;
int newIndex = 0;
for (LineData line : lines) {
int safeLineStart = Math.max(0, Math.min(line.start, text.length()));
int safeLineEnd = Math.max(0, Math.min(line.end, text.length()));
// Handle gap between lines (shouldn't happen normally)
if (safeLineStart > prevEnd) {
if (newStart == -1 && startSelection >= prevEnd && startSelection <= safeLineStart) {
@@ -101,7 +102,7 @@ public class CommentHandler {
newText.append(text, prevEnd, safeLineStart);
newIndex += safeLineStart - prevEnd;
}
// Check if this line is in selection
if (safeLineEnd > startSelection && safeLineStart < endSelection) {
String lineText = text.substring(safeLineStart, safeLineEnd);
@@ -109,7 +110,7 @@ public class CommentHandler {
String newLineText = tr.text;
int nonWs = tr.nonWsIndex;
int delta = tr.delta;
// Update start selection position
if (newStart == -1 && startSelection >= safeLineStart && startSelection <= safeLineEnd) {
int offsetInOld = startSelection - safeLineStart;
@@ -119,7 +120,7 @@ public class CommentHandler {
}
newStart = newIndex + Math.max(0, newOffset);
}
// Update end selection position
if (newEnd == -1 && endSelection >= safeLineStart && endSelection <= safeLineEnd) {
int offsetInOld = endSelection - safeLineStart;
@@ -129,7 +130,7 @@ public class CommentHandler {
}
newEnd = newIndex + Math.max(0, newOffset);
}
newText.append(newLineText);
newIndex += newLineText.length();
} else {
@@ -145,7 +146,7 @@ public class CommentHandler {
}
prevEnd = safeLineEnd;
}
// Handle remaining text after last line
if (prevEnd < text.length()) {
if (newStart == -1 && startSelection >= prevEnd && startSelection <= text.length()) {
@@ -157,35 +158,35 @@ public class CommentHandler {
newText.append(text, prevEnd, text.length());
newIndex += text.length() - prevEnd;
}
// Fallback for positions not found
if (newStart == -1) newStart = Math.max(0, Math.min(startSelection, newText.length()));
if (newEnd == -1) newEnd = Math.max(0, Math.min(endSelection, newText.length()));
return new SelectionToggleResult(newText.toString(), newStart, newEnd);
}
/**
* Toggle comment on a single line at cursor position
*/
public static SingleLineToggleResult toggleCommentAtCursor(
String text,
List<LineData> lines,
int cursorPosition) {
String text,
List<LineData> lines,
int cursorPosition) {
for (LineData line : lines) {
int lineStart = Math.max(0, Math.min(line.start, text.length()));
int lineEnd = Math.max(0, Math.min(line.end, text.length()));
if (cursorPosition >= lineStart && cursorPosition <= lineEnd) {
String lineText = text.substring(lineStart, lineEnd);
ToggleResult tr = toggleLine(lineText);
boolean hadComment = tr.delta < 0;
String before = text.substring(0, lineStart);
String after = lineEnd <= text.length() ? text.substring(lineEnd) : "";
String newText = before + tr.text + after;
// Calculate new cursor position
int cursorDelta = hadComment ? -2 : 2;
int newCursor = cursorPosition + cursorDelta;
@@ -193,25 +194,25 @@ public class CommentHandler {
newCursor = cursorPosition;
}
newCursor = Math.max(lineStart, newCursor);
return new SingleLineToggleResult(newText, newCursor);
}
}
// No line found at cursor - return unchanged
return new SingleLineToggleResult(text, cursorPosition);
}
/**
* Result of toggling comment on single line
*/
public static class SingleLineToggleResult {
public final String newText;
public final int newCursorPosition;
public SingleLineToggleResult(String text, int cursor) {
this.newText = text;
this.newCursorPosition = cursor;
}
}
}
}
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.util.script;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -9,25 +10,25 @@ import java.util.regex.Pattern;
* Handles cursor navigation logic (up, down, left, right, word movement).
*/
public class CursorNavigation {
/**
* Move cursor up one line, maintaining column position
*/
public static int cursorUp(int cursorPosition, List<LineData> lines, String text) {
if (lines == null || lines.isEmpty()) return 0;
for (int i = 0; i < lines.size(); i++) {
LineData data = lines.get(i);
boolean isLastLine = (i == lines.size() - 1);
boolean isOnLine = isLastLine
? (cursorPosition >= data.start && cursorPosition <= data.end)
: (cursorPosition >= data.start && cursorPosition < data.end);
boolean isOnLine = isLastLine
? (cursorPosition >= data.start && cursorPosition <= data.end)
: (cursorPosition >= data.start && cursorPosition < data.end);
if (isOnLine) {
if (i == 0) {
return 0; // Already on first line
}
int column = Math.min(cursorPosition - data.start, data.text.length());
LineData target = lines.get(i - 1);
int targetColumn = Math.min(column, target.text.length());
@@ -39,26 +40,26 @@ public class CursorNavigation {
}
return 0;
}
/**
* Move cursor down one line, maintaining column position
*/
public static int cursorDown(int cursorPosition, List<LineData> lines, String text) {
if (lines == null || lines.isEmpty()) return text != null ? text.length() : 0;
if (text != null && cursorPosition == text.length()) return cursorPosition;
for (int i = 0; i < lines.size(); i++) {
LineData data = lines.get(i);
boolean isLastLine = (i == lines.size() - 1);
boolean isOnLine = isLastLine
? (cursorPosition >= data.start && cursorPosition <= data.end)
: (cursorPosition >= data.start && cursorPosition < data.end);
boolean isOnLine = isLastLine
? (cursorPosition >= data.start && cursorPosition <= data.end)
: (cursorPosition >= data.start && cursorPosition < data.end);
if (isOnLine) {
if (i >= lines.size() - 1) {
return cursorPosition; // Already on last line
}
int column = Math.min(cursorPosition - data.start, data.text.length());
LineData target = lines.get(i + 1);
int targetColumn = Math.min(column, target.text.length());
@@ -70,13 +71,13 @@ public class CursorNavigation {
}
return text != null ? text.length() : 0;
}
/**
* Move cursor left, optionally by word
*/
public static int cursorLeft(int cursorPosition, String text, Pattern wordPattern, boolean byWord) {
if (text == null || cursorPosition <= 0) return 0;
int moveAmount = 1;
if (byWord && wordPattern != null) {
Matcher m = wordPattern.matcher(text.substring(0, cursorPosition));
@@ -88,7 +89,7 @@ public class CursorNavigation {
}
return Math.max(cursorPosition - moveAmount, 0);
}
/**
* Move cursor right, optionally by word
*/
@@ -96,7 +97,7 @@ public class CursorNavigation {
if (text == null) return 0;
int textLen = text.length();
if (cursorPosition >= textLen) return textLen;
int moveAmount = 1;
if (byWord && wordPattern != null) {
Matcher m = wordPattern.matcher(text.substring(cursorPosition));
@@ -108,45 +109,45 @@ public class CursorNavigation {
}
return Math.min(cursorPosition + moveAmount, textLen);
}
/**
* Get cursor position from mouse click coordinates
*/
public static int getPositionFromMouse(
int mouseX, int mouseY,
int areaX, int areaY,
int gutterWidth,
int lineHeight,
int scrolledLine,
double scrollFracOffset,
List<LineData> lines,
String text,
FontWidthProvider fontWidth) {
int mouseX, int mouseY,
int areaX, int areaY,
int gutterWidth,
int lineHeight,
int scrolledLine,
double scrollFracOffset,
List<LineData> lines,
String text,
FontWidthProvider fontWidth) {
int xMouse = mouseX - (areaX + gutterWidth + 1);
int yMouse = mouseY - areaY - 1;
// Account for fractional scroll offset
double fracPixels = scrollFracOffset * lineHeight;
yMouse = (int) Math.round(yMouse + fracPixels);
if (lines == null || lines.isEmpty()) {
return text != null ? text.length() : 0;
}
int visibleLines = Math.min(lines.size(), scrolledLine + 50); // Reasonable limit
for (int i = 0; i < lines.size(); i++) {
LineData data = lines.get(i);
if (i >= scrolledLine && i <= visibleLines) {
int yPos = (i - scrolledLine) * lineHeight;
if (yMouse >= yPos && yMouse < yPos + lineHeight) {
// Found the line, now find character position
int lineWidth = 0;
char[] chars = data.text.toCharArray();
for (int j = 1; j <= chars.length; j++) {
int w = fontWidth.getWidth(data.text.substring(0, j));
if (xMouse < lineWidth + (w - lineWidth) / 2) {
@@ -154,24 +155,24 @@ public class CursorNavigation {
}
lineWidth = w;
}
// Click past end of line - place cursor at end of text (not on newline)
int posAfterChars = data.start + chars.length;
return Math.min(posAfterChars, text.length());
}
}
}
return text != null ? text.length() : 0;
}
/**
* Interface for font width measurement
*/
public interface FontWidthProvider {
int getWidth(String text);
}
/**
* Get leading whitespace count of a line
*/
@@ -184,26 +185,26 @@ public class CursorNavigation {
}
return indent;
}
/**
* Find line index containing given position
*/
public static int findLineIndex(int position, List<LineData> lines) {
if (lines == null || lines.isEmpty()) return 0;
for (int i = 0; i < lines.size(); i++) {
LineData line = lines.get(i);
boolean isLastLine = (i == lines.size() - 1);
boolean isOnLine = isLastLine
? (position >= line.start && position <= line.end)
: (position >= line.start && position < line.end);
boolean isOnLine = isLastLine
? (position >= line.start && position <= line.end)
: (position >= line.start && position < line.end);
if (isOnLine) {
return i;
}
}
return lines.size() - 1;
}
/**
* Find line data containing given position
*/
@@ -214,4 +215,4 @@ public class CursorNavigation {
}
return null;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -5,7 +5,6 @@ import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.gui.util.GuiUtil;
import noppes.npcs.client.gui.util.key.OverlayKeyPresetViewer;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
@@ -13,7 +12,7 @@ import org.lwjgl.opengl.GL11;
/**
* Go To Line:Column dialog for the script editor.
* Provides IntelliJ-like "Go to Line" functionality (Ctrl+G).
*
* <p>
* Input format: "line" or "line:column"
* Example: "42" goes to line 42, column 1
* Example: "42:15" goes to line 42, column 15
@@ -55,26 +54,35 @@ public class GoToLineDialog {
* Callback interface for go-to-line operations
*/
public interface GoToLineCallback {
/** Get total line count */
/**
* Get total line count
*/
int getLineCount();
/** Get the column count for a specific line (0-indexed) */
/**
* Get the column count for a specific line (0-indexed)
*/
int getColumnCount(int lineIndex);
/** Navigate to specific line and column (both 1-indexed for user display) */
/**
* Navigate to specific line and column (both 1-indexed for user display)
*/
void goToLineColumn(int line, int column);
/** Called when dialog closes - should restore focus to editor */
/**
* Called when dialog closes - should restore focus to editor
*/
void onDialogClose();
void unfocusMainEditor();
void focusMainEditor();
}
public void setCallback(GoToLineCallback callback) {
this.callback = callback;
}
/**
* Initialize/update position for the dialog
*/
@@ -163,7 +171,7 @@ public class GoToLineDialog {
int fieldY = y + padding + 14 + 5;
textFieldWidth = dialogWidth - padding * 2;
drawTextField(fieldX, fieldY, textFieldWidth, textFieldHeight, inputText, cursor,
selectionStart, selectionEnd, scrollOffset, focused);
selectionStart, selectionEnd, scrollOffset, focused);
if (inputText.isEmpty())
font.drawString("[Line][:Column]", x + padding + 6, y + padding + 23, 0xFF888888);
@@ -228,7 +236,7 @@ public class GoToLineDialog {
int maxSel = Math.max(adjustedSelStart, adjustedSelEnd);
String beforeSel = visibleText.substring(0, Math.min(minSel, visibleText.length()));
String inSel = visibleText.substring(Math.min(minSel, visibleText.length()),
Math.min(maxSel, visibleText.length()));
Math.min(maxSel, visibleText.length()));
int selX = textX + font.getStringWidth(beforeSel);
int selW = font.getStringWidth(inSel);
Gui.drawRect(selX, textY - 1, selX + selW, textY + 9, 0xFF264f78);
@@ -240,7 +248,7 @@ public class GoToLineDialog {
// Draw cursor
if (isFocused && shouldShowCursor()) {
String beforeCursor = adjustedCursor > 0 && adjustedCursor <= visibleText.length()
? visibleText.substring(0, adjustedCursor) : "";
? visibleText.substring(0, adjustedCursor) : "";
int cursorX = textX + font.getStringWidth(beforeCursor);
Gui.drawRect(cursorX, textY - 1, cursorX + 1, textY + 9, 0xFFe0e0e0);
}
@@ -258,13 +266,13 @@ public class GoToLineDialog {
int fieldX = x + padding;
int fieldY = y + padding + 14;
if (mouseX >= fieldX && mouseX < fieldX + textFieldWidth &&
mouseY >= fieldY && mouseY < fieldY + textFieldHeight) {
mouseY >= fieldY && mouseY < fieldY + textFieldHeight) {
focused = true;
if (callback != null) callback.unfocusMainEditor();
// Position cursor based on click
int clickX = mouseX - fieldX - 4;
String visibleText = scrollOffset > 0 && scrollOffset < inputText.length()
? inputText.substring(scrollOffset) : inputText;
? inputText.substring(scrollOffset) : inputText;
int newCursor = getCharIndexAtX(visibleText, clickX) + scrollOffset;
cursor = Math.max(0, Math.min(newCursor, inputText.length()));
selectionStart = cursor;
@@ -297,7 +305,7 @@ public class GoToLineDialog {
close();
return true;
}
if (!visible || !focused)
return false;
@@ -617,4 +625,4 @@ public class GoToLineDialog {
public int getTotalHeight() {
return visible ? dialogHeight + 10 : 0;
}
}
}
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.util.script;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import java.util.Arrays;
import java.util.List;
@@ -8,9 +9,9 @@ import java.util.List;
* Helper class for indentation-related operations.
*/
public class IndentHelper {
public static final int TAB_SIZE = 4;
/**
* Get leading whitespace count of a line
*/
@@ -23,7 +24,7 @@ public class IndentHelper {
}
return leading;
}
/**
* Extract leading whitespace as string
*/
@@ -31,7 +32,7 @@ public class IndentHelper {
int indent = getLineIndent(lineText);
return lineText.substring(0, indent);
}
/**
* Create a string of n spaces
*/
@@ -41,16 +42,16 @@ public class IndentHelper {
Arrays.fill(arr, ' ');
return new String(arr);
}
/**
* Calculate expected indent for a line based on context
*/
public static int getExpectedIndent(LineData currentLine, List<LineData> allLines) {
if (currentLine == null || allLines == null) return 0;
int idx = allLines.indexOf(currentLine);
if (idx <= 0) return 0;
// Find previous non-empty line
LineData prevLine = null;
for (int i = idx - 1; i >= 0; i--) {
@@ -60,40 +61,40 @@ public class IndentHelper {
break;
}
}
if (prevLine == null) return 0;
int prevIndent = getLineIndent(prevLine.text);
String prevTrimmed = prevLine.text.trim();
String currTrimmed = currentLine.text.trim();
// If current line starts with }, expected is one level back
if (currTrimmed.startsWith("}")) {
return Math.max(0, prevIndent - TAB_SIZE);
}
// If previous line ends with {, expected is one level forward
if (prevTrimmed.endsWith("{")) {
return prevIndent + TAB_SIZE;
}
return prevIndent;
}
/**
* Calculate auto-indent for Enter key
*/
public static String getAutoIndentForEnter(String lineText, int cursorInLine) {
int leading = 0;
while (leading < lineText.length() &&
(lineText.charAt(leading) == ' ' || lineText.charAt(leading) == '\t')) {
while (leading < lineText.length() &&
(lineText.charAt(leading) == ' ' || lineText.charAt(leading) == '\t')) {
leading++;
}
String baseIndent = lineText.substring(0, leading);
int relativeCursor = Math.max(0, Math.min(cursorInLine, lineText.length()));
String beforeCursor = lineText.substring(0, relativeCursor);
// Find last non-whitespace before cursor
int lastNonWs = -1;
for (int i = beforeCursor.length() - 1; i >= 0; i--) {
@@ -102,7 +103,7 @@ public class IndentHelper {
break;
}
}
// Add extra indent if last char is {
// Only add extra indent if cursor is actually after the opening brace (not just in trailing whitespace)
// Check that the last non-whitespace is at or after the line's indent position
@@ -110,10 +111,10 @@ public class IndentHelper {
if (opensBlock) {
return baseIndent + spaces(TAB_SIZE);
}
return baseIndent;
}
/**
* Calculate target indent for Tab key
*/
@@ -136,62 +137,63 @@ public class IndentHelper {
}
}
}
/**
* Calculate target indent for Shift+Tab
*/
public static int calculateShiftTabTargetIndent(int currentIndent) {
return Math.max(0, ((currentIndent - 1) / TAB_SIZE) * TAB_SIZE);
}
/**
* Format entire text with proper indentation and operator spacing
*/
public static FormatResult formatText(String text, int cursorPosition) {
return formatText(text, cursorPosition, 0);
}
/**
* Format entire text with proper indentation, operator spacing, and optional line wrapping
* @param text The text to format
*
* @param text The text to format
* @param cursorPosition Current cursor position
* @param viewportWidth Viewport width for line wrapping (0 = no wrapping)
* @param viewportWidth Viewport width for line wrapping (0 = no wrapping)
*/
public static FormatResult formatText(String text, int cursorPosition, int viewportWidth) {
// First pass: fix indentation
String indented = formatIndentation(text, cursorPosition);
// Second pass: apply operator spacing and whitespace normalization
FormatHelper helper = new FormatHelper();
FormatHelper.FormatSettings settings = helper.getSettings();
// Enable wrapping if viewport width is provided
if (viewportWidth > 0) {
settings.wrapLongLines = true;
settings.wrapComments = true;
// Use 75% of viewport width as max line length for some margin
int charWidth = 6; // Approximate character width
settings.maxLineLength = Math.max(60, (int)(viewportWidth * 0.8f / charWidth));
settings.maxLineLength = Math.max(60, (int) (viewportWidth * 0.8f / charWidth));
}
String formatted = helper.format(indented);
// Apply wrapping if enabled
if (viewportWidth > 0 && settings.wrapLongLines) {
formatted = helper.wrapLines(formatted, settings.maxLineLength);
}
// Recalculate cursor position (try to maintain relative position)
int newCursorPos = Math.min(cursorPosition, formatted.length());
// Try to find cursor on same line with same content context
String[] origLines = text.split("\n", -1);
String[] newLines = formatted.split("\n", -1);
int lineStartPos = 0;
int cursorLine = -1;
int cursorColInLine = 0;
for (int li = 0; li < origLines.length; li++) {
int lineEndPos = lineStartPos + origLines[li].length();
if (cursorPosition >= lineStartPos && cursorPosition <= lineEndPos) {
@@ -201,7 +203,7 @@ public class IndentHelper {
}
lineStartPos = lineEndPos + 1;
}
if (cursorLine >= 0 && cursorLine < newLines.length) {
int newLineStart = 0;
for (int li = 0; li < cursorLine; li++) {
@@ -210,51 +212,66 @@ public class IndentHelper {
// Clamp cursor to new line length
newCursorPos = newLineStart + Math.min(cursorColInLine, newLines[cursorLine].length());
}
return new FormatResult(formatted, newCursorPos);
}
/**
* Format indentation only (first pass)
*/
private static String formatIndentation(String text, int cursorPosition) {
String[] linesArr = text.split("\n", -1);
StringBuilder out = new StringBuilder(text.length() + 32);
boolean inString = false;
boolean escape = false;
boolean inBlockComment = false;
int depth = 0;
for (int li = 0; li < linesArr.length; li++) {
String line = linesArr[li];
String trimmedLeading = line.replaceAll("^[ \\t]+", "");
int originalIndent = getLineIndent(line);
int opens = 0, closes = 0;
boolean startsWithClose = false;
// Parse line for braces
for (int idx = 0; idx < line.length(); idx++) {
char c = line.charAt(idx);
char next = idx + 1 < line.length() ? line.charAt(idx + 1) : 0;
if (inString) {
if (escape) { escape = false; }
else if (c == '\\') { escape = true; }
else if (c == '"') { inString = false; }
if (escape) {
escape = false;
} else if (c == '\\') {
escape = true;
} else if (c == '"') {
inString = false;
}
continue;
}
if (inBlockComment) {
if (c == '*' && next == '/') { inBlockComment = false; idx++; }
if (c == '*' && next == '/') {
inBlockComment = false;
idx++;
}
continue;
}
if (c == '/' && next == '/') break;
if (c == '/' && next == '*') { inBlockComment = true; idx++; continue; }
if (c == '"') { inString = true; escape = false; continue; }
if (c == '/' && next == '*') {
inBlockComment = true;
idx++;
continue;
}
if (c == '"') {
inString = true;
escape = false;
continue;
}
if (c == '{') {
opens++;
} else if (c == '}') {
@@ -264,11 +281,11 @@ public class IndentHelper {
}
}
}
int indentLevel = depth;
if (startsWithClose) indentLevel = Math.max(0, indentLevel - 1);
int targetIndent = indentLevel * TAB_SIZE;
// Check if this is a continuation line:
// 1. Line starts with operator/dot (explicit continuation)
// 2. Previous line ends with operator (implicit continuation - this line continues it)
@@ -279,7 +296,7 @@ public class IndentHelper {
String prevLine = linesArr[li - 1].trim();
isContinuation = lineEndsWithContinuationOperator(prevLine);
}
if (isContinuation && originalIndent > targetIndent) {
// This is a continuation line - preserve its extra indent
out.append(spaces(originalIndent)).append(trimmedLeading);
@@ -287,13 +304,13 @@ public class IndentHelper {
out.append(spaces(targetIndent)).append(trimmedLeading);
}
if (li < linesArr.length - 1) out.append('\n');
depth = Math.max(0, depth + opens - closes);
}
return out.toString();
}
/**
* Check if a line appears to be a continuation of a previous line
* (i.e., starts with an operator, dot, or other continuation character)
@@ -302,7 +319,7 @@ public class IndentHelper {
if (trimmedContent.isEmpty()) return false;
char firstChar = trimmedContent.charAt(0);
// Lines starting with these are likely continuations
if (firstChar == '.' || firstChar == '+' || firstChar == '-' ||
if (firstChar == '.' || firstChar == '+' || firstChar == '-' ||
firstChar == '*' || firstChar == '/' || firstChar == '%' ||
firstChar == '&' || firstChar == '|' || firstChar == '^' ||
firstChar == '?' || firstChar == ':' || firstChar == ',') {
@@ -314,7 +331,7 @@ public class IndentHelper {
}
return false;
}
/**
* Check if a line ends with an operator that indicates the next line is a continuation
*/
@@ -326,10 +343,10 @@ public class IndentHelper {
trimmedLine = trimmedLine.substring(0, commentIdx).trim();
}
if (trimmedLine.isEmpty()) return false;
// Check if ends with operator
char lastChar = trimmedLine.charAt(trimmedLine.length() - 1);
if (lastChar == '+' || lastChar == '-' || lastChar == '*' ||
if (lastChar == '+' || lastChar == '-' || lastChar == '*' ||
lastChar == '/' || lastChar == '%' || lastChar == '=' ||
lastChar == '&' || lastChar == '|' || lastChar == '^' ||
lastChar == '?' || lastChar == ':' || lastChar == ',' ||
@@ -343,17 +360,17 @@ public class IndentHelper {
}
return false;
}
/**
* Result of text formatting
*/
public static class FormatResult {
public final String text;
public final int cursorPosition;
public FormatResult(String text, int cursorPosition) {
this.text = text;
this.cursorPosition = cursorPosition;
}
}
}
}
@@ -11,37 +11,38 @@ import java.util.regex.Pattern;
public class JavaTextContainer extends TextContainer {
public static final Pattern MODIFIER = Pattern.compile(
"\\b(public|protected|private|static|final|abstract|synchronized|native|default)\\b");
"\\b(public|protected|private|static|final|abstract|synchronized|native|default)\\b");
public static final Pattern KEYWORD = Pattern.compile(
"\\b(null|boolean|int|float|double|long|char|byte|short|void|if|else|switch|case|for|while|do|try|catch|finally|return|throw|var|let|const|function|continue|break|this|new|typeof|instanceof|import)\\b");
"\\b(null|boolean|int|float|double|long|char|byte|short|void|if|else|switch|case|for|while|do|try|catch|finally|return|throw|var|let|const|function|continue|break|this|new|typeof|instanceof|import)\\b");
public static final Pattern CLASS_DECL = Pattern.compile("\\b(class|interface|enum)\\s+([A-Za-z_][a-zA-Z0-9_]*)");
public static final Pattern NEW_TYPE = Pattern.compile("\\bnew\\s+([A-Za-z_][a-zA-Z0-9_]*)");;
public static final Pattern NEW_TYPE = Pattern.compile("\\bnew\\s+([A-Za-z_][a-zA-Z0-9_]*)");
;
public static final Pattern METHOD_DECL = Pattern.compile("\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name
);
public static final Pattern METHOD_CALL = Pattern.compile("([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(");
// Class-level global fields
public static final Pattern GLOBAL_FIELD_DECL = Pattern.compile(
"\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
"\\b([A-Za-z_][a-zA-Z0-9_<>\\[\\]]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
// Local fields inside methods (simplified)
public static final Pattern LOCAL_FIELD_DECL = Pattern.compile(
"\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
"\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
public static final Pattern STRING = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1");
public static final Pattern COMMENT = Pattern.compile("/\\*[\\s\\S]*?(?:\\*/|$)|//.*|#.*");
public static final Pattern NUMBER = Pattern.compile(
"\\b-?(?:0[xX][\\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?(?:[fFbBdDlLsS])?|NaN|null|Infinity|true|false)\\b");
"\\b-?(?:0[xX][\\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?(?:[fFbBdDlLsS])?|NaN|null|Infinity|true|false)\\b");
// Import statement: import [static] package.path.ClassName [.*]; (semicolon optional for live typing)
// Allows optional whitespace (including newlines) around the dots so wrapped imports match.
// Match imports while allowing optional whitespace/newlines around dots.
public static final Pattern IMPORT = Pattern.compile(
"(?m)\\bimport\\s+(?:static\\s+)?([A-Za-z_][A-Za-z0-9_]*(?:\\s*\\.\\s*[A-Za-z_][A-Za-z0-9_]*)*)(?:\\s*\\.\\s*\\*?)?\\s*(?:;|$)");
// Import statement: import [static] package.path.ClassName [.*]; (semicolon optional for live typing)
// Allows optional whitespace (including newlines) around the dots so wrapped imports match.
// Match imports while allowing optional whitespace/newlines around dots.
public static final Pattern IMPORT = Pattern.compile(
"(?m)\\bimport\\s+(?:static\\s+)?([A-Za-z_][A-Za-z0-9_]*(?:\\s*\\.\\s*[A-Za-z_][A-Za-z0-9_]*)*)(?:\\s*\\.\\s*\\*?)?\\s*(?:;|$)");
// ClassPathFinder for resolving imports and determining class types
private final ClassPathFinder classPathFinder = new ClassPathFinder();
@@ -73,10 +74,10 @@ public class JavaTextContainer extends TextContainer {
return pathStart + orig.length();
}
public void init(String text,int width, int height) {
public void init(String text, int width, int height) {
this.text = text == null ? "" : text.replaceAll("\\r?\\n|\\r", "\n");
lines.clear();
String[] split = text.split("\n",-1);
String[] split = text.split("\n", -1);
int totalChars = 0;
for (String l : split) {
@@ -196,32 +197,38 @@ public class JavaTextContainer extends TextContainer {
}
}
}
/**
* Parse and highlight generic type parameters using ClassPathFinder.
* Handles arbitrarily nested generics like "Map<String, List<Map<String, String>>>".
*/
private void highlightGenericTypes(String genericContent, int contentStart, List<Mark> marks, List<int[]> excluded) {
if (genericContent == null || genericContent.isEmpty()) return;
List<ClassPathFinder.TypeOccurrence> occurrences = classPathFinder.parseGenericTypes(genericContent, importedClasses, importedPackages);
for (ClassPathFinder.TypeOccurrence occ : occurrences) {
int absStart = contentStart + occ.startOffset;
int absEnd = contentStart + occ.endOffset;
if (!isInExcludedRange(absStart, excluded)) {
TokenType tokenType;
switch (occ.type) {
case INTERFACE: tokenType = TokenType.INTERFACE_DECL; break;
case ENUM: tokenType = TokenType.ENUM_DECL; break;
default: tokenType = TokenType.IMPORTED_CLASS; break;
case INTERFACE:
tokenType = TokenType.INTERFACE_DECL;
break;
case ENUM:
tokenType = TokenType.ENUM_DECL;
break;
default:
tokenType = TokenType.IMPORTED_CLASS;
break;
}
marks.add(new Mark(absStart, absEnd, tokenType));
}
}
}
private void collectFields() {
globalFields.clear();
localFields.clear();
@@ -229,7 +236,7 @@ public class JavaTextContainer extends TextContainer {
// Extract method blocks first
methodBlocks = MethodBlock.collectMethodBlocks(text);
// Get excluded ranges (strings and comments) for the entire text
List<int[]> excludedRanges = MethodBlock.getExcludedRanges(text);
@@ -238,7 +245,7 @@ public class JavaTextContainer extends TextContainer {
while (mGlobal.find()) {
String varName = mGlobal.group(2);
int varPosition = mGlobal.start(2);
// Skip if inside a string or comment
if (isInExcludedRange(varPosition, excludedRanges)) {
continue;
@@ -298,7 +305,7 @@ public class JavaTextContainer extends TextContainer {
"String", "Object", "Array", "Math", "System", "Integer", "Double", "Float",
"Boolean", "Long", "Byte", "Short", "Character", "List", "Map", "Set"
));
// First pass: handle field accesses (this.field and obj.field patterns)
Pattern thisFieldPattern = Pattern.compile("\\bthis\\s*\\.\\s*([a-zA-Z_][a-zA-Z0-9_]*)");
Matcher thisFieldMatcher = thisFieldPattern.matcher(text);
@@ -312,7 +319,7 @@ public class JavaTextContainer extends TextContainer {
marks.add(new Mark(fieldPos, thisFieldMatcher.end(1), TokenType.UNDEFINED_VAR));
}
}
// Handle identifier.field patterns (e.g., obj.field, global.field)
// The field part should be highlighted as GLOBAL_FIELD (light blue)
// Also, detect chained accesses like `a.b.c` and treat subsequent segments
@@ -378,13 +385,13 @@ public class JavaTextContainer extends TextContainer {
marks.add(new Mark(fieldPos, objFieldMatcher.end(2), TokenType.GLOBAL_FIELD));
}
}
Pattern identifier = Pattern.compile("\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b");
Matcher m = identifier.matcher(text);
while (m.find()) {
String name = m.group(1);
int position = m.start(1);
// Skip known keywords
if (knownIdentifiers.contains(name)) continue;
@@ -462,24 +469,24 @@ public class JavaTextContainer extends TextContainer {
}
return false;
}
/**
* Check if the identifier at this position is a field access (preceded by a dot)
* e.g., in "obj.field", the "field" part is a field access
*/
private boolean isFieldAccess(int position) {
if (position <= 0) return false;
// Look backwards from position, skipping any whitespace
int i = position - 1;
while (i >= 0 && Character.isWhitespace(text.charAt(i))) {
i--;
}
// Check if preceded by a dot
return i >= 0 && text.charAt(i) == '.';
}
/**
* Check if the identifier at this position is a method call (followed by parenthesis)
*/
@@ -497,7 +504,7 @@ public class JavaTextContainer extends TextContainer {
// Check for opening paren
return i < text.length() && text.charAt(i) == '(';
}
/**
* Check if this looks like a type reference (e.g., part of a declaration or generic)
* But NOT a comparison like "i < container" which uses < as less-than operator
@@ -510,7 +517,7 @@ public class JavaTextContainer extends TextContainer {
return true;
}
}
// Check if preceded by < but make sure it's a generic, not a comparison
// Generic: Type<Name or ,Name in generics
// Comparison: value < name (space before < means comparison)
@@ -549,7 +556,7 @@ public class JavaTextContainer extends TextContainer {
}
return false;
}
/**
* Check if position is in an excluded range (string or comment)
*/
@@ -608,9 +615,15 @@ public class JavaTextContainer extends TextContainer {
ClassPathFinder.ClassSegment seg = result.classSegments.get(si);
TokenType segType;
switch (seg.type) {
case INTERFACE: segType = TokenType.INTERFACE_DECL; break;
case ENUM: segType = TokenType.ENUM_DECL; break;
default: segType = TokenType.IMPORTED_CLASS; break;
case INTERFACE:
segType = TokenType.INTERFACE_DECL;
break;
case ENUM:
segType = TokenType.ENUM_DECL;
break;
default:
segType = TokenType.IMPORTED_CLASS;
break;
}
marks.add(new Mark(s, e, segType));
}
@@ -631,9 +644,15 @@ public class JavaTextContainer extends TextContainer {
ClassPathFinder.ClassSegment seg = result.classSegments.get(si);
TokenType segType;
switch (seg.type) {
case INTERFACE: segType = TokenType.INTERFACE_DECL; break;
case ENUM: segType = TokenType.ENUM_DECL; break;
default: segType = TokenType.IMPORTED_CLASS; break;
case INTERFACE:
segType = TokenType.INTERFACE_DECL;
break;
case ENUM:
segType = TokenType.ENUM_DECL;
break;
default:
segType = TokenType.IMPORTED_CLASS;
break;
}
marks.add(new Mark(s, e, segType));
}
@@ -698,7 +717,11 @@ public class JavaTextContainer extends TextContainer {
List<Integer> tokenStarts = new ArrayList<>();
List<Integer> tokenEnds = new ArrayList<>();
Matcher tokm = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*").matcher(orig);
while (tokm.find()) { tokens.add(tokm.group()); tokenStarts.add(tokm.start()); tokenEnds.add(tokm.end()); }
while (tokm.find()) {
tokens.add(tokm.group());
tokenStarts.add(tokm.start());
tokenEnds.add(tokm.end());
}
int tokenCount = tokenStarts.size();
if (tokenCount > 0) {
@@ -713,9 +736,15 @@ public class JavaTextContainer extends TextContainer {
TokenType segType = TokenType.IMPORTED_CLASS;
if (outerInfo != null) {
switch (outerInfo.type) {
case INTERFACE: segType = TokenType.INTERFACE_DECL; break;
case ENUM: segType = TokenType.ENUM_DECL; break;
default: segType = TokenType.IMPORTED_CLASS; break;
case INTERFACE:
segType = TokenType.INTERFACE_DECL;
break;
case ENUM:
segType = TokenType.ENUM_DECL;
break;
default:
segType = TokenType.IMPORTED_CLASS;
break;
}
}
marks.add(new Mark(s, e, segType));
@@ -748,7 +777,6 @@ public class JavaTextContainer extends TextContainer {
}
}
private void collectImportedClassUsages(List<Mark> marks) {
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
@@ -779,7 +807,7 @@ public class JavaTextContainer extends TextContainer {
boolean isShadowed = globalFields.contains(className) || localFields.contains(className);
if (block != null) {
isShadowed = isShadowed || block.parameters.contains(className) || block.isLocalDeclaredAtPosition(
className, start);
className, start);
}
if (isImported && !isShadowed) {
@@ -788,8 +816,12 @@ public class JavaTextContainer extends TextContainer {
TokenType tokenType = TokenType.IMPORTED_CLASS;
if (info != null) {
switch (info.type) {
case INTERFACE: tokenType = TokenType.INTERFACE_DECL; break;
case ENUM: tokenType = TokenType.ENUM_DECL; break;
case INTERFACE:
tokenType = TokenType.INTERFACE_DECL;
break;
case ENUM:
tokenType = TokenType.ENUM_DECL;
break;
}
}
marks.add(new Mark(start, end, tokenType));
@@ -819,7 +851,7 @@ public class JavaTextContainer extends TextContainer {
}
}
}
public void formatCodeText() {
// Step 1: Tokenize the full text
List<Mark> marks = new ArrayList<>();
@@ -855,7 +887,7 @@ public class JavaTextContainer extends TextContainer {
// Compute indent guides based on matched braces, ignoring strings/comments
computeIndentGuides(marks);
// Step 2: Clear existing tokens
for (LineData line : lines) {
line.tokens.clear();
@@ -880,7 +912,7 @@ public class JavaTextContainer extends TextContainer {
if (cursor < tokenStart) {
int end = Math.min(tokenStart, text.length());
line.tokens.add(
new Token(text.substring(cursor, end), TokenType.DEFAULT, cursor, end));
new Token(text.substring(cursor, end), TokenType.DEFAULT, cursor, end));
}
// token text
@@ -910,50 +942,53 @@ public class JavaTextContainer extends TextContainer {
private void collectTypeDeclarations(List<Mark> marks) {
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
// Pattern to find type declarations: Type<...> variableName or Type variableName
// We'll manually parse the generic portion to handle arbitrary nesting
Pattern typeStart = Pattern.compile(
"(?:(?:public|private|protected|static|final|transient|volatile)\\s+)*" +
"([A-Z][a-zA-Z0-9_]*)\\s*" // Group 1 → type name (must start with uppercase)
"([A-Z][a-zA-Z0-9_]*)\\s*" // Group 1 → type name (must start with uppercase)
);
for (LineData ld : lines) {
int lineStart = ld.start;
int lineEnd = ld.end;
if (lineStart >= lineEnd) continue;
String s = ld.text;
Matcher m = typeStart.matcher(s);
int searchFrom = 0;
while (m.find(searchFrom)) {
int typeNameStart = lineStart + m.start(1);
int typeNameEnd = lineStart + m.end(1);
// Skip if in excluded range
boolean skip = false;
for (int[] r : excluded) {
if (typeNameStart < r[1] && typeNameEnd > r[0]) { skip = true; break; }
if (typeNameStart < r[1] && typeNameEnd > r[0]) {
skip = true;
break;
}
}
if (skip) {
searchFrom = m.end();
continue;
}
String typeName = m.group(1);
int posAfterType = m.end(1);
// Skip whitespace after type name
while (posAfterType < s.length() && Character.isWhitespace(s.charAt(posAfterType))) {
posAfterType++;
}
// Check for generic parameters
String genericContent = null;
int genericStart = -1;
int genericEnd = -1;
if (posAfterType < s.length() && s.charAt(posAfterType) == '<') {
genericStart = posAfterType;
int depth = 1;
@@ -970,12 +1005,12 @@ public class JavaTextContainer extends TextContainer {
posAfterType = genericEnd;
}
}
// Skip whitespace after generics
while (posAfterType < s.length() && Character.isWhitespace(s.charAt(posAfterType))) {
posAfterType++;
}
// Check if this looks like a type declaration:
// 1. Has generic content (e.g., List<String>) - always a type
// 2. Followed by a variable name (lowercase start or underscore)
@@ -983,38 +1018,43 @@ public class JavaTextContainer extends TextContainer {
boolean hasGeneric = genericContent != null && !genericContent.isEmpty();
boolean atEndOfLine = posAfterType >= s.length();
boolean followedByVarName = false;
if (!atEndOfLine) {
char nextChar = s.charAt(posAfterType);
followedByVarName = Character.isLetter(nextChar) || nextChar == '_';
}
// Accept as type if: has generics OR followed by variable name
// This handles both `List<String> myList` and wrapped lines like `List<String>`
if (hasGeneric || followedByVarName) {
// This looks like a type declaration
// Resolve the main type
ClassPathFinder.ClassInfo info = classPathFinder.resolveSimpleName(typeName, importedClasses, importedPackages);
TokenType tokenType = TokenType.UNDEFINED_VAR;
if (info != null) {
switch (info.type) {
case INTERFACE: tokenType = TokenType.INTERFACE_DECL; break;
case ENUM: tokenType = TokenType.ENUM_DECL; break;
default: tokenType = TokenType.TYPE_DECL;
case INTERFACE:
tokenType = TokenType.INTERFACE_DECL;
break;
case ENUM:
tokenType = TokenType.ENUM_DECL;
break;
default:
tokenType = TokenType.TYPE_DECL;
}
}
marks.add(new Mark(typeNameStart, typeNameEnd, tokenType));
// Handle generic content
if (hasGeneric && genericStart >= 0) {
int absGenericStart = lineStart + genericStart;
int absGenericEnd = lineStart + genericEnd;
// Mark < and > as default
marks.add(new Mark(absGenericStart, absGenericStart + 1, TokenType.DEFAULT));
marks.add(new Mark(absGenericEnd - 1, absGenericEnd, TokenType.DEFAULT));
// Parse and highlight all types in generic content
int contentStart = lineStart + genericStart + 1;
highlightGenericTypes(genericContent, contentStart, marks, excluded);
@@ -1046,7 +1086,7 @@ public class JavaTextContainer extends TextContainer {
}
}
}
searchFrom = m.end();
}
}
@@ -11,17 +11,17 @@ public class MethodBlock {
// pattern matches returnType + methodName + parentheses
public static final Pattern METHOD_PATTERN = Pattern.compile(
"\\b([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name
"\\b([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(" // method name
);
// Pattern for variable declarations (same as in JavaTextContainer)
public static final Pattern LOCAL_VAR_DECL = Pattern.compile(
"\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
"\\b([A-Z][a-zA-Z0-9_<>\\[\\]]*|[a-z][a-zA-Z0-9_]*)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(=|;)");
// Pattern for method parameters: Type name (with optional ... for varargs)
public static final Pattern PARAMETER_PATTERN = Pattern.compile(
"([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*(?:\\.{3})?)\\s+([a-zA-Z_][a-zA-Z0-9_]*)");
"([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*(?:\\.{3})?)\\s+([a-zA-Z_][a-zA-Z0-9_]*)");
public int startOffset;
public int endOffset;
@@ -37,22 +37,22 @@ public class MethodBlock {
extractParameters();
extractLocalVariables();
}
// Extract method parameters from the method signature
private void extractParameters() {
parameters.clear();
// Find the parameter list between ( and )
int parenStart = text.indexOf('(');
int parenEnd = text.indexOf(')');
if (parenStart < 0 || parenEnd <= parenStart) return;
String paramList = text.substring(parenStart + 1, parenEnd);
// Skip if empty
if (paramList.trim().isEmpty()) return;
// Split by comma (but be careful of generic types like List<A, B>)
Matcher m = PARAMETER_PATTERN.matcher(paramList);
while (m.find()) {
@@ -67,20 +67,20 @@ public class MethodBlock {
private void extractLocalVariables() {
localVariables.clear();
localVarPositions.clear();
// Get excluded ranges (strings and comments) for this method's text
List<int[]> excludedRanges = getExcludedRanges(text);
Matcher m = LOCAL_VAR_DECL.matcher(text);
while (m.find()) {
String varName = m.group(2);
int declPosition = m.start();
// Skip if inside a string or comment
if (isInExcludedRange(declPosition, excludedRanges)) {
continue;
}
// Check if this is a "this.field" assignment - if so, skip it
// Look backwards from the declaration position to see if preceded by "this."
boolean isThisFieldAssignment = false;
@@ -91,7 +91,7 @@ public class MethodBlock {
isThisFieldAssignment = true;
}
}
if (!isThisFieldAssignment && !localVariables.contains(varName)) {
localVariables.add(varName);
// Store the absolute position in the full text (startOffset + relative position)
@@ -99,7 +99,7 @@ public class MethodBlock {
}
}
}
// Check if a reference position comes before the local variable declaration
// This handles cases like: global.field on line 7, then var global = "x" on line 9
// At line 7, the local 'global' doesn't exist yet, so it should refer to the global 'global'
@@ -129,10 +129,10 @@ public class MethodBlock {
// Matches: returnType methodName(...) { (non-greedy capture until first { )
Pattern methodPattern = Pattern.compile(
"\\b([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\([^)]*\\)\\s*" + // method name + parameters
"\\{", // opening brace
Pattern.MULTILINE);
"\\b([a-zA-Z_][a-zA-Z0-9_<>\\[\\]]*)\\s+" + // return type
"([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\([^)]*\\)\\s*" + // method name + parameters
"\\{", // opening brace
Pattern.MULTILINE);
Matcher m = methodPattern.matcher(text);
while (m.find()) {
@@ -160,14 +160,14 @@ public class MethodBlock {
Pattern stringPattern = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1");
Matcher stringMatcher = stringPattern.matcher(text);
while (stringMatcher.find()) {
ranges.add(new int[] { stringMatcher.start(), stringMatcher.end() });
ranges.add(new int[]{stringMatcher.start(), stringMatcher.end()});
}
// Find all comments (block and line comments)
Pattern commentPattern = Pattern.compile("/\\*[\\s\\S]*?(?:\\*/|$)|//.*");
Matcher commentMatcher = commentPattern.matcher(text);
while (commentMatcher.find()) {
ranges.add(new int[] { commentMatcher.start(), commentMatcher.end() });
ranges.add(new int[]{commentMatcher.start(), commentMatcher.end()});
}
if (ranges.isEmpty())
@@ -7,7 +7,6 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
@@ -1,7 +1,6 @@
package noppes.npcs.client.gui.util.script;
import net.minecraft.client.gui.GuiScreen;
import noppes.npcs.client.ClientProxy;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import org.lwjgl.input.Keyboard;
@@ -12,7 +11,7 @@ import java.util.regex.Pattern;
/**
* Handles IntelliJ-like rename refactoring with scope-aware renaming.
*
* <p>
* Features:
* - Scope detection: local variables rename only within their block, global fields rename everywhere
* - Visual feedback: primary occurrence has white border, others just highlighted
@@ -33,7 +32,7 @@ public class RenameRefactorHandler {
private int primaryOccurrenceEnd = -1;
private List<int[]> allOccurrences = new ArrayList<>();
private ScopeInfo scope = null;
// For global scope, track positions that have local shadowing (to exclude them)
private List<int[]> localShadowedPositions = new ArrayList<>();
@@ -141,10 +140,10 @@ public class RenameRefactorHandler {
initialWord = text.substring(wordBounds[0], wordBounds[1]); // Remember for undo
originalWord = initialWord;
currentWord = initialWord;
// Determine scope for this identifier - MUST check if local shadows global
scope = determineScope(text, wordBounds[0], originalWord, callback.getContainer());
// If global scope, find all positions where local variables shadow this name
localShadowedPositions.clear();
if (scope != null && scope.isGlobal) {
@@ -158,12 +157,12 @@ public class RenameRefactorHandler {
return false;
active = true;
// Set selection to full word (uses GuiScriptTextArea's selection)
primaryOccurrenceStart = wordBounds[0];
primaryOccurrenceEnd = wordBounds[1];
callback.getSelectionState().setSelection(wordBounds[0], wordBounds[1]);
// callback.setCursorPosition(wordBounds[1]);
// callback.setCursorPosition(wordBounds[1]);
callback.getSelectionState().markActivity();
return true;
@@ -207,7 +206,7 @@ public class RenameRefactorHandler {
// During live editing we used setTextWithoutUndo to avoid creating intermediate
// undo entries; pushing the original snapshot here gives a single predictable
// undo step back to the pre-rename state.
if (originalText != null && !originalText.isEmpty())
if (originalText != null && !originalText.isEmpty())
callback.pushUndoState(originalText, originalCursorPos);
// Calculate cursor position relative to primary occurrence
@@ -237,6 +236,7 @@ public class RenameRefactorHandler {
/**
* Handle keyboard input during rename
*
* @return true if input was consumed
*/
public boolean keyTyped(char c, int keyCode) {
@@ -264,7 +264,7 @@ public class RenameRefactorHandler {
// Get selection state
SelectionState sel = callback.getSelectionState();
boolean hasSelection = sel.hasSelection();
// Calculate cursor position within the word
int cursorInWord = callback.getCursorPosition() - primaryOccurrenceStart;
cursorInWord = Math.max(0, Math.min(cursorInWord, currentWord.length()));
@@ -315,7 +315,7 @@ public class RenameRefactorHandler {
sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart);
callback.setCursorPosition(primaryOccurrenceStart);
}
// Left arrow
if (keyCode == Keyboard.KEY_LEFT) {
if (cursorInWord > 0) {
@@ -354,7 +354,7 @@ public class RenameRefactorHandler {
// Ctrl+A - select all (select the whole word)
if (keyCode == Keyboard.KEY_A &&
Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
sel.setSelection(primaryOccurrenceStart, primaryOccurrenceStart + currentWord.length());
callback.setCursorPosition(primaryOccurrenceStart + currentWord.length());
sel.markActivity();
@@ -537,22 +537,22 @@ public class RenameRefactorHandler {
}
}
}
/**
* Find all positions where local variables with the same name shadow the global variable.
* This populates localShadowedPositions with ranges where local declarations exist.
*/
private void findLocalShadowedPositions(String text, String varName) {
localShadowedPositions.clear();
List<MethodBlock> methods = MethodBlock.collectMethodBlocks(text);
List<int[]> excluded = MethodBlock.getExcludedRanges(text);
for (MethodBlock method : methods) {
// Check if this method has a local variable or parameter with the same name
boolean hasLocalDecl = method.localVariables.contains(varName);
boolean hasParamDecl = isParameterInMethod(text, varName, method);
if (hasLocalDecl || hasParamDecl) {
// Find where the local/param scope starts
int scopeStart;
@@ -564,18 +564,18 @@ public class RenameRefactorHandler {
scopeStart = findLocalDeclarationPosition(text, varName, method);
if (scopeStart < 0) scopeStart = method.startOffset;
}
// Find all occurrences of varName within this method's shadowed range
Pattern pattern = Pattern.compile("\\b" + Pattern.quote(varName) + "\\b");
Matcher m = pattern.matcher(text);
while (m.find()) {
int pos = m.start();
// Skip if in string or comment
if (isInExcludedRange(pos, excluded))
continue;
// Check if within the shadowed scope of this method
if (pos >= scopeStart && pos < method.endOffset) {
localShadowedPositions.add(new int[]{m.start(), m.end()});
@@ -584,7 +584,7 @@ public class RenameRefactorHandler {
}
}
}
/**
* Check if a position is within a locally shadowed range
*/
@@ -595,13 +595,13 @@ public class RenameRefactorHandler {
}
return false;
}
/**
* Check if varName is a parameter in the method
*/
private boolean isParameterInMethod(String text, String varName, MethodBlock method) {
String methodHeader = text.substring(method.startOffset,
Math.min(method.startOffset + 500, method.endOffset));
Math.min(method.startOffset + 500, method.endOffset));
int parenStart = methodHeader.indexOf('(');
int parenEnd = methodHeader.indexOf(')');
if (parenStart >= 0 && parenEnd > parenStart) {
@@ -687,7 +687,7 @@ public class RenameRefactorHandler {
// Cursor is inside a method
// Check if it's a method parameter first
String methodHeader = text.substring(containingMethod.startOffset,
Math.min(containingMethod.startOffset + 500, containingMethod.endOffset));
Math.min(containingMethod.startOffset + 500, containingMethod.endOffset));
int parenStart = methodHeader.indexOf('(');
int parenEnd = methodHeader.indexOf(')');
if (parenStart >= 0 && parenEnd > parenStart) {
@@ -861,9 +861,9 @@ public class RenameRefactorHandler {
public boolean isWordFullySelected() {
if (callback == null) return false;
SelectionState selection = callback.getSelectionState();
return selection.hasSelection() &&
selection.getStartSelection() == primaryOccurrenceStart &&
selection.getEndSelection() == primaryOccurrenceEnd;
return selection.hasSelection() &&
selection.getStartSelection() == primaryOccurrenceStart &&
selection.getEndSelection() == primaryOccurrenceEnd;
}
/**
@@ -884,7 +884,7 @@ public class RenameRefactorHandler {
public boolean handleClick(int clickPosInText) {
if (!active || callback == null)
return false;
return false;
}
@@ -21,12 +21,12 @@ public class ScrollState {
private int scrollbarDragOffset = 0;
// Whether currently dragging the scrollbar
private boolean clickScrolling = false;
// Animation parameters
private static final double TAU = 0.1; // Time constant (~55ms feels snappy)
private static final double SNAP_THRESHOLD = 0.01; // Snap to target when this close
private static final double MAX_DT = 0.05; // Max delta time for stability
/**
* Reset scroll state to initial values
*/
@@ -37,7 +37,7 @@ public class ScrollState {
scrolledLine = 0;
lastScrollTime = System.currentTimeMillis();
}
/**
* Initialize scroll position if not already initialized
*/
@@ -47,18 +47,19 @@ public class ScrollState {
lastScrollTime = System.currentTimeMillis();
}
}
/**
* Update scroll animation. Call once per frame.
*
* @param maxScroll Maximum valid scroll position
*/
public void update(int maxScroll) {
long nowMs = System.currentTimeMillis();
double dt = Math.min(MAX_DT, (nowMs - lastScrollTime) / 1000.0);
lastScrollTime = nowMs;
double dist = targetScroll - scrollPos;
// Snap to target if close enough
if (Math.abs(dist) < SNAP_THRESHOLD) {
scrollPos = targetScroll;
@@ -69,21 +70,21 @@ public class ScrollState {
double prev = scrollPos;
scrollPos += dist * alpha;
scrollVelocity = (scrollPos - prev) / (dt > 0 ? dt : 1e-6);
// Clamp overshoot
if ((dist > 0 && scrollPos > targetScroll) || (dist < 0 && scrollPos < targetScroll)) {
scrollPos = targetScroll;
scrollVelocity = 0.0;
}
}
// Keep in bounds
clampToBounds(maxScroll);
// Update integer line for rendering
scrolledLine = Math.max(0, Math.min((int) Math.floor(scrollPos), maxScroll));
}
/**
* Clamp scroll position to valid bounds
*/
@@ -94,35 +95,37 @@ public class ScrollState {
if (targetScroll > maxScroll) targetScroll = maxScroll;
scrolledLine = Math.max(0, Math.min(scrolledLine, maxScroll));
}
/**
* Apply mouse wheel scroll
*
* @param wheelDelta Positive = scroll up, negative = scroll down
* @param maxScroll Maximum valid scroll position
* @param maxScroll Maximum valid scroll position
*/
public void applyWheelScroll(int wheelDelta, int maxScroll) {
double sign = Math.copySign(1, wheelDelta);
targetScroll -= sign * 2.0; // 2 lines per wheel tick
clampToBounds(maxScroll);
}
/**
* Set target scroll directly (for scrollbar dragging)
*/
public void setTargetScroll(double target, int maxScroll) {
targetScroll = Math.max(0, Math.min(target, maxScroll));
}
/**
* Scroll to make a specific line visible
* @param lineIdx Line index to make visible
*
* @param lineIdx Line index to make visible
* @param visibleLines Number of visible lines in viewport
* @param maxScroll Maximum scroll position
* @param maxScroll Maximum scroll position
*/
public void scrollToLine(int lineIdx, int visibleLines, int maxScroll) {
int firstVisible = scrolledLine;
int lastFullyVisible = scrolledLine + visibleLines;
if (lineIdx < firstVisible) {
// Line is above viewport - scroll up
targetScroll = lineIdx;
@@ -132,41 +135,66 @@ public class ScrollState {
}
// If line is visible, don't change scroll
}
// Getters
public double getScrollPos() { return scrollPos; }
public double getTargetScroll() { return targetScroll; }
/** @return First visible line **/
// Getters
public double getScrollPos() {
return scrollPos;
}
public double getTargetScroll() {
return targetScroll;
}
/**
* @return First visible line
**/
public int getScrolledLine() {
return scrolledLine;
}
public double getScrollVelocity() { return scrollVelocity; }
public boolean isClickScrolling() { return clickScrolling; }
public int getScrollbarDragOffset() { return scrollbarDragOffset; }
public double getScrollVelocity() {
return scrollVelocity;
}
public boolean isClickScrolling() {
return clickScrolling;
}
public int getScrollbarDragOffset() {
return scrollbarDragOffset;
}
/**
* Get fractional offset for sub-pixel rendering
*/
public double getFractionalOffset() {
return scrollPos - scrolledLine;
}
// Setters for scrollbar interaction
public void setClickScrolling(boolean scrolling) { this.clickScrolling = scrolling; }
public void setScrollbarDragOffset(int offset) { this.scrollbarDragOffset = offset; }
public void setScrolledLine(int line) { this.scrolledLine = line; }
public void setClickScrolling(boolean scrolling) {
this.clickScrolling = scrolling;
}
public void setScrollbarDragOffset(int offset) {
this.scrollbarDragOffset = offset;
}
public void setScrolledLine(int line) {
this.scrolledLine = line;
}
/**
* Handle scrollbar dragging interaction. This encapsulates the logic that was
* previously in the GUI class for handling thumb clicks/drags.
* @param yMouse current mouse Y coordinate
* @param areaX GUI area X (unused but kept for parity)
* @param areaY GUI area Y (top of text area)
* @param areaHeight height of the scroll track area
*
* @param yMouse current mouse Y coordinate
* @param areaX GUI area X (unused but kept for parity)
* @param areaY GUI area Y (top of text area)
* @param areaHeight height of the scroll track area
* @param visibleLines number of visible lines in viewport
* @param linesCount total number of lines
* @param maxScroll maximum allowed scroll value
* @param linesCount total number of lines
* @param maxScroll maximum allowed scroll value
*/
public void handleClickScrolling(int yMouse, int areaX, int areaY, int areaHeight, int visibleLines, int linesCount, int maxScroll) {
// Keep dragging while mouse button is down
@@ -210,4 +238,4 @@ public class ScrollState {
int thumbTop = (int) (areaY + 1f * getScrollPos() / linesCountD * (areaHeight - 4)) + 1;
setScrollbarDragOffset(yMouse - thumbTop);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
package noppes.npcs.client.gui.util.script;
import noppes.npcs.client.gui.util.script.JavaTextContainer.LineData;
import java.util.List;
import java.util.regex.Pattern;
@@ -12,14 +13,14 @@ public class SelectionState {
private int endSelection = 0;
private int cursorPosition = 0;
private long lastInputTime = 0L;
/**
* Reset all cursor selections to a single position
*/
public void reset(int position) {
startSelection = endSelection = cursorPosition = position;
}
/**
* Clamp all selection bounds to valid text range
*/
@@ -32,13 +33,13 @@ public class SelectionState {
endSelection = Math.max(0, Math.min(endSelection, textLength));
cursorPosition = Math.max(0, Math.min(cursorPosition, textLength));
}
/**
* Set cursor position, optionally extending selection
*/
public void setCursor(int position, int textLength, boolean extendSelection) {
position = Math.max(0, Math.min(position, textLength));
if (position != cursorPosition) {
if (!extendSelection) {
endSelection = startSelection = cursorPosition = position;
@@ -49,7 +50,7 @@ public class SelectionState {
} else if (cursorPosition == endSelection) {
endSelection -= diff;
}
// Ensure start <= end
if (startSelection > endSelection) {
int temp = endSelection;
@@ -62,7 +63,7 @@ public class SelectionState {
markActivity();
}
}
/**
* Select a range of text
*/
@@ -70,7 +71,7 @@ public class SelectionState {
startSelection = Math.min(start, end);
endSelection = Math.max(start, end);
}
/**
* Select all text
*/
@@ -78,14 +79,14 @@ public class SelectionState {
startSelection = cursorPosition = 0;
endSelection = textLength;
}
/**
* Check if there's an active selection (not just cursor)
*/
public boolean hasSelection() {
return startSelection != endSelection;
}
/**
* Get selected text
*/
@@ -95,7 +96,7 @@ public class SelectionState {
int end = Math.max(0, Math.min(endSelection, text.length()));
return text.substring(start, end);
}
/**
* Get text before selection/cursor
*/
@@ -103,7 +104,7 @@ public class SelectionState {
if (text == null || startSelection <= 0) return "";
return text.substring(0, Math.min(startSelection, text.length()));
}
/**
* Get text after selection/cursor
*/
@@ -112,37 +113,37 @@ public class SelectionState {
int pos = Math.min(endSelection, text.length());
return text.substring(pos);
}
/**
* Find which line the cursor is on (0-indexed)
*/
public int getCursorLineIndex(List<LineData> lines, int textLength) {
if (lines == null || lines.isEmpty()) return 0;
for (int i = 0; i < lines.size(); i++) {
LineData ld = lines.get(i);
boolean isLastLine = (i == lines.size() - 1);
boolean isOnLine = isLastLine
? (cursorPosition >= ld.start && cursorPosition <= ld.end)
: (cursorPosition >= ld.start && cursorPosition < ld.end);
boolean isOnLine = isLastLine
? (cursorPosition >= ld.start && cursorPosition <= ld.end)
: (cursorPosition >= ld.start && cursorPosition < ld.end);
if (isOnLine) {
return i;
}
}
return lines.size() - 1;
}
/**
* Check if cursor is on a specific line, handling the last line specially
* (last line doesn't have trailing newline, so use <= for end boundary)
* Check if cursor is on a specific line, handling the last line specially
* (last line doesn't have trailing newline, so use <= for end boundary)
*/
public boolean isCursorOnLine(int lineIndex, LineData line, int totalLines) {
boolean isLastLine = (lineIndex == totalLines - 1);
return isLastLine
? (cursorPosition >= line.start && cursorPosition <= line.end)
: (cursorPosition >= line.start && cursorPosition < line.end);
return isLastLine
? (cursorPosition >= line.start && cursorPosition <= line.end)
: (cursorPosition >= line.start && cursorPosition < line.end);
}
/**
* Find line containing the cursor
*/
@@ -156,32 +157,51 @@ public class SelectionState {
}
return null;
}
/**
* Mark user activity (for cursor blink timing)
*/
public void markActivity() {
lastInputTime = System.currentTimeMillis();
}
/**
* Check if there was recent input (for cursor blink pause)
*/
public boolean hadRecentInput() {
return System.currentTimeMillis() - lastInputTime < 500;
}
// Getters
public int getStartSelection() { return startSelection; }
public int getEndSelection() { return endSelection; }
public int getCursorPosition() { return cursorPosition; }
public long getLastInputTime() { return lastInputTime; }
public int getStartSelection() {
return startSelection;
}
public int getEndSelection() {
return endSelection;
}
public int getCursorPosition() {
return cursorPosition;
}
public long getLastInputTime() {
return lastInputTime;
}
// Direct setters (use with caution, prefer higher-level methods)
public void setStartSelection(int pos) { this.startSelection = pos; }
public void setEndSelection(int pos) { this.endSelection = pos; }
public void setCursorPositionDirect(int pos) { this.cursorPosition = pos; }
public void setStartSelection(int pos) {
this.startSelection = pos;
}
public void setEndSelection(int pos) {
this.endSelection = pos;
}
public void setCursorPositionDirect(int pos) {
this.cursorPosition = pos;
}
/**
* After text modification, update selection to new position
*/
@@ -219,4 +239,4 @@ public class SelectionState {
}
}
}
}
}
@@ -7,90 +7,92 @@ import java.util.List;
* Manages undo/redo stacks for the text editor.
*/
public class UndoManager {
/**
* Stores a snapshot of text state for undo/redo
*/
public static class UndoState {
public final String text;
public final int cursorPosition;
public UndoState(String text, int cursorPosition) {
this.text = text;
this.cursorPosition = cursorPosition;
}
}
private final List<UndoState> undoStack = new ArrayList<>();
private final List<UndoState> redoStack = new ArrayList<>();
private boolean isUndoing = false;
// Optional: limit stack size to prevent memory issues
private static final int MAX_STACK_SIZE = 100;
/**
* Record current state before making a change
*/
public void recordState(String text, int cursorPosition) {
if (isUndoing) return;
undoStack.add(new UndoState(text, cursorPosition));
redoStack.clear();
// Trim stack if too large
while (undoStack.size() > MAX_STACK_SIZE) {
undoStack.remove(0);
}
}
/**
* Undo to previous state
* @param currentText Current text before undo
*
* @param currentText Current text before undo
* @param currentCursor Current cursor position
* @return Previous state, or null if nothing to undo
*/
public UndoState undo(String currentText, int currentCursor) {
if (undoStack.isEmpty()) return null;
isUndoing = true;
redoStack.add(new UndoState(currentText, currentCursor));
UndoState state = undoStack.remove(undoStack.size() - 1);
isUndoing = false;
return state;
}
/**
* Redo to next state
* @param currentText Current text before redo
*
* @param currentText Current text before redo
* @param currentCursor Current cursor position
* @return Next state, or null if nothing to redo
*/
public UndoState redo(String currentText, int currentCursor) {
if (redoStack.isEmpty()) return null;
isUndoing = true;
undoStack.add(new UndoState(currentText, currentCursor));
UndoState state = redoStack.remove(redoStack.size() - 1);
isUndoing = false;
return state;
}
/**
* Check if undo is available
*/
public boolean canUndo() {
return !undoStack.isEmpty();
}
/**
* Check if redo is available
*/
public boolean canRedo() {
return !redoStack.isEmpty();
}
/**
* Clear all history
*/
@@ -98,22 +100,27 @@ public class UndoManager {
undoStack.clear();
redoStack.clear();
}
/**
* Check if currently performing an undo/redo operation
*/
public boolean isUndoing() {
return isUndoing;
}
/**
* Set undoing flag (for external control during setText)
*/
public void setUndoing(boolean undoing) {
this.isUndoing = undoing;
}
// For backward compatibility with existing code
public List<UndoState> getUndoList() { return undoStack; }
public List<UndoState> getRedoList() { return redoStack; }
}
public List<UndoState> getUndoList() {
return undoStack;
}
public List<UndoState> getRedoList() {
return redoStack;
}
}
@@ -15,10 +15,27 @@ public class KeyEvent {
this.timestamp = System.currentTimeMillis();
}
public boolean is(KeyPreset.PressType t) { return this.type == t; }
public boolean isPress() { return is(KeyPreset.PressType.PRESS); }
public boolean isHold() { return is(KeyPreset.PressType.HOLD); }
public boolean isRelease() { return is(KeyPreset.PressType.RELEASE); }
public boolean isSinglePress() { return is(KeyPreset.PressType.SINGLE_PRESS); }
public boolean isPressRelease() { return is(KeyPreset.PressType.PRESS_RELEASE); }
public boolean is(KeyPreset.PressType t) {
return this.type == t;
}
public boolean isPress() {
return is(KeyPreset.PressType.PRESS);
}
public boolean isHold() {
return is(KeyPreset.PressType.HOLD);
}
public boolean isRelease() {
return is(KeyPreset.PressType.RELEASE);
}
public boolean isSinglePress() {
return is(KeyPreset.PressType.SINGLE_PRESS);
}
public boolean isPressRelease() {
return is(KeyPreset.PressType.PRESS_RELEASE);
}
}
@@ -13,8 +13,10 @@ public class KeyPreset {
* @field SINGLE_PRESS => on releasing before 5 ticks press time
* @field PRESS_RELEASE => on pressing and releasing
*/
/** Press types for key events. */
public enum PressType { PRESS, HOLD, RELEASE, SINGLE_PRESS, PRESS_RELEASE }
/**
* Press types for key events.
*/
public enum PressType {PRESS, HOLD, RELEASE, SINGLE_PRESS, PRESS_RELEASE}
public KeyState defaultState = new KeyState();
public KeyState currentState = new KeyState();
@@ -81,7 +83,7 @@ public class KeyPreset {
if (throttleInterval <= 0) return false;
long currentTime = System.currentTimeMillis();
long intervalToUse = pressType == PressType.HOLD && isFirstAction && firstThrottleInterval > 0 ?
firstThrottleInterval : throttleInterval;
firstThrottleInterval : throttleInterval;
if (currentTime - lastActionTime < intervalToUse) return true;
lastActionTime = currentTime;
isFirstAction = false;
@@ -108,7 +110,7 @@ public class KeyPreset {
}
if (!down && isDown) { // just released
if (getPressTime() <= SHORT_PRESS_MS)
if (getPressTime() <= SHORT_PRESS_MS)
onAction(PressType.SINGLE_PRESS);
onAction(PressType.RELEASE, PressType.PRESS_RELEASE);
pressStartMs = 0;
@@ -116,10 +118,10 @@ public class KeyPreset {
if (down) // while held
onAction(PressType.HOLD);
this.isDown = down;
}
public long getPressTime() {
return pressStartMs > 0 ? (System.currentTimeMillis() - pressStartMs) : 0L;
}
@@ -25,7 +25,7 @@ public class KeyPresetManager {
}
public void tick() {
for (KeyPreset key : keys)
for (KeyPreset key : keys)
key.tick();
}
@@ -5,8 +5,8 @@ import noppes.npcs.client.key.KeyPresetManager;
import org.lwjgl.input.Keyboard;
public class ScriptEditorKeys extends KeyPresetManager {
////////////////////
/// /////////////////
// Editor shortcuts (mapped from GuiScriptTextArea.handleShortcutKeys)
public final KeyPreset COPY = add("Copy").setDefaultState(Keyboard.KEY_C, true, false, false);
public final KeyPreset PASTE = add("Paste").setDefaultState(Keyboard.KEY_V, true, false, false);
@@ -14,20 +14,20 @@ public class ScriptEditorKeys extends KeyPresetManager {
public final KeyPreset DUPLICATE = add("Duplicate").setDefaultState(Keyboard.KEY_D, true, false, false);
public final KeyPreset UNDO = add("Undo").setDefaultState(Keyboard.KEY_Z, true, false, false);
public final KeyPreset REDO = add("Redo").setDefaultState(Keyboard.KEY_Y, true, false, false);
public final KeyPreset FORMAT = add("Format Code").setDefaultState(Keyboard.KEY_F, false, true, false);
public final KeyPreset TOGGLE_COMMENT = add("Toggle Comment").setDefaultState(Keyboard.KEY_SLASH, true, false, false);
// Search/Replace
public final KeyPreset SEARCH = add("Search").setDefaultState(Keyboard.KEY_F, true, false, false);
public final KeyPreset SEARCH_REPLACE = add("Replace").setDefaultState(Keyboard.KEY_F, true, false, true);
// Navigation
public final KeyPreset GO_TO_LINE = add("Go to Line").setDefaultState(Keyboard.KEY_G, true, false, false);
// Refactoring
public final KeyPreset RENAME = add("Rename").setDefaultState(Keyboard.KEY_R, true, false, false);
// View
public final KeyPreset FULLSCREEN = add("Toggle Fullscreen").setDefaultState(Keyboard.KEY_F11, false, false, false);
@@ -17,7 +17,7 @@ import noppes.npcs.entity.EntityNpcPony;
import org.lwjgl.opengl.GL11;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
@@ -2,7 +2,7 @@ package noppes.npcs.client.renderer;
import net.minecraft.client.renderer.ImageBufferDownload;
import java.awt.*;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
@@ -25,7 +25,7 @@ import noppes.npcs.entity.EntityNpcPony;
import org.lwjgl.opengl.GL11;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
@@ -23,7 +23,7 @@ import noppes.npcs.blocks.tiles.TileScripted.TextPlane;
import noppes.npcs.client.TextBlockClient;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.awt.Color;
import java.util.Random;
public class BlockScriptedRenderer extends BlockRendererInterface {
@@ -5,7 +5,13 @@ import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.Point2D;
@@ -5,7 +5,8 @@ import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.awt.Font;
import java.awt.Point;
import java.awt.font.GlyphVector;
import java.lang.ref.WeakReference;
import java.text.Bidi;
@@ -1,13 +1,29 @@
package noppes.npcs.constants;
import noppes.npcs.api.event.*;
import noppes.npcs.api.event.IAnimationEvent;
import noppes.npcs.api.event.IBlockEvent;
import noppes.npcs.api.event.ICustomGuiEvent;
import noppes.npcs.api.event.IDialogEvent;
import noppes.npcs.api.event.IFactionEvent;
import noppes.npcs.api.event.IForgeEvent;
import noppes.npcs.api.event.IItemEvent;
import noppes.npcs.api.event.INpcEvent;
import noppes.npcs.api.event.IPartyEvent;
import noppes.npcs.api.event.IPlayerEvent;
import noppes.npcs.api.event.IProjectileEvent;
import noppes.npcs.api.event.IQuestEvent;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Represents a script context that maps to one or more event interface namespaces.
*
* <p>
* A script context can have multiple namespaces because script editors often
* support hooks from multiple event types. For example, Player scripts support:
* - IPlayerEvent (core player hooks)
@@ -15,17 +31,17 @@ import java.util.concurrent.ConcurrentHashMap;
* - IPartyEvent (party hooks)
* - ICustomGuiEvent (custom GUI hooks)
* - etc.
*
* <p>
* Each context also has a hookContext string used by ScriptHookController for
* hook registration and lookup.
*
* <p>
* This is a registerable system - any mod can register their own contexts:
*
* // Register a new context with multiple namespaces:
* ScriptContext.register("DBC", "dbc", IDBCEvent.class, IDBCPlayerEvent.class);
*
* // Or add namespaces to an existing context:
* ScriptContext.PLAYER.addNamespace("IDBCPlayerEvent");
* <p>
* // Register a new context with multiple namespaces:
* ScriptContext.register("DBC", "dbc", IDBCEvent.class, IDBCPlayerEvent.class);
* <p>
* // Or add namespaces to an existing context:
* ScriptContext.PLAYER.addNamespace("IDBCPlayerEvent");
*/
public class ScriptContext {
@@ -35,42 +51,42 @@ public class ScriptContext {
// ==================== BUILT-IN CONTEXTS ====================
public static final ScriptContext NPC = register("NPC", "npc",
INpcEvent.class,
IProjectileEvent.class
INpcEvent.class,
IProjectileEvent.class
);
public static final ScriptContext PLAYER = register("PLAYER", "player",
IPlayerEvent.class,
IAnimationEvent.class,
IPartyEvent.class,
IDialogEvent.class,
IQuestEvent.class,
IFactionEvent.class,
ICustomGuiEvent.class
IPlayerEvent.class,
IAnimationEvent.class,
IPartyEvent.class,
IDialogEvent.class,
IQuestEvent.class,
IFactionEvent.class,
ICustomGuiEvent.class
);
public static final ScriptContext BLOCK = register("BLOCK", "block",
IBlockEvent.class
IBlockEvent.class
);
public static final ScriptContext ITEM = register("ITEM", "item",
IItemEvent.class
IItemEvent.class
);
public static final ScriptContext FORGE = register("FORGE", "forge",
IForgeEvent.class
IForgeEvent.class
);
public static final ScriptContext LINKED_ITEM = register("LINKED_ITEM", "linked_item",
IItemEvent.class
IItemEvent.class
);
public static final ScriptContext RECIPE = register("RECIPE", "recipe",
"Recipe"
"Recipe"
);
public static final ScriptContext EFFECT = register("EFFECT", "effect",
"Effect"
"Effect"
);
public static final ScriptContext GLOBAL = register("GLOBAL", "",
@@ -79,13 +95,19 @@ public class ScriptContext {
// ==================== INSTANCE FIELDS ====================
/** Unique identifier for this context (e.g., "NPC", "PLAYER", "DBC") */
/**
* Unique identifier for this context (e.g., "NPC", "PLAYER", "DBC")
*/
public final String id;
/** Hook context identifier used by ScriptHookController (e.g., "npc", "player") */
/**
* Hook context identifier used by ScriptHookController (e.g., "npc", "player")
*/
public final String hookContext;
/** The event interface namespaces this context supports */
/**
* The event interface namespaces this context supports
*/
private final List<String> namespaces;
// ==================== CONSTRUCTOR ====================
@@ -144,9 +166,9 @@ public class ScriptContext {
/**
* Register a new script context with a hook context and one or more namespaces.
*
* @param id Unique identifier (e.g., "DBC", "CUSTOM")
* @param id Unique identifier (e.g., "DBC", "CUSTOM")
* @param hookContext The hook context string for ScriptHookController (e.g., "dbc")
* @param namespaces The event interface names (e.g., "IDBCEvent", "IDBCPlayerEvent")
* @param namespaces The event interface names (e.g., "IDBCEvent", "IDBCPlayerEvent")
* @return The registered ScriptContext
*/
public static ScriptContext register(String id, String hookContext, String... namespaces) {
@@ -158,12 +180,12 @@ public class ScriptContext {
/**
* Register a new script context using event interface classes.
* Automatically extracts the simple name from each class.
*
* <p>
* Example:
* ScriptContext.register("NPC", "npc", INpcEvent.class, IProjectileEvent.class);
* ScriptContext.register("NPC", "npc", INpcEvent.class, IProjectileEvent.class);
*
* @param id Unique identifier (e.g., "DBC", "CUSTOM")
* @param hookContext The hook context string for ScriptHookController (e.g., "npc")
* @param id Unique identifier (e.g., "DBC", "CUSTOM")
* @param hookContext The hook context string for ScriptHookController (e.g., "npc")
* @param eventClasses The event interface classes (simple names will be extracted)
* @return The registered ScriptContext
*/
@@ -231,10 +231,9 @@ public class AnimationController implements IAnimationHandler {
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////
// ANIMATION MAP
public File getMapDir() {
File dir = CustomNpcs.getWorldSaveDirectory();
if (!dir.exists())
@@ -97,7 +97,7 @@ public class HookDefinition implements IHookDefinition {
* Create a hook definition from a hook name and event class.
* Automatically derives imports from the event class.
*
* @param hookName The hook function name
* @param hookName The hook function name
* @param eventClass The event class (e.g., INpcEvent.InitEvent.class)
* @return A hook definition with auto-derived imports
*/
@@ -131,7 +131,7 @@ public class HookDefinition implements IHookDefinition {
* This provides backward compatibility with the annotation-based hook definition approach.
*
* @param hookName The hook name (may differ from method name)
* @param method The method to extract metadata from
* @param method The method to extract metadata from
* @return A hook definition with extracted metadata
*/
public static HookDefinition fromMethod(String hookName, Method method) {
@@ -165,7 +165,7 @@ public class HookDefinition implements IHookDefinition {
} else {
// Fallback: use lowercase simple type name
names[i] = Character.toLowerCase(params[i].getType().getSimpleName().charAt(0))
+ params[i].getType().getSimpleName().substring(1);
+ params[i].getType().getSimpleName().substring(1);
}
}
builder.paramNames(names);
@@ -94,8 +94,8 @@ public class LinkedItemController {
return this.linkedItemsScripts.get(id);
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////
public void load() {
lastUsedID = 0;
@@ -247,10 +247,9 @@ public class LinkedItemController {
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////
/// /////////////////////////////////////////////////////
// LINKED ITEMS MAP
public File getMapDir() {
File dir = CustomNpcs.getWorldSaveDirectory();
if (!dir.exists())
@@ -15,7 +15,7 @@ import java.util.concurrent.ConcurrentHashMap;
* Central registry for linked market synchronization.
* Tracks which RoleTrader instances use which markets,
* and which players are viewing each market.
*
* <p>
* This enables immediate sync across all traders sharing
* the same market when a purchase occurs.
*/
@@ -270,41 +270,41 @@ public class ScriptContainer implements IScriptUnit {
this.evaluated = false;
}
}
// ==================== IScriptUnit IMPLEMENTATION ====================
@Override
public String getScript() {
return this.script;
}
@Override
public void setScript(String script) {
this.script = script;
this.evaluated = false;
}
@Override
public List<String> getExternalScripts() {
return this.scripts;
}
@Override
public void setExternalScripts(List<String> scripts) {
this.scripts = scripts;
this.evaluated = false;
}
@Override
public TreeMap<Long, String> getConsole() {
return this.console;
}
@Override
public void clearConsole() {
this.console.clear();
}
@Override
public String getLanguage() {
// If a specific language is set for this container, use it
@@ -314,7 +314,7 @@ public class ScriptContainer implements IScriptUnit {
}
return handler != null ? handler.getLanguage() : "ECMAScript";
}
@Override
public void setLanguage(String language) {
if (!Objects.equals(this.currentScriptLanguage, language)) {
@@ -322,7 +322,7 @@ public class ScriptContainer implements IScriptUnit {
this.evaluated = false;
}
}
@Override
public String generateHookStub(String hookName, Object hookData) {
// ECMAScript function template
@@ -330,13 +330,14 @@ public class ScriptContainer implements IScriptUnit {
}
@Override
public void ensureCompiled() {}
public void ensureCompiled() {
}
@Override
public boolean hasErrored() {
return this.errored;
}
@Override
public void setErrored(boolean errored) {
this.errored = errored;
@@ -1,16 +1,43 @@
package noppes.npcs.controllers;
import noppes.npcs.api.event.*;
import noppes.npcs.api.event.IAbilityEvent;
import noppes.npcs.api.event.IAnimationEvent;
import noppes.npcs.api.event.IBlockEvent;
import noppes.npcs.api.event.ICustomGuiEvent;
import noppes.npcs.api.event.ICustomNPCsEvent;
import noppes.npcs.api.event.IDialogEvent;
import noppes.npcs.api.event.IFactionEvent;
import noppes.npcs.api.event.IForgeEvent;
import noppes.npcs.api.event.IItemEvent;
import noppes.npcs.api.event.ILinkedItemEvent;
import noppes.npcs.api.event.INpcEvent;
import noppes.npcs.api.event.IPartyEvent;
import noppes.npcs.api.event.IPlayerEvent;
import noppes.npcs.api.event.IProjectileEvent;
import noppes.npcs.api.event.IQuestEvent;
import noppes.npcs.api.event.IRecipeEvent;
import noppes.npcs.api.handler.IHookDefinition;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.controllers.data.RecipeScript;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static noppes.npcs.constants.EnumScriptType.*;
import static noppes.npcs.constants.ScriptContext.*;
import static noppes.npcs.constants.ScriptContext.BLOCK;
import static noppes.npcs.constants.ScriptContext.EFFECT;
import static noppes.npcs.constants.ScriptContext.FORGE;
import static noppes.npcs.constants.ScriptContext.ITEM;
import static noppes.npcs.constants.ScriptContext.LINKED_ITEM;
import static noppes.npcs.constants.ScriptContext.NPC;
import static noppes.npcs.constants.ScriptContext.PLAYER;
import static noppes.npcs.constants.ScriptContext.RECIPE;
/**
* Controller for managing script hooks.
@@ -290,8 +317,8 @@ public class ScriptHookController implements IScriptHookHandler {
* Register a hook with event class (auto-derives imports).
* For addon mods to register custom hooks.
*
* @param context Hook context (e.g., "npc", "player")
* @param hookName Function name in scripts
* @param context Hook context (e.g., "npc", "player")
* @param hookName Function name in scripts
* @param eventClass The event class (imports auto-derived from enclosing class)
*/
public void registerHook(String context, String hookName, Class<?> eventClass) {
@@ -185,16 +185,26 @@ public class Animation implements IAnimation {
}
@Override
public boolean hasData(String key) {return dataStore.containsKey(key);}
@Override
public Object getData(String key) {return dataStore.get(key);}
public boolean hasData(String key) {
return dataStore.containsKey(key);
}
@Override
public IAnimation setData(String key, Object v) {dataStore.put(key, v);return this;}
public Object getData(String key) {
return dataStore.get(key);
}
@Override
public IAnimation removeData(String key) {dataStore.remove(key);return this;}
public IAnimation setData(String key, Object v) {
dataStore.put(key, v);
return this;
}
@Override
public IAnimation removeData(String key) {
dataStore.remove(key);
return this;
}
public void readFromNBT(NBTTagCompound compound) {
if (compound.hasKey("ID")) {
@@ -323,13 +333,13 @@ public class Animation implements IAnimation {
this.onAnimationStart = task;
return this;
}
@Override
public IAnimation onFrame(BiConsumer<Integer, IAnimation> task) {
this.onAnimationFrame = task;
return this;
}
@Override
public IAnimation onEnd(Consumer<IAnimation> task) {
this.onAnimationEnd = task;
@@ -355,7 +365,7 @@ public class Animation implements IAnimation {
}
/**
* Only called on setAnimation, to transfer tasks from
* Only called on setAnimation, to transfer tasks from
* this global instance stored in AnimationController
* to the new local instance on entity's AnimationData,
* and clear them from the global instance.
@@ -372,6 +382,6 @@ public class Animation implements IAnimation {
this.dataStore.putAll(animation.dataStore);
animation.dataStore.clear();
}
}
@@ -194,7 +194,7 @@ public class CustomEffect implements ICustomEffect {
return;
}
script.callScript(EnumScriptType.ON_EFFECT_ADD, event);
script.callScript(EnumScriptType.ON_EFFECT_ADD, event);
}
EventHooks.onEffectAdded(iPlayer, playerEffect);
@@ -214,7 +214,7 @@ public class CustomEffect implements ICustomEffect {
return;
}
script.callScript(EnumScriptType.ON_EFFECT_TICK, event);
script.callScript(EnumScriptType.ON_EFFECT_TICK, event);
}
EventHooks.onEffectTick(iPlayer, playerEffect);
@@ -235,7 +235,7 @@ public class CustomEffect implements ICustomEffect {
return;
}
script.callScript(EnumScriptType.ON_EFFECT_REMOVE, event);
script.callScript(EnumScriptType.ON_EFFECT_REMOVE, event);
}
EventHooks.onEffectRemove(iPlayer, playerEffect, type);
@@ -312,6 +312,7 @@ public class DataScript implements IScriptHandlerPacket {
public Collection<ScriptContainer> getNPCScripts() {
return this.scripts.values();
}
@Override
public IScriptUnit createJaninoScriptUnit() {
return new EventJaninoScript(ScriptContext.NPC);
@@ -2,9 +2,7 @@ package noppes.npcs.controllers.data;
import kamkeel.npcs.network.packets.request.script.EffectScriptPacket;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.api.handler.IScriptHookHandler;
import noppes.npcs.constants.ScriptContext;
import noppes.npcs.scripted.event.player.PlayerEvent;
/**
* Script handler for CustomEffect scripts.
@@ -12,7 +10,9 @@ import noppes.npcs.scripted.event.player.PlayerEvent;
*/
public class EffectScript extends SingleScriptHandler implements IScriptHandlerPacket {
/** The effect ID for packet communication. -1 if not bound to an effect. */
/**
* The effect ID for packet communication. -1 if not bound to an effect.
*/
private int effectId = -1;
/**
@@ -23,6 +23,7 @@ public class EffectScript extends SingleScriptHandler implements IScriptHandlerP
/**
* Create an EffectScript bound to a specific effect (for GUI use).
*
* @param effectId The ID of the CustomEffect
*/
public EffectScript(int effectId) {
@@ -13,16 +13,16 @@ import java.util.TreeMap;
public interface IScriptHandler {
default void callScript(EnumScriptType type, Event event) {
if (type != null)
if (type != null)
callScript(type.function, event);
}
void callScript(String hookName, Event event);
/**
* Call a function by name and return its result.
*
* <p>
* Default implementation calls the function on each script unit (in order) and returns
* the first non-null value.
*/
@@ -86,7 +86,7 @@ public interface IScriptHandler {
default Map<Long, String> getConsoleText() {
Map<Long, String> map = new TreeMap<>();
int tab = 0;
for (IScriptUnit script : getScripts()) {
++tab;
for (Map.Entry<Long, String> entry : script.getConsole().entrySet()) {
@@ -97,24 +97,24 @@ public interface IScriptHandler {
}
default void clearConsole() {
for (IScriptUnit script : getScripts())
for (IScriptUnit script : getScripts())
script.clearConsole();
}
/**
* Create a new Janino (Java) script unit for this handler.
* Handlers that don't support Janino scripts should return null.
*
*
* @return A new JaninoScript instance, or null if not supported
*/
default IScriptUnit createJaninoScriptUnit() {
return null; // Default: Janino not supported
}
/**
* Check if this handler supports Janino (Java) scripts.
*
*
* @return true if createJaninoScriptUnit() can create valid Janino scripts
*/
default boolean supportsJanino() {
@@ -133,7 +133,7 @@ public interface IScriptHandler {
/**
* Get the hook context identifier for this handler.
* Used by ScriptHookController to look up available hooks.
*
* <p>
* By default, derives from getContext().hookContext.
* Override if a different hook context is needed.
*
@@ -152,9 +152,9 @@ public interface IScriptHandler {
*/
default List<String> getHooks() {
String context = getHookContext();
if (context == null || context.isEmpty())
if (context == null || context.isEmpty())
return Collections.emptyList();
return ScriptHookController.Instance.getAllHooks(context);
}
@@ -15,9 +15,9 @@ public interface IScriptHandlerPacket extends IScriptHandler {
/**
* Client-side: send a script container packet to the server.
*
* @param index {@code >= 0} for a script tab, {@code -1} for handler metadata (language/enabled/console)
* @param index {@code >= 0} for a script tab, {@code -1} for handler metadata (language/enabled/console)
* @param totalCount Total number of scripts for this handler
* @param nbt The script container NBT (tab content or metadata)
* @param nbt The script container NBT (tab content or metadata)
*/
void sendSavePacket(int index, int totalCount, NBTTagCompound nbt);
@@ -6,7 +6,6 @@ import noppes.npcs.constants.EnumScriptType;
import noppes.npcs.controllers.ScriptContainer;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
@@ -15,24 +14,24 @@ import java.util.TreeMap;
* This allows GuiScriptInterface to work with both script types uniformly.
*/
public interface IScriptUnit {
// NBT type identifiers
String NBT_TYPE_KEY = "ScriptUnitType";
String TYPE_ECMASCRIPT = "ECMAScript";
String TYPE_JANINO = "Janino";
/**
* Create an IScriptUnit from NBT data.
* Uses the "ScriptUnitType" tag to determine which implementation to create.
*
*
* @param compound The NBT data
* @param handler The script handler (used for ScriptContainer)
* @param handler The script handler (used for ScriptContainer)
* @return A ScriptContainer or JaninoScript based on the NBT type
*/
static IScriptUnit createFromNBT(NBTTagCompound compound, IScriptHandler handler) {
String type = compound.getString(NBT_TYPE_KEY);
IScriptUnit unit;
if (TYPE_JANINO.equals(type)) {
// Create appropriate JaninoScript based on handler
unit = handler.createJaninoScriptUnit();
@@ -44,96 +43,97 @@ public interface IScriptUnit {
// Default to ScriptContainer for ECMAScript or missing type
unit = new ScriptContainer(handler);
}
unit.readFromNBT(compound);
return unit;
}
// ==================== SCRIPT CONTENT ====================
/**
* Get the main script text content.
*/
String getScript();
/**
* Set the main script text content.
*/
void setScript(String script);
/**
* Get the list of external script file names loaded for this unit.
*/
List<String> getExternalScripts();
/**
* Set the list of external script file names to load.
*/
void setExternalScripts(List<String> scripts);
// ==================== CONSOLE ====================
/**
* Get the console output map (timestamp -> message).
*/
TreeMap<Long, String> getConsole();
/**
* Clear all console output.
*/
void clearConsole();
/**
* Append a message to the console.
*/
void appendConsole(String message);
// ==================== LANGUAGE ====================
/**
* Get the scripting language for this unit.
* Returns "ECMAScript", "Java", etc.
*/
String getLanguage();
/**
* Set the scripting language for this unit.
*
* @param language The language name (e.g., "ECMAScript", "Java")
*/
void setLanguage(String language);
/**
* Check if this script unit uses Janino (Java) compilation.
*/
default boolean isJanino() {
return "Java".equals(getLanguage());
}
// ==================== HOOK GENERATION ====================
/**
* Generate a stub/template for the given hook name.
* ECMAScript: function hookName(event) { }
* Janino: full Java method signature with return type
*
*
* @param hookName The hook name to generate a stub for
* @param hookData Optional data (e.g., Method object for Janino)
* @return The generated stub string
*/
String generateHookStub(String hookName, Object hookData);
// ==================== NBT ====================
/**
* Write this script unit to NBT.
*/
NBTTagCompound writeToNBT(NBTTagCompound compound);
/**
* Read this script unit from NBT.
*/
void readFromNBT(NBTTagCompound compound);
// ==================== STATE ====================
/**
@@ -141,43 +141,43 @@ public interface IScriptUnit {
* No-op for ScriptContainer.
*/
void ensureCompiled();
/**
* Check if this script unit has any code (script or external scripts).
*/
boolean hasCode();
/**
* Check if this script unit has encountered an error during execution.
*/
boolean hasErrored();
/**
* Set the error state of this script unit.
*/
void setErrored(boolean errored);
// ==================== EXECUTION ====================
/**
* Execute this script unit for the given hook type and event.
*
* @param type The script hook type
*
* @param type The script hook type
* @param event The event object
*/
void run(EnumScriptType type, Event event);
/**
* Execute this script unit for the given hook name and event.
*
* @param hookName The hook name (e.g., "init", "interact")
* @param event The event object
* @param event The event object
*/
void run(String hookName, Object event);
/**
* Call a script function by name and return its result.
*
* <p>
* Default implementation returns null (not supported).
*/
default Object callFunction(String hookName, Object... args) {
@@ -11,13 +11,13 @@ import java.util.function.Supplier;
/**
* Reusable IScriptHandler implementation for objects that own an optional single JaninoScript unit.
*
* <p>
* This is meant for "function provider" scripts (not EnumScriptType driven). Execution is typically
* initiated by the owning system calling script.call(...) directly.
*
* <p>
* NBT storage is kept under the parent compound key "Script" (same convention as JaninoScriptable).
*/
public class JaninoScriptHandler<S extends JaninoScript<?>> extends ScriptHandler {
public class JaninoScriptHandler<S extends JaninoScript<?>> extends ScriptHandler {
protected S script;
@@ -41,9 +41,9 @@ public class JaninoScriptHandler<S extends JaninoScript<?>> extends ScriptHandle
}
public JaninoScript createScript() {
if (script == null)
if (script == null)
script = factory.get();
return script;
}
@@ -96,9 +96,9 @@ public class JaninoScriptHandler<S extends JaninoScript<?>> extends ScriptHandle
@Override
public List<IScriptUnit> getScripts() {
if (script == null)
if (script == null)
return Collections.emptyList();
return Collections.<IScriptUnit>singletonList(script);
}
@@ -249,8 +249,8 @@ public class LinkedItem implements ILinkedItem {
@Override
public void setAttackSpeed(int time) {
if(time <= 0) {
time = 10;
if (time <= 0) {
time = 10;
}
this.attackSpeed = time;
}
@@ -9,44 +9,47 @@ import noppes.npcs.constants.ScriptContext;
* Manages a single script container for linked item hooks.
*/
public class LinkedItemScript extends SingleScriptHandler implements IScriptHandlerPacket {
/** The linked item ID for packet communication. -1 if not bound. */
/**
* The linked item ID for packet communication. -1 if not bound.
*/
private int linkedItemId = -1;
/**
* Create an unbound LinkedItemScript (for server-side use).
*/
public LinkedItemScript() {
}
/**
* Create a LinkedItemScript bound to a specific linked item (for GUI use).
*
* @param linkedItemId The ID of the LinkedItem
*/
public LinkedItemScript(int linkedItemId) {
this.linkedItemId = linkedItemId;
}
@Override
public ScriptContext getContext() {
return ScriptContext.LINKED_ITEM;
}
@Override
public String noticeString() {
return "LinkedItem";
}
@Override
public void requestData() {
if (linkedItemId >= 0)
if (linkedItemId >= 0)
LinkedItemScriptPacket.Get(linkedItemId);
}
@Override
public void sendSavePacket(int index, int totalCount, NBTTagCompound nbt) {
if (linkedItemId >= 0)
if (linkedItemId >= 0)
LinkedItemScriptPacket.Save(linkedItemId, index, totalCount, nbt);
}
}
@@ -7,13 +7,11 @@ import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.ScriptController;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
/**
* Base class for script handlers that manage multiple script containers (tabs).
* Provides shared NBT serialization and common script execution patterns.
*
* <p>
* Subclasses should:
* - Override getContext() to return the appropriate ScriptContext
* - Override getHookContext() if not using ScriptContext's hookContext
@@ -21,7 +19,7 @@ import java.util.TreeMap;
* - Override isEnabled() if custom enable logic is needed
*/
public abstract class MultiScriptHandler extends ScriptHandler implements IScriptHandlerPacket {
// ==================== NBT SERIALIZATION ====================
/**
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more